provider: a relay key bills at its sub2api group rate times the provider's top-up rate (@YIXIE233 on X)
@YIXIE233 has several sub2api relays. Each reports a key's group rate at GET /v1/sub2api/billing, and each sells its dollars at its own price (¥1 for $1 at one, ¥7 for $100 at another). Until now every key's rate was typed by hand and typed again whenever a relay changed its prices. Now a provider of API keys has a "Top-up rate" under Advanced, next to Price rate (TopUpRate: above 0 up to 1000, at most four decimals). With one set, the gateway's KeepKeyRatesRead asks each key's relay for its rate in the background. It reads at start, every 6h, 30 min after a failed read, and at once on a save that sets a new top-up rate. It is never on a request's path. The relay asked is the origin of its sub2api key query, else of its first base; loopback and vendor hosts are never asked. Readings go to key-rates.json beside providers.json. A key then bills at group rate x top-up rate, and that rate reaches both places a price is used: PriceAt (Cheapest/By price routing) and BaseKeyPriceIn (the ledger, Usage, spend caps). A group rate of 0 prices at 0 (zeroRate), not at the list price. - A key's own KeyPriceRates still wins. - A key never read, or whose reads all failed, is unknown and bills at the provider's PriceRate, never 1x. - A failed reread keeps the last rate it read. The Usage caches key on a hash of the rates read, so a reread that finds the same rates keeps them. /api/providers lists keyGroupRates, which the editor names under the box. An empty per-key line's placeholder shows group rate x top-up rate. `magpie provider key-rate` lists both. i18n: zh, zh-TW, ja, de. Not counted yet: sub2api's peak-hour multiplier (#7286). Run (mote, via mote-run): - At7dc85f26e, before the rebase: go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok. gofmt -l: nothing. - go test -count=1 ./internal/provider ./internal/cli ./internal/usage: ok. - go test ./internal/gui: two reds, TestBuiltinsTranslated (a Routing string in zh/zh-TW/ja/de) and TestSettingsSaveKeepsWhatItDoesNotSend (RedactModelDir). This change doesn't touch either; checked against origin/main below. - The box's code lives in the lazy keyrates.js (loaded for a provider of keys of its own too, keyRateField's new `on`). The top-up rate rides keyPriceRates(ed, body), and keyPriceRates gives undefined when no per-key lines were drawn. With that, app.js stays under TestCoreScriptBudget with no raise (a first cut was 261 bytes over). - go test -run 'CoreScriptBudget|TopUpRate|KeyPriceRate|I18n|Translated' ./internal/gui at the rebased head (c2924c36d): ok except TestBuiltinsTranslated (#7257). That test and TestSettingsSaveKeepsWhatItDoesNotSend (#7240) fail the same on an archive of origin/mainc2924c36d. - node --test top-up-rate, key-price-rate, provider-price-rate and old-webkit .test.cjs (Chromium and WebKit, en/zh/zh-TW/ja/de): 62 pass, 2 fail. Both fails are old-webkit (guideback.js imported by navpages.js, the class of #6570, and Safari 15 styles, #7235), and they fail the same on origin/mainc2924c36d. Broken by hand: with readKeyPriceRate turned off and zeroRate dropped from tariffOf, TestKeyGroupRateTimesTopUpRate, ...FailedReadIsUnknown and ...Zero go red ($1.8 where $0.14 was wanted); green again once restored. Not tried: a real sub2api relay. The fixtures are sub2api's own reply shapes from backend/internal/handler/gateway_key_billing.go (schema 1), served by httptest.
This commit is contained in:
@@ -20,6 +20,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| Provider | `Provider` holds the endpoint bases for each `Protocol` (Chat, Responses, Anthropic, Gemini), the keys, `Fallback`, `Routing`, `Sink`, `UseFirst` (Smart puts it ahead of the other providers it weighs it with, [gateway routing](gateway-routing.md)), `NoStandIn` (never a fallback for another model, [gateway routing](gateway-routing.md)), `Affinity`, concurrency and queue limits, `MaxImages` (the most images one request to it may carry, the user's word: by model id, `"*"` for all, `ImageCapOf`; set in the editor's Advanced › Images per request or with `magpie provider set <id> max-images=<n> max-images.<model>=<n>`, renamed with a model's local id; past it the gateway leaves the oldest images out before sending, `image_cap.go`, #6849), `Headers`, `Proxy`, models, and balance settings. `BaseAPI` is the API a custom provider's editor shows its Base URL as: the one the user picked and saved, while it has a URL, so a provider with a chat URL beside its Responses one isn't shown as OpenAI compatible after Responses was picked. Requests go by which URLs are set; `Native`, the API agents' model files ask a model on, takes `BaseAPI` where it serves the model, after the OpenAI-model and Claude-on-Messages rules (nb5p on Discord: dsh asked a Responses relay's GPTs on Chat). A custom provider's `Gemini` URL is the base of Google's Gemini API, or of one that answers as it does (#1346): `GeminiBase` keeps it as the base, as typed (a pasted endpoint or model list cut back; only Google's own bare host is given /v1beta, JNDliuliuM on X), and `Base(Gemini)` asks it at `GeminiAsked`'s base: a bare host at its /v1beta, as Google's SDKs ask one, any base with a path as typed (equinox0253 on X, `TestGeminiAsked`, `TestGeminiBareHostAskedAtV1beta`). Requests, a model's test and the model list go there: requests to `models/{model}:streamGenerateContent?alt=sse` under it (`GeminiPath`), a namespaced id's slashes kept and each segment escaped (`GeminiModelPath`, which Vertex AI's, a plugin's Code Assist and Gemini image generation (`draw.go`) share; an id with an empty, `.` or `..` segment goes as one escaped segment, #6695) signed with `x-goog-api-key` (`AuthHeaders`), and its models are listed by `catalog.FetchGemini` (paged, only those serving generateContent). Factory's sign-in alone keeps its own `/generate` route and token (`FactoryGemini`). `Account` is set only for a subscription and is never saved (`json:"-"`). | [`provider.go`](../../internal/provider/provider.go) |
|
||||
| Rate windows | A provider bills the hours it says at its own rate (#2463): `RateWindows`, each a span `HH:MM`–`HH:MM` on this computer's clock whose end may pass its start over midnight, the days it is on (`Days`, `time.Weekday`'s numbers, none for every day), and a rate from just over 0 to 1000 at three decimals. The first window that holds a call's time multiplies the price again, on top of `PriceRate` — a price the user set for a model included, which the price rate alone leaves as set — and outside every window the price rate alone counts. A call is priced at its own time wherever a cost is counted call by call — the Usage page and its CSV, a gateway key's cost limit, the gateway's sessions in Usage — by `EffectivePriceAt`, which `EffectivePriceIn` is at `time.Now()`, and its record's time is read on this computer's clock whatever zone it was written in (a call reported as `…Z`); the Sessions page sums a session's calls by model, not by time, so it prices them without any window (`BasePriceIn` in `sessions.priceOf`), the same at every hour it is read; the ledger's `Pricer` holds each provider's base price and windows once and reads each record's rate at the record's own time, so a window that opens mid-page prices only the calls inside it; a gateway block's rows (`blockPricer`, the Requests tab) take their price from a memo asked with no time, which `RateAt` reads as no window, and each row is put at its own window's rate there (`atWindow` before `Price.In`). A list price billed double at peak (`Peak`, DeepSeek's, Ollama Cloud's two DeepSeek models' and the relays `PeakOf` names) is part of the base: the final price is that base, peak included, times the window's rate, so a provider with a `Peak` needs no window for the same hours: the order is the spec (the author, YangHonghang), so a 0.8 window on a shared DeepSeek key takes 0.8 off the peak price at peak, and a window set over the official peak hours would double them twice, which the editor's hint says under the windows. `/v1/models` prices its list at now (`EntryPricer`); the model list magpie writes into an agent's own config (`AgentPricer`, Pi's and omp's cost) leaves every window out, since nothing rewrites that file as a window opens or closes. `CheckRateWindows` says what is wrong with a set; the editor keeps the windows under Advanced, drawn by `ratewindows.js`, which app.js imports when an editor draws the field (`rateWindowsField`) so it adds nothing to the core's scripts — until it has loaded, a save leaves `rateWindows` out, which keeps them. A provider with windows shows what it bills at now on its row (`rateNow` in `/api/providers`, `rateNowOf` in the GUI's `providers.go`: `RateAt` on the server's clock, which calls are counted on, never the browser's); one with a price rate alone shows nothing new. Windows are kept with the provider: a save that leaves them out keeps them, null or an empty list clears them, and a signed-in account's survive its `Save` — the account branch and `withPicks` both go through one list, `accountSettings`, beside its `PriceRate`, or the editor's Save would quietly drop what it shows (#4738: two lists drifted, and `additionalTools`, extraBody, reply headers, its rests, `limitRestOff` and patience were each lost one way; `TestAccountSettingsKept`). | [`ratewindow.go`](../../internal/provider/ratewindow.go), [`models.go`](../../internal/provider/models.go), [`ledger.go`](../../internal/usage/ledger.go) (`Pricer`), [`app.js`](../../internal/gui/assets/app.js) (`rateWindowsField`), [`ratewindows.js`](../../internal/gui/assets/ratewindows.js), [`gui/providers.go`](../../internal/gui/providers.go) (`rateNowOf`) |
|
||||
| Key price rates | A provider of API keys can bill each key at a price rate of its own (`KeyPriceRates`, by the key's fingerprint in lower case, above 0 up to 1000 at three decimals; @tnt12231 on X: a relay sells keys in groups at 0.5× and 1.2× under one endpoint). A key without one bills at the provider's `PriceRate` (`KeyPriceRate`). The ledger's `Pricer` memoizes by the record's `ProviderKeyID` too and prices through `BaseKeyPriceIn`, so the Usage page, its CSV, a key's spend cap and a typed balance (`usage.KeySpent`) count each key's calls at its rate; `PriceAt` prices a routing candidate at the rate of the key it holds (By price). A call with no key recorded, the Sessions page and the budget's estimate before a key is picked use the provider's rate. A price the user set for a model stands as set, as under the provider's rate, and rate windows multiply on top. `SetKeyPriceRate` refuses a subscription, a rate of 0 or out of range and a key the provider hasn't; nil takes it off. `ReplaceKey` carries it to the new value. Set under the editor's Advanced, a line per key under Price rate once there are two keys or more (folded past eight as the per-key proxies are; an empty line shows the provider's rate as its placeholder), saved as `keyPriceRates` on `provider/save` (`{}` takes them off, left out keeps them), or `magpie provider key-rate <id> [key [rate|default]]`, which also lists each key's rate. | [`key_rate.go`](../../internal/provider/key_rate.go), `TestKeyPriceRateSet`, `TestKeyPriceRatePrices`, `TestPricerKeyPriceRates`, `TestKeyRateCmd`, `TestProviderSaveKeyPriceRates`, [`key-price-rate.test.cjs`](../../internal/gui/tests/key-price-rate.test.cjs) |
|
||||
| Group rates read from a relay | A provider of API keys with a top-up rate (`TopUpRate`, what one of the relay's dollars cost the user, above 0 up to 1000 at four decimals; @YIXIE233 on X: ¥1 per $1 at one relay is 1, ¥7 per $100 at another is 0.07) has each key's group rate read from sub2api's `GET /v1/sub2api/billing` with that key (`resolved_rate_multiplier`, else `group_rate_multiplier`; a reply without `object: "sub2api.key_billing"` is not one). The gateway's `KeepKeyRatesRead` asks each key in the background, never on a request's path: at start, every six hours, half an hour after a failed read, and at once when a save gives a new top-up rate (`ReadKeyRatesSoon`). The relay asked is the origin of its sub2api key query, else of its first base; this computer and a vendor's own hosts are never asked (`notProbed`). Readings are kept by provider and key fingerprint in `key-rates.json` beside providers.json, with their origin (a new origin starts over) and the last error, the key masked. A key with no rate of its own bills at group rate × top-up rate (`KeyPriceRate`, rounded to six decimals; a group billed at 0 is free); a key's own `KeyPriceRates` stands over it, and a key never read, or whose reads all failed, is unknown and bills at the provider's `PriceRate`, never at 1×; a failed reread keeps the rate read before. The Usage page's caches key on `KeyRatesKey`, a hash of the rates read, so a reread that finds the same rates keeps them. sub2api's peak multiplier (`peak_rate_multiplier`) is not counted yet (#7286). Set under the editor's Advanced, next to Price rate, for a provider of keys (`topUpRate` on `provider/save`: null takes it off, left out keeps it); `/api/providers` lists `keyGroupRates` by key id, named under the box, and an empty per-key line shows group rate × top-up rate as its placeholder. `magpie provider key-rate <id>` lists a read key's rate with its group's. | [`key_rate_read.go`](../../internal/provider/key_rate_read.go), `TestKeyGroupRateTimesTopUpRate`, `TestKeyGroupRateFailedReadIsUnknown`, `TestKeyGroupRateZero`, `TestKeyGroupRateOnlyWhenAsked`, `TestParseKeyBilling`, `TestProviderSaveTopUpRate`, [`top-up-rate.test.cjs`](../../internal/gui/tests/top-up-rate.test.cjs) |
|
||||
| Billing | Whether a provider is on a plan or paid as used, marked by a grey badge on its Providers row and summed up as a tag on a routing group's card (EV_John_Liu on X). `BillingKind` ([`billing.go`](../../internal/provider/billing.go)) is the user's word (`Billing`: the editor's *Billing* under Advanced, Auto/Plan/Pay as you go; `magpie provider set <id> billing=plan\|payg\|auto`), else a signed-in account (a plan), a plan's own preset (`planPresets`: Kimi Code, the Token Plans, OpenCode Go, ClinePass), else the name of the preset region it sits at (`regionOf`: "Pay as you go…" or "…Plan…"; one named by place, or a preset with no regions, is the vendor's API, pay as you go), and `mixed` when a key of it is on a plan of the other kind (`KeyAccount.Plan`). It is "", and nothing is shown, for a provider added by its address, a local server, another magpie, a decision model, or a preset whose one endpoint takes both (`unsaidPresets`: MiniMax, ModelScope and the like). `/api/providers` gives `billing` and `billingKind`, a group's `memberInfo[].billing`; the card's tag is shown only when every member's is known. It marks only: routing and prices don't read it. `TestBillingKind`, `TestBillingEveryRegion`, `TestProviderBilling`, `TestProviderSetBilling`, `provider-billing.test.cjs`. | [`billing.go`](../../internal/provider/billing.go), [`providers.go`](../../internal/gui/providers.go) |
|
||||
| Anthropic key header | A provider of the user's own on a third-party Anthropic API is sent its key as both `x-api-key` and `Authorization: Bearer` (`AuthHeaders`); Anthropic's own API, Bedrock, Azure, Vertex and every subscription account have their own and never this choice (`BothAuth` is false). Some services refuse the two together with a 401 (Aloha on Discord: "鉴权 header, x-api-key 和 Authorization 不可以同时存在"), so `Provider.AuthHeader` (`authHeader`: empty for both, `x-api-key` or `bearer`; anything else is read as empty) sends one alone, picked in the editor's Key header row (shown while `bothAuth` is true, or a custom provider's Anthropic URL is a third party's). Left at both, a 401 whose body `catalog.BothAuthRefused` tells as that refusal (it names both headers and says they can't be together, in Chinese or English) is asked once more with x-api-key alone, then Bearer alone (`RetryOneAuth`, in the gateway's `forwardOnce` and the provider test's `probe`; `catalog.fetchOne` for the model list through `listAuth`); the first not answered 401 or 403 is kept with `LearnAuthHeader`, which never changes a pick the user made. A request carrying the user's own `Authorization` or `x-api-key` header is never retried. | [`authheader.go`](../../internal/provider/authheader.go), [`test.go`](../../internal/provider/test.go), [`catalog/authheader.go`](../../internal/catalog/authheader.go), [`catalog/live.go`](../../internal/catalog/live.go) |
|
||||
| GLM Coding Plan key at pay as you go | Zhipu's and Z.ai's presets offer Pay as you go first (`/api/paas/v4`) and the Coding Plan (`/api/coding/paas/v4`, Responses at `/api/v1`); both share `/api/anthropic`, which bills the plan, so a plan's key left at Pay as you go worked in Claude Code and was refused 429 code 1113 "余额不足或无可用资源包" in Codex (@cleverpigo on X). Nothing in the key tells the two apart, so a Chat request to `open.bigmodel.cn` or `api.z.ai` at `/api/paas/v4` refused 1113 is asked once more at `/api/coding/paas/v4` (`RetryZhipuCoding`, in the gateway's `forwardOnce` and the provider test's `probe`). Served there, `LearnZhipuCoding` moves a saved provider with that one key, still at that URL, to the plan's OpenAI URL (and the preset's plan Responses URL when it has none); one with other keys stays and is asked again each time. Refused there too, the 1113 body keeps its code and gets both URLs and what to change in its message (`ZhipuNoBalanceHint`). A pay-as-you-go key with a balance is never answered 1113 and never sent to the plan's endpoint. | [`zhipu_coding.go`](../../internal/provider/zhipu_coding.go), [`test.go`](../../internal/provider/test.go) |
|
||||
|
||||
@@ -58,9 +58,12 @@ func keyRateCmd(rest []string) error {
|
||||
name = k.Name + " " + muted.Render(k.Masked+" · "+k.ID)
|
||||
}
|
||||
r, own := p.KeyPriceRate(k.ID)
|
||||
g, read := p.KeyGroupRate(k.ID)
|
||||
switch {
|
||||
case own:
|
||||
fmt.Println(name, "· ×"+rateText(r))
|
||||
case read && p.TopUpRate > 0:
|
||||
fmt.Println(name, muted.Render("· ×"+rateText(r)+", its group's ×"+rateText(g)+" read from the relay, at the top-up rate ×"+rateText(p.TopUpRate)))
|
||||
case r > 0:
|
||||
fmt.Println(name, muted.Render("· ×"+rateText(r)+", the provider's"))
|
||||
default:
|
||||
|
||||
@@ -955,6 +955,8 @@ func (s *Server) ListenAndServe(ctx context.Context) error {
|
||||
go provider.KeepListsFresh(ctx)
|
||||
// and follows a Remote magpie's list as it changes there (KaCli)
|
||||
go provider.KeepRemoteListsFollowed(ctx)
|
||||
// and reads the group rate of each key of a relay given a top-up rate (@YIXIE233 on X)
|
||||
go provider.KeepKeyRatesRead(ctx)
|
||||
// and keeps the community's plugins up to date, noting others' updates, and the Bun they run on
|
||||
go plugin.KeepUpdated(ctx)
|
||||
go plugin.KeepBunUpdated(ctx)
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
const GROUPS = [
|
||||
["Routing", ["Routing", "Rate limited", "Stays", "Resets", "Warm up", "Check in", "Claude Code", "Fallback", "Rests", "Errors"]],
|
||||
["Models", ["Context window", "Max output", "Compaction", "Compact at", "Images", "Web search"]],
|
||||
["Limits and cost", ["Requests at once", "Accounts at once", "Requests per minute", "Queue size", "Price rate", "Free for me", "Billing", "Rate windows", "Account balance", "Balance URL", "Balance field"]],
|
||||
["Limits and cost", ["Requests at once", "Accounts at once", "Requests per minute", "Queue size", "Price rate", "Top-up rate", "Free for me", "Billing", "Rate windows", "Account balance", "Balance URL", "Balance field"]],
|
||||
["Connection", ["Headers", "Extra body", "Reply headers", "Request headers to pass", "Proxy", "Upstream", "Key header", "User-Agent", "Codex client", "Masking", "Certificate", "HTTP version", "WebSocket", "Agents"]],
|
||||
];
|
||||
window.advGroups = function (box) {
|
||||
|
||||
@@ -8129,7 +8129,7 @@ const groupAdvanced = (b) => self.advGroups?.(b);
|
||||
function advancedSet(d, p) {
|
||||
return (d.headers || []).some(([k]) => (k || "").trim()) || !!(d.extraBody || "").trim() || !!(d.replyHeaders || d.passHeaders || "").trim() ||
|
||||
!!d.proxyMode || Object.values(d.accountProxies || {}).some((x) => x?.mode) || Object.values(d.keyPriceRates || {}).some((v) => String(v).trim()) ||
|
||||
[d.concurrency, d.maxAccounts, d.queueLimit, d.queueWait, d.maxRPM, d.priceRate, d.contexts, d.outputs, d.compacts].some((v) => String(v ?? "").trim()) ||
|
||||
[d.concurrency, d.maxAccounts, d.queueLimit, d.queueWait, d.maxRPM, d.priceRate, d.topUpRate ?? p?.topUpRate, d.contexts, d.outputs, d.compacts].some((v) => String(v ?? "").trim()) ||
|
||||
!!d.rateWindows?.length ||
|
||||
!!(d.searches || d.authHeader || d.passUserAgent === false || d.unredacted || d.countFree || d.billing || d.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff || d.noBalanceProbe || d.http1 || d.socket || d.imageFilesOff || d.passErrors || d.clientCert || d.serverCA || d.serverPin || d.resolve) ||
|
||||
!!d.fallback?.length || !!(p?.balanceToken?.set || p?.connectAgents || p?.maxImages);
|
||||
@@ -8349,7 +8349,9 @@ function accountProxiesOfDraft() {
|
||||
|
||||
// a key's own price rate (@tnt12231 on X), in keyrates.js, and any other
|
||||
// part keyrates.js draws for a provider with two or more keys (f)
|
||||
const keyRateField = (p, f = "keyPriceRateField", at = el("span")) => p?.keyList?.length > 1 ? (import("./keyrates.js").then(() => at.isConnected && at.replaceWith(...window[f](p)), () => {}), [at]) : [];
|
||||
// (on: two keys or more, unless said); a relay's top-up rate
|
||||
// (@YIXIE233 on X) is drawn there too
|
||||
const keyRateField = (p, f = "keyPriceRateField", on = p?.keyList?.length > 1, at = el("span")) => on ? (import("./keyrates.js").then(() => at.isConnected && at.replaceWith(...window[f](p)), () => {}), [at]) : [];
|
||||
|
||||
// headers as ordered [name, value, json?] rows that survive a redraw; headersOf folds them back
|
||||
function headerRows(obj) {
|
||||
@@ -10065,7 +10067,7 @@ function drawEditor(p, presetID) {
|
||||
if (perKey) proxies.append(perKey);
|
||||
advIn.append(...field(t("Proxy"), proxies));
|
||||
advIn.append(...concurrencyField(p));
|
||||
advIn.append(...priceRateField(), ...keyRateField(p), ...countFreeField(), ...billingField(), ...rateWindowsField());
|
||||
advIn.append(...priceRateField(), ...keyRateField(p, "topUpRateField", custom || p?.topUpRate), ...keyRateField(p), ...countFreeField(), ...billingField(), ...rateWindowsField());
|
||||
|
||||
if (p?.cline || (isNew && pr?.id === "clinepass")) advIn.append(...upstreamField());
|
||||
|
||||
@@ -10567,7 +10569,7 @@ function drawEditor(p, presetID) {
|
||||
Object.assign(body, queue);
|
||||
body.priceRate = priceRateOfDraft();
|
||||
if (body.priceRate === undefined) return priceRateError(ed);
|
||||
if ((body.keyPriceRates = self.keyPriceRates?.(ed)) === null) return;
|
||||
if ((body.keyPriceRates = self.keyPriceRates?.(ed, body)) === null) return;
|
||||
body.rateWindows = self.rateWindowsOfDraft?.();
|
||||
if (body.rateWindows === false) return rateWindowsError(ed);
|
||||
if (p && priceTypedError(ed)) return;
|
||||
|
||||
@@ -3037,6 +3037,10 @@ const I18N = {
|
||||
"A number of your own, up to 1000": "自定义数字,最大 1000",
|
||||
"No limit": "不限制",
|
||||
"Price rate": "价格倍率",
|
||||
"Top-up rate": "充值折扣",
|
||||
"What one dollar of the relay cost you, like 0.07 for ¥7 per $100. Each key's group rate is read from the relay, and its calls cost the two multiplied": "中转站一美元额度你实际花了多少,比如 ¥7 买 $100 就填 0.07。每个 key 的分组倍率从中转站读取,调用按两者相乘计费",
|
||||
"Read from the relay: {rates}": "已从中转站读取:{rates}",
|
||||
"Top-up rate: a number above 0 up to 1000, at most four decimals": "充值折扣:大于 0、不超过 1000 的数字,最多四位小数",
|
||||
"Free for me": "对我免费",
|
||||
"Count its models as free": "把它的模型算作免费",
|
||||
"For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed.": "适用于免费额度,比如每日免费额度:「免费优先」会先用它的模型,再用付费的;「最便宜优先」把它们算作不花钱。价格和用量统计的费用保持原样。",
|
||||
@@ -8542,6 +8546,10 @@ const I18N = {
|
||||
"A number of your own, up to 1000": "自定義數字,最大 1000",
|
||||
"No limit": "不限制",
|
||||
"Price rate": "價格倍率",
|
||||
"Top-up rate": "儲值折扣",
|
||||
"What one dollar of the relay cost you, like 0.07 for ¥7 per $100. Each key's group rate is read from the relay, and its calls cost the two multiplied": "中轉站一美元額度你實際花了多少,例如 ¥7 買 $100 就填 0.07。每個 key 的分組倍率從中轉站讀取,呼叫按兩者相乘計費",
|
||||
"Read from the relay: {rates}": "已從中轉站讀取:{rates}",
|
||||
"Top-up rate: a number above 0 up to 1000, at most four decimals": "儲值折扣:大於 0、不超過 1000 的數字,最多四位小數",
|
||||
"Free for me": "對我免費",
|
||||
"Count its models as free": "把它的模型算作免費",
|
||||
"For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed.": "適用於免費額度,例如每日免費額度:「免費優先」會先用它的模型,再用付費的;「最便宜優先」把它們算作不花錢。價格和用量統計的費用維持原樣。",
|
||||
@@ -14018,6 +14026,10 @@ const I18N = {
|
||||
"A number of your own, up to 1000": "任意の数(最大 1000)",
|
||||
"No limit": "上限なし",
|
||||
"Price rate": "価格倍率",
|
||||
"Top-up rate": "チャージ倍率",
|
||||
"What one dollar of the relay cost you, like 0.07 for ¥7 per $100. Each key's group rate is read from the relay, and its calls cost the two multiplied": "リレーの 1 ドル分に実際に払った額。¥7 で $100 なら 0.07。各キーのグループ倍率はリレーから読み取り、呼び出しは両者を掛けた額で計上します",
|
||||
"Read from the relay: {rates}": "リレーから読み取り済み:{rates}",
|
||||
"Top-up rate: a number above 0 up to 1000, at most four decimals": "チャージ倍率:0 より大きく 1000 以下、小数は 4 桁まで",
|
||||
"Free for me": "自分には無料",
|
||||
"Count its models as free": "このモデルを無料として扱う",
|
||||
"For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed.": "毎日の無料枠のような無料分に。「無料優先」は有料のものより先にこのモデルを使い、「最安優先」はコストなしとして扱います。価格と使用量で数える費用はそのままです。",
|
||||
@@ -19537,6 +19549,10 @@ const I18N = {
|
||||
"A number of your own, up to 1000": "Eine eigene Zahl, bis 1000",
|
||||
"No limit": "Kein Limit",
|
||||
"Price rate": "Preisfaktor",
|
||||
"Top-up rate": "Aufladefaktor",
|
||||
"What one dollar of the relay cost you, like 0.07 for ¥7 per $100. Each key's group rate is read from the relay, and its calls cost the two multiplied": "Was dich ein Dollar des Relays gekostet hat, etwa 0,07 für ¥7 pro $100. Der Gruppenfaktor jedes Schlüssels wird vom Relay gelesen, und seine Aufrufe kosten beides multipliziert",
|
||||
"Read from the relay: {rates}": "Vom Relay gelesen: {rates}",
|
||||
"Top-up rate: a number above 0 up to 1000, at most four decimals": "Aufladefaktor: eine Zahl über 0 bis 1000, höchstens vier Nachkommastellen",
|
||||
"Free for me": "Für mich kostenlos",
|
||||
"Count its models as free": "Seine Modelle als kostenlos zählen",
|
||||
"For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed.": "Für ein Gratiskontingent, etwa ein tägliches: „Kostenlos zuerst“ nutzt seine Modelle vor bezahlten, und „Günstigste zuerst“ rechnet sie als kostenlos. Preise und die Kosten in der Nutzung bleiben wie gelistet.",
|
||||
|
||||
@@ -2,14 +2,54 @@
|
||||
// at their own rates against the official price). The provider editor's
|
||||
// Advanced draws a line for each key, folded as keyProxyPicker's lines
|
||||
// (proxyLines); a key left empty bills at the provider's Price rate.
|
||||
// app.js imports this when a provider with two or more keys opens
|
||||
// (keyRateLines), so it weighs nothing on the core.
|
||||
// app.js imports this when a provider with two or more keys opens, or a
|
||||
// provider of keys of its own (keyRateField), so it weighs nothing on the
|
||||
// core.
|
||||
//
|
||||
// A relay's top-up rate (@YIXIE233 on X): a relay built on sub2api tells
|
||||
// each key its group's rate, and relays sell their dollars at their own
|
||||
// prices (¥1 for $1 at one, ¥7 for $100 at another). The user types once
|
||||
// what a dollar of the relay cost them; magpie reads each key's group
|
||||
// rate from the relay and counts its calls at the two multiplied
|
||||
// (provider/key_rate_read.go).
|
||||
window.topUpRateField = function (p) {
|
||||
const box = input(draft.topUpRate ?? (p?.topUpRate ? String(p.topUpRate) : ""), "0.07");
|
||||
box.classList.add("top-up-rate");
|
||||
box.inputMode = "decimal";
|
||||
box.oninput = () => { draft.topUpRate = box.value; };
|
||||
const rates = Object.entries(p?.keyGroupRates || {});
|
||||
let hint = t("What one dollar of the relay cost you, like 0.07 for ¥7 per $100. Each key's group rate is read from the relay, and its calls cost the two multiplied");
|
||||
if (rates.length) {
|
||||
const name = (id) => { const k = p.keyList?.find((x) => x.id === id); return k ? k.name || k.masked : id; };
|
||||
const read = rates.length === 1 ? "×" + rates[0][1] : rates.map(([id, r]) => name(id) + " ×" + r).join(", ");
|
||||
hint += " · " + t("Read from the relay: {rates}", { rates: read });
|
||||
}
|
||||
return field(t("Top-up rate"), box, hint);
|
||||
};
|
||||
// topUpRateOf is the top-up rate typed in box as saved, null for none; a
|
||||
// rate typed wrong is focused and named, and gives undefined
|
||||
function topUpRateOf(box) {
|
||||
const v = box.value.trim();
|
||||
if (!v) return null;
|
||||
const n = decimalOf(v);
|
||||
if (n > 0 && n <= 1000 && Math.abs(n * 10000 - Math.round(n * 10000)) <= 1e-6) return n;
|
||||
shown(box).focus(NO_SCROLL);
|
||||
editorError(t("Top-up rate: a number above 0 up to 1000, at most four decimals"), "warn");
|
||||
return undefined;
|
||||
}
|
||||
// keyRateHint is what a key left empty bills at: its group's rate g read
|
||||
// from the relay times the top-up rate top, else the provider's Price rate
|
||||
const keyRateHint = (ed, g, top) => {
|
||||
top = decimalOf(String(top ?? "").trim());
|
||||
return g != null && top > 0 ? String(+(g * top).toFixed(6)) : (ed?.querySelector("input.price-rate")?.value ?? String(draft.priceRate ?? "")).trim() || "1";
|
||||
};
|
||||
function keyPriceRateLine(it) {
|
||||
const line = el("div", "key-rate");
|
||||
line.dataset.key = it.key;
|
||||
if (it.g != null) line.dataset.g = it.g;
|
||||
const who = el("span", "who", it.name);
|
||||
who.title = it.name;
|
||||
const box = input(draft.keyPriceRates[it.k] ?? "", String(draft.priceRate ?? "").trim() || "1");
|
||||
const box = input(draft.keyPriceRates[it.k] ?? "", keyRateHint(null, it.g, draft.topUpRate ?? it.top));
|
||||
box.classList.add("key-price-rate");
|
||||
box.inputMode = "decimal";
|
||||
box.setAttribute("aria-label", t("Price rate of {user}", { user: it.name }));
|
||||
@@ -19,21 +59,31 @@ function keyPriceRateLine(it) {
|
||||
}
|
||||
window.keyPriceRateField = function (p) {
|
||||
draft.keyPriceRates = draft.keyPriceRates || {};
|
||||
const items = (p?.keyList || []).map((k) => ({ k: k.id, name: k.name || k.masked, key: k.id, info: k }));
|
||||
const items = (p?.keyList || []).map((k) => ({ k: k.id, name: k.name || k.masked, key: k.id, info: k, g: p?.keyGroupRates?.[k.id], top: p?.topUpRate }));
|
||||
return field(t("Price rate per key"), proxyLines(items, "A key left empty bills at the provider's price rate", true,
|
||||
{ lineOf: keyPriceRateLine, own: (it) => !!String(draft.keyPriceRates[it.k] ?? "").trim(), cls: "key-rates" }));
|
||||
};
|
||||
// a key left empty bills at the provider's Price rate: its placeholder
|
||||
// follows that box as it is typed
|
||||
// a key left empty bills at the provider's Price rate, or its read group
|
||||
// rate times the top-up rate: its placeholder follows those boxes as they
|
||||
// are typed
|
||||
document.addEventListener("input", (e) => {
|
||||
const box = e.target;
|
||||
if (!box.matches?.("input.price-rate")) return;
|
||||
for (const k of box.closest(".inner")?.querySelectorAll("input.key-price-rate") || []) k.placeholder = box.value.trim() || "1";
|
||||
if (!box.matches?.("input.price-rate, input.top-up-rate")) return;
|
||||
const ed = box.closest(".inner");
|
||||
for (const k of ed?.querySelectorAll("input.key-price-rate") || []) {
|
||||
const g = k.closest(".key-rate")?.dataset.g;
|
||||
k.placeholder = keyRateHint(ed, g == null ? null : +g, ed.querySelector("input.top-up-rate")?.value);
|
||||
}
|
||||
});
|
||||
// keyPriceRates is each key's own price rate as saved, the keys left
|
||||
// empty out; a key typed wrong is focused and named, and gives null. An
|
||||
// editor that drew no lines sends them as they were.
|
||||
window.keyPriceRates = function (ed) {
|
||||
// editor that drew no lines sends them as they were (undefined). It puts
|
||||
// the top-up rate in body too, when the editor drew its box, and gives
|
||||
// null when that is typed wrong.
|
||||
window.keyPriceRates = function (ed, body) {
|
||||
const top = ed.querySelector("input.top-up-rate");
|
||||
if (top && (body.topUpRate = topUpRateOf(top)) === undefined) return null;
|
||||
if (!ed.querySelector(".key-rates")) return undefined;
|
||||
const map = {};
|
||||
for (const [k, v] of Object.entries(draft.keyPriceRates || {})) {
|
||||
const s = String(v ?? "").trim();
|
||||
|
||||
@@ -472,6 +472,10 @@ type providerJSON struct {
|
||||
// each key's own rate on the official price, by its id, where it
|
||||
// bills apart from PriceRate (@tnt12231 on X)
|
||||
KeyPriceRates map[string]float64 `json:"keyPriceRates,omitempty"`
|
||||
// what one of a sub2api relay's dollars cost the user, and each key's
|
||||
// group rate read from the relay, by its id (@YIXIE233 on X)
|
||||
TopUpRate float64 `json:"topUpRate,omitempty"`
|
||||
KeyGroupRates map[string]float64 `json:"keyGroupRates,omitempty"`
|
||||
|
||||
// what it charges against the official price, 0 for that (#819)
|
||||
PriceRate float64 `json:"priceRate,omitempty"`
|
||||
@@ -989,7 +993,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs
|
||||
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountWindowAmounts: p.AccountWindowAmounts, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, Billing: p.Billing, BillingKind: p.BillingKind(), InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), HTTP1: p.HTTP1, ClientCert: tilde(p.ClientCert), ClientKey: tilde(p.ClientKey), ServerCA: tilde(p.ServerCA), TakesClientCert: p.TakesClientCert(), ServerPin: p.ServerPin, TakesServerPin: p.TakesServerPin(), Resolve: p.Resolve, TakesResolve: p.TakesResolve(), Socket: p.Socket, TakesSocket: p.TakesSocket(), LimitRestOff: p.LimitRestOff, UpstreamProviders: p.UpstreamProviders, ImageFilesOff: p.ImageFilesOff, TakesImageFiles: p.TakesImageFiles(), NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: !p.MagpieUserAgent, OwnClient: p.OwnClient(), PassErrors: p.PassErrors, TakesPassErrors: p.TakesPassErrors(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, NoBalanceProbe: p.NoBalanceProbe, ModelsURL: p.ModelsURL, ListOff: p.ListsOff(), TakesListOff: p.Account == nil && !p.IsPlugin() && !p.DecideOnly(), TakesModelHeaders: p.Account == nil, DecideAPIKind: p.DecideAPIKind(),
|
||||
Ready: p.Ready(), Chosen: p.PicksOf(avail), Agents: make([]providerAgent, 0, len(agents)),
|
||||
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, UseFirst: p.UseFirst, NoStandIn: p.NoStandIn, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, RestartApp: p.RestartApp, Self: p.SelfAnswered(), KeepSelf: p.KeepSelf, ThisDevice: p.ThisDevice, 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(), MaxAccounts: p.MaxAccounts, PluginAccounts: p.PluginAtOnce(), PriceRate: p.PriceRate, KeyPriceRates: p.KeyPriceRates,
|
||||
MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), MaxAccounts: p.MaxAccounts, PluginAccounts: p.PluginAtOnce(), PriceRate: p.PriceRate, KeyPriceRates: p.KeyPriceRates, TopUpRate: p.TopUpRate, KeyGroupRates: keyGroupRatesOf(p),
|
||||
RateWindows: p.RateWindows, RateNow: rateNowOf(p, time.Now()),
|
||||
AccountConcurrency: p.AccountConcurrency, AccountWeights: p.AccountWeights, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, MaxImages: p.MaxImages,
|
||||
Outputs: provider.OutputsOf(p.ID), Compacts: provider.CompactsOf(p.ID),
|
||||
@@ -1976,7 +1980,11 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
RateWindows json.RawMessage `json:"rateWindows"`
|
||||
// PriceRate is what it charges against the official price
|
||||
// (#819): a number, null or 0 for none; left out, it is kept
|
||||
PriceRate json.RawMessage `json:"priceRate"`
|
||||
PriceRate json.RawMessage `json:"priceRate"`
|
||||
// TopUpRate is what one of a sub2api relay's dollars cost
|
||||
// (@YIXIE233 on X): a number, null or 0 for none; left out,
|
||||
// it is kept
|
||||
TopUpRate json.RawMessage `json:"topUpRate"`
|
||||
AccountOrder []string `json:"accountOrder"`
|
||||
// New is set by the editor's Add: the provider is one more, never
|
||||
// one replacing the provider that has its id or name
|
||||
@@ -2355,6 +2363,12 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
return
|
||||
}
|
||||
in.PriceRate = rate
|
||||
topUp, keepTopUp, err := topUpRateOf(req.TopUpRate)
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
in.TopUpRate = topUp
|
||||
// each key's own rate, by its id (@tnt12231 on X): {} takes
|
||||
// them all off, left out they are kept
|
||||
for k, r := range in.KeyPriceRates {
|
||||
@@ -2512,6 +2526,12 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
if keepRate && old != nil {
|
||||
in.PriceRate = old.PriceRate
|
||||
}
|
||||
if keepTopUp && old != nil {
|
||||
in.TopUpRate = old.TopUpRate
|
||||
}
|
||||
if in.TopUpRate > 0 && (old == nil || old.TopUpRate != in.TopUpRate) {
|
||||
defer provider.ReadKeyRatesSoon()
|
||||
}
|
||||
if in.KeyPriceRates == nil && old != nil {
|
||||
in.KeyPriceRates = old.KeyPriceRates
|
||||
}
|
||||
@@ -3992,6 +4012,43 @@ func priceRateOf(raw json.RawMessage) (r float64, keep bool, err error) {
|
||||
return *n, false, nil
|
||||
}
|
||||
|
||||
// topUpRateOf is a save's topUpRate: keep when the save left it out, 0
|
||||
// for null, else the rate.
|
||||
func topUpRateOf(raw json.RawMessage) (r float64, keep bool, err error) {
|
||||
if len(raw) == 0 {
|
||||
return 0, true, nil
|
||||
}
|
||||
var n *float64
|
||||
if err := json.Unmarshal(raw, &n); err != nil {
|
||||
return 0, false, fmt.Errorf("a top-up rate is a number, like 0.07, not %s", raw)
|
||||
}
|
||||
if n == nil {
|
||||
return 0, false, nil
|
||||
}
|
||||
if bad := provider.TopUpRateOK(*n); bad != "" {
|
||||
return 0, false, fmt.Errorf("%s, not %v", bad, *n)
|
||||
}
|
||||
return *n, false, nil
|
||||
}
|
||||
|
||||
// keyGroupRatesOf is each of p's keys' group rate read from its relay, by
|
||||
// the key's id: nil when none was read.
|
||||
func keyGroupRatesOf(p provider.Provider) map[string]float64 {
|
||||
if p.Account != nil || p.Key == "" {
|
||||
return nil
|
||||
}
|
||||
var out map[string]float64
|
||||
for _, k := range p.KeyList() {
|
||||
if g, ok := p.KeyGroupRate(k.ID); ok {
|
||||
if out == nil {
|
||||
out = map[string]float64{}
|
||||
}
|
||||
out[k.ID] = g
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// rateWindowsOf is a save's rateWindows: keep when the save left it out,
|
||||
// none for null or an empty list, else the windows as checked
|
||||
// (CheckRateWindows).
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A relay's top-up rate (@YIXIE233 on X: relays on sub2api report each
|
||||
// key's group rate, and each sells its dollars at its own price). A
|
||||
// provider of API keys has the box under Advanced; a subscription has
|
||||
// none. The rates read from the relay are named under it, and a key left
|
||||
// empty shows its group rate times the top-up rate as its placeholder,
|
||||
// following the box as it is typed; a key's own rate stands. Save posts
|
||||
// the rate, null when emptied, and refuses one out of range or past four
|
||||
// decimals before anything is posted. In every language.
|
||||
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 unfold = async (page) => {
|
||||
const adv = page.locator(".editor details.advanced");
|
||||
await adv.waitFor({ state: "attached" });
|
||||
if (!(await adv.evaluate((d) => d.open))) await adv.locator(":scope > summary").click();
|
||||
};
|
||||
const key = (id, name) => ({ id, name, masked: `sk-…${id.slice(0, 3)}`, active: id === "aaaaaaaaaa", on: true });
|
||||
const base = {
|
||||
icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "",
|
||||
models: [{ id: "model-a", name: "Model A", on: true }], agents: [], fallback: [], headers: {},
|
||||
key: { set: true, masked: "sk-…one" }, balanceToken: { takes: false, set: false }, proxy: "", maxConcurrency: null,
|
||||
};
|
||||
const relay = { ...base, id: "relay", name: "Relay", keyList: [key("aaaaaaaaaa", "Cheap"), key("bbbbbbbbbb", "Pro"), key("cccccccccc", "Own")],
|
||||
keyPriceRates: { cccccccccc: 0.3 }, topUpRate: 0.07, keyGroupRates: { aaaaaaaaaa: 1, bbbbbbbbbb: 2.5 } };
|
||||
const plain = { ...base, id: "plain", name: "Plain", keyList: [key("aaaaaaaaaa", "Only")] };
|
||||
const sub = { ...base, id: "codex", name: "Codex Sub", icon: "openai", account: { kind: "codex" }, key: { set: false }, keyList: [] };
|
||||
|
||||
function serve(lang, posts) {
|
||||
const providers = { providers: [relay, plain, sub], presets: [], excluded: [], gateway: { running: true, window: true } };
|
||||
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
|
||||
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:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json(state);
|
||||
if (url.pathname === "/api/providers") return json(providers);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname.startsWith("/api/provider/") && route.request().method() === "POST") {
|
||||
posts.push({ action: url.pathname.slice("/api/provider/".length), body: route.request().postDataJSON() });
|
||||
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)];
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const strings = ["Save", "Top-up rate", "What one dollar of the relay cost you, like 0.07 for ¥7 per $100. Each key's group rate is read from the relay, and its calls cost the two multiplied",
|
||||
"Read from the relay: {rates}", "Top-up rate: a number above 0 up to 1000, at most four decimals"];
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||||
const open = async (t, name) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await (await browser.newContext({ viewport: { width: 900, height: 760 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const posts = [];
|
||||
await page.route("**/*", serve(lang, posts));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
await page.locator(".row.provider", { hasText: name }).click();
|
||||
await page.locator(".editor details.advanced").waitFor({ state: "attached" });
|
||||
await page.waitForTimeout(300);
|
||||
const w = await page.evaluate(([lang, strings]) => Object.fromEntries(strings.map((s) => [s, lang === "en" ? s : I18N[lang]?.[s]])), [lang, strings]);
|
||||
return { page, errors, posts, w };
|
||||
};
|
||||
const saveButton = async (page) => page.locator(".editor .bar").getByRole("button", { name: await page.evaluate((lang) => lang === "en" ? "Save" : I18N[lang].Save, lang), exact: true });
|
||||
const save = async (page, posts) => {
|
||||
const n = posts.length;
|
||||
await (await saveButton(page)).click();
|
||||
for (let i = 0; i < 50 && posts.length === n; i++) await page.waitForTimeout(50);
|
||||
return posts.at(-1);
|
||||
};
|
||||
const box = (page) => page.locator(".editor input.top-up-rate");
|
||||
const rate = (page, id) => page.locator(`.editor .key-rate[data-key="${id}"] input.key-price-rate`);
|
||||
|
||||
test(`${engine} ${lang}: a relay's top-up rate times each key's group rate`, async (t) => {
|
||||
const { page, errors, posts, w } = await open(t, "Relay");
|
||||
for (const s of strings) assert(w[s], `${s} has its ${lang}`);
|
||||
assert(await page.locator(".editor details.advanced").evaluate((d) => d.open), "a top-up rate opens Advanced");
|
||||
await box(page).waitFor();
|
||||
assert.equal(await box(page).inputValue(), "0.07");
|
||||
const text = await page.locator(".editor details.advanced").textContent();
|
||||
assert(text.includes(w["Read from the relay: {rates}"].replace("{rates}", "Cheap ×1, Pro ×2.5")), "the rates read are named");
|
||||
// an empty key shows what it bills at: its group's rate × the top-up rate
|
||||
await rate(page, "bbbbbbbbbb").waitFor();
|
||||
assert.equal(await rate(page, "aaaaaaaaaa").getAttribute("placeholder"), "0.07");
|
||||
assert.equal(await rate(page, "bbbbbbbbbb").getAttribute("placeholder"), "0.175");
|
||||
assert.equal(await rate(page, "cccccccccc").inputValue(), "0.3", "the key's own rate stands");
|
||||
await box(page).fill("0.08");
|
||||
assert.equal(await rate(page, "bbbbbbbbbb").getAttribute("placeholder"), "0.2");
|
||||
|
||||
for (const v of ["0.07142", "1001", "-1", "abc"]) {
|
||||
await box(page).fill(v);
|
||||
await (await saveButton(page)).click();
|
||||
await page.locator(".editor .editor-error").waitFor();
|
||||
assert.equal(await page.locator(".editor .editor-error").textContent(), w["Top-up rate: a number above 0 up to 1000, at most four decimals"], v);
|
||||
assert.equal(posts.length, 0, `${v} is not posted`);
|
||||
}
|
||||
// a comma for the decimal point, as some keyboards type it
|
||||
await box(page).fill("0,0714");
|
||||
let saved = await save(page, posts);
|
||||
assert.equal(saved.action, "save");
|
||||
assert.equal(saved.body.topUpRate, 0.0714);
|
||||
assert.deepEqual(saved.body.keyPriceRates, { cccccccccc: 0.3 });
|
||||
|
||||
await page.locator(".row.provider", { hasText: "Relay" }).click();
|
||||
await box(page).waitFor();
|
||||
await box(page).fill("");
|
||||
saved = await save(page, posts);
|
||||
assert.equal(saved.body.topUpRate, null, "emptied, it is taken off");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang}: a provider of keys has it under Advanced, a subscription none`, async (t) => {
|
||||
const { page, errors, posts } = await open(t, "Plain");
|
||||
assert(!(await page.locator(".editor details.advanced").evaluate((d) => d.open)), "nothing set, Advanced stays folded");
|
||||
await unfold(page);
|
||||
await box(page).waitFor();
|
||||
assert.equal(await box(page).inputValue(), "");
|
||||
const saved = await save(page, posts);
|
||||
assert.equal(saved.body.topUpRate, null);
|
||||
await page.locator(".row.provider", { hasText: "Codex Sub" }).click();
|
||||
await unfold(page);
|
||||
await page.waitForTimeout(300);
|
||||
assert.equal(await box(page).count(), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A save's topUpRate (@YIXIE233 on X): taken and listed back, kept when
|
||||
// the save leaves it out, taken off with null, and refused out of range
|
||||
// or past four decimals with nothing written.
|
||||
func TestProviderSaveTopUpRate(t *testing.T) {
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
t.Setenv("USERPROFILE", os.Getenv("HOME"))
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "sk-a", Chat: "http://127.0.0.1:1/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
providerRoutes(mux, nil)
|
||||
post := func(extra string) int {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
body := `{"id":"relay","from":"relay","name":"Relay","key":"","chat":"http://127.0.0.1:1/v1","icon":"generic","models":[],"headers":{}` + extra + `}`
|
||||
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/provider/save", strings.NewReader(body)))
|
||||
return w.Code
|
||||
}
|
||||
listed := func() float64 {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/providers", nil))
|
||||
var got struct {
|
||||
Providers []struct {
|
||||
ID string `json:"id"`
|
||||
TopUpRate float64 `json:"topUpRate"`
|
||||
} `json:"providers"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("%v: %s", err, w.Body)
|
||||
}
|
||||
for _, p := range got.Providers {
|
||||
if p.ID == "relay" {
|
||||
return p.TopUpRate
|
||||
}
|
||||
}
|
||||
t.Fatal("no relay")
|
||||
return 0
|
||||
}
|
||||
if c := post(`,"topUpRate":0.07`); c != 200 {
|
||||
t.Fatalf("save: %d", c)
|
||||
}
|
||||
if got := listed(); got != 0.07 {
|
||||
t.Fatalf("listed %v", got)
|
||||
}
|
||||
if c := post(""); c != 200 || listed() != 0.07 {
|
||||
t.Fatalf("left out, not kept: %d %v", c, listed())
|
||||
}
|
||||
for _, bad := range []string{"-1", "1001", "0.07142", `"abc"`} {
|
||||
if c := post(`,"topUpRate":` + bad); c == 200 {
|
||||
t.Fatalf("%s taken", bad)
|
||||
}
|
||||
}
|
||||
if got := listed(); got != 0.07 {
|
||||
t.Fatalf("a refused save changed it: %v", got)
|
||||
}
|
||||
if c := post(`,"topUpRate":null`); c != 200 || listed() != 0 {
|
||||
t.Fatalf("null didn't take it off: %d %v", c, listed())
|
||||
}
|
||||
}
|
||||
@@ -10,27 +10,51 @@ package provider
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// KeyPriceRate is the price rate the key keyID bills at: its own when the
|
||||
// user gave it one, else the provider's (0: the price as listed). own
|
||||
// says which.
|
||||
// user gave it one; else, on a provider with a top-up rate, its group's
|
||||
// rate read from the relay times that (key_rate_read.go) once one is
|
||||
// read; else the provider's (0: the price as listed). own says the user
|
||||
// gave the key its rate.
|
||||
func (p Provider) KeyPriceRate(keyID string) (rate float64, own bool) {
|
||||
if r, ok := p.KeyPriceRates[strings.ToLower(keyID)]; ok && r > 0 {
|
||||
return r, true
|
||||
}
|
||||
if r, ok := p.readKeyPriceRate(keyID); ok {
|
||||
return r, false
|
||||
}
|
||||
return p.PriceRate, false
|
||||
}
|
||||
|
||||
// readKeyPriceRate is the key's group rate read from its relay times the
|
||||
// provider's top-up rate, when it has one and a rate was read.
|
||||
func (p Provider) readKeyPriceRate(keyID string) (float64, bool) {
|
||||
if p.TopUpRate <= 0 || p.Account != nil || keyID == "" {
|
||||
return 0, false
|
||||
}
|
||||
g, ok := readKeyRate(p.ID, keyID)
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
return math.Round(g*p.TopUpRate*1e6) / 1e6, true
|
||||
}
|
||||
|
||||
// atKeyRate is p as the key keyID bills: its price rate the key's own when
|
||||
// it has one, so pricing p prices that key's calls.
|
||||
// it has one, so pricing p prices that key's calls. A read rate of 0 (a
|
||||
// free group) prices at nothing, not as listed.
|
||||
func (p Provider) atKeyRate(keyID string) Provider {
|
||||
if keyID == "" {
|
||||
return p
|
||||
}
|
||||
p.PriceRate, _ = p.KeyPriceRate(keyID)
|
||||
p.zeroRate = false
|
||||
if p.PriceRate == 0 {
|
||||
_, p.zeroRate = p.readKeyPriceRate(keyID)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
package provider
|
||||
|
||||
// A key's group rate read from its relay (@YIXIE233 on X): a relay built on
|
||||
// sub2api tells each key the rate its group bills at against the official
|
||||
// price, at GET /v1/sub2api/billing, and relays sell their credit at
|
||||
// different prices (¥1 for $1 at one, ¥7 for $100 at another). The user
|
||||
// says once, on the provider, what a relay dollar cost them (TopUpRate),
|
||||
// and each key bills at its group's rate times that, read again every few
|
||||
// hours, so a relay changing its prices needs nothing typed again.
|
||||
//
|
||||
// The read is never on a request's path: KeepKeyRatesRead asks each
|
||||
// relay in the background, and pricing looks the last reading up. A rate
|
||||
// the user gave a key of its own (KeyPriceRates) stands. A key not read
|
||||
// yet, or whose read failed with nothing read before, is unknown and
|
||||
// bills at the provider's PriceRate as before, never at 1× for a guess.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// sub2APIKeyBilling is sub2api's query for the rate a key's group bills at
|
||||
// (backend/internal/handler/gateway_key_billing.go): asked with the key,
|
||||
// it skips the panel's billing checks and doesn't mark the key used.
|
||||
const sub2APIKeyBilling = "/v1/sub2api/billing"
|
||||
|
||||
// keyRateEvery is how long a key's read rate stands before it is read
|
||||
// again, keyRateRetry how long after a failed read; keyRateTick how often
|
||||
// the loop looks for a key that is due.
|
||||
var (
|
||||
keyRateEvery = 6 * time.Hour
|
||||
keyRateRetry = 30 * time.Minute
|
||||
keyRateTick = 5 * time.Minute
|
||||
)
|
||||
|
||||
// TopUpRateOK says what is wrong with a provider's top-up rate, "" when
|
||||
// nothing: above 0 up to 1000, at most four decimals (¥5 for $70 is
|
||||
// 0.0714). None (0) is no rate: no key's group rate is read.
|
||||
func TopUpRateOK(r float64) string {
|
||||
if math.IsNaN(r) || r < 0 || r > 1000 {
|
||||
return "a top-up rate is from 0 to 1000"
|
||||
}
|
||||
if math.Abs(r*10000-math.Round(r*10000)) > 1e-6 {
|
||||
return "a top-up rate has at most four decimals, like 0.0714"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// keyRateRead is one key's last reading.
|
||||
type keyRateRead struct {
|
||||
// Rate is the group's rate, Known whether one was ever read
|
||||
Rate float64 `json:"rate"`
|
||||
Known bool `json:"known,omitempty"`
|
||||
// At is when it was last asked, Err what went wrong then ("" when
|
||||
// it answered)
|
||||
At time.Time `json:"at"`
|
||||
Err string `json:"err,omitempty"`
|
||||
Origin string `json:"origin,omitempty"`
|
||||
}
|
||||
|
||||
var keyRates struct {
|
||||
sync.Mutex
|
||||
m map[string]keyRateRead // provider id + " " + key id
|
||||
path string // the file m was read from
|
||||
}
|
||||
|
||||
func keyRatesPath() string { return filepath.Join(filepath.Dir(Path()), "key-rates.json") }
|
||||
|
||||
func keyRateKey(providerID, keyID string) string {
|
||||
return providerID + " " + strings.ToLower(keyID)
|
||||
}
|
||||
|
||||
// keyRatesLocked is the map, read from the file the first time (and
|
||||
// again for another config folder); a file that can't be read or doesn't
|
||||
// parse is nothing read yet. The caller holds keyRates.
|
||||
func keyRatesLocked() map[string]keyRateRead {
|
||||
path := keyRatesPath()
|
||||
if keyRates.m != nil && keyRates.path == path {
|
||||
return keyRates.m
|
||||
}
|
||||
keyRates.m, keyRates.path = map[string]keyRateRead{}, path
|
||||
if b, err := os.ReadFile(path); err == nil {
|
||||
var saved map[string]keyRateRead
|
||||
if json.Unmarshal(b, &saved) == nil {
|
||||
for k, v := range saved {
|
||||
keyRates.m[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
return keyRates.m
|
||||
}
|
||||
|
||||
func saveKeyRatesLocked() {
|
||||
b, err := json.Marshal(keyRates.m)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_ = os.MkdirAll(filepath.Dir(keyRatesPath()), 0o700)
|
||||
_ = writeFileAtomic(keyRatesPath(), b)
|
||||
}
|
||||
|
||||
// readKeyRate is the group rate last read for the key keyID of the
|
||||
// provider id, and whether one is known.
|
||||
func readKeyRate(providerID, keyID string) (float64, bool) {
|
||||
if providerID == "" || keyID == "" {
|
||||
return 0, false
|
||||
}
|
||||
keyRates.Lock()
|
||||
defer keyRates.Unlock()
|
||||
r, ok := keyRatesLocked()[keyRateKey(providerID, keyID)]
|
||||
return r.Rate, ok && r.Known
|
||||
}
|
||||
|
||||
// KeyRatesKey names the group rates read so far by what they are, for a
|
||||
// cache of costs to be built again when one changes: a read that found
|
||||
// the same rates leaves it as it was.
|
||||
func KeyRatesKey() string {
|
||||
keyRates.Lock()
|
||||
defer keyRates.Unlock()
|
||||
m := keyRatesLocked()
|
||||
if len(m) == 0 {
|
||||
return ""
|
||||
}
|
||||
ks := make([]string, 0, len(m))
|
||||
for k, r := range m {
|
||||
if r.Known {
|
||||
ks = append(ks, k+"="+strconv.FormatFloat(r.Rate, 'g', -1, 64))
|
||||
}
|
||||
}
|
||||
if len(ks) == 0 {
|
||||
return ""
|
||||
}
|
||||
slices.Sort(ks)
|
||||
sum := sha256.Sum256([]byte(strings.Join(ks, ";")))
|
||||
return "|rates:" + hex.EncodeToString(sum[:8])
|
||||
}
|
||||
|
||||
// KeyGroupRate is the group rate read from the relay for the key keyID,
|
||||
// and whether one is known, for a page to show; any provider's.
|
||||
func (p Provider) KeyGroupRate(keyID string) (float64, bool) {
|
||||
return readKeyRate(p.ID, keyID)
|
||||
}
|
||||
|
||||
// readsKeyRates says p's keys have their group rates read: a provider of
|
||||
// API keys the user gave a top-up rate.
|
||||
func readsKeyRates(p Provider) bool {
|
||||
return p.TopUpRate > 0 && p.Account == nil && !p.Off && !p.Hidden
|
||||
}
|
||||
|
||||
// keyRateOrigin is where p's relay is asked: the origin of its sub2api
|
||||
// key query when it has one, else of the first base it names. "" for a
|
||||
// host never asked (this computer, a vendor's own).
|
||||
func keyRateOrigin(p Provider) string {
|
||||
if sub2APIKeyLimits(p) {
|
||||
u, _ := BalanceQuery(p)
|
||||
if pu, err := url.Parse(strings.TrimSpace(u)); err == nil && pu.Host != "" && !notProbed(pu.Hostname()) {
|
||||
return pu.Scheme + "://" + strings.ToLower(pu.Host)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if origins := probeOrigins(p); len(origins) > 0 {
|
||||
return origins[0]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// sub2APIBilling is the part of sub2api's reply read: schema 1's object
|
||||
// and the rate it resolved for the key (its group's, or the user's own on
|
||||
// that group).
|
||||
type sub2APIBilling struct {
|
||||
Object string `json:"object"`
|
||||
ResolvedRateMultiplier *float64 `json:"resolved_rate_multiplier"`
|
||||
GroupRateMultiplier *float64 `json:"group_rate_multiplier"`
|
||||
}
|
||||
|
||||
// parseKeyBilling is the rate in a reply of sub2api's billing query; an
|
||||
// error for anything else.
|
||||
func parseKeyBilling(b []byte) (float64, error) {
|
||||
var r sub2APIBilling
|
||||
if err := json.Unmarshal(b, &r); err != nil {
|
||||
return 0, fmt.Errorf("not a sub2api billing reply: %w", err)
|
||||
}
|
||||
if r.Object != "sub2api.key_billing" {
|
||||
return 0, errors.New("not a sub2api billing reply")
|
||||
}
|
||||
rate := r.ResolvedRateMultiplier
|
||||
if rate == nil {
|
||||
rate = r.GroupRateMultiplier
|
||||
}
|
||||
if rate == nil || math.IsNaN(*rate) || math.IsInf(*rate, 0) || *rate < 0 {
|
||||
return 0, errors.New("the reply has no rate")
|
||||
}
|
||||
return *rate, nil
|
||||
}
|
||||
|
||||
// askKeyRate asks origin's billing query with p's key.
|
||||
func askKeyRate(ctx context.Context, p Provider, origin string) (float64, error) {
|
||||
ctx, cancel := context.WithTimeout(p.Via(ctx), 20*time.Second)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, origin+sub2APIKeyBilling, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
for k, v := range AuthHeaders(p, Chat) {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
for k, v := range p.SentHeaders(ctx) {
|
||||
req.Header.Set(k, withBalanceKey(v, p.Key, false))
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
b, _ := io.ReadAll(io.LimitReader(res.Body, 64<<10))
|
||||
if res.StatusCode >= 300 {
|
||||
return 0, fmt.Errorf("%s", res.Status)
|
||||
}
|
||||
return parseKeyBilling(b)
|
||||
}
|
||||
|
||||
// keyRateJob is one key to read.
|
||||
type keyRateJob struct {
|
||||
p Provider // with the key as its Key
|
||||
key string // keyRateKey
|
||||
origin string
|
||||
}
|
||||
|
||||
// keyRatesDue are the keys due a read at now.
|
||||
func keyRatesDue(now time.Time) []keyRateJob {
|
||||
var jobs []keyRateJob
|
||||
for _, p := range All() {
|
||||
if !readsKeyRates(p) {
|
||||
continue
|
||||
}
|
||||
origin := keyRateOrigin(p)
|
||||
if origin == "" {
|
||||
continue
|
||||
}
|
||||
keys := []string{p.Key}
|
||||
for _, k := range p.Keys {
|
||||
if !k.Off && k.Key != "" && k.Key != p.Key {
|
||||
keys = append(keys, k.Key)
|
||||
}
|
||||
}
|
||||
for _, k := range keys {
|
||||
if k == "" {
|
||||
continue
|
||||
}
|
||||
id := keyRateKey(p.ID, keyID(k))
|
||||
keyRates.Lock()
|
||||
last, seen := keyRatesLocked()[id]
|
||||
keyRates.Unlock()
|
||||
wait := keyRateEvery
|
||||
if last.Err != "" {
|
||||
wait = keyRateRetry
|
||||
}
|
||||
if seen && last.Origin == origin && now.Sub(last.At) < wait {
|
||||
continue
|
||||
}
|
||||
q := p
|
||||
q.Key = k
|
||||
jobs = append(jobs, keyRateJob{q, id, origin})
|
||||
}
|
||||
}
|
||||
return jobs
|
||||
}
|
||||
|
||||
// readKeyRatesDue reads every key that is due, one after another, and
|
||||
// keeps what each answered. A failed read keeps the rate read before, if
|
||||
// any, and is tried again sooner.
|
||||
func readKeyRatesDue(ctx context.Context) {
|
||||
for _, j := range keyRatesDue(time.Now()) {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
rate, err := askKeyRate(ctx, j.p, j.origin)
|
||||
keyRates.Lock()
|
||||
m := keyRatesLocked()
|
||||
r := m[j.key]
|
||||
if r.Origin != j.origin {
|
||||
r = keyRateRead{} // another relay's rate is not this one's
|
||||
}
|
||||
r.At, r.Origin = time.Now(), j.origin
|
||||
if err != nil {
|
||||
r.Err = Mask(j.p.Key) + ": " + strings.ReplaceAll(err.Error(), j.p.Key, Mask(j.p.Key))
|
||||
} else {
|
||||
r.Rate, r.Known, r.Err = rate, true, ""
|
||||
}
|
||||
m[j.key] = r
|
||||
saveKeyRatesLocked()
|
||||
keyRates.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// KeepKeyRatesRead reads the group rate of every key whose provider has a
|
||||
// top-up rate, when the magpie serving the gateway starts and again as
|
||||
// each is due (every six hours, half an hour after a failed read), until
|
||||
// ctx ends.
|
||||
func KeepKeyRatesRead(ctx context.Context) {
|
||||
t := time.NewTimer(0)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
case <-keyRatesPoke:
|
||||
}
|
||||
readKeyRatesDue(ctx)
|
||||
if !t.Stop() {
|
||||
select {
|
||||
case <-t.C:
|
||||
default:
|
||||
}
|
||||
}
|
||||
t.Reset(keyRateTick)
|
||||
}
|
||||
}
|
||||
|
||||
// keyRatesPoke wakes KeepKeyRatesRead before its next tick.
|
||||
var keyRatesPoke = make(chan struct{}, 1)
|
||||
|
||||
// ReadKeyRatesSoon has the keys due a read read now, not at the loop's
|
||||
// next tick: a top-up rate the user just gave a provider.
|
||||
func ReadKeyRatesSoon() {
|
||||
select {
|
||||
case keyRatesPoke <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// sub2api's own replies to GET /v1/sub2api/billing, as its handler writes
|
||||
// them (backend/internal/handler/gateway_key_billing.go, schema 1): a key
|
||||
// on a group of its own, one the user has a rate of their own on, with a
|
||||
// peak window.
|
||||
const (
|
||||
sub2APIBillingGroup = `{"object":"sub2api.key_billing","schema_version":1,"billing_scope":"token","group_rate_multiplier":0.08,"resolved_rate_multiplier":0.08,"peak_rate_enabled":false,"effective_rate_multiplier":0.08,"observed_at":"2026-11-20T03:00:00Z"}`
|
||||
sub2APIBillingUser = `{"object":"sub2api.key_billing","schema_version":1,"billing_scope":"token","group_rate_multiplier":1.2,"user_rate_multiplier":0.8,"resolved_rate_multiplier":0.8,"peak_rate_enabled":true,"peak_start":"09:00","peak_end":"18:00","peak_rate_multiplier":1.5,"applied_peak_multiplier":1,"effective_rate_multiplier":0.8,"timezone":"Asia/Shanghai","observed_at":"2026-11-20T03:00:00Z"}`
|
||||
)
|
||||
|
||||
func TestParseKeyBilling(t *testing.T) {
|
||||
for in, want := range map[string]float64{
|
||||
sub2APIBillingGroup: 0.08,
|
||||
sub2APIBillingUser: 0.8,
|
||||
`{"object":"sub2api.key_billing","group_rate_multiplier":2}`: 2,
|
||||
`{"object":"sub2api.key_billing","group_rate_multiplier":0,"resolved_rate_multiplier":0}`: 0,
|
||||
} {
|
||||
got, err := parseKeyBilling([]byte(in))
|
||||
if err != nil || got != want {
|
||||
t.Errorf("%s: %v %v, want %v", in, got, err, want)
|
||||
}
|
||||
}
|
||||
for _, in := range []string{
|
||||
``, `<html>`, `{}`, `{"error":{"code":"not_found"}}`,
|
||||
`{"object":"balance","resolved_rate_multiplier":1}`,
|
||||
`{"object":"sub2api.key_billing"}`,
|
||||
`{"object":"sub2api.key_billing","resolved_rate_multiplier":-1}`,
|
||||
} {
|
||||
if r, err := parseKeyBilling([]byte(in)); err == nil {
|
||||
t.Errorf("%q read as %v", in, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// relayKeys is a fake sub2api relay: each key's reply by its value, and
|
||||
// the keys it was asked with.
|
||||
type relayKeys struct {
|
||||
sync.Mutex
|
||||
reply map[string]func(w http.ResponseWriter)
|
||||
asked []string
|
||||
}
|
||||
|
||||
func (f *relayKeys) serve(t *testing.T) *httptest.Server {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != sub2APIKeyBilling {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
f.Lock()
|
||||
f.asked = append(f.asked, key)
|
||||
do := f.reply[key]
|
||||
f.Unlock()
|
||||
if do == nil {
|
||||
http.Error(w, `{"error":"invalid api key"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
do(w)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
func (f *relayKeys) set(key string, do func(w http.ResponseWriter)) {
|
||||
f.Lock()
|
||||
defer f.Unlock()
|
||||
f.reply[key] = do
|
||||
}
|
||||
|
||||
func (f *relayKeys) count() int {
|
||||
f.Lock()
|
||||
defer f.Unlock()
|
||||
return len(f.asked)
|
||||
}
|
||||
|
||||
func billing(rate string) func(w http.ResponseWriter) {
|
||||
return func(w http.ResponseWriter) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"object":"sub2api.key_billing","schema_version":1,"billing_scope":"token","group_rate_multiplier":` + rate + `,"resolved_rate_multiplier":` + rate + `,"peak_rate_enabled":false,"effective_rate_multiplier":` + rate + `,"observed_at":"2026-11-20T03:00:00Z"}`))
|
||||
}
|
||||
}
|
||||
|
||||
// keyRateHome is a sandbox home with the models.dev cache of priceCatalog
|
||||
// and a relay on loopback that may be asked.
|
||||
func keyRateHome(t *testing.T) {
|
||||
t.Helper()
|
||||
priceHome(t)
|
||||
priceCatalog(t)
|
||||
probeLocal = true
|
||||
t.Cleanup(func() { probeLocal = false })
|
||||
}
|
||||
|
||||
// @YIXIE233 on X: a sub2api relay reports each key's group rate, and the
|
||||
// user says once what a relay dollar cost (¥7 for $100 is 0.07). Each key
|
||||
// then bills at group rate × top-up rate, in the cost of a call and in
|
||||
// routing by price; a key the user gave a rate of their own keeps it.
|
||||
func TestKeyGroupRateTimesTopUpRate(t *testing.T) {
|
||||
keyRateHome(t)
|
||||
f := &relayKeys{reply: map[string]func(w http.ResponseWriter){"sk-cheap": billing("1"), "sk-pro": billing("2.5"), "sk-own": billing("4")}}
|
||||
srv := f.serve(t)
|
||||
own := keyID("sk-own")
|
||||
if err := Save(Provider{ID: "openai", Name: "Relay", Chat: srv.URL + "/v1", Key: "sk-cheap", Models: []string{"sol"}, PriceRate: 0.9, TopUpRate: 0.07,
|
||||
Keys: []KeyAccount{{Name: "Pro", Key: "sk-pro"}, {Name: "Own", Key: "sk-own"}},
|
||||
KeyPriceRates: map[string]float64{own: 0.3}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
readKeyRatesDue(t.Context())
|
||||
if n := f.count(); n != 3 {
|
||||
t.Fatalf("asked %d times, want each key once", n)
|
||||
}
|
||||
s := settings.Load()
|
||||
for _, c := range []struct {
|
||||
key string
|
||||
want float64
|
||||
}{
|
||||
{keyID("sk-cheap"), 2 * 0.07}, // $2 list × 1 × 0.07
|
||||
{keyID("sk-pro"), 2 * 0.175}, // × 2.5 × 0.07
|
||||
{own, 2 * 0.3}, // the user's own rate stands
|
||||
{"", 2 * 0.9}, // a call whose key isn't known: the provider's
|
||||
{"0000000000", 2 * 0.9},
|
||||
} {
|
||||
pr, ok, _ := BaseKeyPriceIn(s, "openai", c.key, "sol")
|
||||
if !ok || !near(pr.Input, c.want) {
|
||||
t.Errorf("key %q: $%v in, want $%v (%v)", c.key, pr.Input, c.want, ok)
|
||||
}
|
||||
}
|
||||
p, _ := Find("openai")
|
||||
q := *p
|
||||
q.Key = "sk-pro"
|
||||
if pr, ok := q.PriceAt(s, "sol", time.Time{}); !ok || !near(pr.Input, 0.35) {
|
||||
t.Fatalf("PriceAt with Pro: %+v %v", pr, ok)
|
||||
}
|
||||
if r, own := p.KeyPriceRate(keyID("sk-pro")); own || !near(r, 0.175) {
|
||||
t.Fatalf("KeyPriceRate: %v %v", r, own)
|
||||
}
|
||||
// not due again: nothing is asked a second time
|
||||
readKeyRatesDue(t.Context())
|
||||
if n := f.count(); n != 3 {
|
||||
t.Fatalf("asked again before it was due: %d", n)
|
||||
}
|
||||
// the reading is kept in the file, read by a magpie started after
|
||||
b, err := os.ReadFile(keyRatesPath())
|
||||
if err != nil || !strings.Contains(string(b), `"rate":2.5`) || strings.Contains(string(b), "sk-pro") {
|
||||
t.Fatalf("key-rates.json: %s %v", b, err)
|
||||
}
|
||||
}
|
||||
|
||||
func near(a, b float64) bool { return a-b < 1e-9 && b-a < 1e-9 }
|
||||
|
||||
// A read that fails is unknown, never 1×: a key never read bills at the
|
||||
// provider's PriceRate, and one read before keeps that reading while the
|
||||
// relay is down, its error kept with the key masked.
|
||||
func TestKeyGroupRateFailedReadIsUnknown(t *testing.T) {
|
||||
keyRateHome(t)
|
||||
f := &relayKeys{reply: map[string]func(w http.ResponseWriter){
|
||||
"sk-down": func(w http.ResponseWriter) { http.Error(w, "unavailable", http.StatusInternalServerError) },
|
||||
"sk-good": billing("2"),
|
||||
}}
|
||||
srv := f.serve(t)
|
||||
if err := Save(Provider{ID: "openai", Name: "Relay", Chat: srv.URL + "/v1", Key: "sk-down", Models: []string{"sol"}, PriceRate: 0.5, TopUpRate: 0.1,
|
||||
Keys: []KeyAccount{{Name: "Good", Key: "sk-good"}, {Name: "Gone", Key: "sk-gone"}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
readKeyRatesDue(t.Context())
|
||||
s := settings.Load()
|
||||
price := func(k string) float64 {
|
||||
t.Helper()
|
||||
pr, ok, _ := BaseKeyPriceIn(s, "openai", keyID(k), "sol")
|
||||
if !ok {
|
||||
t.Fatalf("%s: no price", k)
|
||||
}
|
||||
return pr.Input
|
||||
}
|
||||
if got := price("sk-down"); !near(got, 1) {
|
||||
t.Fatalf("a 500: $%v, want the provider's $1", got)
|
||||
}
|
||||
if got := price("sk-gone"); !near(got, 1) {
|
||||
t.Fatalf("a 401: $%v, want the provider's $1", got)
|
||||
}
|
||||
if got := price("sk-good"); !near(got, 0.4) {
|
||||
t.Fatalf("read: $%v, want $0.4", got)
|
||||
}
|
||||
// the relay goes down; the rate read before stands, tried again soon
|
||||
f.set("sk-good", func(w http.ResponseWriter) { w.WriteHeader(http.StatusNotFound) })
|
||||
keyRates.Lock()
|
||||
m := keyRatesLocked()
|
||||
r := m[keyRateKey("openai", keyID("sk-good"))]
|
||||
r.At = time.Now().Add(-keyRateEvery - time.Minute)
|
||||
m[keyRateKey("openai", keyID("sk-good"))] = r
|
||||
keyRates.Unlock()
|
||||
readKeyRatesDue(t.Context())
|
||||
if got := price("sk-good"); !near(got, 0.4) {
|
||||
t.Fatalf("a failed reread lost the rate: $%v", got)
|
||||
}
|
||||
keyRates.Lock()
|
||||
r = keyRatesLocked()[keyRateKey("openai", keyID("sk-good"))]
|
||||
keyRates.Unlock()
|
||||
if r.Err == "" || strings.Contains(r.Err, "sk-good") {
|
||||
t.Fatalf("its error: %q", r.Err)
|
||||
}
|
||||
}
|
||||
|
||||
// A group billed at 0 (a free group) is free, not the provider's rate.
|
||||
func TestKeyGroupRateZero(t *testing.T) {
|
||||
keyRateHome(t)
|
||||
f := &relayKeys{reply: map[string]func(w http.ResponseWriter){"sk-free": billing("0")}}
|
||||
srv := f.serve(t)
|
||||
if err := Save(Provider{ID: "openai", Name: "Relay", Chat: srv.URL + "/v1", Key: "sk-free", Models: []string{"sol"}, PriceRate: 0.5, TopUpRate: 0.07}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
readKeyRatesDue(t.Context())
|
||||
pr, ok, _ := BaseKeyPriceIn(settings.Load(), "openai", keyID("sk-free"), "sol")
|
||||
if !ok || pr.Input != 0 {
|
||||
t.Fatalf("a free group: %+v %v", pr, ok)
|
||||
}
|
||||
p, _ := Find("openai")
|
||||
if pr, ok := p.PriceAt(settings.Load(), "sol", time.Time{}); !ok || pr.Input != 0 {
|
||||
t.Fatalf("PriceAt: %+v %v", pr, ok)
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing is read for a provider without a top-up rate, and a relay on
|
||||
// this computer is never asked.
|
||||
func TestKeyGroupRateOnlyWhenAsked(t *testing.T) {
|
||||
keyRateHome(t)
|
||||
f := &relayKeys{reply: map[string]func(w http.ResponseWriter){"sk-a": billing("3")}}
|
||||
srv := f.serve(t)
|
||||
if err := Save(Provider{ID: "openai", Name: "Relay", Chat: srv.URL + "/v1", Key: "sk-a", Models: []string{"sol"}, PriceRate: 0.5}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
readKeyRatesDue(t.Context())
|
||||
if n := f.count(); n != 0 {
|
||||
t.Fatalf("no top-up rate, asked %d times", n)
|
||||
}
|
||||
p, _ := Find("openai")
|
||||
p.TopUpRate = 0.07
|
||||
if err := Save(*p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
probeLocal = false
|
||||
readKeyRatesDue(t.Context())
|
||||
if n := f.count(); n != 0 {
|
||||
t.Fatalf("a relay on loopback asked %d times", n)
|
||||
}
|
||||
if pr, ok, _ := BaseKeyPriceIn(settings.Load(), "openai", keyID("sk-a"), "sol"); !ok || !near(pr.Input, 1) {
|
||||
t.Fatalf("not read: %+v %v", pr, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTopUpRateOK(t *testing.T) {
|
||||
for _, r := range []float64{0, 0.07, 0.0714, 1, 1000} {
|
||||
if e := TopUpRateOK(r); e != "" {
|
||||
t.Errorf("%v: %s", r, e)
|
||||
}
|
||||
}
|
||||
for _, r := range []float64{-0.1, 1000.5, 0.07142} {
|
||||
if TopUpRateOK(r) == "" {
|
||||
t.Errorf("%v taken", r)
|
||||
}
|
||||
}
|
||||
// a rate kept wrong in the file is dropped on Save
|
||||
priceHome(t)
|
||||
if err := Save(Provider{ID: "relay", Name: "Relay", Chat: "https://relay.test/v1", Key: "sk-a", TopUpRate: 0.07142}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p, _ := Find("relay"); p.TopUpRate != 0 {
|
||||
t.Fatalf("kept %v", p.TopUpRate)
|
||||
}
|
||||
}
|
||||
|
||||
// KeepKeyRatesRead ends with its context.
|
||||
func TestKeepKeyRatesReadEnds(t *testing.T) {
|
||||
priceHome(t)
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
done := make(chan struct{})
|
||||
go func() { KeepKeyRatesRead(ctx); close(done) }()
|
||||
ReadKeyRatesSoon()
|
||||
cancel()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("still running")
|
||||
}
|
||||
}
|
||||
@@ -3045,7 +3045,7 @@ func tariffOf(s settings.Settings, p Provider, known bool, model string) (catalo
|
||||
pr.Peak = k
|
||||
}
|
||||
// what the provider bills against it (#819)
|
||||
if ok && p.PriceRate > 0 {
|
||||
if ok && (p.PriceRate > 0 || p.zeroRate) {
|
||||
pr = pr.Times(p.PriceRate)
|
||||
}
|
||||
if ok && p.cacheWritesAlike() {
|
||||
|
||||
@@ -607,6 +607,15 @@ type Provider struct {
|
||||
// at 0.5× and 1.2×), by its KeyID. A key not in it bills at PriceRate
|
||||
// (see key_rate.go).
|
||||
KeyPriceRates map[string]float64 `json:"keyPriceRates,omitempty"`
|
||||
// TopUpRate is, for a relay built on sub2api, what one of its dollars
|
||||
// cost the user (@YIXIE233 on X: ¥7 for $100 is 0.07): each key's
|
||||
// group rate is read from the relay (key_rate_read.go) and the key
|
||||
// bills at that times this, unless it has a rate in KeyPriceRates.
|
||||
// 0 is none: no group rate is read.
|
||||
TopUpRate float64 `json:"topUpRate,omitempty"`
|
||||
// zeroRate marks a PriceRate of 0 that is a rate, a free group's, not
|
||||
// the price as listed; set by atKeyRate alone
|
||||
zeroRate bool
|
||||
|
||||
// BalanceURL, when set, is where the vendor tells what is left on a
|
||||
// key, asked with the key the way a chat request carries it; BalancePath
|
||||
@@ -1888,6 +1897,9 @@ func normalize(p Provider) Provider {
|
||||
p.KeySpendCaps = normalKeySpendCaps(p.KeySpendCaps)
|
||||
p.KeyOwnBalances = normalKeyOwnBalances(p.KeyOwnBalances)
|
||||
p.KeyPriceRates = normalKeyPriceRates(p.KeyPriceRates)
|
||||
if TopUpRateOK(p.TopUpRate) != "" {
|
||||
p.TopUpRate = 0
|
||||
}
|
||||
if len(p.Models) > 0 {
|
||||
p.NoModels = false // a pick is no longer Select none
|
||||
}
|
||||
|
||||
@@ -919,7 +919,7 @@ func readRequestState(now time.Time) requestState {
|
||||
cfg := settings.Load()
|
||||
prices, _ := json.Marshal(cfg.ModelPrices)
|
||||
wires, _ := json.Marshal(cfg.Wires())
|
||||
meta := fmt.Sprintf("%s|%s|%s|%s|%s|%s|%s|%s", ids, renamed, prices, wires, statKey(provider.Path()), "asked:"+catalogBase(), clientAgentsKey(), clearedKey())
|
||||
meta := fmt.Sprintf("%s|%s|%s|%s|%s|%s|%s|%s", ids, renamed, prices, wires, statKey(provider.Path())+provider.KeyRatesKey(), "asked:"+catalogBase(), clientAgentsKey(), clearedKey())
|
||||
h := sha256.New()
|
||||
for _, current := range provider.All() {
|
||||
fmt.Fprintf(h, "%q:%q:%v:%t:%t:%t;", current.ID, current.Where(), current.Catalogs(), current.IsPlugin(), current.Account == nil, current.Key != "")
|
||||
|
||||
@@ -133,7 +133,7 @@ func usagePriceCacheKey(now time.Time) string {
|
||||
// one catalog for the providers and the group names read below (#5978)
|
||||
defer provider.Hold()()
|
||||
_, offset := now.Zone()
|
||||
meta := fmt.Sprintf("%s|%s|%s|%s|%s|%s|%d", statKey(settings.Path()), statKey(provider.Path()), catalog.CacheKey(), liveListKey("antigravity"), now.Format("2006-01-02"), now.Location(), offset)
|
||||
meta := fmt.Sprintf("%s|%s|%s|%s|%s|%s|%d", statKey(settings.Path()), statKey(provider.Path())+provider.KeyRatesKey(), catalog.CacheKey(), liveListKey("antigravity"), now.Format("2006-01-02"), now.Location(), offset)
|
||||
// Sign-ins and plugin lists can change independently of providers.json.
|
||||
// Their identity and price feeds affect both grouping and historical costs.
|
||||
h := sha256.New()
|
||||
|
||||
Reference in New Issue
Block a user