routing: Until used up stays on the next account once the first is used up (dzxx0496)

dzxx0496 on Discord: with free accounts one after another, the first used
up, requests went to the second; when the first renewed they went back to
it ("如果第一个恢复了,它又优先用第一个了"). No routing did what they asked:
In order and Smart both put the first back first.

A new routing, Until used up (drain, 用完再换): requests stay on one seat
until its quota is used up, then go on to the next in the list and stay
there. A seat counts as used up when its known allowance is at 100% or
it was refused for quota or credit (failQuota / failCredit, routes.Drained
called where the rest is recorded, so a failover inside one request moves
the pool too). A rate limit or other failure only passes it over while
it rests, as In order does. Each pool (a provider, a group/<id>) keeps its
own place; routes.Forget clears it.

Offered wherever a routing is picked: the provider editor, a group's row
menu and editor (app menu, no native select), the TUI, `magpie group set
<id> routing=drain` and a provider's routing=drain. Nothing defaults to
it, so no saved setting changes. SpentShareOf is 100 for it, as for In
order. Words in en, zh, zh-TW, ja and de (i18n.js and the routing
plugin's own), docs/subsystems and the site's start page (en, zh, ja).

Tests:
- internal/routes/drain_test.go: stays on the next when the first renews,
  through a rate limit, all used up, a seat gone, per pool, Forget,
  Drained after a renewal.
- internal/gateway/drain_test.go: a real request path with a fake upstream;
  k1 refused for quota, k2 takes over, k1 renews: drain stays on k2,
  In order goes back to k1. Red without the Drained hook (request 3 went
  to k1). A rate limit comes back to k1; drain is saved on a provider and
  a group.
- routing-drain.test.cjs: the Routing page's why and mode line in 5
  languages, 1100px and 420px, Chromium and WebKit; red on the old assets
  (20 of 20).
- routing-group-strategy, routing-save, builtins: the menu has 11 routings.

Run on mote (macOS) at origin/main 699ddf152 with this commit and its
two neighbours (nb5p chip, dzxx0496 renewal, dzxx0496 Until used up).
Pushed on b2145eac1, whose five commits since change app.css and app.js
only for a key row's chips; at the pushed tree gofmt, the gui, routes
and gateway vets (Linux nogui, Windows), TestCoreScriptBudget (core
1,532,891), the Drain Go tests and 11 GUI files (gateway-model-chip-
height, routing-drain, routing-renews-stay, routing-behind-why,
routing-group-strategy, routing-save, builtins, i18n-keys, gui-de,
gui-zh-tw, key-row-chips-fit) were run again: 190 of 190 ok.
- gofmt -l clean; GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./... and go vet ok.
- go test internal/routes, internal/gateway, internal/provider,
  internal/cli, internal/tui, plugins/rotation: ok; internal/gui's
  TestCoreScriptBudget ok (core 1,532,816 of 1,533,105).
- GUI: routing-*, builtins, gateway-model*, model-chip*, i18n-keys,
  gui-* and codex-credits-last in both engines: 2211 tests, 68 red,
  none new: model-chip-steady 20 (#4388), gui-ja's {agent} string
  (#4580), and 11 routing-* files under load (#4585, #3789, #3799).
  The same 11 files run alone at cdfdb62c6 were 32 of 116 red, and 26
  with the stack, the same tests but rule-remove, whose red languages
  vary run to run (9 cases, then 5). model-chip-steady was 20 of 20 red
  at cdfdb62c6 alone.
Earlier, at f811bf291 with the stack: go test -timeout 45m ./... had 82
packages ok, internal/gui red only on
TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
TestMainWindowCorners/macOS_26_SDK (#3949). The whole GUI suite had 301
of 16930 red in 52 files. Those 52 files rerun had 272 red with the
stack and 276 at f811bf291 alone, the same tests.
This commit is contained in:
yetone
2026-11-01 09:53:50 +08:00
parent 72114566bf
commit 9162277b91
29 changed files with 555 additions and 37 deletions
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -199,7 +199,7 @@ the core. The seven other routings are the built-in plugin `rotation`'s.
| `routes.Strategy` | `Order(pool, seats) []int`: a permutation of the seats' indexes. `pool` is a provider's id or `group/<id>`, for a strategy that keeps a round per pool. `Exact` keeps the order as given; otherwise a provider's API keys that fit the request better go first, each in its order. `ByUse` puts each seat's recent tokens in the trace; `ByFree` has the gateway fill `Seat.Free`, and `BySpeed` `Seat.TTFT` and `TPS` (its speed lately, gateway `speed.go`), each only for a strategy that asks. | [`routes.go`](../../internal/routes/routes.go) |
| `routes.Seat` | What a strategy weighs, read by `weighRouted` under the routing state's lock: its rest key, whether it is an account, whether its allowance is known or it learns it as it answers, the share used, when its windows renew, its weekly pace, its key's weight, whether it rests now, its tokens of the last hours, a prepaid wallet's balance and the provider and unit it is in (`Left`, `LeftIn`, #3950), and, when the strategy asks, whether its model is free and its ms to the first token and tokens a second lately. | [`routes.go`](../../internal/routes/routes.go), [`routing.go`](../../internal/gateway/routing.go) |
| `Register`, `Find`, `Apply` | `Register(routing, s)` serves a routing until its remove; registering again stacks, and the last one serves. `Find("")` is `Smart` always. `Apply` fails open: a strategy that panics, or answers what isn't a permutation, leaves the pool in its listed order, logged. Every route is still tried. | [`routes.go`](../../internal/routes/routes.go) |
| Strategies | `Smart` (core), and `Ordered`, `Rotate`, `LeastUsed`, `Pace`, `Weighted`, `FreeFirst`, `Fastest` and `Cheapest` (a group's only: `provider.normalize` drops `cheap` from a provider) in `routes.Builtin`. `Rotate` keeps a turn per pool and `Weighted` a smooth weighted round (`Round`, `MoveRound`), both moved out of the gateway, and `Fastest` a probe count per pool, so a seat not measured lately gets one request in `ProbeEvery`; `Forget` clears them. | [`strategies.go`](../../internal/routes/strategies.go), [`round.go`](../../internal/routes/round.go) |
| Strategies | `Smart` (core), and `Ordered`, `Rotate`, `LeastUsed`, `Pace`, `Weighted`, `FreeFirst`, `Fastest`, `Cheapest` (a group's only: `provider.normalize` drops `cheap` from a provider) and `Drain` in `routes.Builtin`. `Drain` remembers the seat each pool is on (`drains`). `Rotate` keeps a turn per pool and `Weighted` a smooth weighted round (`Round`, `MoveRound`), both moved out of the gateway, and `Fastest` a probe count per pool, so a seat not measured lately gets one request in `ProbeEvery`; `Forget` clears them, `Drain`'s too. | [`strategies.go`](../../internal/routes/strategies.go), [`round.go`](../../internal/routes/round.go) |
| Off | A routing no strategy serves is its listed order. `routingOf` in the gateway reads it as `order` wherever the core asks about a routing (a turn's mark, `sinks`, a rotate group's sessions, a group's heads), so nothing of the routing is left half on. | [`routing.go`](../../internal/gateway/routing.go) |
| `plugins/rotation` | Requires `providers` and `gateway`, `Essential`. Apply registers every `routes.Builtin` and removes them when turned off. `InUse` counts the providers and groups providers.json routes by one of them (`provider.Routings`, the file alone, not the catalog); an unreadable providers.json is an error, so it stays on. The gateway's `KeepFresh` watches providers.json too, so a routing set from the CLI or the TUI turns it on within 2s. Off, the window's routing pickers (the provider editor, the Routing page's pools and groups) offer Smart alone: their options are marked `data-feature="rotation"` (`routingSegs`). | [`rotation.go`](../../plugins/rotation/rotation.go), [`provider.go`](../../internal/provider/provider.go), [`app.js`](../../internal/gui/assets/app.js) |
+5 -1
View File
@@ -90,6 +90,8 @@ const groupUsage = `usage:
how many models each matches now, and says when one matches nothing
routing smart (default) of the subscriptions with quota to spare, the one renewing soonest first
order the first model until it can't answer, then the next
drain one account or key until it is used up, then the next, and stays there: an
earlier one that renews meanwhile doesn't take the requests back
rotate each conversation's next turn goes to the next member's account or key
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
@@ -124,6 +126,7 @@ const groupUsage = `usage:
magpie group set opus-anywhere routing=weight weight=claude/claude-opus-5-5=3
magpie group set deepseek-anywhere routing=fast # the provider that answered it fastest lately first
magpie group set deepseek-anywhere routing=cheap # the provider it costs least on now first (DeepSeek's off-peak hours)
magpie group set free-pool routing=drain # one account until it is used up, then the next, never back
magpie group pick opus-anywhere copilot/claude-opus-5.5
magpie claude group/opus-anywhere`
@@ -142,6 +145,7 @@ var routingNames = []struct {
{provider.FreeFirst, "free", []string{"free-first", "freest", "no-cost"}},
{provider.Fastest, "fast", []string{"fastest", "speed", "speed-first"}},
{provider.Cheapest, "cheap", []string{"cheapest", "cheapest-first", "price", "cost"}},
{provider.Drain, "drain", []string{"until-used-up", "use-up", "sticky"}},
{provider.Manual, "manual", []string{"pick", "picked", "pinned"}},
}
@@ -1074,7 +1078,7 @@ func groups() error {
r.how += muted.Render(fmt.Sprintf(" · %d rule%s", n, map[bool]string{true: "", false: "s"}[n == 1]))
}
sep, ready := muted.Render(" · "), false
if g.Routing == provider.Ordered {
if g.Routing == provider.Ordered || g.Routing == provider.Drain {
sep = muted.Render(" → ")
}
var ms []string
+1 -1
View File
@@ -90,7 +90,7 @@ const usage = `magpie — one place to pick every agent's model
or only the models ticked for it, a new one off until it is ticked
magpie search [add <api> <key>|rm <api>] Tavily, Brave, Exa, Firecrawl, You.com, DeepSeek, Doubao Search (Volcengine), Yuanbao Search (Tencent Cloud) or SearXNG for web search when no provider can search
magpie groups routing groups: several models agents pick as one, group/<id>
magpie group add <name> models=<m1>,<m2> [routing=smart|order|rotate|usage|pace|weight|free|fast|cheap] [stays=auto|session|turn|off]
magpie group add <name> models=<m1>,<m2> [routing=smart|order|rotate|usage|pace|weight|free|fast|cheap|drain] [stays=auto|session|turn|off]
magpie group <id> | set <id> k=v… | rm <id> show, change or remove one (magpie group help for more)
magpie accounts [agent] [--json] every subscription magpie knows, with each one's allowance used and when it resets
magpie accounts add <agent> sign in to one more Claude, ChatGPT or Google (Gemini CLI, Antigravity) subscription
+4 -3
View File
@@ -42,8 +42,9 @@ const providerUsage = `usage:
compaction=native asks the provider Codex's own compaction and hands
Codex its sealed item as it came (a Responses API, a ChatGPT account,
Copilot), compaction=magpie, the default, has magpie summarise
routing=smart|order|rotate|usage|pace|weight|free|fast spreads requests
over its keys or accounts (fast: the one that answered fastest lately first);
routing=smart|order|rotate|usage|pace|weight|free|fast|drain spreads requests
over its keys or accounts (fast: the one that answered fastest lately first;
drain: one until it is used up, then the next, never back to an earlier one);
prompt=as-written sends Antigravity the system prompt exactly as written;
prompt=default, the default, breaks up the lines Google answers with a
false 429 (Codex's, Claude Code's, Hermes' old persona) with a zero-width space
@@ -1240,7 +1241,7 @@ func applyPairs(p *provider.Provider, pairs []string) error {
if r == provider.Manual || r == provider.Cheapest {
// cheap: its keys and accounts all bill the provider's one
// price, so there is nothing to weigh
return fmt.Errorf("routing=%s is a group's: a provider's keys or accounts are routed smart, order, rotate, usage, pace, weight, free or fast", r)
return fmt.Errorf("routing=%s is a group's: a provider's keys or accounts are routed smart, order, rotate, usage, pace, weight, free, fast or drain", r)
}
p.Routing = r
case "icon":
+168
View File
@@ -0,0 +1,168 @@
package gateway
import (
"io"
"net/http"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/routes"
)
// drained answers each key, or refuses it with its status and body.
type drained struct {
sync.Mutex
tried []string
fail map[string][2]string // key → status, body
}
func (d *drained) ServeHTTP(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
d.Lock()
d.tried = append(d.tried, key)
f, failing := d.fail[key]
d.Unlock()
w.Header().Set("Content-Type", "application/json")
if failing {
code := map[string]int{"429": 429, "402": 402}[f[0]]
w.WriteHeader(code)
io.WriteString(w, f[1])
return
}
io.WriteString(w, `{"id":"x","choices":[{"index":0,"message":{"role":"assistant","content":"from `+key+`"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}`)
}
func (d *drained) set(key, status, body string) {
d.Lock()
defer d.Unlock()
if status == "" {
delete(d.fail, key)
return
}
d.fail[key] = [2]string{status, body}
}
func (d *drained) last() string {
d.Lock()
defer d.Unlock()
return d.tried[len(d.tried)-1]
}
// wake ends every rest, as each one's time running out would.
func wake() {
restingUntil.Lock()
restingUntil.m = map[string]time.Time{}
restingUntil.note = map[string]Rest{}
restingUntil.Unlock()
}
const outOfQuota = `{"error":{"message":"You exceeded your current quota, please check your plan","type":"insufficient_quota"}}`
// dzxx0496 on Discord: an account's free quota used up, the next takes
// over, and when the first renews requests go back to it. Routed Until used
// up, they stay on the one that took over; In order still goes back to the
// first, as it always has.
func TestDrainKeepsTheOneThatTookOver(t *testing.T) {
for _, c := range []struct {
routing, want string
}{
{provider.Drain, "k2"},
{provider.Ordered, "k1"},
} {
t.Run(c.routing, func(t *testing.T) {
fresh(t)
up := &drained{fail: map[string][2]string{}}
serveOn(t, "dr", "k1", []string{"m1"}, up, "k2", "k3")
if err := provider.SetRouting("dr", c.routing); err != nil {
t.Fatal(err)
}
if err := provider.SetAffinity("dr", provider.AffinityOff); err != nil {
t.Fatal(err)
}
routes.Forget("dr")
s := New()
ask := func(n int) string {
t.Helper()
code, out := postAs(t, s, "", `{"model":"dr/m1","messages":[{"role":"user","content":"ask `+strings.Repeat("x", n)+`"}]}`)
if code != 200 {
t.Fatalf("%d %s", code, out)
}
return up.last()
}
if k := ask(1); k != "k1" {
t.Fatalf("first request went to %s, want k1", k)
}
// k1's quota used up: k2 takes over
up.set("k1", "429", outOfQuota)
if k := ask(2); k != "k2" {
t.Fatalf("k1 out of quota: went to %s, want k2 (tried %v)", k, up.tried)
}
// k1 renews
up.set("k1", "", "")
wake()
for i := 3; i < 6; i++ {
if k := ask(i); k != c.want {
t.Fatalf("after k1 renewed, request %d went to %s, want %s (tried %v)", i, k, c.want, up.tried)
}
}
})
}
}
// A rate limit is not the quota used up: the next answers while it rests,
// and the requests go back to the one it was on after.
func TestDrainComesBackAfterARateLimit(t *testing.T) {
fresh(t)
up := &drained{fail: map[string][2]string{}}
serveOn(t, "dl", "k1", []string{"m1"}, up, "k2")
if err := provider.SetRouting("dl", provider.Drain); err != nil {
t.Fatal(err)
}
if err := provider.SetAffinity("dl", provider.AffinityOff); err != nil {
t.Fatal(err)
}
routes.Forget("dl")
s := New()
ask := func(n int) string {
t.Helper()
code, out := postAs(t, s, "", `{"model":"dl/m1","messages":[{"role":"user","content":"ask `+strings.Repeat("y", n)+`"}]}`)
if code != 200 {
t.Fatalf("%d %s", code, out)
}
return up.last()
}
up.set("k1", "429", `{"error":{"message":"slow down"}}`)
if k := ask(1); k != "k2" {
t.Fatalf("k1 rate limited: went to %s, want k2", k)
}
up.set("k1", "", "")
wake()
if k := ask(2); k != "k1" {
t.Fatalf("k1's rate limit over: went to %s, want k1 again (tried %v)", k, up.tried)
}
}
// Saved, the routing is kept: a provider's and a group's.
func TestDrainIsSaved(t *testing.T) {
fresh(t)
serveOn(t, "ds", "k1", []string{"m1"}, &drained{fail: map[string][2]string{}}, "k2")
if err := provider.SetRouting("ds", provider.Drain); err != nil {
t.Fatal(err)
}
p, err := provider.Find("ds")
if err != nil || p.Routing != provider.Drain {
t.Fatalf("provider routing %q, %v; want %q", p.Routing, err, provider.Drain)
}
if err := provider.SaveGroup(provider.Group{ID: "dg", Name: "DG", Members: []string{"ds/m1"}, Routing: provider.Drain}); err != nil {
t.Fatal(err)
}
for _, g := range provider.Groups() {
if g.ID == "dg" && g.Routing != provider.Drain {
t.Fatalf("group routing %q, want %q", g.Routing, provider.Drain)
}
}
}
+7 -1
View File
@@ -1532,6 +1532,12 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo
restingUntil.note[id] = r
}
restingUntil.Unlock()
if id == c.restKey() && (why == failQuota || why == failCredit) {
// a pool routed Until used up goes on from it, though it renews
// before the pool's next request (dzxx0496); one model of it
// refused leaves the account in use for the others
routes.Drained(c.rest)
}
if kept {
saveRests() // a magpie started again rests it out, and climbs on
}
@@ -2063,7 +2069,7 @@ func weighRouted(p provider.Provider, cs []candidate, model string, from provide
}
seats[i] = routes.Seat{Key: c.rest, Account: c.p.Account != nil, Known: known, Learns: learns(c, wg.lefts),
Used: l.used, Soon: l.soon, Lapse: l.lapse, Pace: pace, Weight: keyWeight(c), Resting: resting(c), Tokens: routed.used[c.restKey()].now(now), Credits: l.credits,
Left: l.bal, LeftIn: l.balIn}
Left: l.bal, LeftIn: l.balIn, Spent: spentRest(c)}
}
routed.Unlock()
if st.ByUse {
+7
View File
@@ -32,6 +32,13 @@ func keyWeight(c candidate) int {
return max(c.p.KeyWeight, 1)
}
// spentRest says whether c rests out of its quota or its credit, not for
// a rate limit or a failure: routes.Seat.Spent, what Drain goes on from.
func spentRest(c candidate) bool {
r, ok := restingOf(c)
return ok && (r.Why == failQuota || r.Why == failCredit)
}
// resting says whether c rests now, as restLast will find.
func resting(c candidate) bool {
if _, ok := restOf(c.restKey()); ok {
+5 -2
View File
@@ -11865,6 +11865,9 @@ function renderDrawers(p) {
const ROUTINGS = [
["", "Smart", "The first takes requests while it has quota to spare; when it runs low, the one with the most left takes over. One out of credit sits out half an hour, one out of quota until it resets, one rate limited as long as the vendor asks, and one that fails a minute, longer each time it fails again."],
["order", "In order", "Requests go to the first; the next takes over when the one before runs out of quota, hits a rate limit or fails."],
// dzxx0496 on Discord: free accounts one after another, the first not
// taking the requests back once it renews (routes.Drain)
["drain", "Until used up", "Requests stay on one until it is used up, then go to the next in the list and stay there: one before it that renews meanwhile doesn't take them back. One rate limited or failing is passed over while it rests, and requests come back to it after."],
["rotate", "In turn", "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."],
["usage", "Least used first", "Each request goes to the one used least: a subscription by the share of its allowance used, a key by the tokens it served in the last hours."],
["pace", "Weekly pace", "Each request goes to the subscription 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 week is lost at its reset; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours."],
@@ -11875,7 +11878,7 @@ const ROUTINGS = [
// the routings besides Smart are the built-in plugin rotation's
// (plugins/rotation): off, their options leave the page, as anything marked
// data-feature does, and Smart is left — one in use keeps it on
const ROTATION = new Set(["order", "rotate", "usage", "pace", "weight", "free", "fast", "cheap"]);
const ROTATION = new Set(["order", "drain", "rotate", "usage", "pace", "weight", "free", "fast", "cheap"]);
// jsRoutings: the routings JS gateway plugins serve now ("<plugin>/<name>",
// settings' jsRoutings, plugins/middleware's), and saved, a routing none
// serves now, shown as it is: its pool is tried in its listed order
@@ -11937,7 +11940,7 @@ function renderRouting(p) {
? t("Routing picks the account for each request through magpie, in the accounts' order; {agent} on its own stays signed in to {user}, whatever it has left.", { agent: a.agentName, user: keptLogin(p) })
: p.keepLogin && !p.switchOnly
? t("Routing picks the account for each request through magpie; {agent} on its own stays signed in to the first account, whatever it has left.", { agent: a.agentName })
: routing === "order"
: routing === "order" || routing === "drain"
? t("Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is used up, and back to the first once that has room again.", { agent: a.agentName })
: a.agent === "codex" && !p.switchOnly || p.keepLogin
? t("Routing picks the account for each request through magpie; {agent} on its own uses the one it is signed in to, which magpie moves to the next ticked account with room once it is 98% used, and back to the first once that has room again.", { agent: a.agentName })
+12 -4
View File
@@ -875,7 +875,7 @@ const I18N = {
"Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse": "把每个请求的追踪和指标发送到 OpenTelemetry 收集器,比如 Langfuse",
"Sending to a collector": "正在发送到收集器",
"Routing strategies": "路由策略",
"The routings besides Smart: In order, In turn, Least used first, Weekly pace, By weight, Free first, Speed first and Cheapest first": "智能以外的路由方式:按顺序、轮流、用量少的优先、重置前用完、按权重、免费优先、速度优先和最便宜优先",
"The routings besides Smart: In order, Until used up, In turn, Least used first, Weekly pace, By weight, Free first, Speed first and Cheapest first": "智能以外的路由方式:按顺序、用完再换、轮流、用量少的优先、重置前用完、按权重、免费优先、速度优先和最便宜优先",
"1 provider or group routed so": "1 个提供商或路由组在用",
"{n} providers and groups routed so": "{n} 个提供商和路由组在用",
"Run the JavaScript gateway plugins: middleware on agents' requests and replies, routings and usage observers": "运行 JavaScript 网关插件:Agent 请求和回复上的中间件、路由方式和用量观察者",
@@ -1758,6 +1758,8 @@ const I18N = {
"Smart": "智能",
"The first takes requests while it has quota to spare; when it runs low, the one with the most left takes over. One out of credit sits out half an hour, one out of quota until it resets, one rate limited as long as the vendor asks, and one that fails a minute, longer each time it fails again.": "额度充足时请求都给第一个;快用完时由剩余最多的接手。欠费的暂停半小时,额度用完的暂停到重置,被限流的按厂商要求暂停,出错的暂停一分钟,再出错则逐次延长。",
"In order": "按顺序",
"Until used up": "用完再换",
"Requests stay on one until it is used up, then go to the next in the list and stay there: one before it that renews meanwhile doesn't take them back. One rate limited or failing is passed over while it rests, and requests come back to it after.": "请求一直发给同一个,直到它的额度用完,再换列表里的下一个并留在那里:前面的额度恢复了也不会切回去。被限流或出错的那个只在休息期间跳过,之后请求仍回到它。",
"In turn": "轮流",
"Least used first": "用量少的优先",
"By weight": "按权重",
@@ -5192,7 +5194,7 @@ const I18N = {
"Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse": "把每個請求的追蹤和指標傳送到 OpenTelemetry 收集器,例如 Langfuse",
"Sending to a collector": "正在傳送到收集器",
"Routing strategies": "路由策略",
"The routings besides Smart: In order, In turn, Least used first, Weekly pace, By weight, Free first, Speed first and Cheapest first": "智慧以外的路由方式:按順序、輪流、用量少的優先、重置前用完、按權重、免費優先、速度優先和最便宜優先",
"The routings besides Smart: In order, Until used up, In turn, Least used first, Weekly pace, By weight, Free first, Speed first and Cheapest first": "智慧以外的路由方式:按順序、用完再換、輪流、用量少的優先、重置前用完、按權重、免費優先、速度優先和最便宜優先",
"1 provider or group routed so": "1 個提供商或路由組在用",
"{n} providers and groups routed so": "{n} 個提供商和路由組在用",
"Run the JavaScript gateway plugins: middleware on agents' requests and replies, routings and usage observers": "執行 JavaScript 閘道外掛:Agent 請求和回覆上的中介軟體、路由方式和用量觀察者",
@@ -6064,6 +6066,8 @@ const I18N = {
"Smart": "智慧",
"The first takes requests while it has quota to spare; when it runs low, the one with the most left takes over. One out of credit sits out half an hour, one out of quota until it resets, one rate limited as long as the vendor asks, and one that fails a minute, longer each time it fails again.": "額度充足時請求都給第一個;快用完時由剩餘最多的接手。欠費的暫停半小時,額度用完的暫停到重置,被限流的按廠商要求暫停,出錯的暫停一分鐘,再出錯則逐次延長。",
"In order": "按順序",
"Until used up": "用完再換",
"Requests stay on one until it is used up, then go to the next in the list and stay there: one before it that renews meanwhile doesn't take them back. One rate limited or failing is passed over while it rests, and requests come back to it after.": "請求一直發給同一個,直到它的額度用完,再換列表裡的下一個並留在那裡:前面的額度恢復了也不會切回去。被限流或出錯的那個只在休息期間跳過,之後請求仍回到它。",
"In turn": "輪流",
"Least used first": "用量少的優先",
"By weight": "按權重",
@@ -9480,7 +9484,7 @@ const I18N = {
"Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse": "各リクエストのトレースとメトリクスを Langfuse などの OpenTelemetry コレクターに送ります",
"Sending to a collector": "コレクターに送信中",
"Routing strategies": "ルーティング戦略",
"The routings besides Smart: In order, In turn, Least used first, Weekly pace, By weight, Free first, Speed first and Cheapest first": "スマート以外のルーティング:順番、交互、使用量が最少のものを優先、週ペース、重み付け、無料優先、速度優先、最安優先",
"The routings besides Smart: In order, Until used up, In turn, Least used first, Weekly pace, By weight, Free first, Speed first and Cheapest first": "スマート以外のルーティング:順番、使い切ってから次へ、交互、使用量が最少のものを優先、週ペース、重み付け、無料優先、速度優先、最安優先",
"1 provider or group routed so": "1 個のプロバイダーまたはグループが使用中",
"{n} providers and groups routed so": "{n} 個のプロバイダーとグループが使用中",
"Run the JavaScript gateway plugins: middleware on agents' requests and replies, routings and usage observers": "JavaScript ゲートウェイプラグインを実行します:エージェントのリクエストと応答のミドルウェア、ルーティング、使用量オブザーバー",
@@ -10346,6 +10350,8 @@ const I18N = {
"Smart": "スマート",
"The first takes requests while it has quota to spare; when it runs low, the one with the most left takes over. One out of credit sits out half an hour, one out of quota until it resets, one rate limited as long as the vendor asks, and one that fails a minute, longer each time it fails again.": "クォータに余裕がある間は最初のアカウントがリクエストを受け、残量が少なくなると残りが最も多いアカウントが引き継ぎます。クレジット切れは30分、クォータ切れはリセットまで、レート制限はベンダーの指定する時間、エラーは1分(失敗が続くたびに長く)休止します。",
"In order": "順番",
"Until used up": "使い切ってから次へ",
"Requests stay on one until it is used up, then go to the next in the list and stay there: one before it that renews meanwhile doesn't take them back. One rate limited or failing is passed over while it rests, and requests come back to it after.": "リクエストは 1 つを使い切るまでそこに送り、使い切ったらリストの次へ移ってそこに留まります。その間に前のものが回復しても戻りません。レート制限やエラーで休んでいるものは休止中だけ飛ばし、その後はまたそこへ送ります。",
"In turn": "交互",
"Least used first": "使用量が最少のものを優先",
"By weight": "重み付け",
@@ -13783,7 +13789,7 @@ const I18N = {
"Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse": "Traces und Metriken jeder Anfrage an einen OpenTelemetry-Collector senden, etwa Langfuse",
"Sending to a collector": "Sendet an einen Collector",
"Routing strategies": "Routing-Strategien",
"The routings besides Smart: In order, In turn, Least used first, Weekly pace, By weight, Free first, Speed first and Cheapest first": "Die Routings neben Intelligent: Der Reihe nach, Abwechselnd, Am wenigsten genutzte zuerst, Wochentempo, Nach Gewicht, Kostenlos zuerst, Schnellste zuerst und Günstigste zuerst",
"The routings besides Smart: In order, Until used up, In turn, Least used first, Weekly pace, By weight, Free first, Speed first and Cheapest first": "Die Routings neben Intelligent: Der Reihe nach, Bis aufgebraucht, Abwechselnd, Am wenigsten genutzte zuerst, Wochentempo, Nach Gewicht, Kostenlos zuerst, Schnellste zuerst und Günstigste zuerst",
"1 provider or group routed so": "1 Anbieter oder Gruppe so geroutet",
"{n} providers and groups routed so": "{n} Anbieter und Gruppen so geroutet",
"Run the JavaScript gateway plugins: middleware on agents' requests and replies, routings and usage observers": "Die JavaScript-Gateway-Plugins ausführen: Middleware auf Anfragen und Antworten der Agenten, Routings und Nutzungsbeobachter",
@@ -14659,6 +14665,8 @@ const I18N = {
"Smart": "Intelligent",
"The first takes requests while it has quota to spare; when it runs low, the one with the most left takes over. One out of credit sits out half an hour, one out of quota until it resets, one rate limited as long as the vendor asks, and one that fails a minute, longer each time it fails again.": "Das erste erhält Anfragen, solange es Kontingent übrig hat; wird es knapp, übernimmt das mit dem meisten Rest. Eines ohne Guthaben pausiert eine halbe Stunde, eines ohne Kontingent bis zum Reset, ein gedrosseltes so lange, wie der Anbieter verlangt, und ein fehlschlagendes eine Minute, bei jedem weiteren Fehler länger.",
"In order": "Der Reihe nach",
"Until used up": "Bis aufgebraucht",
"Requests stay on one until it is used up, then go to the next in the list and stay there: one before it that renews meanwhile doesn't take them back. One rate limited or failing is passed over while it rests, and requests come back to it after.": "Anfragen bleiben bei einem, bis es aufgebraucht ist, gehen dann zum nächsten in der Liste und bleiben dort: Ein früheres, das sich inzwischen erneuert, holt sie nicht zurück. Eines, das rate-limitiert ist oder fehlschlägt, wird übergangen, solange es ruht, und bekommt die Anfragen danach wieder.",
"In turn": "Abwechselnd",
"Least used first": "Am wenigsten genutzte zuerst",
"By weight": "Nach Gewicht",
@@ -526,6 +526,7 @@ function routingPage(part) {
const MODES = {
"": ["Smart", "Smart: of the accounts with quota to spare, the one whose allowance renews soonest goes first — what it has left would be lost at the reset. The week decides; an account with five hours and no week goes by its five hours. One at 90% or more waits until the others can't answer; one resting after a failure goes last."],
order: ["In order", "In order: the first answers everything until it can't; then the next."],
drain: ["Until used up", "Until used up: one answers everything until its quota is used up; then the next, which keeps them even after the one before renews."],
rotate: ["In turn", "In turn: each conversation's next turn goes to the account after the one that answered its last, and a new conversation starts one further along; the requests within a turn stay put, keeping the prompt cache."],
usage: ["Least used", "Least used first: the account with the most of its allowance left goes first; a key by the tokens magpie sent it lately."],
pace: ["Weekly pace", "Weekly pace: the account with the most of its week left per hour until it renews goes first — the one with the most to lose at its reset; an account with five hours and no week by what its five hours have left per hour. One at 90% or more waits until the others can't answer; a key by the tokens magpie sent it lately."],
@@ -740,6 +741,7 @@ function routingPage(part) {
case "order": return rested.length
? t("In order: with {rested} resting after a failure, {who} is the first that can answer.", { rested: rested.join(", "), who: w })
: t("In order: {who} is first, and answers everything while it can.", { who: w });
case "drain": return t("Until used up: {who} is the one in use, and answers everything until it is used up.", { who: w });
case "rotate": return t("In turn: it's {who}'s turn — each request starts one further along.", { who: w });
case "weight": return t(f.kind === "account" ? "By weight: it's {who}'s share — each account takes requests as its weight says." : "By weight: it's {who}'s share — each key takes requests as its weight says.", { who: w });
case "free":
@@ -5056,7 +5058,7 @@ function routingPage(part) {
// after the requests: a request picked in the list plays on the stage,
// so the list sits right under it
more.append(gsec);
const ROUTE_OPTS = [["", "Smart"], ["order", "In order"], ["rotate", "In turn"], ["usage", "Least used"], ["pace", "Weekly pace"], ["free", "Free first"], ["fast", "Speed first"]];
const ROUTE_OPTS = [["", "Smart"], ["order", "In order"], ["drain", "Until used up"], ["rotate", "In turn"], ["usage", "Least used"], ["pace", "Weekly pace"], ["free", "Free first"], ["fast", "Speed first"]];
// 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
// and by its members' weights, as a provider's keys are (#1910)
@@ -5097,6 +5099,7 @@ function routingPage(part) {
const GROUP_HINT = {
"": "Smart, over the members' accounts and keys together: of the subscriptions with quota to spare, the one whose allowance renews soonest goes first — the week decides, and an account with five hours and no week (Claude Enterprise) goes by its five hours, so ahead of every week renewing later; one resting after a failure goes last.",
order: "In order: the first model until it can't answer, then the next — each over its own accounts or keys as its provider routes them.",
drain: "Until used up: one account or key, across the members, takes every request until it is used up; then the next in the list, which keeps them even after an earlier one renews. One rate limited or failing is passed over only while it rests.",
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.",
@@ -434,6 +434,9 @@ magpie.strings({
"Every one is resting after a failure, so {who}, first in line, is tried all the same.": "所有账号都在失败后休息,仍先试排第一的 {who}。",
"{name} is resting, so its fallback {fb} goes first.": "{name} 正在休息,其备用 {fb} 排第一。",
"In order: {who} is first, and answers everything while it can.": "按顺序:{who} 排第一,能响应就由它处理。",
"Until used up: one answers everything until its quota is used up; then the next, which keeps them even after the one before renews.": "用完再换:一个处理所有请求,直到额度用完;再换下一个,前一个恢复后也继续用这个。",
"Until used up: one account or key, across the members, takes every request until it is used up; then the next in the list, which keeps them even after an earlier one renews. One rate limited or failing is passed over only while it rests.": "用完再换:所有成员的账号或密钥中,一个处理所有请求,直到它用完;再换列表里的下一个,前面的恢复后也继续用这个。被限流或出错的只在休息期间跳过。",
"Until used up: {who} is the one in use, and answers everything until it is used up.": "用完再换:当前用的是 {who},用完之前由它处理所有请求。",
"In turn: it's {who}'s turn — each request starts one further along.": "轮流:本次轮到 {who},每个请求从下一个开始。",
"Least used first: {who} has the most of its allowance left — {n} used.": "最少使用优先:{who} 剩余额度最多,已用 {n}。",
"Least used first: {who} served the fewest tokens lately — {n}.": "最少使用优先:{who} 最近处理的 token 最少({n})。",
@@ -1071,6 +1074,9 @@ magpie.strings({
"Every one is resting after a failure, so {who}, first in line, is tried all the same.": "所有帳號都在失敗後休息,仍先試排第一的 {who}。",
"{name} is resting, so its fallback {fb} goes first.": "{name} 正在休息,其備用 {fb} 排第一。",
"In order: {who} is first, and answers everything while it can.": "按順序:{who} 排第一,能回應就由它處理。",
"Until used up: one answers everything until its quota is used up; then the next, which keeps them even after the one before renews.": "用完再換:一個處理所有請求,直到額度用完;再換下一個,前一個恢復後也繼續用這個。",
"Until used up: one account or key, across the members, takes every request until it is used up; then the next in the list, which keeps them even after an earlier one renews. One rate limited or failing is passed over only while it rests.": "用完再換:所有成員的帳號或金鑰中,一個處理所有請求,直到它用完;再換列表裡的下一個,前面的恢復後也繼續用這個。被限流或出錯的只在休息期間跳過。",
"Until used up: {who} is the one in use, and answers everything until it is used up.": "用完再換:目前用的是 {who},用完之前由它處理所有請求。",
"In turn: it's {who}'s turn — each request starts one further along.": "輪流:本次輪到 {who},每個請求從下一個開始。",
"Least used first: {who} has the most of its allowance left — {n} used.": "最少使用優先:{who} 剩餘額度最多,已用 {n}。",
"Least used first: {who} served the fewest tokens lately — {n}.": "最少使用優先:{who} 最近處理的 token 最少({n})。",
@@ -1706,6 +1712,9 @@ magpie.strings({
"Every one is resting after a failure, so {who}, first in line, is tried all the same.": "すべて失敗後の休止中のため、先頭の {who} をそのまま試します。",
"{name} is resting, so its fallback {fb} goes first.": "{name} は休止中のため、フォールバックの {fb} が先です。",
"In order: {who} is first, and answers everything while it can.": "順番:{who} が先頭で、応答できる限りすべてに応答します。",
"Until used up: one answers everything until its quota is used up; then the next, which keeps them even after the one before renews.": "使い切ってから次へ:1 つがクォータを使い切るまですべてに応答し、その後は次へ。前のものが回復しても次のものが続けます。",
"Until used up: one account or key, across the members, takes every request until it is used up; then the next in the list, which keeps them even after an earlier one renews. One rate limited or failing is passed over only while it rests.": "使い切ってから次へ:メンバー全体のアカウントやキーのうち 1 つが、使い切るまですべてのリクエストを受けます。その後はリストの次へ移り、前のものが回復してもそのまま続けます。レート制限やエラーのものは休止中だけ飛ばします。",
"Until used up: {who} is the one in use, and answers everything until it is used up.": "使い切ってから次へ:今使っているのは {who} で、使い切るまですべてに応答します。",
"In turn: it's {who}'s turn — each request starts one further along.": "交互:{who} の番です — 各リクエストは 1 つ先から始まります。",
"Least used first: {who} has the most of its allowance left — {n} used.": "使用量が最少:{who} は利用枠の残りが最も多いです — 使用済み {n}。",
"Least used first: {who} served the fewest tokens lately — {n}.": "使用量が最少:{who} は最近処理したトークンが最も少ないです — {n}。",
@@ -2343,6 +2352,9 @@ magpie.strings({
"Every one is resting after a failure, so {who}, first in line, is tried all the same.": "Alle pausieren nach einem Fehler, daher wird {who} als Erstes in der Reihe trotzdem versucht.",
"{name} is resting, so its fallback {fb} goes first.": "{name} pausiert, daher kommt sein Ausweich {fb} zuerst.",
"In order: {who} is first, and answers everything while it can.": "Der Reihe nach: {who} ist zuerst dran und beantwortet alles, solange es kann.",
"Until used up: one answers everything until its quota is used up; then the next, which keeps them even after the one before renews.": "Bis aufgebraucht: Eines beantwortet alles, bis sein Kontingent aufgebraucht ist; dann das nächste, das sie behält, auch wenn sich das vorherige erneuert.",
"Until used up: one account or key, across the members, takes every request until it is used up; then the next in the list, which keeps them even after an earlier one renews. One rate limited or failing is passed over only while it rests.": "Bis aufgebraucht: Ein Konto oder Schlüssel über alle Mitglieder nimmt jede Anfrage, bis es aufgebraucht ist; dann das nächste in der Liste, das sie behält, auch wenn sich ein früheres erneuert. Eines, das rate-limitiert ist oder fehlschlägt, wird nur übergangen, solange es ruht.",
"Until used up: {who} is the one in use, and answers everything until it is used up.": "Bis aufgebraucht: {who} ist das aktuelle und beantwortet alles, bis es aufgebraucht ist.",
"In turn: it's {who}'s turn — each request starts one further along.": "Abwechselnd: {who} ist an der Reihe – jede Anfrage beginnt eines weiter.",
"Least used first: {who} has the most of its allowance left — {n} used.": "Am wenigsten genutzt zuerst: {who} hat das größte Restkontingent – {n} verbraucht.",
"Least used first: {who} served the fewest tokens lately — {n}.": "Am wenigsten genutzt zuerst: {who} hat zuletzt die wenigsten Token verarbeitet – {n}.",
+1 -1
View File
@@ -26,7 +26,7 @@ const PLUGINS = [
{ id: "middleware", name: "JS gateway plugins", sub: "Run the JavaScript gateway plugins: middleware on agents' requests and replies, routings and usage observers", one: "1 gateway plugin on", many: "{n} gateway plugins on" },
{ id: "otel", name: "Observability", sub: "Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse", one: "Sending to a collector", many: "Sending to a collector" },
{ id: "redact", name: "Privacy masking", sub: "Secrets, personal data and your own words go to vendors as placeholders, and come back as they were", one: "Masking is on", many: "Masking is on" },
{ id: "rotation", name: "Routing strategies", sub: "The routings besides Smart: In order, In turn, Least used first, Weekly pace, By weight, Free first, Speed first and Cheapest first", one: "1 provider or group routed so", many: "{n} providers and groups routed so" },
{ id: "rotation", name: "Routing strategies", sub: "The routings besides Smart: In order, Until used up, In turn, Least used first, Weekly pace, By weight, Free first, Speed first and Cheapest first", one: "1 provider or group routed so", many: "{n} providers and groups routed so" },
{ id: "routing", name: "Routing", sub: "Each request as the gateway routes it, the accounts it weighed and what each answered, and your routing groups", one: "1 group in use", many: "{n} groups in use" },
{ id: "search", name: "Web search", sub: "Models that can't search the web search with a provider that can, or a search API", one: "1 search source set up", many: "{n} search sources set up" },
{ id: "sessions", name: "Sessions", sub: "Your agents' past conversations: read, search, resume and export them", one: "Recording gateway conversations", many: "Recording gateway conversations" },
+84
View File
@@ -0,0 +1,84 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Until used up (routes.Drain, dzxx0496 on Discord): on the Routing page a
// request routed so says the one in use answers everything until it is
// used up, and the mode line says the next keeps the requests once the one
// before renews. The option is named in every language, in both engines,
// at the window's width and a phone's.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const now = new Date();
const ago = (minutes) => new Date(now.getTime() - minutes * 60e3).toISOString();
const acct = (who, more) => ({ id: "wb#" + who, provider: "wb", name: "WorkBuddy", who, kind: "account", model: "glm-5", routing: "drain", known: true, used: 30, ...more });
function serve(lang) {
// the second account is in use: the first renewed after it was used up
const order = [acct("two@example.test"), acct("three@example.test", { used: 5 }), acct("one@example.test", { used: 0 })];
const route = {
id: 1, seq: 1, time: ago(1), agent: "codex", model: "glm-5", provider: "wb", done: true, status: 200, ms: 900, tokens: 1200, order,
tries: [{ id: order[0].id, model: "glm-5", start: ago(1), done: true, status: 200, ms: 900 }],
};
return async (request) => {
const url = new URL(request.request().url());
const json = (data) => request.fulfill({ json: data });
if (url.pathname === "/boot.js") return request.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return request.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes
return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 1 }, routes: [route] });
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], excluded: [], gateway: { running: true, window: true } });
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 request.fulfill({ body: await fs.readFile(file), contentType });
};
}
async function open(t, engine, lang, width) {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await browser.newPage({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (error) => errors.push(error.message));
await page.route("**/*", serve(lang));
await page.goto("http://magpie.test/?view=routing");
const req = page.locator(".rt-req").first();
await req.waitFor();
if (await req.getAttribute("aria-pressed") !== "true") await req.click();
await page.locator(".rt-steps li.why").first().waitFor();
const say = (key, vars = {}) => page.evaluate(([lang, key, vars]) => {
const s = (lang !== "en" && I18N[lang]?.[key]) || key;
return s.replace(/\{(\w+)\}/g, (_, k) => vars[k] ?? `{${k}}`);
}, [lang, key, vars]);
return { page, errors, say };
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
for (const width of [1100, 420]) {
test(`${engine} ${lang} ${width}: Until used up says the one in use keeps the requests`, async (t) => {
const { page, errors, say } = await open(t, engine, lang, width);
const why = (await page.locator(".rt-steps li.why").first().textContent()).trim();
assert.equal(why, await say("Until used up: {who} is the one in use, and answers everything until it is used up.", { who: "two@example.test" }));
assert.equal((await page.locator(".rt-mode").textContent()).trim(),
await say("Until used up: one answers everything until its quota is used up; then the next, which keeps them even after the one before renews."));
if (lang !== "en") {
for (const k of ["Until used up", "Requests stay on one until it is used up, then go to the next in the list and stay there: one before it that renews meanwhile doesn't take them back. One rate limited or failing is passed over while it rests, and requests come back to it after."])
assert.notEqual(await say(k), k, `${lang} says ${k}`);
}
assert.ok(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth + 1), "fits");
assert.deepEqual(errors, []);
});
}
}
}
@@ -26,7 +26,7 @@ const base = { members: ["a/sol", "b/flash", "c/luna"], ready: true, memberInfo:
const words = {
en: { order: "In order", manual: "Manual", weight: "By weight", smart: "Smart", head: "Routing", edit: "Edit",
names: ["Smart", "In order", "In turn", "Least used", "Weekly pace", "Free first", "Speed first", "Cheapest first", "By weight", "Manual"],
names: ["Smart", "In order", "Until used up", "In turn", "Least used", "Weekly pace", "Free first", "Speed first", "Cheapest first", "By weight", "Manual"],
tip: "How Auto routes: click to change it", saved: "Auto: Manual" },
zh: { order: "按顺序", manual: "手动", weight: "按权重", smart: "智能", head: "路由", edit: "编辑",
tip: "Auto 的路由方式:点击更改", saved: "Auto:手动" },
@@ -140,7 +140,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(await menu.locator(".pm-head").textContent(), w.head);
const items = menu.locator(".pm-item");
if (w.names) assert.deepEqual(await items.locator(".pm-name").allTextContents(), w.names);
assert.equal(await items.count(), 10);
assert.equal(await items.count(), 11);
assert.deepEqual(await menu.locator('.pm-item[aria-checked="true"] .pm-name').allTextContents(), [w.order]);
assert.equal(await page.locator(".rt-gedit").count(), 0, "opening the menu opens no editor");
// the menu sits inside the window
@@ -229,7 +229,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(await btn.getAttribute("title"), words[lang].tip);
await btn.click();
await page.locator(".proto-menu").waitFor();
assert.equal(await page.locator(".proto-menu .pm-item").count(), 10);
assert.equal(await page.locator(".proto-menu .pm-item").count(), 11);
assert.deepEqual(errors, []);
});
}
+2 -2
View File
@@ -55,7 +55,7 @@ function serve(lang, posts, off = []) {
}
const ROUTINGS = [
["", "Smart", "智能"], ["order", "In order", "按顺序"], ["rotate", "In turn", "轮流"],
["", "Smart", "智能"], ["order", "In order", "按顺序"], ["drain", "Until used up", "用完再换"], ["rotate", "In turn", "轮流"],
["usage", "Least used first", "用量少的优先"], ["pace", "Weekly pace", "重置前用完"],
];
const STAYS = [["", "Auto", "自动"], ["session", "Session", "整个会话"], ["turn", "Within a turn", "一轮之内"], ["off", "Off", "关闭"]];
@@ -160,7 +160,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await page.evaluate(() => applyFeatures([{ id: "rotation", on: true }]));
const back = await field.locator(".segs").first().evaluate((box) => [...box.querySelectorAll(".opt")].filter((b) => getComputedStyle(b).display !== "none").length);
// By weight is offered for accounts as for keys (rubbzha on X)
assert.equal(back, 8, `${where}: every routing back`);
assert.equal(back, 9, `${where}: every routing back`);
assert.deepEqual(errors, [], where);
await page.context().close();
}
+2 -2
View File
@@ -118,9 +118,9 @@ const SpentShare = 98
// SpentShareOf is the share past which routing counts an account spent:
// SpentShare, but In order sends requests to the first until a window of it
// is used up or the vendor refuses it, so there an account at 98% is still
// tried in its turn (#530).
// tried in its turn (#530); Until used up stays on one until then too.
func SpentShareOf(routing string) float64 {
if routing == Ordered {
if routing == Ordered || routing == Drain {
return 100
}
return SpentShare
+1 -1
View File
@@ -1459,7 +1459,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 != Weighted && g.Routing != FreeFirst && g.Routing != Fastest && g.Routing != Cheapest && g.Routing != Manual && !PluginRouting(g.Routing) {
if g.Routing != Ordered && g.Routing != Rotate && g.Routing != LeastUsed && g.Routing != Pace && g.Routing != Weighted && g.Routing != FreeFirst && g.Routing != Fastest && g.Routing != Cheapest && g.Routing != Drain && g.Routing != Manual && !PluginRouting(g.Routing) {
g.Routing = ""
}
if !slices.Contains(Affinities, g.Affinity) {
+5 -3
View File
@@ -120,8 +120,10 @@ type Provider struct {
// its window resets first, so less allowance is lost at reset.
// The window can be shorter than a week. "weight" by each key's
// weight, a key with 3 taking three requests to one with 1's.
// Whichever it is, one out of credit, out of quota, rate limited or
// failing is passed over for as long as that lasts.
// "drain" one until it is used up, then the next, which keeps them
// when an earlier one renews (routes.Drain). Whichever it is, one out
// of credit, out of quota, rate limited or failing is passed over for
// as long as that lasts.
Routing string `json:"routing,omitempty"`
// Sink sends a key or account that a 429 rate limited while it still
@@ -1522,7 +1524,7 @@ func normalize(p Provider) Provider {
if (p.Preset == OMLXPreset || p.Preset == MLXServePreset || p.Preset == "ollama" || p.Preset == "ollama-cloud") && p.Decide == "" && p.Chat != "" {
p.Decide = p.Chat
}
if p.Routing != Ordered && p.Routing != Rotate && p.Routing != LeastUsed && p.Routing != Pace && p.Routing != Weighted && p.Routing != FreeFirst && p.Routing != Fastest && !PluginRouting(p.Routing) {
if p.Routing != Ordered && p.Routing != Rotate && p.Routing != LeastUsed && p.Routing != Pace && p.Routing != Weighted && p.Routing != FreeFirst && p.Routing != Fastest && p.Routing != Drain && !PluginRouting(p.Routing) {
p.Routing = ""
}
if !slices.Contains(Affinities, p.Affinity) {
+5
View File
@@ -44,6 +44,11 @@ const (
// (routes.Cheapest). A group's only: a provider's keys and accounts
// all bill its one price.
Cheapest = "cheap"
// Drain stays on one key or account until it is used up, then goes
// on to the next in the listed order, and stays on that one: one
// before it that renews meanwhile doesn't take its requests back
// (dzxx0496 on Discord; routes.Drain).
Drain = "drain"
)
// pluginRouting is a routing a plugin serves: "<plugin>/<name>".
+139
View File
@@ -0,0 +1,139 @@
package routes
import (
"slices"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// dzxx0496 on Discord: free accounts one after another, each until its
// quota is used up, and the first not taking the requests back when its
// quota renews. Drain stays on the one it went on to; In order and Smart
// go back to the first.
func TestDrainStaysOnTheNextWhenTheFirstRenews(t *testing.T) {
Forget()
t.Cleanup(func() { Forget() })
const pool = "workbuddy"
order := func(seats ...Seat) []int { return Apply(Drain, pool, seats) }
a, b, c := Seat{Key: "a", Known: true}, Seat{Key: "b", Known: true}, Seat{Key: "c", Known: true}
if got := order(a, b, c); !slices.Equal(got, []int{0, 1, 2}) {
t.Fatalf("fresh: %v, want the first first", got)
}
// a used up: b, then c, then a for failover
spentA := a
spentA.Used = 100
if got := order(spentA, b, c); !slices.Equal(got, []int{1, 2, 0}) {
t.Fatalf("a used up: %v, want b first", got)
}
// a renews: the pool stays on b
if got := order(a, b, c); !slices.Equal(got, []int{1, 2, 0}) {
t.Fatalf("a renewed: %v, want b still first", got)
}
// asked again with nothing changed (a preview): the same
if got := order(a, b, c); !slices.Equal(got, []int{1, 2, 0}) {
t.Fatalf("asked again: %v", got)
}
// b refused for its quota (resting, Spent): on to c, and it stays there
// once b's rest is over
spentB := b
spentB.Resting, spentB.Spent = true, true
if got := order(a, spentB, c); !slices.Equal(got, []int{2, 0, 1}) {
t.Fatalf("b out of quota: %v, want c first", got)
}
if got := order(a, b, c); !slices.Equal(got, []int{2, 0, 1}) {
t.Fatalf("b back: %v, want c still first", got)
}
// c used up: round to a, which renewed
spentC := c
spentC.Used = 100
if got := order(a, b, spentC); !slices.Equal(got, []int{0, 1, 2}) {
t.Fatalf("c used up: %v, want a first again", got)
}
// what the other routings do with the same: back to the first
if got := Apply(Ordered, pool, []Seat{a, b, c}); got[0] != 0 {
t.Fatalf("In order: %v", got)
}
}
// A rate limit or a failure rests a seat without using it up: the gateway
// tries the others meanwhile (restLast), and Drain stays on it.
func TestDrainStaysThroughARateLimit(t *testing.T) {
Forget()
t.Cleanup(func() { Forget() })
const pool = "group/free"
a, b := Seat{Key: "a", Known: true}, Seat{Key: "b", Known: true}
limited := a
limited.Resting = true
if got := Apply(Drain, pool, []Seat{limited, b}); !slices.Equal(got, []int{0, 1}) {
t.Fatalf("a rate limited: %v, want it kept first", got)
}
// 98% is not used up: In order's line (#530); a key's Used, not an
// allowance, never counts
key := Seat{Key: "a", Used: 100}
if got := Apply(Drain, pool, []Seat{key, b}); !slices.Equal(got, []int{0, 1}) {
t.Fatalf("a key: %v, want it kept first", got)
}
low := a
low.Used = provider.SpentShare
if got := Apply(Drain, pool, []Seat{low, b}); !slices.Equal(got, []int{0, 1}) {
t.Fatalf("a at %v%%: %v, want it kept first", provider.SpentShare, got)
}
}
// Every seat used up: it stays where it is. The seat it was on gone from
// the pool: the first not used up.
func TestDrainAllSpentAndGone(t *testing.T) {
Forget()
t.Cleanup(func() { Forget() })
const pool = "p"
a, b, c := Seat{Key: "a", Known: true}, Seat{Key: "b", Known: true}, Seat{Key: "c", Known: true}
spent := func(s Seat) Seat { s.Used = 100; return s }
Apply(Drain, pool, []Seat{spent(a), b, c}) // on b
if got := Apply(Drain, pool, []Seat{spent(a), spent(b), spent(c)}); !slices.Equal(got, []int{1, 2, 0}) {
t.Fatalf("all used up: %v, want it kept on b", got)
}
// b turned off: the first not used up, c
if got := Apply(Drain, pool, []Seat{spent(a), c}); !slices.Equal(got, []int{1, 0}) {
t.Fatalf("b gone: %v, want c first", got)
}
// another pool goes its own way
if got := Apply(Drain, "other", []Seat{a, b}); !slices.Equal(got, []int{0, 1}) {
t.Fatalf("another pool: %v", got)
}
// Forget starts the pool anew
Forget(pool)
if got := Apply(Drain, pool, []Seat{a, b, c}); !slices.Equal(got, []int{0, 1, 2}) {
t.Fatalf("forgotten: %v", got)
}
}
func TestDrainIsBuiltin(t *testing.T) {
s, ok := Builtin[provider.Drain]
if !ok || !s.Exact {
t.Fatalf("Builtin[%q] = %+v, %v; want an exact strategy", provider.Drain, s, ok)
}
}
// Refused for its quota (Drained) and renewed before the pool's next
// request: the pool goes on from it all the same. Another pool on another
// seat is left where it is.
func TestDrainedGoesOnThoughItRenewed(t *testing.T) {
Forget()
t.Cleanup(func() { Forget() })
a, b, c := Seat{Key: "a"}, Seat{Key: "b"}, Seat{Key: "c"}
Apply(Drain, "p", []Seat{a, b, c})
Apply(Drain, "q", []Seat{b, c})
Drained("a")
if got := Apply(Drain, "p", []Seat{a, b, c}); !slices.Equal(got, []int{1, 2, 0}) {
t.Fatalf("a refused, then renewed: %v, want b first", got)
}
if got := Apply(Drain, "p", []Seat{a, b, c}); !slices.Equal(got, []int{1, 2, 0}) {
t.Fatalf("asked again: %v, want b still first", got)
}
if got := Apply(Drain, "q", []Seat{b, c}); !slices.Equal(got, []int{0, 1}) {
t.Fatalf("another pool: %v, want it left on b", got)
}
}
+5 -2
View File
@@ -79,21 +79,24 @@ func MoveRound(pool, picked, kept string) {
r.last = kept
}
// Forget drops what pool's round and turn hold, every pool's with none
// Forget drops what pool's round, turn and drain hold, every pool's with none
// named: a test starts each anew.
func Forget(pools ...string) {
rounds.Lock()
turns.Lock()
probes.Lock()
drains.Lock()
defer rounds.Unlock()
defer drains.Unlock()
defer turns.Unlock()
defer probes.Unlock()
if len(pools) == 0 {
rounds.m, turns.m, probes.m = map[string]*round{}, map[string]int{}, map[string]probe{}
rounds.m, turns.m, probes.m, drains.m = map[string]*round{}, map[string]int{}, map[string]probe{}, map[string]drainAt{}
}
for _, p := range pools {
delete(rounds.m, p)
delete(turns.m, p)
delete(probes.m, p)
delete(drains.m, p)
}
}
+5 -1
View File
@@ -5,7 +5,8 @@
// failover itself; a Strategy only says the order.
//
// Smart, the default, is the core's. The others a provider or group can be
// routed by (order, rotate, usage, pace, weight, free, fast) are here for a plugin to
// routed by (order, rotate, usage, pace, weight, free, fast, cheap,
// drain) are here for a plugin to
// register: plugins/rotation does, and off, a pool routed by one of them is
// tried in its listed order, as an unknown routing always was.
package routes
@@ -44,6 +45,9 @@ type Seat struct {
Weight int
// Resting: it rests after a failure now
Resting bool
// Spent: it rests because it is out of quota or credit, not for a
// rate limit or a failure. Drain goes on from it.
Spent bool
// Tokens is what magpie sent it lately, decayed by an hour's half-life
Tokens float64
// Free: the model this seat would be asked for costs nothing on it —
+63
View File
@@ -2,6 +2,7 @@ package routes
import (
"cmp"
"slices"
"sort"
"sync"
"time"
@@ -181,6 +182,67 @@ func spentBefore(a, b Seat) bool {
// Ordered tries a pool in its order: the first until it can't answer.
var Ordered = Strategy{Exact: true, Order: func(_ string, seats []Seat) []int { return identity(len(seats)) }}
var drains = struct {
sync.Mutex
m map[string]drainAt // pool → the seat it is on
}{m: map[string]drainAt{}}
// drainAt is the seat a pool routed Until used up is on: its Key, and past
// once it was refused for its quota or credit (Drained), so the pool goes
// on from it even if it renews before the pool's next request.
type drainAt struct {
key string
past bool
}
// Drained says key was refused for its quota or its credit: every pool
// routed Until used up that is on it goes on to the next at its next
// request, though key renews before then. The gateway's failover has
// already tried the next for the request refused; without this, a pool
// asked again only after key renewed went back to it.
func Drained(key string) {
drains.Lock()
defer drains.Unlock()
for pool, at := range drains.m {
if at.key == key {
drains.m[pool] = drainAt{key, true}
}
}
}
// Drain stays on one seat until it is used up, then goes on to the next
// in the listed order, and stays on that one (dzxx0496 on Discord: free
// accounts one after another, the first not taking the requests back when
// its quota renews). The one it is on goes first, the others after it in
// their listed order from there, so failover goes on as Ordered's does.
// Used up is a window of it used up (provider.SpentShareOf: 100, as In
// order goes on at, #530), resting out of quota or credit (Seat.Spent),
// or refused so since the pool's last request (Drained); a rate limit or
// a failure only rests a seat, which the gateway tries last meanwhile,
// and the pool stays on it. With every seat used up it stays where it
// is. A seat it is on that leaves the pool (turned off, removed) leaves
// it on the first not used up, in the listed order. Asking again with
// nothing changed gives the same order, so a preview moves nothing.
var Drain = Strategy{Exact: true, Order: func(pool string, seats []Seat) []int {
spent := func(s Seat) bool { return s.Spent || s.Known && s.Used >= provider.SpentShareOf(provider.Drain) }
drains.Lock()
defer drains.Unlock()
on := drains.m[pool]
at := slices.IndexFunc(seats, func(s Seat) bool { return s.Key != "" && s.Key == on.key })
if at < 0 {
at = max(0, slices.IndexFunc(seats, func(s Seat) bool { return !spent(s) }))
} else if on.past || spent(seats[at]) {
for k := 1; k < len(seats); k++ {
if i := (at + k) % len(seats); !spent(seats[i]) {
at = i
break
}
}
}
drains.m[pool] = drainAt{key: seats[at].Key}
return append(identity(len(seats))[at:], identity(at)...)
}}
var turns = struct {
sync.Mutex
m map[string]int // pool → requests routed in turn
@@ -398,4 +460,5 @@ var Builtin = map[string]Strategy{
provider.FreeFirst: FreeFirst,
provider.Fastest: Fastest,
provider.Cheapest: Cheapest,
provider.Drain: Drain,
}
+3 -1
View File
@@ -68,7 +68,7 @@ func (m model) listedMembers(g provider.Group) ([]string, int) {
return on, len(g.Members) - len(on)
}
var routings = []string{"", provider.Ordered, provider.Rotate, provider.LeastUsed, provider.Pace, provider.Weighted, provider.FreeFirst, provider.Fastest, provider.Cheapest, provider.Manual}
var routings = []string{"", provider.Ordered, provider.Rotate, provider.LeastUsed, provider.Pace, provider.Weighted, provider.FreeFirst, provider.Fastest, provider.Cheapest, provider.Drain, provider.Manual}
func routingName(v string) string {
switch v {
@@ -88,6 +88,8 @@ func routingName(v string) string {
return "speed first"
case provider.Cheapest:
return "cheapest first"
case provider.Drain:
return "until used up"
case provider.Manual:
return "manual"
}
+4 -3
View File
@@ -1,6 +1,7 @@
// Package rotation is the routings a provider or group can be set to
// besides Smart: In order, In turn, Least used first, Weekly pace, By
// weight, Free first, Speed first and Cheapest first (a group's). While a provider or group is routed by one, it
// besides Smart: In order, Until used up, In turn, Least used first,
// Weekly pace, By weight, Free first, Speed first and Cheapest first (a
// group's). While a provider or group is routed by one, it
// stays on.
//
// It is the first consumer of the gateway's router strategy point (P3 of
@@ -18,7 +19,7 @@ import (
func init() {
pluginrt.Register(pluginrt.Manifest{
ID: "rotation", API: "^1", Requires: []string{"providers", "gateway"}, Essential: true,
Name: "Routing strategies", Sub: "The routings besides Smart: In order, In turn, Least used first, Weekly pace, By weight, Free first, Speed first and Cheapest first",
Name: "Routing strategies", Sub: "The routings besides Smart: In order, Until used up, In turn, Least used first, Weekly pace, By weight, Free first, Speed first and Cheapest first",
One: "1 provider or group routed so", Many: "{n} providers and groups routed so",
InUse: inUse,
Parts: []pluginrt.Part{{Slot: "part", Key: "rotation"}},
+2 -1
View File
@@ -167,7 +167,7 @@
</figure>
<h3>1 つのプロバイダに複数のアカウントやキー</h3>
<p>プロバイダの行を開き、使うアカウントやキーをすべてチェックします。<span class="ui">Routing</span> はリクエストをそれらにどう振り分けるかを決めます:<span class="ui">Smart</span>(デフォルト)、<span class="ui">In order</span>、<span class="ui">In turn</span>、<span class="ui">Least used first</span>、<span class="ui">Weekly pace</span>、<span class="ui">By weight</span>(各アカウントやキーが横で設定した重みで取り分を受けます。たとえば Max アカウントは 5、Pro は 1)、<span class="ui">Speed first</span>(最近いちばん速く応答したキーが先)。<span class="ui">Fallback</span> には、プロバイダのクォータ切れ、レート制限、ダウン時に代わりに使うモデルを並べます。</p>
<p>プロバイダの行を開き、使うアカウントやキーをすべてチェックします。<span class="ui">Routing</span> はリクエストをそれらにどう振り分けるかを決めます:<span class="ui">Smart</span>(デフォルト)、<span class="ui">In order</span>、<span class="ui">Until used up</span>(使い切ったら次へ移り、前のものが回復しても戻りません)、<span class="ui">In turn</span>、<span class="ui">Least used first</span>、<span class="ui">Weekly pace</span>、<span class="ui">By weight</span>(各アカウントやキーが横で設定した重みで取り分を受けます。たとえば Max アカウントは 5、Pro は 1)、<span class="ui">Speed first</span>(最近いちばん速く応答したキーが先)。<span class="ui">Fallback</span> には、プロバイダのクォータ切れ、レート制限、ダウン時に代わりに使うモデルを並べます。</p>
<h3>1 つのモデルを複数のプロバイダで</h3>
<p>グループとは、1 つまたは複数のプロバイダのモデルを、エージェントが 1 つとして選べるようにまとめたものです。ピッカーの <em>Routing groups</em> の下に <code>group/&lt;id&gt;</code> として表示されます。2 つのプロバイダが同じ名前で提供しているモデルは、それだけでグループになります。<span class="ui">Routing</span> タブの <span class="ui">New group</span> では、好きなモデルを組み合わせてグループを作れます。グループで何ができるかは、最初のモデルが基準になります。</p>
@@ -177,6 +177,7 @@
<tr><th>ルーティング</th><th>先に使われるもの</th></tr>
<tr><td>スマート <code>smart</code></td><td>デフォルトです。メンバーのアカウントとキーをまとめて扱い(グループ内のグループは 1 つとして扱います。下記参照)、クォータに余裕のあるサブスクリプションのうち、利用枠が最も早く更新されるもの。基準は週の枠です。週の枠がなく 5 時間枠だけのアカウント(Claude Enterprise)は 5 時間枠で判断されるため、それより後に週の枠が更新されるものすべてより先になります。リセットのないクレジット(WorkBuddy のパッケージはそれぞれの日に失効します)は、残りのうち最も早く失効する時点で判断されるため、クレジットが最も早く失効する WorkBuddy アカウントが先になります。同時に更新されるアカウント(無料アカウントはすべて月末)は、その後に残りのクレジットが先に失効するものが先になります。失敗後に休止中のものは最後に回ります。</td></tr>
<tr><td>順番どおり <code>order</code></td><td>最初のモデルが応答できなくなるまでそれを使い、次へ進みます。</td></tr>
<tr><td>使い切ってから次へ <code>drain</code></td><td>1 つのアカウントやキーを使い切るまで使い、その後は次へ移ってそのまま使い続けます。その間に前のものが回復しても戻りません。レート制限やエラーのものは休止中だけ飛ばします。</td></tr>
<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>
+2 -1
View File
@@ -167,7 +167,7 @@
</figure>
<h3>Several accounts or keys in one provider</h3>
<p>Open the provider’s row and tick every account or key to use. <span class="ui">Routing</span> says how requests spread over them: <span class="ui">Smart</span> (the default), <span class="ui">In order</span>, <span class="ui">In turn</span>, <span class="ui">Least used first</span>, <span class="ui">Weekly pace</span>, <span class="ui">By weight</span>, each account or key taking its share by the weight set beside it (a Max account 5, a Pro one 1), or <span class="ui">Speed first</span>, the key that answered fastest lately first. <span class="ui">Fallback</span> lists models to use instead when the provider is out of quota, rate limited or down.</p>
<p>Open the provider’s row and tick every account or key to use. <span class="ui">Routing</span> says how requests spread over them: <span class="ui">Smart</span> (the default), <span class="ui">In order</span>, <span class="ui">Until used up</span>, staying on the next once one is used up even after the first renews, <span class="ui">In turn</span>, <span class="ui">Least used first</span>, <span class="ui">Weekly pace</span>, <span class="ui">By weight</span>, each account or key taking its share by the weight set beside it (a Max account 5, a Pro one 1), or <span class="ui">Speed first</span>, the key that answered fastest lately first. <span class="ui">Fallback</span> lists models to use instead when the provider is out of quota, rate limited or down.</p>
<h3>One model over several providers</h3>
<p>A group is several models, from one provider or many, that an agent picks as one: <code>group/&lt;id&gt;</code>, under <em>Routing groups</em> in the picker. A model two of your providers serve under the same name becomes a group on its own; <span class="ui">New group</span> in the <span class="ui">Routing</span> tab makes one of any models you like. The first model answers for what the group can do.</p>
@@ -177,6 +177,7 @@
<tr><th>Routing</th><th>What goes first</th></tr>
<tr><td>Smart <code>smart</code></td><td>The default. Over the members’ accounts and keys together (a group in the group as one, see below): of the subscriptions with quota to spare, the one whose allowance renews soonest. The week decides; an account with five hours and no week (Claude Enterprise) goes by its five hours, so ahead of every week renewing later. Credits with no reset (WorkBuddy’s packages, each ending on its own day) count as renewing when the soonest of those left run out, so the WorkBuddy account whose credits end first goes first; accounts renewing together (free ones at the month’s end) go by whose credits left end first after that. One resting after a failure goes last.</td></tr>
<tr><td>In order <code>order</code></td><td>The first model until it can’t answer, then the next.</td></tr>
<tr><td>Until used up <code>drain</code></td><td>One account or key until it is used up, then the next, which keeps the requests: one before it that renews meanwhile doesn’t take them back. One rate limited or failing is passed over only while it rests.</td></tr>
<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>
+2 -1
View File
@@ -167,7 +167,7 @@
</figure>
<h3>一个供应商里的多个账号或密钥</h3>
<p>展开供应商那一行,勾选要用的每个账号或密钥。<span class="ui">路由</span> 决定请求怎么分给它们:<span class="ui">智能</span>(默认)、<span class="ui">按顺序</span>、<span class="ui">轮流</span>、<span class="ui">用量少的优先</span>、<span class="ui">重置前用完</span>、<span class="ui">按权重</span>(每个账号或密钥按旁边设的权重分得请求,比如 Max 账号设 5、Pro 账号设 1)或 <span class="ui">速度优先</span>(最近回答最快的密钥先用)。<span class="ui">备用</span> 里列出这个供应商额度用完、被限流或不可用时改用的模型。</p>
<p>展开供应商那一行,勾选要用的每个账号或密钥。<span class="ui">路由</span> 决定请求怎么分给它们:<span class="ui">智能</span>(默认)、<span class="ui">按顺序</span>、<span class="ui">用完再换</span>(一个用完再换下一个,前面的恢复了也不切回去)、<span class="ui">轮流</span>、<span class="ui">用量少的优先</span>、<span class="ui">重置前用完</span>、<span class="ui">按权重</span>(每个账号或密钥按旁边设的权重分得请求,比如 Max 账号设 5、Pro 账号设 1)或 <span class="ui">速度优先</span>(最近回答最快的密钥先用)。<span class="ui">备用</span> 里列出这个供应商额度用完、被限流或不可用时改用的模型。</p>
<h3>跨供应商的同一个模型</h3>
<p>路由组是几个模型(来自一个或多个供应商),Agent 把它当作一个来选:<code>group/&lt;id&gt;</code>,在选择列表的 <em>路由组</em> 下面。两个供应商用同一个名字提供的模型会自动成组;在 <span class="ui">路由</span> 标签页点 <span class="ui">新建组</span> 可以把任意模型组到一起。排第一的模型决定这个组对外的能力。</p>
@@ -177,6 +177,7 @@
<tr><th>路由</th><th>谁排在前面</th></tr>
<tr><td>智能 <code>smart</code></td><td>默认。把成员的账号和 Key 放在一起排(组里的路由组算一个,见下文):还有余量的订阅里,额度最先重置的排第一。看周额度的重置时间;只有 5 小时额度、没有周额度的账号(如 Claude Enterprise)看它的 5 小时重置,所以排在所有更晚重置的周额度前面。没有重置时间的积分(WorkBuddy 的积分包,各自到期)按剩余积分最早过期的时间算,所以积分最先过期的 WorkBuddy 账号排第一;同时重置的账号(免费账号都在月底)再看剩余积分哪个先过期。失败后在休息的排最后。</td></tr>
<tr><td>按顺序 <code>order</code></td><td>先用第一个模型,它答不了再换下一个。</td></tr>
<tr><td>用完再换 <code>drain</code></td><td>一个账号或 Key 用到额度用完,再换下一个,并一直用它:前面的额度恢复了也不会切回去。被限流或出错的只在休息期间跳过。</td></tr>
<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>