routing: By weight spreads a subscription's requests over its accounts
rubbzha on X (tweet 2116346330625036794): a Claude Max account and a Pro
one signed in to one subscription should share its requests by how much
each allows. The provider editor's Routing now offers By weight for
subscription accounts as it does for keys. With it picked, each account
in use shows "Weight N · S%" beside its name, the key weight's chip, and
a click edits it in place (POST /api/provider/accountweight {id, account,
weight}). CLI: `magpie provider account-weight <id> [account [n|default]]`.
The weight is kept per account by its lower-case name
(Provider.AccountWeights), and is moved with a rename (moveAccountSettings).
The gateway's keyWeight reads it from the candidate, with no file read, so
the smooth weighted pick treats accounts as it treats keys: Stays keeps a
conversation on its account, and a resting account is passed over while
the others share its requests. The default is 1. Nothing is prefilled from
the plan, and 1 is stored as no entry, so a value the user set is never
overridden.
Re-derived: ROUTINGS' weight text and routingsOf (the editor), the Routing
page's MODES, provider-row options and its "why first" text for an account,
the routing and accounts subsystem pages, the start docs (en, zh, ja), and
i18n in zh, zh-TW, ja and de (i18n.js and plugins/routing/i18n.js).
app.js is 74 bytes smaller than before (a long comment cut, keyWeight
reused), so neither script budget is raised.
key-weight.test.cjs read #status before accountAction's second round trip
(/api/state) had written it. The same race is now waited on in both tests:
with a 400ms delay injected on /api/state, the old read is red and the
new one is green.
Run (rebased on 03f3e1528; then on ef8dfaa46, where the budget, i18n and
own tests were run again and passed: Budget|I18n|Weight Go tests,
account-weight, key-weight and i18n-keys GUI files 10/10):
- New tests, each red on the old code: TestSetAccountWeight,
TestAccountWeightMovesWithRename (red with the moveKey line removed),
TestAccountWeightSharesRequests (6/2 for weights 3/1; alternating with
keyWeight forced to 1), TestAccountWeightCmd, and
account-weight.test.cjs (chromium + webkit, widths 1000/560 and web 390,
en/zh/zh-TW/ja/de; red on 3e5aa1151's assets: no By weight for accounts).
- account-weight, key-weight, routing-weight-chip, account-row-line GUI
files on the Linux box: 24/24 after the status wait (23/24 before, the
race above). On mote, 13 of 24 timed out launching a browser at load 24
with 116 Playwright processes from other sessions (#4125).
- mote `go test -timeout 45m ./...`: every package ok except
internal/proc's TestNoCommandBypassesProc (claudetui on main, #4491) and
internal/gui's ten real-window AppKit tests killed at their deadlines
under load (#2645, #4125). Neither touches this change.
- gofmt -l clean; go vet ./... (darwin), GOOS=windows go vet ./... and
GOOS=linux go vet -tags nogui ./... ok on mote.
- Whole GUI suite on the Linux box: still running at push; reds are filed
after.
Not tried: real Max and Pro accounts through the gateway; the Routing
page's own account row under By weight has no GUI test; the whole GUI
suite on macOS WebKit (mote was saturated by other sessions' suites).
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -284,6 +284,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.
|
||||
- Not read for Vertex AI: the metadata server of Compute Engine, Cloud Run and GKE; workload identity federation (`external_account`, `external_account_authorized_user`, refused by name); credentials whose `universe_domain` isn't `googleapis.com`; Vertex AI's express-mode API keys (Save refuses a key). No quota project is sent: Vertex AI bills the project in the URL.
|
||||
- `GOOGLE_APPLICATION_CREDENTIALS` and `CLOUDSDK_CONFIG` are in `agentenv.Vars`. The desktop app takes them from the login shell when it wasn't started with them (`proc.UserPath`, macOS and Linux), and `testenv` clears both. Vertex AI reads them as set (`vertexEnvPath`), not through `appdir.Getenv`, which takes a relative value as unset: a `~/` that starts one is the home, and one that still isn't a full path is refused, naming the variable. Passed over, it would have the request signed from gcloud's own file, which may be another account's (a person's, where the variable named a service account's key).
|
||||
- The Vertex AI preset's `HeaderHints` are Google's Priority PayGo and Flex PayGo headers, `X-Vertex-AI-LLM-Request-Type` and `X-Vertex-AI-LLM-Shared-Request-Type`: the editor offers to add them, the values are the user's, and they go as `Headers` do. Priority PayGo couldn't be confirmed: on the project it was tried on, Vertex AI answered with `trafficType` `ON_DEMAND`.
|
||||
- An account's weight under `weight` routing is kept per account too (`AccountWeights`, by the account in lower case, 2–1000; one not in it weighs 1, and nothing sets one from the plan), as a key's is (`KeyAccount.Weight`), so a Max and a Pro account can share requests by how much more one allows (rubbzha on X). `SetAccountWeight` (GUI `provider/accountweight`, the chip beside each account in use in the editor while the routing is By weight; `magpie provider account-weight <id> [account [n|default]]`) sets it, `moveAccountSettings` carries it through a Copilot rename, and `withPicks` puts it on the accounts `All` gives, so the gateway's `keyWeight` reads it with no file read (`Provider.AccountWeight`).
|
||||
- A usage cap is kept per account (`AccountCaps`, 1–99) and, beside it, per window (`AccountWindowCaps`, by the account and the window's `capId`, its name in lower case: `WindowCapID`). A window's own share wins over the account's; 100 is no cap on that window. `CapsOf` gives both (`WindowCaps`), `CapHeld` and `capReached` judge each window by its own, and `SetWindowCap` (GUI `provider/windowcap`, `magpie provider account-cap <id> <account> --window <name>`) sets one. A config without window caps reads as before. How a pool ends at its caps is kept with the provider (plugins#349): `CapStop` answers 429 rather than going on to the fallbacks once every account in use is at its cap, and `CapCareful` reads usage again near a cap and holds an account whose usage can't be told (both off by default; `SetCapStop`, `SetCapCareful`, GUI `provider/capstop` and `provider/capcareful`, ticks under the account list once an account has a cap). `UsageRead` says when an account's usage was last read well and whether the last try failed (a failed try keeps the good reading's time), and `ReadUsageNow` reads it again. `magpie provider pool <id> [--accounts a,b,…] [--cap percent|off] [--stop on|off] [--careful on|off]` shows and sets the whole pool in one command: which accounts are on and in what order, each one's cap, and both settings, and names the accounts in use with no cap.
|
||||
- A window whose reset time has passed has started again, whatever share it was read at (`resetPassed`). That holds for a reading kept from before (`AsOf`) and for a fresh one: Claude Code's `/usage` gives a reset to the minute and can lag it, so a run just after a reset can still say 100% with that reset. `claudeWindows` hands such a window back empty on every path, and `usedPast`, `usedUp`, `BackAt` and `capReached` leave it out when they judge an account spent, for Codex, Claude Code and `magpie quota wait` alike. A card can still show a kept reading as it was read (`reported`, for a Claude card while `/usage` is unavailable); that changes what it shows, never which account is used. A reset `/usage` gives as a time alone ("resets 3pm") can be read as its next one, a day on (`claudeResetTime`), and is then not seen as passed here.
|
||||
- A restart to update can run two magpies for up to the old one's drain
|
||||
@@ -317,6 +318,8 @@ go test -tags nogui ./internal/provider -run 'TestSeat|TestPlanOfASignedInAccoun
|
||||
go test -tags nogui . -run TestAccountsAlias
|
||||
node --test internal/gui/tests/account-alias.test.cjs
|
||||
go test -tags nogui . -run TestAccountCapCmd
|
||||
go test -tags nogui ./internal/provider ./internal/gateway ./internal/cli -run 'TestSetAccountWeight|TestAccountWeight'
|
||||
node --test internal/gui/tests/account-weight.test.cjs
|
||||
node --test internal/gui/tests/account-cap.test.cjs internal/gui/tests/window-cap.test.cjs
|
||||
go test -tags nogui ./internal/provider -run 'TestRemoteMagpie'
|
||||
go test -tags nogui ./internal/provider -run 'TestVolc|TestQianfan|TestBedrock|TestMantleBase|TestAddCopy|TestBackupBalanceToken'
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// magpie provider account-weight gives a subscription account its share
|
||||
// of the requests under routing=weight (rubbzha on X: a Max account 5, a
|
||||
// Pro one 1), default takes it back to 1; a weight out of 1–1000, an
|
||||
// account the subscription hasn't, or a provider with keys is an error.
|
||||
func TestAccountWeightCmd(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
t.Setenv("DSH_HOME", "")
|
||||
jwt := func(m map[string]any) string {
|
||||
b, _ := json.Marshal(m)
|
||||
return "h." + base64.RawURLEncoding.EncodeToString(b) + ".s"
|
||||
}
|
||||
auth, _ := json.Marshal(map[string]any{"auth_mode": "chatgpt", "tokens": map[string]any{
|
||||
"id_token": jwt(map[string]any{"email": "me@example.com"}),
|
||||
"access_token": jwt(map[string]any{"exp": time.Now().Add(time.Hour).Unix()}),
|
||||
"refresh_token": "r", "account_id": "acct-1"}})
|
||||
os.MkdirAll(filepath.Join(home, ".codex"), 0o755)
|
||||
if err := os.WriteFile(filepath.Join(home, ".codex", "auth.json"), auth, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
provider.ForgetAccounts()
|
||||
t.Cleanup(provider.ForgetAccounts)
|
||||
weight := func() int {
|
||||
p, err := provider.Find("codex")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p.AccountWeight("me@example.com")
|
||||
}
|
||||
|
||||
if err := providerCmd([]string{"provider", "account-weight", "codex", "Me@Example.com", "5"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := weight(); w != 5 {
|
||||
t.Fatalf("weight %d", w)
|
||||
}
|
||||
for _, args := range [][]string{{"provider", "account-weight", "codex"}, {"provider", "account-weight", "codex", "me@example.com"}} {
|
||||
if err := providerCmd(args); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"1.5", "1001", "-2", "lots"} {
|
||||
if err := providerCmd([]string{"provider", "account-weight", "codex", "me@example.com", bad}); err == nil {
|
||||
t.Fatalf("%s taken", bad)
|
||||
}
|
||||
}
|
||||
if w := weight(); w != 5 {
|
||||
t.Fatalf("a refused weight changed it to %d", w)
|
||||
}
|
||||
if err := providerCmd([]string{"provider", "account-weight", "codex", "nobody@example.com", "2"}); err == nil {
|
||||
t.Fatal("an account it hasn't was weighed")
|
||||
}
|
||||
if err := providerCmd([]string{"provider", "account-weight", "codex", "me@example.com", "default"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := weight(); w != 1 {
|
||||
t.Fatalf("default left %d", w)
|
||||
}
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k1", Chat: "http://127.0.0.1:1/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := providerCmd([]string{"provider", "account-weight", "relay", "k1", "3"}); err == nil {
|
||||
t.Fatal("a key provider's account was weighed")
|
||||
}
|
||||
}
|
||||
@@ -84,6 +84,9 @@ const providerUsage = `usage:
|
||||
magpie provider account-concurrency <id> [account|key [n|off|default]]
|
||||
how many requests one account or key has out at once, over every model,
|
||||
routing group and agent: its own, off for none, default for the provider's
|
||||
magpie provider account-weight <id> [account [n|default]]
|
||||
a subscription account's share of the requests with routing=weight:
|
||||
one weighing 3 takes three for each one weighing 1 takes (default 1)
|
||||
magpie provider queue <id> [length [seconds]]
|
||||
how many may wait for each account or key past its limit, and how long;
|
||||
past either a request is turned away with a 429 (0: no bound)
|
||||
@@ -621,6 +624,8 @@ func providerCmd(args []string) error {
|
||||
return poolCmd(rest)
|
||||
case "account-concurrency", "account-limit":
|
||||
return accountConcurrencyCmd(rest)
|
||||
case "account-weight", "account-weights":
|
||||
return accountWeightCmd(rest)
|
||||
case "queue":
|
||||
return queueCmd(rest)
|
||||
case "rpm":
|
||||
@@ -1707,6 +1712,57 @@ func accountConcurrencyCmd(rest []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// accountWeightCmd shows, or sets, the weight of a subscription's accounts
|
||||
// under By weight routing (provider.AccountWeights): each one's share of
|
||||
// the requests, 1 when none is set.
|
||||
func accountWeightCmd(rest []string) error {
|
||||
if len(rest) < 1 || len(rest) > 3 {
|
||||
return fmt.Errorf("magpie provider account-weight <id> [account [n|default]]")
|
||||
}
|
||||
p, err := provider.Find(rest[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Account == nil {
|
||||
return fmt.Errorf("%s has keys, not subscription accounts: a key's weight is set beside it in the app", p.Name)
|
||||
}
|
||||
if len(rest) > 2 {
|
||||
w, err := provider.ParseWeight(rest[2])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := provider.SetAccountWeight(p.ID, rest[1], w); err != nil {
|
||||
return err
|
||||
}
|
||||
if p, err = provider.Find(p.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
refs := p.AccountRefs()
|
||||
if len(rest) > 1 {
|
||||
ref, ok := p.AccountRefOf(rest[1])
|
||||
if !ok {
|
||||
return fmt.Errorf("%s has no account %q", p.Name, rest[1])
|
||||
}
|
||||
refs = []string{ref}
|
||||
}
|
||||
if len(refs) == 0 {
|
||||
fmt.Println(muted.Render(p.Name + " has no account"))
|
||||
return nil
|
||||
}
|
||||
for _, r := range refs {
|
||||
if w := p.AccountWeight(r); w > 1 {
|
||||
fmt.Printf("%s · weight %d\n", r, w)
|
||||
} else {
|
||||
fmt.Println(r, muted.Render("· weight 1"))
|
||||
}
|
||||
}
|
||||
if p.Routing != provider.Weighted {
|
||||
fmt.Println(muted.Render("Weights count with routing=weight: magpie provider set " + p.ID + " routing=weight"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// queueCmd shows, or sets, how many requests may wait for each of a
|
||||
// provider's accounts or keys past its limit, and for how many seconds
|
||||
// (#892).
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A subscription routed by weight spreads its requests over its accounts
|
||||
// by the weight set beside each (rubbzha on X: a Max account and a Pro
|
||||
// one): me@example.com weighing 3 takes three of every four requests and
|
||||
// spare@example.com, with none set, the fourth.
|
||||
func TestAccountWeightSharesRequests(t *testing.T) {
|
||||
codexSignedIn(t, "spare@example.com")
|
||||
b := newResetBackend(t)
|
||||
if err := provider.SetRouting("codex", provider.Weighted); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := provider.SetAffinity("codex", provider.AffinityOff); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := provider.SetAccountWeight("codex", "Me@Example.com", 3); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := New()
|
||||
for range 8 {
|
||||
if code, body := resetPost(t, srv); code != 200 || !strings.Contains(body, "pong") {
|
||||
t.Fatalf("%d %s", code, body)
|
||||
}
|
||||
}
|
||||
tried, _ := b.seen()
|
||||
n := map[string]int{}
|
||||
for _, a := range strings.Split(tried, ",") {
|
||||
n[a]++
|
||||
}
|
||||
if n["acct-1"] != 6 || n["acct-2"] != 2 {
|
||||
t.Fatalf("tried %s: want acct-1 6 times, acct-2 twice", tried)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
package gateway
|
||||
|
||||
// Weighted routing (#841): a provider's requests spread over its keys by
|
||||
// each key's weight, as NGINX's smooth weighted round robin does — keys
|
||||
// each key's weight, and a subscription's over its accounts by each
|
||||
// account's (provider.AccountWeights, rubbzha on X), as NGINX's smooth
|
||||
// weighted round robin does — keys
|
||||
// weighing 3 and 1 go a, a, b, a, a, a, b, a…, the ratio held over a
|
||||
// handful of requests rather than only on average. A key resting after a
|
||||
// failure is left out of the round while it rests, so the others share
|
||||
@@ -21,8 +23,14 @@ import (
|
||||
"github.com/yetone/magpie/internal/routes"
|
||||
)
|
||||
|
||||
// keyWeight is a candidate's weight: its key's, 1 when none.
|
||||
func keyWeight(c candidate) int { return max(c.p.KeyWeight, 1) }
|
||||
// keyWeight is a candidate's weight: its account's (provider.AccountWeights,
|
||||
// rubbzha on X) or its key's, 1 when none.
|
||||
func keyWeight(c candidate) int {
|
||||
if c.p.Account != nil {
|
||||
return c.p.AccountWeight(c.p.Account.User)
|
||||
}
|
||||
return max(c.p.KeyWeight, 1)
|
||||
}
|
||||
|
||||
// resting says whether c rests now, as restLast will find.
|
||||
func resting(c candidate) bool {
|
||||
|
||||
+17
-21
@@ -12047,7 +12047,7 @@ const ROUTINGS = [
|
||||
["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."],
|
||||
["weight", "By weight", "Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with its key as Stays says."],
|
||||
["weight", "By weight", "Requests spread over the keys or accounts by the weight set beside each: one weighing 3 takes three requests for every one weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with it as Stays says."],
|
||||
["free", "Free first", "Requests go to what costs nothing first: the models their vendor serves at no cost to this subscription's allowance or credits, in their listed order, and only when those can't answer to one that spends them. Nothing that cost nothing is left unused."],
|
||||
["fast", "Speed first", "Requests go to the one that has answered this model fastest lately, by its time to the first token and how fast it writes; those within a tenth of each other keep their listed order. One not measured lately gets one request in five, so it is measured again, and one that fails is passed over while it rests."],
|
||||
];
|
||||
@@ -12075,8 +12075,7 @@ function routingSegs(items, current, onPick) {
|
||||
});
|
||||
return box;
|
||||
}
|
||||
// weight is a key's share: offered for a provider with keys only
|
||||
const routingsOf = (p) => [...(p.account ? ROUTINGS.filter(([id]) => id !== "weight") : ROUTINGS), ...jsRoutings(p.routing || "")];
|
||||
const routingsOf = (p) => [...ROUTINGS, ...jsRoutings(p.routing || "")];
|
||||
// as on the Routing page's list of these (routing/client.js AFF_OPTS)
|
||||
const STAYS = [
|
||||
["", "Auto", "A conversation stays with the account or key that answered it while what the vendor cached of it is worth keeping — within a turn always, across turns while it's fresh."],
|
||||
@@ -12133,8 +12132,8 @@ function renderRouting(p) {
|
||||
rUnsaved.hidden = routingNow() === (p.routing || "");
|
||||
// in turn and by weight go round already
|
||||
kLabel.hidden = kWrap.hidden = routingNow() === "rotate" || routingNow() === "weight";
|
||||
// each key's weight shows beside it while the routing is by weight
|
||||
for (const l of document.querySelectorAll(".accts.keys")) if (l.dataset.provider === p.id) l.classList.toggle("weighted", routingNow() === "weight");
|
||||
// each key's or account's weight shows beside it while by weight
|
||||
for (const l of document.querySelectorAll(".accts")) if (l.dataset.provider === p.id) l.classList.toggle("weighted", routingNow() === "weight");
|
||||
};
|
||||
const rPick = routingSegs(routingsOf(p).map(([id, name, , js]) => [id, ROUTINGS.some((r) => r[0] === id) ? t(name) : name, , js]), routingNow(), (routing) => { draft.routing = routing; drawRouting(); });
|
||||
const rRow = el("div", "route-pick");
|
||||
@@ -13230,24 +13229,20 @@ function renderAccounts(a, p) {
|
||||
const sub = subOf(a.agent);
|
||||
const list = el("div", "accts");
|
||||
const ls = loginsInOrder(a, p);
|
||||
if (p) list.dataset.provider = p.id, list.classList.toggle("weighted", (draft?.routing ?? (p.routing || "")) === "weight");
|
||||
// a Claude account whose sign-in Anthropic refused, or that has none,
|
||||
// can't be used till it is signed in again; another subscription's lapse
|
||||
// shows on its quota line only, as before
|
||||
const unusable = (l) => a.agent === "claude" && !!l.lapsed;
|
||||
// a plugin's account whose sign-in its vendor refused (#1363: Grok after
|
||||
// a restart): marked lapsed, or its allowance read saying so. Whatever
|
||||
// else it is (in use, the agent's own), it keeps a way to sign in again
|
||||
// and its Remove, and the reason never stands in their place.
|
||||
// A built-in Copilot account whose GitHub token GitHub refused (echo_ts
|
||||
// on Discord: a revoked token) is the same, marked lapsed by magpie, and
|
||||
// signed in again in place. So is any other built-in account whose
|
||||
// sign-in its vendor revoked (#1793: ChatGPT's 401 token_revoked) or
|
||||
// refused to refresh: the gateway passes over it till then.
|
||||
// one whose sign-in its vendor refused (a plugin's, #1363; Copilot's
|
||||
// revoked token; #1793's token_revoked) keeps Sign in again and Remove
|
||||
const signedOut = (l) => !unusable(l) && (sub?.plugin ? !!l.lapsed || SIGN_IN_GONE.test(quota?.[l.user]?.error || "") : (a.agent === "copilot" && !!l.lapsed) || SIGN_IN_GONE.test(l.lapsed || ""));
|
||||
// a Copilot account on an enterprise's GHE.com is named login@host, and
|
||||
// signs in again there
|
||||
const againSite = (l) => !sub?.plugin && a.agent === "copilot" && String(l.user).includes("@") ? String(l.user).split("@").pop() : undefined;
|
||||
const several = ls.filter((l) => !unusable(l) && ((l.active && !l.paused) || l.on)).length > 1;
|
||||
// each one's weight (provider.AccountWeights), for its share
|
||||
const isOn = (l) => !unusable(l) && !l.paused && (l.active || l.on), wOf = (l) => Math.max(p?.accountWeights?.[String(l.user).toLowerCase()] || 0, 1), weights = ls.filter(isOn).reduce((n, l) => n + wOf(l), 0);
|
||||
// kept signed in to one of the user's choosing (#524), the first is the
|
||||
// first in use in the order, which Make first sets without a sign-in
|
||||
const kept = keptLogin(p);
|
||||
@@ -13267,7 +13262,7 @@ function renderAccounts(a, p) {
|
||||
// it is signed back in once it has room (#408)
|
||||
const back = ls.find((l) => l.returns && !l.active);
|
||||
for (const l of ls) {
|
||||
const on = !unusable(l) && !l.paused && (l.active || l.on);
|
||||
const on = isOn(l);
|
||||
const row = el("div", "acc" + (on ? " in-use" : " off") + (l.user === justAdded ? " new" : ""));
|
||||
// its Remove, titled as given; true: the own account's, else the plain one
|
||||
const forgetOf = (title) => {
|
||||
@@ -13296,6 +13291,7 @@ function renderAccounts(a, p) {
|
||||
const line = el("div", "acc-line");
|
||||
row.append(line);
|
||||
line.append(dot, accountNameButton(p, l.user), el("span", "plan", accountPlan({ agent: a.agent, builtin: a.builtin, plan: l.plan })));
|
||||
if (p && on && several) line.append(keyWeight(p, { name: l.user }, wOf(l), weights, "provider/accountweight", { id: p.id, account: l.user }));
|
||||
// its own models (#474), when there is another account to send the rest to
|
||||
const [amPill, amBox] = ls.length > 1 || accountModelsOf(p, l.user).length ? accountModels(p, l.user, false, l.user) : [];
|
||||
// what is set shows on it; the rest waits under ⋯ on a line below
|
||||
@@ -14566,25 +14562,25 @@ function accountModels(p, ref, isKey, name) {
|
||||
return [pill, box];
|
||||
}
|
||||
|
||||
// keyWeight: a key's weight under By weight routing, and its share of the
|
||||
// requests; a click edits it in place, Enter or leaving it saves it.
|
||||
function keyWeight(p, k, w, total) {
|
||||
// keyWeight: a key's or account's weight under By weight, and its share;
|
||||
// a click edits it in place, Enter or leaving it saves it.
|
||||
function keyWeight(p, k, w, total, path = "keys/weight", body = { id: p.id, ref: k.id }) {
|
||||
const b = el("button", "key-weight", t("Weight {n} · {share}%", { n: w, share: Math.round(100 * w / total) }));
|
||||
b.title = t("Its share of the requests: a key weighing 3 takes three for every one a key weighing 1 takes");
|
||||
b.title = t("Its share of the requests: one weighing 3 takes three for every one weighing 1 takes");
|
||||
b.onclick = () => {
|
||||
const i = input(String(w), "1");
|
||||
i.type = "number";
|
||||
i.min = "1";
|
||||
i.max = "1000";
|
||||
i.className = "key-weight-in";
|
||||
i.setAttribute("aria-label", t("Key weight"));
|
||||
i.setAttribute("aria-label", t(path[0] == "k" ? "Key weight" : "Account weight"));
|
||||
i.title = b.title;
|
||||
let done = false;
|
||||
const save = (keep) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
const n = Math.round(Number(i.value));
|
||||
if (keep && n >= 1 && n <= 1000 && n !== w) accountAction("keys/weight", { id: p.id, ref: k.id, weight: n }, t("{key} weighs {n}", { key: k.name || k.masked, n }));
|
||||
if (keep && n >= 1 && n <= 1000 && n !== w) accountAction(path, { ...body, weight: n }, t("{key} weighs {n}", { key: k.name || k.masked, n }));
|
||||
else renderProviders();
|
||||
};
|
||||
i.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") save(true); else if (e.key === "Escape") save(false); };
|
||||
|
||||
@@ -351,6 +351,7 @@ const I18N = {
|
||||
"Its saved configuration will be removed. Agents using it may switch to another provider or their default model.": "这将删除它的已保存配置。使用它的 Agent 可能切换到其他供应商或默认模型。",
|
||||
"This account or key will stop being used for requests. You will need to add it again to use it.": "此账户或密钥将不再用于请求。要再次使用,需要重新添加。",
|
||||
"Key weight": "密钥权重",
|
||||
"Account weight": "账号权重",
|
||||
"Saved middleware options will be removed. The plugin will run with no options.": "已保存的中间件选项将被移除。插件将不带选项运行。",
|
||||
"Main navigation": "主导航",
|
||||
"Gateway keys": "网关密钥",
|
||||
@@ -1743,9 +1744,9 @@ const I18N = {
|
||||
"Cheapest first: no price is known for {model} on {who}, so it goes in its listed place after every one that has a price.": "最便宜优先:不知道 {model} 在 {who} 上的价格,所以它排在所有有价格的后面,按列出的位置。",
|
||||
"Requests go to what costs nothing first: the models their vendor serves at no cost to this subscription's allowance or credits, in their listed order, and only when those can't answer to one that spends them. Nothing that cost nothing is left unused.": "先把不花钱的用完:供应商对本订阅的额度或积分不收费的模型排在前面,按它们原来的顺序;这些都不能响应时,才用要花额度的。不花额度的一个都不剩下。",
|
||||
"Free first: the members whose model its vendor serves at no cost to the subscription's allowance or credits go first, then the rest — each whole, over its own accounts or keys as its provider routes them. The free ones are tried before any that spends, so nothing that costs nothing is left unused.": "免费优先:成员中那个模型不花订阅额度或积分的排在前面,其余在后;每个成员整体尝试,各自按其供应商的路由在自己的账号或 Key 间分配。免费的先于任何花额度的,所以不花钱的一个都不剩下。",
|
||||
"Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with its key as Stays says.": "请求按每个密钥旁设置的权重分配:权重 3 的密钥每接 3 个请求,权重 1 的接 1 个,几个请求之内就均匀分开。出错的在休息期间被跳过,由其他密钥按各自权重分担;会话按「会话保持」的设置留在原来的密钥上。",
|
||||
"Requests spread over the keys or accounts by the weight set beside each: one weighing 3 takes three requests for every one weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with it as Stays says.": "请求按每个密钥或账号旁设置的权重分配:权重 3 的每接 3 个请求,权重 1 的接 1 个,几个请求之内就均匀分开。出错的在休息期间被跳过,由其他的按各自权重分担;会话按「会话保持」的设置留在原处。",
|
||||
"Weight {n} · {share}%": "权重 {n} · {share}%",
|
||||
"Its share of the requests: a key weighing 3 takes three for every one a key weighing 1 takes": "它在请求中的份额:权重 3 的密钥每接 3 个请求,权重 1 的接 1 个",
|
||||
"Its share of the requests: one weighing 3 takes three for every one weighing 1 takes": "它在请求中的份额:权重 3 的每接 3 个请求,权重 1 的接 1 个",
|
||||
"Weight {n}": "权重 {n}",
|
||||
"{key} weighs {n}": "{key} 的权重已设为 {n}",
|
||||
"Requests go to the first; the next takes over when the one before runs out of quota, hits a rate limit or fails.": "请求先发给第一个;它额度用完、被限流或出错时,由下一个接手。",
|
||||
@@ -4601,6 +4602,7 @@ const I18N = {
|
||||
"Its saved configuration will be removed. Agents using it may switch to another provider or their default model.": "這將刪除它的已儲存設定。使用它的 Agent 可能切換到其他供應商或預設模型。",
|
||||
"This account or key will stop being used for requests. You will need to add it again to use it.": "此帳戶或金鑰將不再用於請求。要再次使用,需要重新新增。",
|
||||
"Key weight": "金鑰權重",
|
||||
"Account weight": "帳號權重",
|
||||
"Saved middleware options will be removed. The plugin will run with no options.": "已儲存的中介軟體選項將被移除。外掛將不帶選項執行。",
|
||||
"Main navigation": "主導航",
|
||||
"Gateway keys": "閘道金鑰",
|
||||
@@ -5975,9 +5977,9 @@ const I18N = {
|
||||
"Cheapest first: no price is known for {model} on {who}, so it goes in its listed place after every one that has a price.": "最便宜優先:不知道 {model} 在 {who} 上的價格,所以它排在所有有價格的後面,按列出的位置。",
|
||||
"Requests go to what costs nothing first: the models their vendor serves at no cost to this subscription's allowance or credits, in their listed order, and only when those can't answer to one that spends them. Nothing that cost nothing is left unused.": "先把不花錢的用完:供應商對本訂閱的額度或點數不收費的模型排在前面,按它們原本的順序;這些都不能回應時,才用要花額度的。不花額度的一個都不剩下。",
|
||||
"Free first: the members whose model its vendor serves at no cost to the subscription's allowance or credits go first, then the rest — each whole, over its own accounts or keys as its provider routes them. The free ones are tried before any that spends, so nothing that costs nothing is left unused.": "免費優先:成員中那個模型不花訂閱額度或點數的排在前面,其餘在後;每個成員整體嘗試,各自依其供應商的路由在自己的帳號或 Key 間分配。免費的先於任何花額度的,所以不花錢的一個都不剩下。",
|
||||
"Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with its key as Stays says.": "請求按每個金鑰旁設定的權重分配:權重 3 的金鑰每接 3 個請求,權重 1 的接 1 個,幾個請求之內就均勻分開。出錯的在休息期間被跳過,由其他金鑰按各自權重分擔;會話按「會話保持」的設定留在原來的金鑰上。",
|
||||
"Requests spread over the keys or accounts by the weight set beside each: one weighing 3 takes three requests for every one weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with it as Stays says.": "請求按每個金鑰或帳號旁設定的權重分配:權重 3 的每接 3 個請求,權重 1 的接 1 個,幾個請求之內就均勻分開。出錯的在休息期間被跳過,由其他的按各自權重分擔;會話按「會話保持」的設定留在原處。",
|
||||
"Weight {n} · {share}%": "權重 {n} · {share}%",
|
||||
"Its share of the requests: a key weighing 3 takes three for every one a key weighing 1 takes": "它在請求中的份額:權重 3 的金鑰每接 3 個請求,權重 1 的接 1 個",
|
||||
"Its share of the requests: one weighing 3 takes three for every one weighing 1 takes": "它在請求中的份額:權重 3 的每接 3 個請求,權重 1 的接 1 個",
|
||||
"Weight {n}": "權重 {n}",
|
||||
"{key} weighs {n}": "{key} 的權重已設為 {n}",
|
||||
"Requests go to the first; the next takes over when the one before runs out of quota, hits a rate limit or fails.": "請求先發給第一個;它額度用完、被限流或出錯時,由下一個接手。",
|
||||
@@ -10184,9 +10186,9 @@ const I18N = {
|
||||
"Cheapest first: no price is known for {model} on {who}, so it goes in its listed place after every one that has a price.": "最安優先:{who} での {model} の価格が分からないため、価格のあるものすべての後ろ、設定順の位置に入ります。",
|
||||
"Requests go to what costs nothing first: the models their vendor serves at no cost to this subscription's allowance or credits, in their listed order, and only when those can't answer to one that spends them. Nothing that cost nothing is left unused.": "無料のものを先に使い切ります:提供元がこのサブスクリプションの利用枠やクレジットを消費しないモデルを、一覧の順に先に試し、それらが応答できないときだけ消費するものへ進みます。無料のものが残ることはありません。",
|
||||
"Free first: the members whose model its vendor serves at no cost to the subscription's allowance or credits go first, then the rest — each whole, over its own accounts or keys as its provider routes them. The free ones are tried before any that spends, so nothing that costs nothing is left unused.": "無料優先:提供元がサブスクリプションの利用枠やクレジットを消費しないモデルのメンバーを先に、残りを後に置きます。各メンバーはまとめて試され、それぞれの提供元のルーティングに従って自分のアカウントや Key に配分されます。無料のものは消費するものより先なので、無料のものは残りません。",
|
||||
"Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with its key as Stays says.": "各キーの横で設定した重みでリクエストを振り分けます。重み 3 のキーは、重み 1 のキーが 1 件受けるごとに 3 件受け、数件のうちに均等に分かれます。失敗したキーは休止中は飛ばされ、他のキーがそれぞれの重みで分担します。会話は「維持」の設定どおりそのキーにとどまります。",
|
||||
"Requests spread over the keys or accounts by the weight set beside each: one weighing 3 takes three requests for every one weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with it as Stays says.": "各キーやアカウントの横で設定した重みでリクエストを振り分けます。重み 3 のものは、重み 1 のものが 1 件受けるごとに 3 件受け、数件のうちに均等に分かれます。失敗したものは休止中は飛ばされ、他がそれぞれの重みで分担します。会話は「維持」の設定どおりそこにとどまります。",
|
||||
"Weight {n} · {share}%": "重み {n} · {share}%",
|
||||
"Its share of the requests: a key weighing 3 takes three for every one a key weighing 1 takes": "リクエストの取り分:重み 3 のキーは、重み 1 のキーが 1 件受けるごとに 3 件受けます",
|
||||
"Its share of the requests: one weighing 3 takes three for every one weighing 1 takes": "リクエストの取り分:重み 3 のものは、重み 1 のものが 1 件受けるごとに 3 件受けます",
|
||||
"Weight {n}": "重み {n}",
|
||||
"{key} weighs {n}": "{key} の重みを {n} にしました",
|
||||
"Requests go to the first; the next takes over when the one before runs out of quota, hits a rate limit or fails.": "リクエストは最初のものに送られます。クォータ切れ、レート制限、エラーのときは次のものが引き継ぎます。",
|
||||
@@ -12450,6 +12452,7 @@ const I18N = {
|
||||
"Its saved configuration will be removed. Agents using it may switch to another provider or their default model.": "保存した設定が削除されます。使用中のエージェントは別のプロバイダーまたは既定のモデルに切り替わる場合があります。",
|
||||
"This account or key will stop being used for requests. You will need to add it again to use it.": "このアカウントまたはキーはリクエストに使用されなくなります。再び使うには追加し直してください。",
|
||||
"Key weight": "キーの重み",
|
||||
"Account weight": "アカウントの重み",
|
||||
"Saved middleware options will be removed. The plugin will run with no options.": "保存したミドルウェアのオプションが削除されます。プラグインはオプションなしで実行されます。",
|
||||
"Main navigation": "メインナビゲーション",
|
||||
// agents' advice after a change (NOTICES)
|
||||
@@ -14423,9 +14426,9 @@ const I18N = {
|
||||
"Cheapest first: no price is known for {model} on {who}, so it goes in its listed place after every one that has a price.": "Günstigste zuerst: Für {model} bei {who} ist kein Preis bekannt, daher kommt es an seinem Platz in der Liste hinter alle mit Preis.",
|
||||
"Requests go to what costs nothing first: the models their vendor serves at no cost to this subscription's allowance or credits, in their listed order, and only when those can't answer to one that spends them. Nothing that cost nothing is left unused.": "Zuerst kommt, was nichts kostet: Modelle, die ihr Anbieter diesem Abonnement ohne Verbrauch von Kontingent oder Guthaben bereitstellt, in ihrer gelisteten Reihenfolge; erst wenn diese nicht antworten können, eines, das verbraucht. Nichts Kostenloses bleibt ungenutzt.",
|
||||
"Free first: the members whose model its vendor serves at no cost to the subscription's allowance or credits go first, then the rest — each whole, over its own accounts or keys as its provider routes them. The free ones are tried before any that spends, so nothing that costs nothing is left unused.": "Kostenlos zuerst: die Mitglieder, deren Modell ihr Anbieter dem Abonnement ohne Verbrauch von Kontingent oder Guthaben bereitstellt, kommen zuerst, dann die übrigen — jedes als Ganzes, über seine eigenen Konten oder Keys, wie es sein Anbieter routet. Die kostenlosen werden vor jedem verbrauchenden versucht, sodass nichts Kostenloses ungenutzt bleibt.",
|
||||
"Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with its key as Stays says.": "Anfragen verteilen sich nach dem Gewicht neben jedem Schlüssel: Einer mit Gewicht 3 bekommt drei Anfragen für jede, die einer mit Gewicht 1 bekommt, schon über wenige Anfragen gleichmäßig. Ein fehlschlagender wird übersprungen, solange er pausiert, und die anderen teilen sich seine Anfragen; ein Gespräch bleibt bei seinem Schlüssel, wie „Bleibt“ es sagt.",
|
||||
"Requests spread over the keys or accounts by the weight set beside each: one weighing 3 takes three requests for every one weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with it as Stays says.": "Anfragen verteilen sich nach dem Gewicht neben jedem Schlüssel oder Konto: Eines mit Gewicht 3 bekommt drei Anfragen für jede, die eines mit Gewicht 1 bekommt, schon über wenige Anfragen gleichmäßig. Eines, das fehlschlägt, wird übersprungen, solange es pausiert, und die anderen teilen sich seine Anfragen; ein Gespräch bleibt dort, wie „Bleibt“ es sagt.",
|
||||
"Weight {n} · {share}%": "Gewicht {n} · {share}%",
|
||||
"Its share of the requests: a key weighing 3 takes three for every one a key weighing 1 takes": "Sein Anteil an den Anfragen: Ein Schlüssel mit Gewicht 3 bekommt drei für jede, die einer mit Gewicht 1 bekommt",
|
||||
"Its share of the requests: one weighing 3 takes three for every one weighing 1 takes": "Sein Anteil an den Anfragen: Eines mit Gewicht 3 bekommt drei für jede, die eines mit Gewicht 1 bekommt",
|
||||
"Weight {n}": "Gewicht {n}",
|
||||
"{key} weighs {n}": "{key} hat jetzt Gewicht {n}",
|
||||
"Requests go to the first; the next takes over when the one before runs out of quota, hits a rate limit or fails.": "Anfragen gehen an das erste; das nächste übernimmt, wenn das vorherige kein Kontingent mehr hat, ein Rate-Limit erreicht oder fehlschlägt.",
|
||||
@@ -16679,6 +16682,7 @@ const I18N = {
|
||||
"Its saved configuration will be removed. Agents using it may switch to another provider or their default model.": "Die gespeicherte Konfiguration wird entfernt. Agenten, die sie verwenden, können zu einem anderen Anbieter oder ihrem Standardmodell wechseln.",
|
||||
"This account or key will stop being used for requests. You will need to add it again to use it.": "Dieses Konto oder dieser Schlüssel wird nicht mehr für Anfragen verwendet. Um es erneut zu verwenden, müssen Sie es wieder hinzufügen.",
|
||||
"Key weight": "Schlüsselgewicht",
|
||||
"Account weight": "Kontogewicht",
|
||||
"Saved middleware options will be removed. The plugin will run with no options.": "Die gespeicherten Middleware-Optionen werden entfernt. Das Plugin läuft ohne Optionen.",
|
||||
"Main navigation": "Hauptnavigation",
|
||||
// agents' advice after a change (NOTICES)
|
||||
|
||||
@@ -521,10 +521,10 @@ function routingPage(part) {
|
||||
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."],
|
||||
manual: ["Manual", "Manual: every request goes to the model picked on the group's card, over its own accounts or keys."],
|
||||
// the provider's key routing (#841); both strings as the provider
|
||||
// editor's routing options say them (app.js ROUTINGS), so every
|
||||
// language is already spoken
|
||||
weight: ["By weight", "Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with its key as Stays says."],
|
||||
// a provider's keys or a subscription's accounts by weight (#841,
|
||||
// rubbzha on X); both strings as the provider editor's routing options
|
||||
// say them (app.js ROUTINGS), so every language is already spoken
|
||||
weight: ["By weight", "Requests spread over the keys or accounts by the weight set beside each: one weighing 3 takes three requests for every one weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with it as Stays says."],
|
||||
free: ["Free first", "Requests go to what costs nothing first: the models their vendor serves at no cost to this subscription's allowance or credits, in their listed order, and only when those can't answer to one that spends them. Nothing that cost nothing is left unused."],
|
||||
cheap: ["Cheapest first", "Requests go to the member whose model costs least now, by its price a million tokens in and out at this hour — DeepSeek's peak hours count double — and the cheaper cache read when two cost the same; those that cost the same keep their listed order, and one with no known price goes last."],
|
||||
fast: ["Speed first", "Requests go to the one that has answered this model fastest lately, by its time to the first token and how fast it writes; those within a tenth of each other keep their listed order. One not measured lately gets one request in five, so it is measured again, and one that fails is passed over while it rests."],
|
||||
@@ -731,7 +731,7 @@ function routingPage(part) {
|
||||
? 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 "rotate": return t("In turn: it's {who}'s turn — each request starts one further along.", { who: w });
|
||||
case "weight": return t("By weight: it's {who}'s share — each key takes requests as its weight says.", { 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":
|
||||
if (f.free) return restedTo(t("it costs nothing there, so it's spent first."))
|
||||
|| t("Free first: {model} costs nothing on {who}, so it's tried before any that spends the allowance.", { model: f.model, who: w });
|
||||
@@ -7139,8 +7139,8 @@ function routingPage(part) {
|
||||
try { await api("provider/" + what, body); status(ok, "ok"); groups = groupsFrom(await api("groups")); load(); } catch (e) { status(e.message, "err"); }
|
||||
};
|
||||
const lab = (s, c) => { const w = el("span", "lab"); w.append(el("small", "", s), c); return w; };
|
||||
// by weight is a key's share (#841), set beside each key in the provider's editor
|
||||
const opts = withJS(p.kind === "account" ? ROUTE_OPTS : [...ROUTE_OPTS, ["weight", "By weight"]], p.routing);
|
||||
// by weight: each key's or account's share (#841), set beside it in the provider's editor
|
||||
const opts = withJS([...ROUTE_OPTS, ["weight", "By weight"]], p.routing);
|
||||
ctl.append(
|
||||
lab(t("Routing"), routingSegs(opts.map(([id, n, js]) => [id, t(n), , js]), p.routing || "", (v) => set("route", { id: p.provider, routing: v }, t("{name}: {routing}", { name: p.name, routing: t(opts.find(([id]) => id === v)[1]) })))),
|
||||
lab(t("Stays"), segs(AFF_OPTS.map(([id, n]) => [id, t(n)]), p.affinity || "", (v) => set("affinity", { id: p.provider, affinity: v }, t("{name}: {routing}", { name: p.name, routing: t(AFF_OPTS.find(([id]) => id === v)[1]) })))));
|
||||
|
||||
@@ -45,6 +45,7 @@ magpie.strings({
|
||||
"{name} switched off": "已关闭 {name}",
|
||||
"in {groups}": "已在 {groups}",
|
||||
"By weight: it's {who}'s share \u2014 each key takes requests as its weight says.": "按权重:轮到 {who} 的份额——每个密钥按自己的权重接请求。",
|
||||
"By weight: it's {who}'s share \u2014 each account takes requests as its weight says.": "按权重:轮到 {who} 的份额——每个账号按自己的权重接请求。",
|
||||
"By weight: it's {who}'s share — each model takes requests as the weight set beside it says.": "按权重:轮到 {who} 的份额——每个模型按旁边设置的权重接请求。",
|
||||
"By weight: each model takes its share of the requests by the weight set beside it — one weighing 3 three for every one a model weighing 1 takes, spread out rather than in bursts. One resting after a failure leaves the round and the others share its requests; the next model is the fallback when one fails.": "按权重:每个模型按旁边设置的权重分得请求——权重 3 的模型每接 3 个,权重 1 的接 1 个,均匀穿插而不是成批连发。失败后休息中的模型退出这一轮,其余模型分担它的请求;某个模型失败时,由下一个模型接替。",
|
||||
"Its share of the requests: a model weighing 3 takes three for every one a model weighing 1 takes": "它在请求中的份额:权重 3 的模型每接 3 个请求,权重 1 的接 1 个",
|
||||
@@ -660,6 +661,7 @@ magpie.strings({
|
||||
"{name} switched off": "已關閉 {name}",
|
||||
"in {groups}": "已在 {groups}",
|
||||
"By weight: it's {who}'s share — each key takes requests as its weight says.": "按權重:輪到 {who} 的份額——每個金鑰按自己的權重接請求。",
|
||||
"By weight: it's {who}'s share \u2014 each account takes requests as its weight says.": "按權重:輪到 {who} 的份額——每個帳號按自己的權重接請求。",
|
||||
"By weight: it's {who}'s share — each model takes requests as the weight set beside it says.": "按權重:輪到 {who} 的份額——每個模型按旁邊設定的權重接請求。",
|
||||
"By weight: each model takes its share of the requests by the weight set beside it — one weighing 3 three for every one a model weighing 1 takes, spread out rather than in bursts. One resting after a failure leaves the round and the others share its requests; the next model is the fallback when one fails.": "按權重:每個模型按旁邊設定的權重分得請求——權重 3 的模型每接 3 個,權重 1 的接 1 個,均勻穿插而不是成批連發。失敗後休息中的模型退出這一輪,其餘模型分擔它的請求;某個模型失敗時,由下一個模型接替。",
|
||||
"Its share of the requests: a model weighing 3 takes three for every one a model weighing 1 takes": "它在請求中的份額:權重 3 的模型每接 3 個請求,權重 1 的接 1 個",
|
||||
@@ -1253,6 +1255,7 @@ magpie.strings({
|
||||
"{name} switched off": "{name} をオフにしました",
|
||||
"in {groups}": "{groups} に追加済み",
|
||||
"By weight: it's {who}'s share \u2014 each key takes requests as its weight says.": "重み付け:{who} の取り分です——各キーは重みどおりにリクエストを受けます。",
|
||||
"By weight: it's {who}'s share \u2014 each account takes requests as its weight says.": "重み付け:{who} の取り分です——各アカウントは重みどおりにリクエストを受けます。",
|
||||
"By weight: it's {who}'s share — each model takes requests as the weight set beside it says.": "重み付け:{who} の取り分です——各モデルは横に設定した重みどおりにリクエストを受けます。",
|
||||
"By weight: each model takes its share of the requests by the weight set beside it — one weighing 3 three for every one a model weighing 1 takes, spread out rather than in bursts. One resting after a failure leaves the round and the others share its requests; the next model is the fallback when one fails.": "重み付け:各モデルは横に設定した重みに応じてリクエストを受けます。重み 3 のモデルは、重み 1 のモデルが 1 件受けるごとに 3 件受け、まとめてではなく分散して届きます。失敗して休止中のモデルは巡回から外れ、残りがその分を分け合います。あるモデルが失敗したときは次のモデルが引き継ぎます。",
|
||||
"Its share of the requests: a model weighing 3 takes three for every one a model weighing 1 takes": "リクエストの取り分:重み 3 のモデルは、重み 1 のモデルが 1 件受けるごとに 3 件受けます",
|
||||
@@ -1858,6 +1861,7 @@ magpie.strings({
|
||||
"{name} switched off": "{name} ausgeschaltet",
|
||||
"in {groups}": "in {groups}",
|
||||
"By weight: it's {who}'s share \u2014 each key takes requests as its weight says.": "Nach Gewicht: {who} ist mit seinem Anteil dran — jeder Schlüssel bekommt Anfragen nach seinem Gewicht.",
|
||||
"By weight: it's {who}'s share \u2014 each account takes requests as its weight says.": "Nach Gewicht: {who} ist mit seinem Anteil dran — jedes Konto bekommt Anfragen nach seinem Gewicht.",
|
||||
"By weight: it's {who}'s share — each model takes requests as the weight set beside it says.": "Nach Gewicht: {who} ist mit seinem Anteil dran — jedes Modell bekommt Anfragen nach dem Gewicht, das daneben eingestellt ist.",
|
||||
"By weight: each model takes its share of the requests by the weight set beside it — one weighing 3 three for every one a model weighing 1 takes, spread out rather than in bursts. One resting after a failure leaves the round and the others share its requests; the next model is the fallback when one fails.": "Nach Gewicht: Jedes Modell bekommt seinen Anteil an den Anfragen nach dem Gewicht daneben – eines mit Gewicht 3 drei für jede, die ein Modell mit Gewicht 1 bekommt, verteilt statt in Schüben. Eines, das nach einem Fehler pausiert, setzt aus, und die anderen teilen sich seine Anfragen; scheitert eines, springt das nächste Modell ein.",
|
||||
"Its share of the requests: a model weighing 3 takes three for every one a model weighing 1 takes": "Sein Anteil an den Anfragen: Ein Modell mit Gewicht 3 bekommt drei für jede, die eines mit Gewicht 1 bekommt",
|
||||
|
||||
@@ -246,6 +246,9 @@ type providerJSON struct {
|
||||
// each key's or account's own limit over it (#892), by its name in
|
||||
// lower case or its key id; 0 there is none
|
||||
AccountConcurrency map[string]int `json:"accountConcurrency,omitempty"`
|
||||
// each subscription account's weight under By weight routing, by its
|
||||
// name in lower case; one not in it weighs 1 (provider.AccountWeights)
|
||||
AccountWeights map[string]int `json:"accountWeights,omitempty"`
|
||||
// how many may wait for each key or account, and for how many seconds
|
||||
// (0: no bound)
|
||||
QueueLimit int `json:"queueLimit,omitempty"`
|
||||
@@ -648,7 +651,7 @@ func providerInfoWith(p provider.Provider, agents []agentUse, desktop map[string
|
||||
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts,
|
||||
MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), PriceRate: p.PriceRate,
|
||||
RateWindows: p.RateWindows, RateNow: rateNowOf(p, time.Now()),
|
||||
AccountConcurrency: p.AccountConcurrency, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM,
|
||||
AccountConcurrency: p.AccountConcurrency, AccountWeights: p.AccountWeights, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM,
|
||||
Outputs: provider.OutputsOf(p.ID), Compacts: provider.CompactsOf(p.ID),
|
||||
}
|
||||
if p.Account != nil {
|
||||
@@ -1357,6 +1360,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
// it follow the account's cap
|
||||
Cap int `json:"cap"`
|
||||
Window string `json:"window"`
|
||||
// Weight, for accountweight: the account's share under By
|
||||
// weight routing, 1 to provider.MaxKeyWeight (0 or 1: none)
|
||||
Weight int `json:"weight"`
|
||||
// Alias, for accountname: the account's name of the user's
|
||||
// own, "" to take it off (#1515)
|
||||
Alias string `json:"alias"`
|
||||
@@ -1700,11 +1706,13 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
if old != nil {
|
||||
in.AccountModels = old.AccountModels
|
||||
}
|
||||
// and their usage caps, with accountcap and windowcap, and their
|
||||
// limits on requests at once, with accountconcurrency
|
||||
// and their usage caps, with accountcap and windowcap, their
|
||||
// limits on requests at once, with accountconcurrency, and
|
||||
// their weights, with accountweight
|
||||
if old != nil {
|
||||
in.AccountCaps, in.AccountWindowCaps = old.AccountCaps, old.AccountWindowCaps
|
||||
in.AccountConcurrency = old.AccountConcurrency
|
||||
in.AccountWeights = old.AccountWeights
|
||||
in.AccountNames = old.AccountNames // with accountname
|
||||
}
|
||||
// the image models unticked in its editor likewise: []
|
||||
@@ -1934,6 +1942,11 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
case "accountweight":
|
||||
if err := provider.SetAccountWeight(in.ID, req.Account, req.Weight); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
case "route":
|
||||
if err := provider.SetRouting(in.ID, in.Routing); err != nil {
|
||||
fail(rw, err)
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A subscription's accounts by weight (rubbzha on X: a Max account and a
|
||||
// Pro one, shared by how much more one allows). The provider editor's
|
||||
// Routing offers By weight for accounts as it does for keys, and with it
|
||||
// picked each account in use shows its weight and its share beside its
|
||||
// name, as a key does; a click edits it in place and posts
|
||||
// provider/accountweight. Hidden under the other routings. Each line stays
|
||||
// one line, with nothing past the sheet's edge, at the window's narrowest
|
||||
// and in a phone's browser, in every language, without the page scrolling.
|
||||
// MAGPIE_ACC_ASSETS runs it on older assets.
|
||||
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(process.env.MAGPIE_ACC_ASSETS || path.resolve(__dirname, "../assets"));
|
||||
const claude = () => ({
|
||||
id: "claude", name: "Claude Code", icon: "claude-color", chat: "", responses: "", anthropic: "", catalog: "", routing: "",
|
||||
models: [{ id: "claude-opus-5-5", name: "Claude Opus 5.5", on: true }], agents: [], fallback: [], headers: {}, keyList: [],
|
||||
account: {
|
||||
agent: "claude", agentName: "Claude Code", user: "max@example.com", plan: "max",
|
||||
logins: [
|
||||
{ user: "max@example.com", plan: "max", active: true, on: true },
|
||||
{ user: "pro@example.com", plan: "pro", on: true },
|
||||
{ user: "off@example.com", plan: "pro", on: false },
|
||||
],
|
||||
},
|
||||
accountWeights: { "max@example.com": 3 },
|
||||
});
|
||||
|
||||
function serve(lang, web, posts) {
|
||||
const p = claude();
|
||||
const providers = { providers: [p], presets: [], excluded: [], gateway: { running: true, window: true } };
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",web:${web}};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
|
||||
if (url.pathname === "/api/providers") return json(providers);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/login/usage") return json({
|
||||
"max@example.com": { windows: [{ label: "5h", used: 10, limit: 100 }] },
|
||||
"pro@example.com": { windows: [{ label: "5h", used: 30, limit: 100 }] },
|
||||
});
|
||||
if (url.pathname === "/api/provider/accountweight" && route.request().method() === "POST") {
|
||||
const body = route.request().postDataJSON();
|
||||
posts.push(body);
|
||||
p.accountWeights = { ...p.accountWeights, [body.account.toLowerCase()]: body.weight };
|
||||
return json(providers);
|
||||
}
|
||||
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)];
|
||||
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
|
||||
};
|
||||
}
|
||||
|
||||
// the app's own words, as t() gives them
|
||||
const say = (page, lang, key, vars = {}) => page.evaluate(([lang, key, vars]) => ((lang !== "en" && I18N[lang]?.[key]) || key).replace(/\{(\w+)\}/g, (_, k) => vars[k]), [lang, key, vars]);
|
||||
|
||||
const langs = ["en", "zh", "zh-TW", "ja", "de"];
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(`${engine}: By weight shows each account's weight and share, and a click sets it`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
for (const [web, width] of [[false, 1000], [false, 560], [true, 390]]) for (const lang of langs) {
|
||||
const at = `${lang} ${web ? "web " : ""}${width}`;
|
||||
const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const posts = [];
|
||||
await page.route("**/*", serve(lang, web, posts));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
await page.locator(".row.provider", { hasText: "Claude Code" }).first().click();
|
||||
await page.locator('.editor .acc[data-account-id="off@example.com"]').waitFor();
|
||||
const chip = (id) => page.locator(`.editor .acc[data-account-id="${id}"] .key-weight`);
|
||||
const scrolled = () => page.evaluate(() => [window.scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop > 0).map((e) => `${e.className}:${e.scrollTop}`)].join(" "));
|
||||
|
||||
// Smart: no weights shown
|
||||
assert.equal(await chip("max@example.com").isVisible(), false, `${at}: a weight under Smart`);
|
||||
const by = page.locator(".editor").getByRole("button", { name: await say(page, lang, "By weight"), exact: true });
|
||||
await by.scrollIntoViewIfNeeded();
|
||||
const sc = await scrolled();
|
||||
await by.click();
|
||||
assert.equal(await scrolled(), sc, `${at}: a click scrolled`);
|
||||
// the routing's hint names accounts too
|
||||
await page.locator(".editor .hint", { hasText: (await say(page, lang, "Requests spread over the keys or accounts by the weight set beside each: one weighing 3 takes three requests for every one weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with it as Stays says.")).slice(0, 20) }).first().waitFor();
|
||||
assert.equal((await chip("max@example.com").textContent()).trim(), await say(page, lang, "Weight {n} · {share}%", { n: 3, share: 75 }), at);
|
||||
assert.equal((await chip("pro@example.com").textContent()).trim(), await say(page, lang, "Weight {n} · {share}%", { n: 1, share: 25 }), at);
|
||||
assert.equal(await chip("off@example.com").count(), 0, `${at}: an account not in use has no share`);
|
||||
|
||||
// each line one line, nothing past its row
|
||||
const fit = await page.evaluate(() => [...document.querySelectorAll(".editor .accts .acc[data-account-id]")].map((r) => {
|
||||
const line = r.querySelector(".acc-line"), c = r.querySelector(".key-weight");
|
||||
return { who: r.dataset.accountId, h: Math.round(line.getBoundingClientRect().height), over: line.scrollWidth - line.clientWidth, out: c ? Math.round(c.getBoundingClientRect().right - r.getBoundingClientRect().right) : -1 };
|
||||
}));
|
||||
for (const f of fit) {
|
||||
assert.ok(f.h <= (web ? 48 : 24), `${at}: ${f.who}'s line is one line (${f.h}px)`);
|
||||
assert.ok(f.over <= 1 && f.out <= 0, `${at}: ${f.who}'s line runs past its row (${f.over}, ${f.out})`);
|
||||
}
|
||||
if (process.env.ARTIFACT_DIR && lang === "en") {
|
||||
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
await page.locator(".editor .accts").screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${web ? "web-" : ""}${width}-account-weight.png`) });
|
||||
}
|
||||
|
||||
// a click edits it in place, Enter saves it
|
||||
await chip("pro@example.com").click();
|
||||
const box = page.locator('.editor .acc[data-account-id="pro@example.com"] .key-weight-in');
|
||||
await box.waitFor();
|
||||
assert.equal(await box.getAttribute("aria-label"), await say(page, lang, "Account weight"), at);
|
||||
assert.equal(await scrolled(), sc, `${at}: a click scrolled`);
|
||||
await box.fill("2");
|
||||
await box.press("Enter");
|
||||
for (let i = 0; i < 60 && !posts.length; i++) await new Promise((r) => setTimeout(r, 50));
|
||||
assert.deepEqual(posts.at(-1), { id: "claude", account: "pro@example.com", weight: 2 }, at);
|
||||
await chip("pro@example.com").filter({ hasText: await say(page, lang, "Weight {n} · {share}%", { n: 2, share: 40 }) }).waitFor();
|
||||
assert.equal((await chip("max@example.com").textContent()).trim(), await say(page, lang, "Weight {n} · {share}%", { n: 3, share: 60 }), at);
|
||||
// said once state is read again, after the chips are drawn: wait for it
|
||||
const note = await say(page, lang, "{key} weighs {n}", { key: "pro@example.com", n: 2 });
|
||||
await page.waitForFunction((n) => document.querySelector("#status")?.textContent.trim() == n, note).catch(() => {});
|
||||
assert.equal((await page.locator("#status").textContent()).trim(), note, at);
|
||||
|
||||
// back to Smart hides them
|
||||
await page.locator(".editor").getByRole("button", { name: await say(page, lang, "Smart"), exact: true }).first().click();
|
||||
assert.equal(await chip("max@example.com").isVisible(), false, `${at}: a weight under Smart`);
|
||||
assert.deepEqual(errors, [], at);
|
||||
await context.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -104,6 +104,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
assert.equal((await chip("aaaaaaaaaa").textContent()).trim(), w.a2);
|
||||
// still shown: the routing picked stays in the editor's draft
|
||||
assert.equal(await chip("bbbbbbbbbb").isVisible(), true);
|
||||
// said once state is read again, after the chips are drawn: wait for it
|
||||
await page.waitForFunction((n) => document.querySelector("#status")?.textContent.trim() == n, w.note).catch(() => {});
|
||||
assert.equal((await page.locator("#status").textContent()).trim(), w.note);
|
||||
|
||||
if (process.env.ARTIFACT_DIR) await page.locator(".editor .accts").screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-key-weight-rows.png`) });
|
||||
|
||||
@@ -78,7 +78,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await page.locator(".rt-prov span").filter({ hasText: chip[lang] }).first().waitFor();
|
||||
const say = (key, vars = {}) => page.evaluate(([lang, key, vars]) => ((lang !== "en" && I18N[lang]?.[key]) || key).replace(/\{(\w+)\}/g, (_, k) => vars[k]), [lang, key, vars]);
|
||||
assert.equal((await page.locator(".rt-mode").textContent()).trim(),
|
||||
await say("Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with its key as Stays says."));
|
||||
await say("Requests spread over the keys or accounts by the weight set beside each: one weighing 3 takes three requests for every one weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with it as Stays says."));
|
||||
// the story says whose share went first
|
||||
await page.locator(".rt-steps li.why").first().waitFor();
|
||||
assert.equal((await page.locator(".rt-steps li.why").first().textContent()).trim(),
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package provider
|
||||
|
||||
// An account's weight (rubbzha on X): a subscription routed by weight
|
||||
// spreads its requests over its accounts as a provider's keys are (#841),
|
||||
// each by the weight set beside it — a Max account allowing several times
|
||||
// what a Pro one does takes that many requests for each the Pro one takes,
|
||||
// so both are used to the end rather than the first run out mid-task. It
|
||||
// is kept per account by its name in lower case (AccountWeights), as its
|
||||
// other settings are; one with none weighs 1. Nothing sets one for the
|
||||
// user, whatever the plan: the plans' allowances aren't told in requests.
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// AccountWeight is the weight of the account user of p under Weighted
|
||||
// routing, 1 when it has none. The accounts All and AlsoOn give carry it,
|
||||
// as the gateway routes them; it is read from p alone, with no file read,
|
||||
// as it is asked for every account of every request weighed.
|
||||
func (p Provider) AccountWeight(user string) int {
|
||||
return max(p.AccountWeights[accountKey(user)], 1)
|
||||
}
|
||||
|
||||
// SetAccountWeight gives the account ref of the subscription id its weight
|
||||
// under Weighted routing, 1 to MaxKeyWeight; 0 or 1 is the default, kept
|
||||
// as none.
|
||||
func SetAccountWeight(id, ref string, weight int) error {
|
||||
if weight < 0 || weight > MaxKeyWeight {
|
||||
return fmt.Errorf("an account's weight is 1 to %d, not %d", MaxKeyWeight, weight)
|
||||
}
|
||||
p, err := Find(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Account == nil {
|
||||
return fmt.Errorf("%s has keys, not subscription accounts: a key's weight is set on the key", p.Name)
|
||||
}
|
||||
r, ok := p.accountRef(ref)
|
||||
if !ok {
|
||||
return fmt.Errorf("%s has no account %q", p.Name, ref)
|
||||
}
|
||||
k := accountKey(r)
|
||||
if max(p.AccountWeights[k], 1) == max(weight, 1) {
|
||||
return nil
|
||||
}
|
||||
m := map[string]int{}
|
||||
for u, w := range p.AccountWeights {
|
||||
m[u] = w
|
||||
}
|
||||
if weight <= 1 {
|
||||
delete(m, k)
|
||||
} else {
|
||||
m[k] = weight
|
||||
}
|
||||
p.AccountWeights = m
|
||||
return Save(*p)
|
||||
}
|
||||
|
||||
// ParseWeight reads a weight as the CLI takes it: a whole number from 1
|
||||
// to MaxKeyWeight, or default (-, 0) for 1.
|
||||
func ParseWeight(s string) (int, error) {
|
||||
s = strings.ToLower(strings.TrimSpace(s))
|
||||
switch s {
|
||||
case "default", "-", "0":
|
||||
return 1, nil
|
||||
}
|
||||
n, err := strconv.Atoi(s)
|
||||
if err != nil || n < 1 || n > MaxKeyWeight {
|
||||
return 0, fmt.Errorf("a weight is a whole number from 1 to %d, or default, not %q", MaxKeyWeight, s)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// normalAccountWeights is m as it is kept: keys in lower case, weights
|
||||
// within 2–MaxKeyWeight, the default 1 left out; nil for none.
|
||||
func normalAccountWeights(m map[string]int) map[string]int {
|
||||
var out map[string]int
|
||||
for u, w := range m {
|
||||
u = accountKey(u)
|
||||
if u == "" || w <= 1 {
|
||||
continue
|
||||
}
|
||||
if out == nil {
|
||||
out = map[string]int{}
|
||||
}
|
||||
out[u] = min(w, MaxKeyWeight)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// An account's weight is kept by its name in lower case, 1 left out of the
|
||||
// file, a weight out of 0–MaxKeyWeight or an account the subscription
|
||||
// hasn't refused, a provider with keys refused (its keys have their own);
|
||||
// the accounts All gives carry it, as the gateway routes them.
|
||||
func TestSetAccountWeight(t *testing.T) {
|
||||
signIn(t) // me@example.com on codex
|
||||
if err := SetAccountWeight("codex", "Me@Example.com", 4); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, err := Find("codex")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := p.AccountWeight("ME@example.com"); w != 4 {
|
||||
t.Fatalf("weight %d", w)
|
||||
}
|
||||
if p.AccountWeights["me@example.com"] != 4 {
|
||||
t.Fatalf("kept as %v", p.AccountWeights)
|
||||
}
|
||||
carried := false
|
||||
for _, a := range All() {
|
||||
if a.ID == "codex" && a.Account != nil && strings.EqualFold(a.Account.User, "me@example.com") {
|
||||
carried = a.AccountWeight(a.Account.User) == 4
|
||||
}
|
||||
}
|
||||
if !carried {
|
||||
t.Fatal("the account All gives doesn't weigh 4")
|
||||
}
|
||||
for _, bad := range []int{-1, MaxKeyWeight + 1} {
|
||||
if err := SetAccountWeight("codex", "me@example.com", bad); err == nil {
|
||||
t.Fatalf("%d taken", bad)
|
||||
}
|
||||
}
|
||||
if err := SetAccountWeight("codex", "nobody@example.com", 2); err == nil {
|
||||
t.Fatal("an account it hasn't was weighed")
|
||||
}
|
||||
if err := SetAccountWeight("codex", "me@example.com", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := os.ReadFile(Path())
|
||||
if strings.Contains(string(b), "accountWeights") {
|
||||
t.Fatalf("1 was written: %s", b)
|
||||
}
|
||||
if err := Save(Provider{ID: "relay", Name: "Relay", Key: "k1", Chat: "http://127.0.0.1:1/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SetAccountWeight("relay", "k1", 3); err == nil {
|
||||
t.Fatal("a key provider's account was weighed")
|
||||
}
|
||||
if got := normalAccountWeights(map[string]int{" A@x ": 2, "b": 1, "c": 5000}); len(got) != 2 || got["a@x"] != 2 || got["c"] != MaxKeyWeight {
|
||||
t.Fatalf("normal %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A Copilot account renamed on GitHub keeps its weight under its new name.
|
||||
func TestAccountWeightMovesWithRename(t *testing.T) {
|
||||
signIn(t)
|
||||
if err := Save(Provider{ID: "copilot", Name: "Copilot", Account: &Account{}, AccountWeights: map[string]int{"old": 3}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := moveAccountSettings("copilot", map[string]string{"Old": "New"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, err := read()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := false
|
||||
for _, p := range f.Providers {
|
||||
if p.ID == "copilot" {
|
||||
found = true
|
||||
if p.AccountWeights["new"] != 3 || p.AccountWeights["old"] != 0 {
|
||||
t.Fatalf("weights after the rename %v", p.AccountWeights)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("copilot not saved")
|
||||
}
|
||||
}
|
||||
@@ -167,6 +167,7 @@ func moveAccountSettings(id string, moves map[string]string) error {
|
||||
moved = moveKey(p.AccountCaps, from, to) || moved
|
||||
moved = moveKey(p.AccountWindowCaps, from, to) || moved
|
||||
moved = moveKey(p.AccountConcurrency, from, to) || moved
|
||||
moved = moveKey(p.AccountWeights, from, to) || moved
|
||||
moved = moveKey(p.AccountNames, from, to) || moved
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,6 +167,11 @@ type Provider struct {
|
||||
// by its KeyID; 0 there is no limit for it. One not in it takes the
|
||||
// provider's (see LaneLimit).
|
||||
AccountConcurrency map[string]int `json:"accountConcurrency,omitempty"`
|
||||
// AccountWeights is, for a subscription, each account's weight under
|
||||
// Weighted routing, by its name in lower case (rubbzha on X: a Max
|
||||
// account and a Pro one shared by how much more one allows); one not
|
||||
// in it weighs 1. A key's weight is its own (KeyAccount.Weight).
|
||||
AccountWeights map[string]int `json:"accountWeights,omitempty"`
|
||||
// QueueLimit is how many requests may wait for a slot of each key or
|
||||
// account at once (#892); one more is turned away as the queue being
|
||||
// full. 0 is no bound.
|
||||
@@ -726,6 +731,7 @@ func (p Provider) clone() Provider {
|
||||
p.AccountWindowCaps = m
|
||||
}
|
||||
p.AccountConcurrency = maps.Clone(p.AccountConcurrency)
|
||||
p.AccountWeights = maps.Clone(p.AccountWeights)
|
||||
p.Contexts = maps.Clone(p.Contexts)
|
||||
if p.AccountModels != nil {
|
||||
m := make(map[string][]string, len(p.AccountModels))
|
||||
@@ -809,6 +815,7 @@ func withPicks(a, pk Provider) Provider {
|
||||
a.AccountNames = pk.AccountNames
|
||||
a.MaxConcurrency, a.PinUpstream = pk.MaxConcurrency, pk.PinUpstream
|
||||
a.AccountConcurrency, a.QueueLimit, a.QueueWait = pk.AccountConcurrency, pk.QueueLimit, pk.QueueWait
|
||||
a.AccountWeights = pk.AccountWeights
|
||||
a.MaxRPM = pk.MaxRPM
|
||||
// what it bills against the official price (#819): an account's editor
|
||||
// sets it as a key provider's does (PaulT on Discord, Codex)
|
||||
@@ -952,7 +959,7 @@ func Save(p Provider) error {
|
||||
if p.ID == "kiro" {
|
||||
key = p.Key
|
||||
}
|
||||
p = Provider{ID: p.ID, Key: key, Models: p.Models, NoModels: p.NoModels, BestInFamily: p.BestInFamily, RateWindows: p.RateWindows, PickedFrom: p.PickedFrom, Delisted: p.Delisted, Unlisted: p.Unlisted, HiddenDrawers: p.HiddenDrawers, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, CapStop: p.CapStop, CapCareful: p.CapCareful, AccountNames: p.AccountNames, MaxConcurrency: p.MaxConcurrency, AccountConcurrency: p.AccountConcurrency, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, PriceRate: p.PriceRate, CountFree: p.CountFree, QuotaRest: p.QuotaRest, QuotaResetAt: p.QuotaResetAt, RestCap: p.RestCap, PinUpstream: p.PinUpstream, NativeCompaction: p.NativeCompaction, PromptAsWritten: p.PromptAsWritten, Unredacted: p.Unredacted, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID), Tucked: tuckedAccount(p.ID)}
|
||||
p = Provider{ID: p.ID, Key: key, Models: p.Models, NoModels: p.NoModels, BestInFamily: p.BestInFamily, RateWindows: p.RateWindows, PickedFrom: p.PickedFrom, Delisted: p.Delisted, Unlisted: p.Unlisted, HiddenDrawers: p.HiddenDrawers, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, CapStop: p.CapStop, CapCareful: p.CapCareful, AccountNames: p.AccountNames, MaxConcurrency: p.MaxConcurrency, AccountConcurrency: p.AccountConcurrency, AccountWeights: p.AccountWeights, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, PriceRate: p.PriceRate, CountFree: p.CountFree, QuotaRest: p.QuotaRest, QuotaResetAt: p.QuotaResetAt, RestCap: p.RestCap, PinUpstream: p.PinUpstream, NativeCompaction: p.NativeCompaction, PromptAsWritten: p.PromptAsWritten, Unredacted: p.Unredacted, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID), Tucked: tuckedAccount(p.ID)}
|
||||
} else {
|
||||
p.AccountProxies = keyProxies(p) // a provider of keys proxies each key apart
|
||||
if subscriptionID(p.ID) && !stored(p.ID) {
|
||||
@@ -1489,6 +1496,7 @@ func normalize(p Provider) Provider {
|
||||
p.MaxConcurrency = new(int)
|
||||
}
|
||||
p.AccountConcurrency = normalAccountConcurrency(p.AccountConcurrency)
|
||||
p.AccountWeights = normalAccountWeights(p.AccountWeights)
|
||||
p.QueueLimit, p.QueueWait = min(max(p.QueueLimit, 0), MaxQueueLimit), min(max(p.QueueWait, 0), MaxQueueWait)
|
||||
p.MaxRPM = min(max(p.MaxRPM, 0), MaxRPMLimit)
|
||||
p.QuotaRest = min(max(p.QuotaRest, 0), MaxQuotaRest)
|
||||
|
||||
@@ -26,7 +26,9 @@ const (
|
||||
LeastUsed = "usage"
|
||||
Pace = "pace"
|
||||
// Weighted spreads a provider's requests over its keys by each key's
|
||||
// weight (KeyAccount.Weight, #841), smoothly: 3 and 1 go a, a, b, a…
|
||||
// weight (KeyAccount.Weight, #841), or a subscription's over its
|
||||
// accounts by each account's (AccountWeights), smoothly: 3 and 1 go
|
||||
// a, a, b, a…
|
||||
Weighted = "weight"
|
||||
// FreeFirst spends what costs nothing first: the models its vendor
|
||||
// serves at no cost to the subscription's allowance or credits, before
|
||||
|
||||
@@ -166,7 +166,7 @@
|
||||
</figure>
|
||||
|
||||
<h3>1 つのプロバイダに複数のアカウントやキー</h3>
|
||||
<p>プロバイダの行を開き、使うアカウントやキーをすべてチェックします。<span class="ui">Routing</span> はリクエストをそれらにどう振り分けるかを決めます:<span class="ui">Smart</span>(デフォルト)、<span class="ui">In order</span>、<span class="ui">In turn</span>、<span class="ui">Least used first</span>、<span class="ui">Weekly pace</span>、<span class="ui">Speed first</span>(最近いちばん速く応答したキーが先)。<span class="ui">Fallback</span> には、プロバイダのクォータ切れ、レート制限、ダウン時に代わりに使うモデルを並べます。</p>
|
||||
<p>プロバイダの行を開き、使うアカウントやキーをすべてチェックします。<span class="ui">Routing</span> はリクエストをそれらにどう振り分けるかを決めます:<span class="ui">Smart</span>(デフォルト)、<span class="ui">In order</span>、<span class="ui">In turn</span>、<span class="ui">Least used first</span>、<span class="ui">Weekly pace</span>、<span class="ui">By weight</span>(各アカウントやキーが横で設定した重みで取り分を受けます。たとえば Max アカウントは 5、Pro は 1)、<span class="ui">Speed first</span>(最近いちばん速く応答したキーが先)。<span class="ui">Fallback</span> には、プロバイダのクォータ切れ、レート制限、ダウン時に代わりに使うモデルを並べます。</p>
|
||||
|
||||
<h3>1 つのモデルを複数のプロバイダで</h3>
|
||||
<p>グループとは、1 つまたは複数のプロバイダのモデルを、エージェントが 1 つとして選べるようにまとめたものです。ピッカーの <em>Routing groups</em> の下に <code>group/<id></code> として表示されます。2 つのプロバイダが同じ名前で提供しているモデルは、それだけでグループになります。<span class="ui">Routing</span> タブの <span class="ui">New group</span> では、好きなモデルを組み合わせてグループを作れます。グループで何ができるかは、最初のモデルが基準になります。</p>
|
||||
|
||||
@@ -166,7 +166,7 @@
|
||||
</figure>
|
||||
|
||||
<h3>Several accounts or keys in one provider</h3>
|
||||
<p>Open the provider’s row and tick every account or key to use. <span class="ui">Routing</span> says how requests spread over them: <span class="ui">Smart</span> (the default), <span class="ui">In order</span>, <span class="ui">In turn</span>, <span class="ui">Least used first</span>, <span class="ui">Weekly pace</span> or <span class="ui">Speed first</span>, the key that answered fastest lately first. <span class="ui">Fallback</span> lists models to use instead when the provider is out of quota, rate limited or down.</p>
|
||||
<p>Open the provider’s row and tick every account or key to use. <span class="ui">Routing</span> says how requests spread over them: <span class="ui">Smart</span> (the default), <span class="ui">In order</span>, <span class="ui">In turn</span>, <span class="ui">Least used first</span>, <span class="ui">Weekly pace</span>, <span class="ui">By weight</span>, each account or key taking its share by the weight set beside it (a Max account 5, a Pro one 1), or <span class="ui">Speed first</span>, the key that answered fastest lately first. <span class="ui">Fallback</span> lists models to use instead when the provider is out of quota, rate limited or down.</p>
|
||||
|
||||
<h3>One model over several providers</h3>
|
||||
<p>A group is several models, from one provider or many, that an agent picks as one: <code>group/<id></code>, under <em>Routing groups</em> in the picker. A model two of your providers serve under the same name becomes a group on its own; <span class="ui">New group</span> in the <span class="ui">Routing</span> tab makes one of any models you like. The first model answers for what the group can do.</p>
|
||||
|
||||
@@ -166,7 +166,7 @@
|
||||
</figure>
|
||||
|
||||
<h3>一个供应商里的多个账号或密钥</h3>
|
||||
<p>展开供应商那一行,勾选要用的每个账号或密钥。<span class="ui">路由</span> 决定请求怎么分给它们:<span class="ui">智能</span>(默认)、<span class="ui">按顺序</span>、<span class="ui">轮流</span>、<span class="ui">用量少的优先</span>、<span class="ui">重置前用完</span> 或 <span class="ui">速度优先</span>(最近回答最快的密钥先用)。<span class="ui">备用</span> 里列出这个供应商额度用完、被限流或不可用时改用的模型。</p>
|
||||
<p>展开供应商那一行,勾选要用的每个账号或密钥。<span class="ui">路由</span> 决定请求怎么分给它们:<span class="ui">智能</span>(默认)、<span class="ui">按顺序</span>、<span class="ui">轮流</span>、<span class="ui">用量少的优先</span>、<span class="ui">重置前用完</span>、<span class="ui">按权重</span>(每个账号或密钥按旁边设的权重分得请求,比如 Max 账号设 5、Pro 账号设 1)或 <span class="ui">速度优先</span>(最近回答最快的密钥先用)。<span class="ui">备用</span> 里列出这个供应商额度用完、被限流或不可用时改用的模型。</p>
|
||||
|
||||
<h3>跨供应商的同一个模型</h3>
|
||||
<p>路由组是几个模型(来自一个或多个供应商),Agent 把它当作一个来选:<code>group/<id></code>,在选择列表的 <em>路由组</em> 下面。两个供应商用同一个名字提供的模型会自动成组;在 <span class="ui">路由</span> 标签页点 <span class="ui">新建组</span> 可以把任意模型组到一起。排第一的模型决定这个组对外的能力。</p>
|
||||
|
||||
Reference in New Issue
Block a user