diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 486aca59d..1a5175efd 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -34,7 +34,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | A found group's two ids | A group magpie found is listed (`/v1/models`, the catalog, the lists written into agents, the pickers, the CLI and TUI) as `auto/`: the model's id as a vendor spells it, dots kept and with no vendor prefix (`auto/claude-opus-5.5`; `provider.Group.Ref`, `spelledIn`), so a client that looks the part after the slash up on models.dev finds it (ZeroClover on X). The spelling is the one models.dev gives the model most (`catalog.Spelling`, its `normal` index: `glm-5.3-flash` whether the members serve `glm-5-3-flash`, Ark's dated id or `glm-5.3-flash`), so it no longer follows the order the providers were added in; for a model models.dev doesn't know, the first member's spelling it lists, else the first member's. The group's name comes from the same choice (`autoGroups`): the name models.dev gives that spelling (`catalog.NameOf`), else a vendor's own name for it, else the spelling itself; they were picked apart, a name of `glm-5-3-flash` beside `auto/glm-5.3-flash` (XYenon on Discord, `TestFoundGroupIDAndNameAreOneSpelling`). A found group the user changed keeps the name they saved. Every spelling it was listed by before is still the group (`CanonicalRef`), and `PublicRef` takes one to the spelling now. Its old id `group/auto-` is served forever. Inside magpie the group keeps that one id: `validateModel` takes `auto/` (with `:level` or `[1m]`) back to it with `provider.CanonicalRef` before key limits, routing, affinity and the usage log see the request, and the request body is rewritten to it, so both ids count as one group. A gateway key naming either id, `group/*` or `auto/*` passes for both (`allows` in `key_models.go`). `SaveGroup` stores a member, rule or classifier picked as `auto/` by the old id. An agent field magpie set to `group/auto-`, or to an `auto/` spelt otherwise than the group is listed now, moves to `auto/` on the next `SyncCatalog` (`agent.renameFoundGroups`, `TestFoundGroupMovedOffAnOldSpelling`), but only while its value is still what applied.json says magpie wrote; a value the user set or changed stays, and is still served. A pick of the group by its old id written now (`Agent.Apply`) is written as `auto/`. An agent's hidden, picked and ordered models saved by the old id hold for the new one (`PublicRef` in `visible.go`), and a bare model id still reaches its found group (`bareTarget`). Claude Code is given a dotted Claude version dashed, so it may send `auto/claude-sonnet-4-5`: that is the same group, and `Reseat` still moves an agent off it once the group is gone (`samePick`). `auto` is no provider id: `Save` and `Rename` refuse it for a new provider, and a plugin's `auto` is `auto-plugin` (`PluginID`). A provider of the user's saved as `auto` before keeps its models: while it exists, `auto/` is its model and found groups list as `group/auto-` (`autoRefsOn`). Hand-made groups stay `group/`. | [`internal/provider/autoref.go`](../../internal/provider/autoref.go), [`key_models.go`](../../internal/gateway/key_models.go), [`internal/agent/autoref.go`](../../internal/agent/autoref.go) | | A model's own id at a provider | A model the user lists by an id of theirs at a provider (a signed-in account's and a plugin's too; settings' `ModelIDs`, `magpie model id `, the editor's "Listed as"; [Providers and accounts](providers-accounts.md#runtime-path)) is that id everywhere the gateway names it: `/v1/models` and the lists written into agents (`Available`), `Resolve`, the routing groups and the group magpie finds for it (`auto/`, with every other provider serving that id), a gateway key's models, `X-Magpie-Model` and the usage log's `model`. Only the upstream request differs: every place that sends a wire name reads `settings.Wires()`, which is `ModelWires` with each `ModelIDs` entry turned round (`"/"` → the vendor's own id, wrapped by a `/*` wire), so the body, a Vertex path and the usage log's endpoint carry the vendor's id; an explicit `ModelWires` entry for that id wins. The vendor's reply names its own id, which the usage log, recent calls and the Routing page keep as `served`; the agent gets the id it asked for back in the reply, in every protocol, streamed or whole (`memberWriter` in [`member.go`](../../internal/gateway/member.go), `replyNamingOf`: the reply's `model`, Responses' `response.model`, Anthropic's `message.model`, Gemini's `modelVersion`; issennknight on Discord, whose agent warned that `deepseek-v4.1-flash` came back as `deepseek-v4.1-flash-1017`). The same holds for a group or a `provider/model` id the vendor knows by another name. A reply whose vendor sent the wire name as asked keeps the vendor's name (a dated `-20261017` included); `memberModel` names the group's member instead, and `X-Magpie-Response-Model: vendor` keeps the vendor's name always (`TestReplyNamesAskedModel`, `TestGeminiReplyNamesAskedModel`, `TestReplyNamesMember`). A request still naming `provider/` (an agent's file magpie didn't rewrite) resolves and goes out as it is. A key held to either id passes for both (`modelAllowed` checks the ref, then `OwnModelID`, then `ListedModelID`); a group member passes the same way. An id is given to a model of the provider's chat list or its picks; the image, video and embeddings routes send no wire name, so they are not served under one (`TestLocalModelIDOnEveryRoute`). At an account or a plugin the account's own say of the model is read by the vendor's id: a plugin's API and fetch, Claude Code's `--model`, Antigravity's variant, and which accounts list it and at what levels (`TestLocalModelIDAtAPlugin`, `TestLocalModelIDAtAClaudeAccount`, `TestLocalModelIDAtAnAntigravityAccount`). | [`internal/provider/localid.go`](../../internal/provider/localid.go), [`internal/settings/settings.go`](../../internal/settings/settings.go), [`key_models.go`](../../internal/gateway/key_models.go) | | Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). A fallback the user unchecked in its own provider's model list is skipped, as a group's member is (`provider.ResolveRoute`, #3911; `fallback_unpicked_test.go`), and so is it where fallbacks are read for careful accounts, native compaction, redaction and Codex's own turns. A fallback can be a routing group (`group/`, 01huadalang on Discord): `planPaused` hands its members to `planLevel` as a request to the group would (`planFallbackGroup`), in the group's own routing and sink, its pause rules applied in `serve`, and its trace rows marked `Fallback` with the group in `Via`. Its turn rules (`ruleFor`, which may ask a classifier) are not applied: the plan is made before the primary is tried, and a classifier call on every request the primary answers costs too much. Each provider/model is tried once a round: a member that is the primary, an earlier fallback or another fallback group's is left out where it came second, so a group holding this provider is no loop (groups have no fallbacks of their own, and a member's are not followed). A group that is gone is passed over. Every place that reads fallbacks (careful accounts, native compaction, redaction, Codex's own turns, Claude's review) reads a group's members through `provider.FallbackModels`. `fallback_group_test.go`. `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576); one left on the default (Smart) in a group that pools (Smart, In turn, Least used, Weekly pace, Free first, Speed first, a plugin's) takes the outer group's, as a provider left on the default does (`provider.Group.Within`, set on `Member.Via`, so the trace's `Subs` and the Routing page read the routing that applies, #3847). In a group In order, By weight or Manual it stays Smart. `TestFreeFirstReachesAGroupInItLeftOnTheDefault`. 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`, `weight`, `free` (free first), `fast` (speed first) or, a group's only, `cheap` (cheapest first). `weighRouted` reads each candidate into a `routes.Seat` and asks the strategy serving its routing (`routes.Find`, the router strategy point of [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)) for the order: Smart is `routes.Smart`, the core's; the others are `routes.Builtin`, registered by the built-in plugin `rotation`. With it off a routing no strategy serves is tried in its listed order, and `routingOf` treats it as `order` wherever the core asks about a routing (a turn's mark, `goesRound`, `sinks`, a rotate group's sessions, a group's heads). 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. Among accounts a plugin reads as prepaid wallets (a window's `balance`, #3950), Smart, `usage` and `pace` put the one with more left first where they would otherwise tie, only within one provider and unit (`routes.Seat.Left`/`LeftIn`, see [provider plugins](provider-plugins.md#a-wallets-balance)): each kind is ordered in the places its own seats take, so a group weighing several providers' accounts as one pool orders each provider's wallets too (#4095, `TestGroupWalletsGoByWhatTheyHaveLeft`). `free` weighs by what a model costs there and nothing else: only a strategy with `routes.Strategy.ByFree` set (`routes.FreeFirst` is the one) has `weighRouted` fill `routes.Seat.Free`, from `provider.FreeModel` — the user's word that the whole provider costs them nothing (`Provider.CountFree`: the editor's Free for me, `magpie provider set free=yes`; jiabubu on Discord, ModelScope's free daily quota), else the vendor's own `catalog.Model.Free` word, else a list price of $0 on every count — so a pool routed any other way never reads a model list for it, and one routed `free` spends the members whose model costs nothing before those that spend the allowance or credits, each tier in its listed order (nothing free is left behind a paid one, and a pool with no free model behaves as `order`). A group routed `free` weighs its members whole, each over its own accounts or keys as its provider routes them. `fast` weighs by speed lately and nothing else: only a strategy with `routes.Strategy.BySpeed` set (`routes.Fastest`) has `weighRouted` fill `routes.Seat.TTFT` and `TPS`, from `speedOf` ([`speed.go`](../../internal/gateway/speed.go)): per `restID` (account or key, and model), a decayed average (half-life 20m) of a streamed answer's ms to its first content and of its output tokens a second as `usage.DecodeOf` counts them, written once as an answer ends (`noteTrySpeed`, beside `servedCandidate`) and read with one map lookup per candidate, never from the usage history; past an hour since its last answer a seat counts as not measured, the records are capped at 4096, and a restart forgets them. `routes.Fastest` ranks the awake by their first token plus 200 tokens at their pace (a seat with no pace at the measured seats' middle pace), keeps seats within a tenth of their band's fastest in listed order, and of a pool's requests with seats both measured and not, gives every fifth to one not measured (round the unmeasured, `probes`, so one is never starved); resting seats go after the awake, used-up ones (`UsedShare`) after those, and rests and failover are as for any routing. The trace's rows carry `lateTtft`/`lateTps` for the Routing page's story ("answered fastest lately — first token in 0.8s"). A non-streamed reply tells nothing (no first token), so a pool that never streams stays in listed order bar the probes. `cheap` (a group's only: `provider.normalize` drops it from a provider, whose keys and accounts all bill one price, and the CLI refuses it there) weighs by price now and nothing else: only a strategy with `routes.Strategy.ByPrice` set (`routes.Cheapest`) has `weighRouted` fill `routes.Seat.Priced`, `Cost` and `CacheCost`, from `provider.Provider.PriceAt` at `priceClock()` — the price Usage would count a call made then (the user's `ModelPrices`, else list or maker price, at the price rate and `RateAt`'s window, a `FreeModel` at 0), doubled in its vendor's peak hours by `catalog.Price.In` (`PeakOf`: DeepSeek's API, Command Code's and OpenCode Go's DeepSeek models). `routes.Cheapest` sorts stably by a million in plus a million out, a tie (within a millionth) by cache read, and unpriced seats after every priced one in listed order; rests and failover are as for any routing. The trace's rows carry `price` (`input`, `output`, `cacheRead`, `peak`) for the Routing page's story ("costs least on Ollama now — $0.150 in, $0.600 out a million tokens"). `TestCheapestFirstGroupFollowsPeakHours` holds the clock at a peak and an off-peak hour. 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 (`routes.Round` over `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, while one whose accounts are only near their limit (Smart's 90% band, not resting) keeps its share, the band ordering only its own accounts (`TestWeightedGroupGivesALowGroupItsShare`; Creat.wu on Discord read the Routing page's "kept for when the others can't" as the member passed over, so the page now tells a member behind another by a group's weights or order as such, `memberSplit` in the routing plugin's `client.js`), and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `routes.MoveRound`). `weight` on a provider spreads its keys by each key's `Weight` and a subscription's accounts by each account's (`AccountWeights`, rubbzha on X): `keyWeight` gives a seat its `Weight`, 1 when none is set, and `routes.Weighted` takes them by smooth weighted round robin, a resting one leaving the round and a kept conversation staying as Stays says (`TestWeightedKeys`, `TestAccountWeightSharesRequests`). 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/routes/`](../../internal/routes), [`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`, `weight`, `free` (free first), `fast` (speed first), `drain` (until used up) or, a group's only, `cheap` (cheapest first). `weighRouted` reads each candidate into a `routes.Seat` and asks the strategy serving its routing (`routes.Find`, the router strategy point of [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)) for the order: Smart is `routes.Smart`, the core's; the others are `routes.Builtin`, registered by the built-in plugin `rotation`. With it off a routing no strategy serves is tried in its listed order, and `routingOf` treats it as `order` wherever the core asks about a routing (a turn's mark, `goesRound`, `sinks`, a rotate group's sessions, a group's heads). 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. Among accounts a plugin reads as prepaid wallets (a window's `balance`, #3950), Smart, `usage` and `pace` put the one with more left first where they would otherwise tie, only within one provider and unit (`routes.Seat.Left`/`LeftIn`, see [provider plugins](provider-plugins.md#a-wallets-balance)): each kind is ordered in the places its own seats take, so a group weighing several providers' accounts as one pool orders each provider's wallets too (#4095, `TestGroupWalletsGoByWhatTheyHaveLeft`). `free` weighs by what a model costs there and nothing else: only a strategy with `routes.Strategy.ByFree` set (`routes.FreeFirst` is the one) has `weighRouted` fill `routes.Seat.Free`, from `provider.FreeModel` — the user's word that the whole provider costs them nothing (`Provider.CountFree`: the editor's Free for me, `magpie provider set free=yes`; jiabubu on Discord, ModelScope's free daily quota), else the vendor's own `catalog.Model.Free` word, else a list price of $0 on every count — so a pool routed any other way never reads a model list for it, and one routed `free` spends the members whose model costs nothing before those that spend the allowance or credits, each tier in its listed order (nothing free is left behind a paid one, and a pool with no free model behaves as `order`). A group routed `free` weighs its members whole, each over its own accounts or keys as its provider routes them. `fast` weighs by speed lately and nothing else: only a strategy with `routes.Strategy.BySpeed` set (`routes.Fastest`) has `weighRouted` fill `routes.Seat.TTFT` and `TPS`, from `speedOf` ([`speed.go`](../../internal/gateway/speed.go)): per `restID` (account or key, and model), a decayed average (half-life 20m) of a streamed answer's ms to its first content and of its output tokens a second as `usage.DecodeOf` counts them, written once as an answer ends (`noteTrySpeed`, beside `servedCandidate`) and read with one map lookup per candidate, never from the usage history; past an hour since its last answer a seat counts as not measured, the records are capped at 4096, and a restart forgets them. `routes.Fastest` ranks the awake by their first token plus 200 tokens at their pace (a seat with no pace at the measured seats' middle pace), keeps seats within a tenth of their band's fastest in listed order, and of a pool's requests with seats both measured and not, gives every fifth to one not measured (round the unmeasured, `probes`, so one is never starved); resting seats go after the awake, used-up ones (`UsedShare`) after those, and rests and failover are as for any routing. The trace's rows carry `lateTtft`/`lateTps` for the Routing page's story ("answered fastest lately — first token in 0.8s"). A non-streamed reply tells nothing (no first token), so a pool that never streams stays in listed order bar the probes. `cheap` (a group's only: `provider.normalize` drops it from a provider, whose keys and accounts all bill one price, and the CLI refuses it there) weighs by price now and nothing else: only a strategy with `routes.Strategy.ByPrice` set (`routes.Cheapest`) has `weighRouted` fill `routes.Seat.Priced`, `Cost` and `CacheCost`, from `provider.Provider.PriceAt` at `priceClock()` — the price Usage would count a call made then (the user's `ModelPrices`, else list or maker price, at the price rate and `RateAt`'s window, a `FreeModel` at 0), doubled in its vendor's peak hours by `catalog.Price.In` (`PeakOf`: DeepSeek's API, Command Code's and OpenCode Go's DeepSeek models). `routes.Cheapest` sorts stably by a million in plus a million out, a tie (within a millionth) by cache read, and unpriced seats after every priced one in listed order; rests and failover are as for any routing. The trace's rows carry `price` (`input`, `output`, `cacheRead`, `peak`) for the Routing page's story ("costs least on Ollama now — $0.150 in, $0.600 out a million tokens"). `TestCheapestFirstGroupFollowsPeakHours` holds the clock at a peak and an off-peak hour. 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 (`routes.Round` over `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, while one whose accounts are only near their limit (Smart's 90% band, not resting) keeps its share, the band ordering only its own accounts (`TestWeightedGroupGivesALowGroupItsShare`; Creat.wu on Discord read the Routing page's "kept for when the others can't" as the member passed over, so the page now tells a member behind another by a group's weights or order as such, `memberSplit` in the routing plugin's `client.js`), and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `routes.MoveRound`). `weight` on a provider spreads its keys by each key's `Weight` and a subscription's accounts by each account's (`AccountWeights`, rubbzha on X): `keyWeight` gives a seat its `Weight`, 1 when none is set, and `routes.Weighted` takes them by smooth weighted round robin, a resting one leaving the round and a kept conversation staying as Stays says (`TestWeightedKeys`, `TestAccountWeightSharesRequests`). 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`). `drain` (dzxx0496 on Discord: free accounts one after another, the first not taking the requests back once it renews) stays on one seat per pool (`routes.Drain`, which remembers the seat's `Key` per pool) until it is used up — a known window at 100% (`provider.SpentShareOf`, as In order) or resting out of quota or credit (`routes.Seat.Spent`, filled by `spentRest` from `restingOf`'s `failQuota`/`failCredit`) — then goes on to the next not used up in listed order and stays there, wrapping round; the others follow it in listed order for failover. A rate limit or a failure only rests the seat, tried last meanwhile, and the pool comes back to it; with every seat used up it stays put, and a seat that leaves the pool leaves it on the first not used up. A group routed `drain` pools its members' accounts and keys under `group/`, as Smart does. A restart forgets where each pool was, and it starts again at the first not used up (`TestDrainKeepsTheOneThatTookOver`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/routes/`](../../internal/routes), [`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`). One with no limit still counts its requests out in a lane of `Limit` 0, which never waits, so `Lanes` (`/v1/magpie/concurrency`, the GUI's `/api/lanes`) says how many run there too and the Providers page's pill shows it (chentuoyan on Discord, `TestLanesCountWithNoLimit`); a limit set while they are out counts them. `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) | | Accounts at once | A provider's `MaxAccounts` (01huadalang on Discord: three ZCode accounts used at once got the exit address refused with a 405, two didn't) is how many of its keys or accounts take requests at the same time: `provider.AtOnce()` is the user's own value, else what its plugin declares (`maxAccounts` on the auth hook or in package.json's `magpie`, read by host.js `atOnceOf`; zcode says 2), else no limit; the user's 0 is no limit over the plugin's. `perKeyBarred` keeps the first N in the user's own order (`rank`, so a dragged list counts), preferring ones not resting, and hands the rest to `keepAtOnce`'s reserves: they go after everything else as asides with `candidate.reserve` set (`Weighed.Reserve`), so whatever the routing mode, a reserve is asked only once the kept ones failed or rest, and a kept one that rests gives its seat to the first reserve on the next request. Three guards keep a reserve from being reached for anything else: `laneMate` never spills a full lane onto one, a full queue (`laneErr`) drops the provider's reserves before passing on (`dropReserves`), so the request is turned away with the 429 instead, and session affinity keeps no conversation on a reserve once the kept ones can take it (`affine`'s "reserve"; Strict still holds). Leak known: a failure that rests nobody (a 5xx on one try) still passes that one request to the reserve, as it does to any next candidate. Set in the provider editor's Advanced (Accounts at once, beside Concurrency) or with `magpie provider at-once`; Routing's row says "in reserve · {n} at once" (`TestAtOnceKeepsFirstInUserOrder`, `TestAtOnceFullLaneWaitsForTheKept`, `TestAtOnceReserveTakesOverAndGivesBack`, `provider-at-once.test.cjs`). | [`fallback.go`](../../internal/gateway/fallback.go), [`concurrency.go`](../../internal/gateway/concurrency.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, or until its rest is lifted by hand (Try now, `Unrest` calls `unsink`, `UnrestAll` `unsinkAll` for the key and each of its models), which puts it back in its place (`TestTryNowPutsASunkAccountBack`, `TestUnrestAllUnsinksTheModels`). Another magpie's model rate limited there, whose rest is the model's alone (`remoteModelRest`), sinks alone too (`restID`), and `sunkAt` reads a candidate's model before its key, so the remote's other models keep their place (#2167, ggbdpq; `TestRemoteMagpieRateLimitSinksTheModel`, `TestMagpieAddedByHandRateLimitSinksTheModel`). A group in a group sinks by its own Sink, within its own order (`sinkOwn`, #2255), and the group asked for then sinks the whole by its own; `TestNestedGroupSinksItsOwnOrder`. | [`sink.go`](../../internal/gateway/sink.go) | diff --git a/docs/subsystems/plugin-runtime.md b/docs/subsystems/plugin-runtime.md index 536befd4c..b70a68b9c 100644 --- a/docs/subsystems/plugin-runtime.md +++ b/docs/subsystems/plugin-runtime.md @@ -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/`, 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) | diff --git a/internal/cli/groups_cli.go b/internal/cli/groups_cli.go index 6451b6ae6..ffaa77981 100644 --- a/internal/cli/groups_cli.go +++ b/internal/cli/groups_cli.go @@ -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 diff --git a/internal/cli/main.go b/internal/cli/main.go index 944a8cc52..eafc4f4c4 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -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 |rm ] 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/ - magpie group add models=, [routing=smart|order|rotate|usage|pace|weight|free|fast|cheap] [stays=auto|session|turn|off] + magpie group add models=, [routing=smart|order|rotate|usage|pace|weight|free|fast|cheap|drain] [stays=auto|session|turn|off] magpie group | set k=v… | rm 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 sign in to one more Claude, ChatGPT or Google (Gemini CLI, Antigravity) subscription diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index cdca22d70..d35855637 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -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": diff --git a/internal/gateway/drain_test.go b/internal/gateway/drain_test.go new file mode 100644 index 000000000..2382021ab --- /dev/null +++ b/internal/gateway/drain_test.go @@ -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) + } + } +} diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 00923164f..7184887ec 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -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 { diff --git a/internal/gateway/weighted.go b/internal/gateway/weighted.go index 302d6e679..b525ed487 100644 --- a/internal/gateway/weighted.go +++ b/internal/gateway/weighted.go @@ -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 { diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 84cb30971..984092ba0 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -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 ("/", // 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 }) diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 74485fd7e..0dfae3591 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -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", diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index 9184d4eba..5cee49902 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -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.", diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js index 9c7f826ea..3f2fcb4eb 100644 --- a/internal/gui/assets/plugins/routing/i18n.js +++ b/internal/gui/assets/plugins/routing/i18n.js @@ -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}.", diff --git a/internal/gui/tests/builtins.test.cjs b/internal/gui/tests/builtins.test.cjs index 5bfe2b9e9..b80d30822 100644 --- a/internal/gui/tests/builtins.test.cjs +++ b/internal/gui/tests/builtins.test.cjs @@ -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" }, diff --git a/internal/gui/tests/routing-drain.test.cjs b/internal/gui/tests/routing-drain.test.cjs new file mode 100644 index 000000000..f6452886e --- /dev/null +++ b/internal/gui/tests/routing-drain.test.cjs @@ -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, []); + }); + } + } +} diff --git a/internal/gui/tests/routing-group-strategy.test.cjs b/internal/gui/tests/routing-group-strategy.test.cjs index 9c62b9844..da56196b5 100644 --- a/internal/gui/tests/routing-group-strategy.test.cjs +++ b/internal/gui/tests/routing-group-strategy.test.cjs @@ -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, []); }); } diff --git a/internal/gui/tests/routing-save.test.cjs b/internal/gui/tests/routing-save.test.cjs index 812f79224..e88fbc6f5 100644 --- a/internal/gui/tests/routing-save.test.cjs +++ b/internal/gui/tests/routing-save.test.cjs @@ -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(); } diff --git a/internal/provider/codex_switch.go b/internal/provider/codex_switch.go index 599fb17eb..054aa556a 100644 --- a/internal/provider/codex_switch.go +++ b/internal/provider/codex_switch.go @@ -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 diff --git a/internal/provider/group.go b/internal/provider/group.go index 4e5a32124..bc532f1eb 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -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) { diff --git a/internal/provider/provider.go b/internal/provider/provider.go index c09d1856e..4dbe47302 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -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) { diff --git a/internal/provider/routing.go b/internal/provider/routing.go index ce22846bc..0fc5a30fd 100644 --- a/internal/provider/routing.go +++ b/internal/provider/routing.go @@ -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: "/". diff --git a/internal/routes/drain_test.go b/internal/routes/drain_test.go new file mode 100644 index 000000000..c5dd243d2 --- /dev/null +++ b/internal/routes/drain_test.go @@ -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) + } +} diff --git a/internal/routes/round.go b/internal/routes/round.go index b7d700bd4..c1f7844ec 100644 --- a/internal/routes/round.go +++ b/internal/routes/round.go @@ -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) } } diff --git a/internal/routes/routes.go b/internal/routes/routes.go index 71a1d1dab..7261e8898 100644 --- a/internal/routes/routes.go +++ b/internal/routes/routes.go @@ -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 — diff --git a/internal/routes/strategies.go b/internal/routes/strategies.go index c0e77ae37..18ed9cb0f 100644 --- a/internal/routes/strategies.go +++ b/internal/routes/strategies.go @@ -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, } diff --git a/internal/tui/routing.go b/internal/tui/routing.go index 4f94206a5..a60565da2 100644 --- a/internal/tui/routing.go +++ b/internal/tui/routing.go @@ -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" } diff --git a/plugins/rotation/rotation.go b/plugins/rotation/rotation.go index 32780efe5..77800462e 100644 --- a/plugins/rotation/rotation.go +++ b/plugins/rotation/rotation.go @@ -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"}}, diff --git a/site/public/docs/ja/start.html b/site/public/docs/ja/start.html index 27f3c1fa1..0b913c953 100644 --- a/site/public/docs/ja/start.html +++ b/site/public/docs/ja/start.html @@ -167,7 +167,7 @@

1 つのプロバイダに複数のアカウントやキー

-

プロバイダの行を開き、使うアカウントやキーをすべてチェックします。Routing はリクエストをそれらにどう振り分けるかを決めます:Smart(デフォルト)、In order、In turn、Least used first、Weekly pace、By weight(各アカウントやキーが横で設定した重みで取り分を受けます。たとえば Max アカウントは 5、Pro は 1)、Speed first(最近いちばん速く応答したキーが先)。Fallback には、プロバイダのクォータ切れ、レート制限、ダウン時に代わりに使うモデルを並べます。

+

プロバイダの行を開き、使うアカウントやキーをすべてチェックします。Routing はリクエストをそれらにどう振り分けるかを決めます:Smart(デフォルト)、In order、Until used up(使い切ったら次へ移り、前のものが回復しても戻りません)、In turn、Least used first、Weekly pace、By weight(各アカウントやキーが横で設定した重みで取り分を受けます。たとえば Max アカウントは 5、Pro は 1)、Speed first(最近いちばん速く応答したキーが先)。Fallback には、プロバイダのクォータ切れ、レート制限、ダウン時に代わりに使うモデルを並べます。

1 つのモデルを複数のプロバイダで

グループとは、1 つまたは複数のプロバイダのモデルを、エージェントが 1 つとして選べるようにまとめたものです。ピッカーの Routing groups の下に group/<id> として表示されます。2 つのプロバイダが同じ名前で提供しているモデルは、それだけでグループになります。Routing タブの New group では、好きなモデルを組み合わせてグループを作れます。グループで何ができるかは、最初のモデルが基準になります。

@@ -177,6 +177,7 @@ ルーティング先に使われるもの スマート smartデフォルトです。メンバーのアカウントとキーをまとめて扱い(グループ内のグループは 1 つとして扱います。下記参照)、クォータに余裕のあるサブスクリプションのうち、利用枠が最も早く更新されるもの。基準は週の枠です。週の枠がなく 5 時間枠だけのアカウント(Claude Enterprise)は 5 時間枠で判断されるため、それより後に週の枠が更新されるものすべてより先になります。リセットのないクレジット(WorkBuddy のパッケージはそれぞれの日に失効します)は、残りのうち最も早く失効する時点で判断されるため、クレジットが最も早く失効する WorkBuddy アカウントが先になります。同時に更新されるアカウント(無料アカウントはすべて月末)は、その後に残りのクレジットが先に失効するものが先になります。失敗後に休止中のものは最後に回ります。 順番どおり order最初のモデルが応答できなくなるまでそれを使い、次へ進みます。 + 使い切ってから次へ drain1 つのアカウントやキーを使い切るまで使い、その後は次へ移ってそのまま使い続けます。その間に前のものが回復しても戻りません。レート制限やエラーのものは休止中だけ飛ばします。 持ち回り rotate各会話の次のターンを、次のメンバーのアカウントやキーに送り、負荷を分散します。 使用量の少ない順 usage利用枠の残りが最も多いアカウントやキー。 週のペース pace更新までの 1 時間あたりの週の枠の残りが最も多いアカウント、つまりリセット時に失う分が最も多いもの。これにより各メンバーの週の枠がリセットで無駄になりにくくなります。週の枠がなく 5 時間枠だけのアカウント(Claude Enterprise)は、更新までの 1 時間あたりの 5 時間枠の残りで判断されるので、ほぼ常に最初になります。使用率が 90% 以上のものは、他が応答できなくなるまで待ちます。キーは最近送ったトークン数で判断します。 diff --git a/site/public/docs/start.html b/site/public/docs/start.html index 2250c4292..f3e9ae3bb 100644 --- a/site/public/docs/start.html +++ b/site/public/docs/start.html @@ -167,7 +167,7 @@

Several accounts or keys in one provider

-

Open the provider’s row and tick every account or key to use. Routing says how requests spread over them: Smart (the default), In order, In turn, Least used first, Weekly pace, By weight, each account or key taking its share by the weight set beside it (a Max account 5, a Pro one 1), or Speed first, the key that answered fastest lately first. Fallback lists models to use instead when the provider is out of quota, rate limited or down.

+

Open the provider’s row and tick every account or key to use. Routing says how requests spread over them: Smart (the default), In order, Until used up, staying on the next once one is used up even after the first renews, In turn, Least used first, Weekly pace, By weight, each account or key taking its share by the weight set beside it (a Max account 5, a Pro one 1), or Speed first, the key that answered fastest lately first. Fallback lists models to use instead when the provider is out of quota, rate limited or down.

One model over several providers

A group is several models, from one provider or many, that an agent picks as one: group/<id>, under Routing groups in the picker. A model two of your providers serve under the same name becomes a group on its own; New group in the Routing tab makes one of any models you like. The first model answers for what the group can do.

@@ -177,6 +177,7 @@ RoutingWhat goes first Smart smartThe 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. In order orderThe first model until it can’t answer, then the next. + Until used up drainOne 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. 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. diff --git a/site/public/docs/zh/start.html b/site/public/docs/zh/start.html index 4616d3bc6..5b4bf9227 100644 --- a/site/public/docs/zh/start.html +++ b/site/public/docs/zh/start.html @@ -167,7 +167,7 @@

一个供应商里的多个账号或密钥

-

展开供应商那一行,勾选要用的每个账号或密钥。路由 决定请求怎么分给它们:智能(默认)、按顺序、轮流、用量少的优先、重置前用完、按权重(每个账号或密钥按旁边设的权重分得请求,比如 Max 账号设 5、Pro 账号设 1)或 速度优先(最近回答最快的密钥先用)。备用 里列出这个供应商额度用完、被限流或不可用时改用的模型。

+

展开供应商那一行,勾选要用的每个账号或密钥。路由 决定请求怎么分给它们:智能(默认)、按顺序、用完再换(一个用完再换下一个,前面的恢复了也不切回去)、轮流、用量少的优先、重置前用完、按权重(每个账号或密钥按旁边设的权重分得请求,比如 Max 账号设 5、Pro 账号设 1)或 速度优先(最近回答最快的密钥先用)。备用 里列出这个供应商额度用完、被限流或不可用时改用的模型。

跨供应商的同一个模型

路由组是几个模型(来自一个或多个供应商),Agent 把它当作一个来选:group/<id>,在选择列表的 路由组 下面。两个供应商用同一个名字提供的模型会自动成组;在 路由 标签页点 新建组 可以把任意模型组到一起。排第一的模型决定这个组对外的能力。

@@ -177,6 +177,7 @@ 路由谁排在前面 智能 smart默认。把成员的账号和 Key 放在一起排(组里的路由组算一个,见下文):还有余量的订阅里,额度最先重置的排第一。看周额度的重置时间;只有 5 小时额度、没有周额度的账号(如 Claude Enterprise)看它的 5 小时重置,所以排在所有更晚重置的周额度前面。没有重置时间的积分(WorkBuddy 的积分包,各自到期)按剩余积分最早过期的时间算,所以积分最先过期的 WorkBuddy 账号排第一;同时重置的账号(免费账号都在月底)再看剩余积分哪个先过期。失败后在休息的排最后。 按顺序 order先用第一个模型,它答不了再换下一个。 + 用完再换 drain一个账号或 Key 用到额度用完,再换下一个,并一直用它:前面的额度恢复了也不会切回去。被限流或出错的只在休息期间跳过。 轮流 rotate会话的每一轮交给下一个成员的账号或 Key,均摊负载。 最少使用 usage剩余额度最多的账号或 Key 排第一。 重置前用完 pace每周剩余额度除以距重置的小时数,最高的账号排第一——重置时损失最多的那个——少让成员的周额度到重置时作废;只有 5 小时额度、没有周额度的账号(如 Claude Enterprise)按 5 小时窗口的剩余额度除以距它重置的小时数算,所以几乎总排第一。用到 90% 以上的等其他账号都答不了时才用。Key 按最近发给它的 token 数排。