providers: each API key can bill at a price rate of its own (tnt12231 on X)
A relay sells keys in groups that bill at different rates against the
official price (0.5x on one, 1.2x on another) under one endpoint, and
magpie had only the provider's price rate. Now a key can have its own:
- provider.KeyPriceRates, keyed by key id like KeySpendCaps: cloned,
normalized on save, carried when a key is replaced. A key without one
bills at the provider's PriceRate. A price the user set for a model
stands as set, as it does under the provider's rate.
- Usage prices each call at its key's rate (usage.Pricer memoizes per
key id, BaseKeyPriceIn), so the Usage page, a key's spend cap and its
typed balance follow it. PriceAt, used to route by price, takes the
rate of the key the provider holds.
- GUI: the provider editor's Advanced has "Price rate per key" under
Price rate, shown only with two or more keys, folded past 8 keys like
the per-key proxies. An empty line shows the provider's rate as its
placeholder. Save sends keyPriceRates ({} clears, left out keeps).
The lines, the check and the placeholder live in keyrates.js,
imported when a provider with two or more keys opens. The core's
budget goes up 397 for what is left in app.js (the import, the
draft's copy, Advanced opening for it, the save's line, proxyLines
drawing another kind of line); app.js stays under its own.
- CLI: magpie provider key-rate <id> [key [rate|default]].
- docs/subsystems/providers-accounts.md: a Key price rates row.
Run, at this head (rebased on 287a1ffa2) through mote-run:
- go test ./internal/usage ./internal/cli ./internal/gui: ok.
./internal/provider: ok but TestHostBuildsNoList, red the same on
origin/main 51b98b1a8 (3 of 3), filed as #6479 (likely 16b8c300f).
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./..., go build: ok.
- GUI: key-price-rate.test.cjs (chromium and webkit x en, zh, zh-TW,
ja, de: own rates saved, provider rate as placeholder, bad values
refused, comma decimals, {} on clear, a folded key keeps its rate,
one key shows no lines and posts none), i18n-keys and
provider-many-keys-proxy (it shares proxyLines): ok. old-webkit:
keyrates.js added to its on-demand list; its two reds (compat.js
first, Safari 15.0 styles) fail the same on origin/main 51b98b1a8
(#5919 and the on-demand list's #6467 family).
- Earlier, at 92bce5c72: the GUI files that reach the provider editor
(134 tests). The 6 provider-many-keys reds fail the same on that base
(#6209); proxy-login-fields' chromium zh timeout passes 12/12 alone on
base and branch (#6374).
Broken by hand: atKeyRate leaving PriceRate as the provider's made
TestKeyPriceRatePrices and TestPricerKeyPriceRates red; the save not
sending keyPriceRates made 20 of 30 key-price-rate GUI tests red, and
keyrates.js dropping each parsed rate made them red again after the
move.
Not tried: a real relay with several keys at different rates; the real
Linux WebKitGTK app. The budget estimate and the Sessions page's costs
still use the provider's rate.
This commit is contained in:
@@ -19,6 +19,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, `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`) 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) |
|
||||
| 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) |
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
const keyRateUsage = "magpie provider key-rate <id> [key [rate|default]]"
|
||||
|
||||
// keyRateCmd shows, or sets, the price rate each of a provider's API keys
|
||||
// bills at (@tnt12231 on X: one relay, keys in groups at 0.5× and 1.2×):
|
||||
// a key's own, or the provider's (provider/key_rate.go).
|
||||
func keyRateCmd(rest []string) error {
|
||||
if len(rest) < 1 || len(rest) > 3 {
|
||||
return fmt.Errorf("%s", keyRateUsage)
|
||||
}
|
||||
p, err := provider.Find(rest[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Account != nil {
|
||||
return fmt.Errorf("%s is a subscription: a price rate of its own is for an API key (the provider's is in its editor)", p.Name)
|
||||
}
|
||||
if len(rest) > 2 {
|
||||
r, err := provider.ParseKeyPriceRate(rest[2])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := provider.SetKeyPriceRate(p.ID, rest[1], r); err != nil {
|
||||
return err
|
||||
}
|
||||
if p, err = provider.Find(p.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
keys := p.KeyList()
|
||||
if len(rest) > 1 {
|
||||
ref, ok := p.AccountRefOf(rest[1])
|
||||
if !ok {
|
||||
return fmt.Errorf("%s has no key %q", p.Name, rest[1])
|
||||
}
|
||||
for _, k := range keys {
|
||||
if k.ID == ref {
|
||||
keys = []provider.KeyInfo{k}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(keys) == 0 {
|
||||
fmt.Println(muted.Render(p.Name + " has no key"))
|
||||
return nil
|
||||
}
|
||||
for _, k := range keys {
|
||||
name := k.Masked + " " + muted.Render(k.ID)
|
||||
if k.Name != "" {
|
||||
name = k.Name + " " + muted.Render(k.Masked+" · "+k.ID)
|
||||
}
|
||||
r, own := p.KeyPriceRate(k.ID)
|
||||
switch {
|
||||
case own:
|
||||
fmt.Println(name, "· ×"+rateText(r))
|
||||
case r > 0:
|
||||
fmt.Println(name, muted.Render("· ×"+rateText(r)+", the provider's"))
|
||||
default:
|
||||
fmt.Println(name, muted.Render("· ×1, the provider's (the official price)"))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// rateText is a price rate as a line tells it: 0.8, 1.25, 2.
|
||||
func rateText(r float64) string { return strconv.FormatFloat(r, 'f', -1, 64) }
|
||||
@@ -0,0 +1,64 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// magpie provider key-rate gives a key a price rate of its own (by its
|
||||
// name or id, @tnt12231 on X), and default has it bill at the provider's
|
||||
// again. With no rate it lists the keys' rates. A key the provider
|
||||
// hasn't, a rate that isn't one and --help as a value are refused, and
|
||||
// nothing is written for them.
|
||||
func TestKeyRateCmd(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", "")
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k1", KeyName: "Team", Chat: "http://127.0.0.1:1/v1", PriceRate: 0.8,
|
||||
Keys: []provider.KeyAccount{{Name: "Spare", Key: "k2"}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rateOf := func(key string) (float64, bool) {
|
||||
t.Helper()
|
||||
p, err := provider.Find("relay")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p.KeyPriceRate(provider.KeyID(key))
|
||||
}
|
||||
if err := providerCmd([]string{"provider", "key-rate", "relay", "Team", "0.5"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r, own := rateOf("k1"); !own || r != 0.5 {
|
||||
t.Fatalf("Team: %v %v", r, own)
|
||||
}
|
||||
if err := providerCmd([]string{"provider", "key-rate", "relay", provider.KeyID("k2"), "1.2x"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r, own := rateOf("k2"); !own || r != 1.2 {
|
||||
t.Fatalf("Spare: %v %v", r, own)
|
||||
}
|
||||
for _, args := range [][]string{{"relay"}, {"relay", "Team"}} {
|
||||
if err := providerCmd(append([]string{"provider", "key-rate"}, args...)); err != nil {
|
||||
t.Fatal(args, err)
|
||||
}
|
||||
}
|
||||
for _, bad := range [][]string{{"relay", "Team", "--help"}, {"relay", "Team", "lots"}, {"relay", "Team", "0"}, {"relay", "nokey", "1"}, {"relay", "--help"}, {"relay", "Team", "1", "extra"}, {}} {
|
||||
if err := providerCmd(append([]string{"provider", "key-rate"}, bad...)); err == nil {
|
||||
t.Fatalf("%v taken", bad)
|
||||
}
|
||||
}
|
||||
if r, _ := rateOf("k1"); r != 0.5 {
|
||||
t.Fatalf("a refused value changed the rate: %v", r)
|
||||
}
|
||||
if err := providerCmd([]string{"provider", "key-rate", "relay", "Team", "default"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r, own := rateOf("k1"); own || r != 0.8 {
|
||||
t.Fatalf("default, the provider's: %v %v", r, own)
|
||||
}
|
||||
}
|
||||
@@ -108,6 +108,10 @@ const providerUsage = `usage:
|
||||
how much an API key may spend, in USD as the Usage page prices its calls,
|
||||
a day (the default), a month or in all from now: at it, routing takes the
|
||||
key for used up and goes on to the other keys and the fallbacks
|
||||
magpie provider key-rate <id> [key [rate|default]]
|
||||
the price rate one API key bills at against the official price, as a relay
|
||||
bills its key groups apart (e.g. 0.5): the Usage page counts that key's calls
|
||||
at it; default has it bill at the provider's rate
|
||||
magpie provider key-balance <id> [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|daily|off] [--expiring amount@yyyy-mm-dd|off]… [--expiring-remove [amount@]yyyy-mm-dd]…]
|
||||
the balance on an API key whose vendor tells none, typed from its own page
|
||||
in USD or in yuan (¥100): the Usage page shows it less what magpie prices the
|
||||
@@ -675,6 +679,8 @@ func providerCmd(args []string) error {
|
||||
return keyBalanceCmd(rest)
|
||||
case "spend-cap", "spend-caps":
|
||||
return spendCapCmd(rest)
|
||||
case "key-rate", "key-rates":
|
||||
return keyRateCmd(rest)
|
||||
case "account-weight", "account-weights":
|
||||
return accountWeightCmd(rest)
|
||||
case "queue":
|
||||
|
||||
@@ -3573,6 +3573,13 @@ body:not(.side-nav) #addSheet > .row-head.stuck::before { box-shadow: 0 1px 0 va
|
||||
.editor .plugin-option .segs { flex: none; }
|
||||
.editor .acct-proxy .who { font-size: 12px; font-weight: 500; color: var(--fg-2); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.editor .acct-proxies > .hint { margin-top: 0; }
|
||||
/* a key's own price rate (@tnt12231 on X): its name, then the rate */
|
||||
.editor .key-rates { display: grid; gap: 8px; margin-top: 4px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 10px; background: var(--card); }
|
||||
.editor .key-rates > .hint { margin-top: 0; }
|
||||
.editor .key-rates > .acct-proxy-more { justify-self: start; }
|
||||
.editor .key-rate { display: grid; grid-template-columns: minmax(0, 1fr) 96px; align-items: center; gap: 8px; min-width: 0; }
|
||||
.editor .key-rate .who { font-size: 12px; font-weight: 500; color: var(--fg-2); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.editor .key-rate input { min-width: 0; width: 100%; }
|
||||
/* past eight keys their lines fold behind All N keys, opened with a filter */
|
||||
.editor .acct-proxy-tools { display: flex; align-items: center; gap: 6px; min-width: 0; }
|
||||
.editor .acct-proxy-tools .acct-proxy-filter { flex: 1 1 auto; min-width: 0; }
|
||||
|
||||
@@ -7983,7 +7983,7 @@ document.addEventListener("click", (e) => {
|
||||
// which opens it: none hides behind a fold
|
||||
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) ||
|
||||
!!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.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) ||
|
||||
@@ -7996,7 +7996,8 @@ function priceRateError(ed) {
|
||||
function concurrencyDraft(p) {
|
||||
return { concurrency: p?.maxConcurrency == null ? "" : String(p.maxConcurrency), priceRate: p?.priceRate ? String(p.priceRate) : "",
|
||||
queueLimit: p?.queueLimit ? String(p.queueLimit) : "", queueWait: p?.queueWait ? String(p.queueWait) : "",
|
||||
maxRPM: p?.maxRPM ? String(p.maxRPM) : "", maxAccounts: p?.maxAccounts == null ? "" : String(p.maxAccounts) };
|
||||
maxRPM: p?.maxRPM ? String(p.maxRPM) : "", maxAccounts: p?.maxAccounts == null ? "" : String(p.maxAccounts),
|
||||
keyPriceRates: { ...p?.keyPriceRates } };
|
||||
}
|
||||
// queueOfDraft: { queueLimit, queueWait, maxRPM } as saved, 0 for none, or { bad }
|
||||
function queueOfDraft() {
|
||||
@@ -8097,13 +8098,15 @@ function keyProxyPicker(p) {
|
||||
}
|
||||
// proxyLines: a line for each account or key, keys folded as keyFold
|
||||
// does (@NetRozee on X); a key not drawn keeps its proxy.
|
||||
function proxyLines(items, hint, foldKeys) {
|
||||
// A key's own price rate draws its lines here too (keyrates.js):
|
||||
// lineOf draws one, own says it has a value of its own, cls is the box's.
|
||||
function proxyLines(items, hint, foldKeys, { lineOf = proxyLine, own = (it) => !!draft.accountProxies[it.k]?.mode, cls = "acct-proxies" } = {}) {
|
||||
if (items.length < 2) return null;
|
||||
draft.accountProxies = draft.accountProxies || {};
|
||||
const box = el("div", "acct-proxies");
|
||||
const box = el("div", cls);
|
||||
const tail = el("div", "hint", t(hint));
|
||||
if (!foldKeys || items.length <= KEYS_FOLD) {
|
||||
for (const it of items) box.append(proxyLine(it));
|
||||
for (const it of items) box.append(lineOf(it));
|
||||
box.append(tail);
|
||||
return box;
|
||||
}
|
||||
@@ -8113,8 +8116,7 @@ function proxyLines(items, hint, foldKeys) {
|
||||
for (const n of [...box.childNodes]) if (n !== tools && n !== tail) n.remove();
|
||||
const add = (n) => box.insertBefore(n, tail);
|
||||
if (q === null) {
|
||||
const own = (it) => !!draft.accountProxies[it.k]?.mode;
|
||||
for (const it of items.filter((it, i) => i < KEYS_FIRST || own(it)).slice(0, KEYS_PAGE)) add(proxyLine(it));
|
||||
for (const it of items.filter((it, i) => i < KEYS_FIRST || own(it)).slice(0, KEYS_PAGE)) add(lineOf(it));
|
||||
const more = el("button", "text acct-proxy-more", t("All {n} keys", { n: items.length }));
|
||||
more.type = "button";
|
||||
more.onclick = () => { q = ""; openTools(); draw(); tools.querySelector("input").focus(NO_SCROLL); };
|
||||
@@ -8122,7 +8124,7 @@ function proxyLines(items, hint, foldKeys) {
|
||||
return;
|
||||
}
|
||||
const matched = items.filter((it) => keyMatches(it.info, q));
|
||||
for (const it of matched.slice(0, KEYS_PAGE)) add(proxyLine(it));
|
||||
for (const it of matched.slice(0, KEYS_PAGE)) add(lineOf(it));
|
||||
if (!matched.length) add(el("div", "hint acct-proxy-none", t("No key matches")));
|
||||
else if (matched.length > KEYS_PAGE) add(el("div", "hint acct-proxy-rest", t("{n} more — type to narrow them down", { n: matched.length - KEYS_PAGE })));
|
||||
};
|
||||
@@ -8200,6 +8202,9 @@ function accountProxiesOfDraft() {
|
||||
return { map: out };
|
||||
}
|
||||
|
||||
// a key's own price rate (@tnt12231 on X), in keyrates.js
|
||||
const keyRateField = (p, at = el("span")) => p?.keyList?.length > 1 ? (import("./keyrates.js").then(() => at.replaceWith(...keyPriceRateField(p)), () => {}), [at]) : [];
|
||||
|
||||
// headers as ordered [name, value, json?] rows that survive a redraw; headersOf folds them back
|
||||
function headerRows(obj) {
|
||||
return Object.entries(obj || {}).map(([k, v]) => [k, v, false]);
|
||||
@@ -9863,7 +9868,7 @@ function drawEditor(p, presetID) {
|
||||
if (perKey) proxies.append(perKey);
|
||||
advIn.append(...field(t("Proxy"), proxies));
|
||||
advIn.append(...concurrencyField(p));
|
||||
advIn.append(...priceRateField(), ...countFreeField(), ...billingField(), ...rateWindowsField());
|
||||
advIn.append(...priceRateField(), ...keyRateField(p), ...countFreeField(), ...billingField(), ...rateWindowsField());
|
||||
|
||||
if (p?.cline || (isNew && pr?.id === "clinepass")) advIn.append(...upstreamField());
|
||||
|
||||
@@ -10362,6 +10367,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;
|
||||
body.rateWindows = self.rateWindowsOfDraft?.();
|
||||
if (body.rateWindows === false) return rateWindowsError(ed);
|
||||
if (p && priceTypedError(ed)) return;
|
||||
|
||||
@@ -2851,6 +2851,10 @@ const I18N = {
|
||||
"1, the official price": "1,即官方价格",
|
||||
"Costs are counted at the official price times this, as a relay bills, like 0.8 or 1.5; a price you set for a model stays as set": "费用按官方价格乘以此倍率计算,同中转站计费方式,例如 0.8 或 1.5;你为某个模型单独设置的价格保持不变",
|
||||
"Price rate: a number from 0 to 1000, at most three decimals": "价格倍率:0 到 1000 之间的数字,最多三位小数",
|
||||
"Price rate per key": "各 Key 的价格倍率",
|
||||
"A key left empty bills at the provider's price rate": "留空的 Key 按供应商的价格倍率计算",
|
||||
"Price rate of {user}": "{user} 的价格倍率",
|
||||
"Price rate of {user}: a number above 0 up to 1000, at most three decimals": "{user} 的价格倍率:大于 0、不超过 1000 的数字,最多三位小数",
|
||||
"{n}, as its plugin says": "{n}(插件的默认值)",
|
||||
"Over it, requests queue and go out in order; 0 or empty is no limit": "超出时排队,按顺序发出;0 或留空为不限制",
|
||||
"Accounts at once": "同时使用的账号数",
|
||||
@@ -8037,6 +8041,10 @@ const I18N = {
|
||||
"1, the official price": "1,即官方價格",
|
||||
"Costs are counted at the official price times this, as a relay bills, like 0.8 or 1.5; a price you set for a model stays as set": "費用按官方價格乘以此倍率計算,同中轉站計費方式,例如 0.8 或 1.5;你為某個模型單獨設定的價格保持不變",
|
||||
"Price rate: a number from 0 to 1000, at most three decimals": "價格倍率:0 到 1000 之間的數字,最多三位小數",
|
||||
"Price rate per key": "各 Key 的價格倍率",
|
||||
"A key left empty bills at the provider's price rate": "留空的 Key 依供應商的價格倍率計算",
|
||||
"Price rate of {user}": "{user} 的價格倍率",
|
||||
"Price rate of {user}: a number above 0 up to 1000, at most three decimals": "{user} 的價格倍率:大於 0、不超過 1000 的數字,最多三位小數",
|
||||
"{n}, as its plugin says": "{n}(外掛的預設值)",
|
||||
"Over it, requests queue and go out in order; 0 or empty is no limit": "超出時排隊,按順序發出;0 或留空為不限制",
|
||||
"Accounts at once": "同時使用的帳號數",
|
||||
@@ -13201,6 +13209,10 @@ const I18N = {
|
||||
"1, the official price": "1(公式価格)",
|
||||
"Costs are counted at the official price times this, as a relay bills, like 0.8 or 1.5; a price you set for a model stays as set": "費用は公式価格にこの倍率を掛けて計算します(中継サービスの課金方式、例: 0.8 や 1.5)。モデルごとに設定した価格はそのままです",
|
||||
"Price rate: a number from 0 to 1000, at most three decimals": "価格倍率: 0〜1000 の数値、小数点以下 3 桁まで",
|
||||
"Price rate per key": "キーごとの価格倍率",
|
||||
"A key left empty bills at the provider's price rate": "空欄のキーはプロバイダの価格倍率で計算されます",
|
||||
"Price rate of {user}": "{user} の価格倍率",
|
||||
"Price rate of {user}: a number above 0 up to 1000, at most three decimals": "{user} の価格倍率: 0 より大きく 1000 以下の数値、小数点以下 3 桁まで",
|
||||
"{n}, as its plugin says": "{n}(プラグインの既定値)",
|
||||
"Over it, requests queue and go out in order; 0 or empty is no limit": "超えたリクエストはキューに入り、順番に送られます。0 または空欄で上限なし",
|
||||
"Accounts at once": "同時に使うアカウント数",
|
||||
@@ -18396,6 +18408,10 @@ const I18N = {
|
||||
"1, the official price": "1, der offizielle Preis",
|
||||
"Costs are counted at the official price times this, as a relay bills, like 0.8 or 1.5; a price you set for a model stays as set": "Kosten werden zum offiziellen Preis mal diesem Faktor gezählt, wie ein Relay abrechnet, etwa 0.8 oder 1.5; ein für ein Modell gesetzter Preis bleibt",
|
||||
"Price rate: a number from 0 to 1000, at most three decimals": "Preisfaktor: eine Zahl von 0 bis 1000, höchstens drei Nachkommastellen",
|
||||
"Price rate per key": "Preisfaktor je Schlüssel",
|
||||
"A key left empty bills at the provider's price rate": "Ein leer gelassener Schlüssel wird zum Preisfaktor des Anbieters abgerechnet",
|
||||
"Price rate of {user}": "Preisfaktor von {user}",
|
||||
"Price rate of {user}: a number above 0 up to 1000, at most three decimals": "Preisfaktor von {user}: eine Zahl über 0 bis 1000, höchstens drei Nachkommastellen",
|
||||
"{n}, as its plugin says": "{n}, laut Erweiterung",
|
||||
"Over it, requests queue and go out in order; 0 or empty is no limit": "Darüber hinaus warten Anfragen in einer Warteschlange und gehen der Reihe nach raus; 0 oder leer heißt kein Limit",
|
||||
"Accounts at once": "Konten gleichzeitig",
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
// A key's own price rate (@tnt12231 on X: a relay bills its key groups
|
||||
// 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.
|
||||
function keyPriceRateLine(it) {
|
||||
const line = el("div", "key-rate");
|
||||
line.dataset.key = it.key;
|
||||
const who = el("span", "who", it.name);
|
||||
who.title = it.name;
|
||||
const box = input(draft.keyPriceRates[it.k] ?? "", String(draft.priceRate ?? "").trim() || "1");
|
||||
box.classList.add("key-price-rate");
|
||||
box.inputMode = "decimal";
|
||||
box.setAttribute("aria-label", t("Price rate of {user}", { user: it.name }));
|
||||
box.oninput = () => { draft.keyPriceRates[it.k] = box.value; };
|
||||
line.append(who, box);
|
||||
return line;
|
||||
}
|
||||
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 }));
|
||||
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
|
||||
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";
|
||||
});
|
||||
// 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) {
|
||||
const map = {};
|
||||
for (const [k, v] of Object.entries(draft.keyPriceRates || {})) {
|
||||
const s = String(v ?? "").trim();
|
||||
if (!s) continue;
|
||||
const n = decimalOf(s);
|
||||
if (!(n > 0 && n <= 1000) || Math.abs(n * 1000 - Math.round(n * 1000)) > 1e-6) {
|
||||
const line = ed.querySelector(`.key-rate[data-key="${k}"]`);
|
||||
shown(line?.querySelector("input.key-price-rate"))?.focus(NO_SCROLL);
|
||||
editorError(t("Price rate of {user}: a number above 0 up to 1000, at most three decimals", { user: line?.querySelector(".who")?.textContent || k }), "warn");
|
||||
return null;
|
||||
}
|
||||
map[k] = n;
|
||||
}
|
||||
return map;
|
||||
};
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
// `git log -L` of this file.
|
||||
const (
|
||||
appScriptBudget = 1_086_267 // app.js: 1,080,614 at 8016205e3, with the 5,653 of room it had
|
||||
coreScriptBudget = 1_268_248 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +168 for Discover's long lists drawn in part (the owner, 11-13), after the rest of its hook moved into plugingrid.js, imported when Plugins first draws; +296 for the cap toggle and Smart sentences that say what they do and the Sign in on another computer row (Wing8Aqua on X), packed to the shortest form, no page left to move them to; +333 for In turn's figure in a provider's editor and its words naming the message that goes round (Wing8Aqua on X), the figure itself in rotfig.js, imported when In turn is first shown, the hook packed to the shortest form; +236 for a lone capped Codex account's row saying its turns go to the fallbacks when Codex is connected (not_4O4 on X), the two helpers inlined, no page left to move it to; +717 for omp's advisor (Awad_Yoo on X, #6408): its three rows moved into ompadvisor.js, imported when an omp's settings show, and what is left is the import, the role's " · off" and the Settings line's name, packed to the shortest form; +468 for a plugin's own file import (auth.import) in the import sheet, in the plugin's words (marchen_cc on X), packed to one statement; importSay is read as the Providers rows draw, so it has no lazy page to go to, and nothing else was moved out; +180 for Claude Magpie's own Claude Code folder (xMopf7RF on X, #6459): its Advanced fold in claudemagpie.js, imported when it first shows, and what is left is the import and the fold's place in the Separate app line, 216 bytes packed to the shortest form, less the 36 of room there was; +81 for the Use Claude Magpie button on Claude Desktop's row (xMopf7RF on X), drawn by claudemagpie.js too, what is left the one line that places it (#2710); +225 for the Hermes row's Other profiles lines (Norethcy on X), which 1d60b165c took out while each profile had a row and c96f33d65 left with no place at all, packed to the shortest form; the dead hermes# Default note went with it, and the Agents rows draw it, so there is no page to move it to
|
||||
coreScriptBudget = 1_268_645 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +168 for Discover's long lists drawn in part (the owner, 11-13), after the rest of its hook moved into plugingrid.js, imported when Plugins first draws; +296 for the cap toggle and Smart sentences that say what they do and the Sign in on another computer row (Wing8Aqua on X), packed to the shortest form, no page left to move them to; +333 for In turn's figure in a provider's editor and its words naming the message that goes round (Wing8Aqua on X), the figure itself in rotfig.js, imported when In turn is first shown, the hook packed to the shortest form; +236 for a lone capped Codex account's row saying its turns go to the fallbacks when Codex is connected (not_4O4 on X), the two helpers inlined, no page left to move it to; +717 for omp's advisor (Awad_Yoo on X, #6408): its three rows moved into ompadvisor.js, imported when an omp's settings show, and what is left is the import, the role's " · off" and the Settings line's name, packed to the shortest form; +468 for a plugin's own file import (auth.import) in the import sheet, in the plugin's words (marchen_cc on X), packed to one statement; importSay is read as the Providers rows draw, so it has no lazy page to go to, and nothing else was moved out; +180 for Claude Magpie's own Claude Code folder (xMopf7RF on X, #6459): its Advanced fold in claudemagpie.js, imported when it first shows, and what is left is the import and the fold's place in the Separate app line, 216 bytes packed to the shortest form, less the 36 of room there was; +81 for the Use Claude Magpie button on Claude Desktop's row (xMopf7RF on X), drawn by claudemagpie.js too, what is left the one line that places it (#2710); +225 for the Hermes row's Other profiles lines (Norethcy on X), which 1d60b165c took out while each profile had a row and c96f33d65 left with no place at all, packed to the shortest form; the dead hermes# Default note went with it, and the Agents rows draw it, so there is no page to move it to; +397 for a key's own price rate (tnt12231 on X): its lines, check and placeholder in keyrates.js, imported when a provider with two or more keys opens, and what is left is the import, the draft's copy, Advanced opening for it, the save's one line and proxyLines drawing another kind of line
|
||||
)
|
||||
|
||||
// codeBytes is how many bytes of b are code: its blank lines, its lines
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A save's keyPriceRates (@tnt12231 on X): each key's own rate is taken
|
||||
// and /api/providers gives it back; left out (an editor of one key, or the
|
||||
// CLI's own) they are kept; {} takes them all off; a rate of 0 or out of
|
||||
// range is refused and nothing is written.
|
||||
func TestProviderSaveKeyPriceRates(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-half", Chat: "http://127.0.0.1:1/v1",
|
||||
Keys: []provider.KeyAccount{{Name: "Premium", Key: "sk-premium"}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
half, premium := provider.KeyID("sk-half"), provider.KeyID("sk-premium")
|
||||
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() map[string]float64 {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/providers", nil))
|
||||
var got struct {
|
||||
Providers []struct {
|
||||
ID string `json:"id"`
|
||||
KeyPriceRates map[string]float64 `json:"keyPriceRates"`
|
||||
} `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.KeyPriceRates
|
||||
}
|
||||
}
|
||||
t.Fatal("no relay")
|
||||
return nil
|
||||
}
|
||||
if c := post(`,"keyPriceRates":{"` + half + `":0.5,"` + premium + `":1.5}`); c != 200 {
|
||||
t.Fatalf("save: %d", c)
|
||||
}
|
||||
if got := listed(); len(got) != 2 || got[half] != 0.5 || got[premium] != 1.5 {
|
||||
t.Fatalf("listed %v", got)
|
||||
}
|
||||
if c := post(""); c != 200 {
|
||||
t.Fatalf("save: %d", c)
|
||||
}
|
||||
if got := listed(); len(got) != 2 || got[half] != 0.5 {
|
||||
t.Fatalf("left out, kept: %v", got)
|
||||
}
|
||||
for _, bad := range []string{"0", "-1", "1001", "0.1234"} {
|
||||
if c := post(`,"keyPriceRates":{"` + half + `":` + bad + `}`); c == 200 {
|
||||
t.Fatalf("%s taken", bad)
|
||||
}
|
||||
}
|
||||
if got := listed(); len(got) != 2 || got[half] != 0.5 {
|
||||
t.Fatalf("a refused save changed them: %v", got)
|
||||
}
|
||||
if c := post(`,"keyPriceRates":{}`); c != 200 {
|
||||
t.Fatalf("save: %d", c)
|
||||
}
|
||||
if got := listed(); len(got) != 0 {
|
||||
t.Fatalf("{} took them off: %v", got)
|
||||
}
|
||||
}
|
||||
@@ -414,6 +414,10 @@ type providerJSON struct {
|
||||
// of the hour (rateNowOf), 0 for 1×: read on this computer's clock,
|
||||
// which calls are counted on, not the browser's
|
||||
RateNow float64 `json:"rateNow,omitempty"`
|
||||
// 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 it charges against the official price, 0 for that (#819)
|
||||
PriceRate float64 `json:"priceRate,omitempty"`
|
||||
Models []modelJSON `json:"models"` // everything the vendor lists, exposed ones flagged
|
||||
@@ -898,7 +902,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,
|
||||
MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), MaxAccounts: p.MaxAccounts, PluginAccounts: p.PluginAtOnce(), PriceRate: p.PriceRate, KeyPriceRates: p.KeyPriceRates,
|
||||
RateWindows: p.RateWindows, RateNow: rateNowOf(p, time.Now()),
|
||||
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),
|
||||
@@ -2148,6 +2152,14 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
return
|
||||
}
|
||||
in.PriceRate = rate
|
||||
// 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 {
|
||||
if bad := provider.KeyPriceRateOK(r); bad != "" {
|
||||
fail(rw, fmt.Errorf("%s, not %v (key %s)", bad, r, k))
|
||||
return
|
||||
}
|
||||
}
|
||||
wins, keepWins, err := rateWindowsOf(req.RateWindows)
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
@@ -2297,6 +2309,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
if keepRate && old != nil {
|
||||
in.PriceRate = old.PriceRate
|
||||
}
|
||||
if in.KeyPriceRates == nil && old != nil {
|
||||
in.KeyPriceRates = old.KeyPriceRates
|
||||
}
|
||||
if keepWins && old != nil {
|
||||
in.RateWindows = old.RateWindows
|
||||
}
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A key's own price rate (@tnt12231 on X: a relay bills its key groups at
|
||||
// rates of their own). A provider of two keys or more has a line for each
|
||||
// key under Advanced, next to its Price rate; a key left empty shows the
|
||||
// provider's rate as its placeholder and bills at it. Save posts the keys
|
||||
// that have one, {} when none has, and refuses a rate that is 0, out of
|
||||
// range or has more than three decimals before anything is posted. A key a
|
||||
// fold hides keeps its rate. A provider of one key has no lines and posts
|
||||
// none, so the server keeps what it had. 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", "Half"), key("bbbbbbbbbb", "Premium"), key("cccccccccc", "Plain")], keyPriceRates: { bbbbbbbbbb: 1.2 } };
|
||||
const many = { ...base, id: "many", name: "Many", keyList: Array.from({ length: 10 }, (_, i) => key(String(i).repeat(10), `Key ${i}`)), keyPriceRates: { "8888888888": 0.6 } };
|
||||
const single = { ...base, id: "single", name: "Single", keyList: [key("aaaaaaaaaa", "Only")] };
|
||||
|
||||
function serve(lang, posts) {
|
||||
const providers = { providers: [relay, many, single], 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", "Price rate per key", "A key left empty bills at the provider's price rate", "Price rate of {user}",
|
||||
"Price rate of {user}: a number above 0 up to 1000, at most three 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 rate = (page, id) => page.locator(`.editor .key-rate[data-key="${id}"] input.key-price-rate`);
|
||||
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);
|
||||
};
|
||||
|
||||
test(`${engine} ${lang}: each key gets its own price rate, the rest the provider's`, 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 key's own rate opens Advanced");
|
||||
assert.equal(await page.locator(".editor label", { hasText: w["Price rate per key"] }).count(), 1);
|
||||
assert.equal(await page.locator(".editor .key-rates > .hint").textContent(), w["A key left empty bills at the provider's price rate"]);
|
||||
assert.equal(await page.locator(".editor .key-rate").count(), 3);
|
||||
assert.equal(await rate(page, "bbbbbbbbbb").inputValue(), "1.2");
|
||||
assert.equal(await rate(page, "aaaaaaaaaa").inputValue(), "");
|
||||
assert.equal(await rate(page, "aaaaaaaaaa").getAttribute("placeholder"), "1", "the official price when the provider has no rate");
|
||||
assert.equal(await rate(page, "aaaaaaaaaa").getAttribute("aria-label"), w["Price rate of {user}"].replace("{user}", "Half"));
|
||||
|
||||
// the provider's rate is what an empty key shows
|
||||
await page.locator(".editor input.price-rate").fill("0.9");
|
||||
assert.equal(await rate(page, "cccccccccc").getAttribute("placeholder"), "0.9");
|
||||
|
||||
const bad = w["Price rate of {user}: a number above 0 up to 1000, at most three decimals"].replace("{user}", "Half");
|
||||
for (const v of ["0", "0.1234", "1001", "-1", "abc"]) {
|
||||
await rate(page, "aaaaaaaaaa").fill(v);
|
||||
await (await saveButton(page)).click();
|
||||
await page.locator(".editor .editor-error").waitFor();
|
||||
assert.equal(await page.locator(".editor .editor-error").textContent(), bad, v);
|
||||
assert.equal(posts.length, 0, `${v} is not posted`);
|
||||
}
|
||||
// a comma for the decimal point, as some keyboards type it
|
||||
await rate(page, "aaaaaaaaaa").fill("0,5");
|
||||
let saved = await save(page, posts);
|
||||
assert.equal(saved.action, "save");
|
||||
assert.equal(saved.body.priceRate, 0.9);
|
||||
assert.deepEqual(saved.body.keyPriceRates, { aaaaaaaaaa: 0.5, bbbbbbbbbb: 1.2 });
|
||||
|
||||
await page.locator(".row.provider", { hasText: "Relay" }).click();
|
||||
await unfold(page);
|
||||
await rate(page, "bbbbbbbbbb").fill("");
|
||||
saved = await save(page, posts);
|
||||
assert.deepEqual(saved.body.keyPriceRates, {}, "every key back on the provider's rate is {}, not left out");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang}: a key a fold hides keeps its rate`, async (t) => {
|
||||
const { page, errors, posts } = await open(t, "Many");
|
||||
await unfold(page);
|
||||
// the first five, and the one with a rate of its own
|
||||
assert.equal(await page.locator(".editor .key-rate").count(), 6);
|
||||
assert.equal(await rate(page, "8888888888").inputValue(), "0.6");
|
||||
await rate(page, "0000000000").fill("2");
|
||||
const saved = await save(page, posts);
|
||||
assert.deepEqual(saved.body.keyPriceRates, { "0000000000": 2, "8888888888": 0.6 });
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang}: one key has no lines and posts none`, async (t) => {
|
||||
const { page, errors, posts } = await open(t, "Single");
|
||||
await unfold(page);
|
||||
await page.locator(".editor input.price-rate").waitFor();
|
||||
assert.equal(await page.locator(".editor .key-rates").count(), 0);
|
||||
const saved = await save(page, posts);
|
||||
assert(!Object.hasOwn(saved.body, "keyPriceRates"), "the server keeps what it had");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -181,9 +181,10 @@ test("compat.js is the first of the page's own scripts", async () => {
|
||||
// rotfig.js when a routing's In turn is first shown;
|
||||
// ompadvisor.js when an omp's settings first show;
|
||||
// claudemagpie.js when Claude Desktop's twin button or Advanced fold first shows;
|
||||
// keyrates.js when a provider with two or more keys opens;
|
||||
// the checks above
|
||||
// still read them
|
||||
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quotatable.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "agentwindow.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js", "addfloat.js", "plugingrid.js", "rotfig.js", "ompadvisor.js", "claudemagpie.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
|
||||
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quotatable.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "agentwindow.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js", "addfloat.js", "plugingrid.js", "rotfig.js", "ompadvisor.js", "claudemagpie.js", "keyrates.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
|
||||
});
|
||||
|
||||
test("the styles hold up in Safari 15.0", async () => {
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
package provider
|
||||
|
||||
// A key's own price rate (@tnt12231 on X): a relay sells keys in groups
|
||||
// that bill at different rates against the official price, 0.5× on one
|
||||
// and 1.2× on another, under one endpoint. Each key the user gave a rate
|
||||
// of its own bills at it wherever a call it sent is counted (the Usage
|
||||
// page, a key's spend cap and its typed balance); every other key bills at
|
||||
// the provider's PriceRate. A price the user set for a model stands as
|
||||
// set, as it does under the provider's rate.
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"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.
|
||||
func (p Provider) KeyPriceRate(keyID string) (rate float64, own bool) {
|
||||
if r, ok := p.KeyPriceRates[strings.ToLower(keyID)]; ok && r > 0 {
|
||||
return r, true
|
||||
}
|
||||
return p.PriceRate, false
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (p Provider) atKeyRate(keyID string) Provider {
|
||||
if keyID == "" {
|
||||
return p
|
||||
}
|
||||
p.PriceRate, _ = p.KeyPriceRate(keyID)
|
||||
return p
|
||||
}
|
||||
|
||||
// KeyPriceRateOK says what is wrong with a key's own price rate, "" when
|
||||
// nothing: above 0 up to 1000, at most three decimals. None is no value:
|
||||
// the key bills at the provider's rate.
|
||||
func KeyPriceRateOK(r float64) string {
|
||||
if bad := PriceRateOK(r); bad != "" {
|
||||
return bad
|
||||
}
|
||||
if r == 0 {
|
||||
return "a key's own price rate is above 0; take it off for the provider's"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// SetKeyPriceRate gives the key ref (its id or name) of the provider id a
|
||||
// price rate of its own, or with nil the provider's again.
|
||||
func SetKeyPriceRate(id, ref string, rate *float64) error {
|
||||
if rate != nil {
|
||||
if bad := KeyPriceRateOK(*rate); bad != "" {
|
||||
return fmt.Errorf("%s, not %v", bad, *rate)
|
||||
}
|
||||
}
|
||||
p, err := Find(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Account != nil {
|
||||
return fmt.Errorf("%s is a subscription: a price rate of its own is for an API key (the provider's is in its editor)", p.Name)
|
||||
}
|
||||
r, ok := p.accountRef(ref)
|
||||
if !ok {
|
||||
return fmt.Errorf("%s has no key %q", p.Name, ref)
|
||||
}
|
||||
k := strings.ToLower(r)
|
||||
m := map[string]float64{}
|
||||
for id, v := range p.KeyPriceRates {
|
||||
m[id] = v
|
||||
}
|
||||
if rate == nil {
|
||||
if _, had := m[k]; !had {
|
||||
return nil
|
||||
}
|
||||
delete(m, k)
|
||||
} else {
|
||||
m[k] = *rate
|
||||
}
|
||||
p.KeyPriceRates = m
|
||||
return Save(*p)
|
||||
}
|
||||
|
||||
// ParseKeyPriceRate reads a key's price rate as the CLI takes it: a number
|
||||
// ("0.8", "1.5x", "×1.2"), or default (nil) for the provider's.
|
||||
func ParseKeyPriceRate(s string) (*float64, error) {
|
||||
v := strings.ToLower(strings.TrimSpace(s))
|
||||
switch v {
|
||||
case "default", "provider", "off", "none", "-":
|
||||
return nil, nil
|
||||
}
|
||||
v = strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(strings.TrimPrefix(v, "×"), "x"), "x"))
|
||||
r, err := strconv.ParseFloat(v, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("a key's price rate is a number like 0.8 or 1.5, or default for the provider's, not %q", s)
|
||||
}
|
||||
if bad := KeyPriceRateOK(r); bad != "" {
|
||||
return nil, fmt.Errorf("%s, not %v", bad, r)
|
||||
}
|
||||
return &r, nil
|
||||
}
|
||||
|
||||
// normalKeyPriceRates is m as it is kept: key ids in lower case, rates
|
||||
// that aren't one left out; nil for none.
|
||||
func normalKeyPriceRates(m map[string]float64) map[string]float64 {
|
||||
var out map[string]float64
|
||||
for k, r := range m {
|
||||
k = strings.ToLower(strings.TrimSpace(k))
|
||||
if k == "" || KeyPriceRateOK(r) != "" {
|
||||
continue
|
||||
}
|
||||
if out == nil {
|
||||
out = map[string]float64{}
|
||||
}
|
||||
out[k] = r
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// A key's own price rate (@tnt12231 on X) is set by the key's id or name,
|
||||
// kept by its fingerprint in lower case, and taken off with nil; a key
|
||||
// without one bills at the provider's PriceRate. A rate of 0 or out of
|
||||
// range and a key the provider hasn't are refused, a subscription has no
|
||||
// keys to rate, and a key's value replaced keeps its rate.
|
||||
func TestKeyPriceRateSet(t *testing.T) {
|
||||
priceHome(t)
|
||||
if err := Save(Provider{ID: "relay", Name: "Relay", Chat: "https://relay.test/v1", Key: "sk-half", KeyName: "Half", PriceRate: 0.8,
|
||||
Keys: []KeyAccount{{Name: "Premium", Key: "sk-premium"}, {Name: "Plain", Key: "sk-plain"}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
half, premium, plain := keyID("sk-half"), keyID("sk-premium"), keyID("sk-plain")
|
||||
rateOf := func(ref string) (float64, bool) {
|
||||
t.Helper()
|
||||
p, err := Find("relay")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p.KeyPriceRate(ref)
|
||||
}
|
||||
if r, own := rateOf(half); own || r != 0.8 {
|
||||
t.Fatalf("no rate of its own, the provider's: %v %v", r, own)
|
||||
}
|
||||
if err := SetKeyPriceRate("relay", "Half", new(0.5)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SetKeyPriceRate("relay", strings.ToUpper(premium), new(1.2)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r, own := rateOf(strings.ToUpper(half)); !own || r != 0.5 {
|
||||
t.Fatalf("Half: %v %v", r, own)
|
||||
}
|
||||
if r, own := rateOf(premium); !own || r != 1.2 {
|
||||
t.Fatalf("Premium: %v %v", r, own)
|
||||
}
|
||||
if r, own := rateOf(plain); own || r != 0.8 {
|
||||
t.Fatalf("Plain follows the provider: %v %v", r, own)
|
||||
}
|
||||
if p, _ := Find("relay"); p.PriceRate != 0.8 {
|
||||
t.Fatalf("the provider's own rate changed: %v", p.PriceRate)
|
||||
}
|
||||
for _, bad := range []float64{0, -1, 1001, 0.1234} {
|
||||
if err := SetKeyPriceRate("relay", "Plain", new(bad)); err == nil {
|
||||
t.Fatalf("%v was taken", bad)
|
||||
}
|
||||
}
|
||||
if err := SetKeyPriceRate("relay", "nobody", new(1.0)); err == nil {
|
||||
t.Fatal("a key the provider hasn't got a rate")
|
||||
}
|
||||
// the value replaced, the rate goes with the key
|
||||
if _, _, err := ReplaceKey("relay", half, "sk-half-2"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r, own := rateOf(keyID("sk-half-2")); !own || r != 0.5 {
|
||||
t.Fatalf("replaced, Half's rate %v %v", r, own)
|
||||
}
|
||||
if err := SetKeyPriceRate("relay", "Half", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r, own := rateOf(keyID("sk-half-2")); own || r != 0.8 {
|
||||
t.Fatalf("taken off, the provider's again: %v %v", r, own)
|
||||
}
|
||||
// a rate kept wrong in the file (typed by hand) is left out on Save
|
||||
p, _ := Find("relay")
|
||||
p.KeyPriceRates = map[string]float64{strings.ToUpper(plain): 2, premium: 0, "": 3}
|
||||
if err := Save(*p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p, _ := Find("relay"); len(p.KeyPriceRates) != 1 || p.KeyPriceRates[plain] != 2 {
|
||||
t.Fatalf("kept: %v", p.KeyPriceRates)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeyPriceRateOnASubscription(t *testing.T) {
|
||||
user := signIn(t)
|
||||
if err := SetKeyPriceRate("codex", user, new(0.5)); err == nil {
|
||||
t.Fatal("a subscription's account got a key's rate")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseKeyPriceRate(t *testing.T) {
|
||||
for in, want := range map[string]float64{"0.8": 0.8, "1.5x": 1.5, "×1.2": 1.2, " 2 ": 2, "X0.5": 0.5} {
|
||||
r, err := ParseKeyPriceRate(in)
|
||||
if err != nil || r == nil || *r != want {
|
||||
t.Errorf("%q: %v %v", in, r, err)
|
||||
}
|
||||
}
|
||||
for _, in := range []string{"default", "Provider", "off", "-"} {
|
||||
if r, err := ParseKeyPriceRate(in); err != nil || r != nil {
|
||||
t.Errorf("%q: %v %v", in, r, err)
|
||||
}
|
||||
}
|
||||
for _, in := range []string{"0", "abc", "1001", "0.1234", ""} {
|
||||
if _, err := ParseKeyPriceRate(in); err == nil {
|
||||
t.Errorf("%q taken", in)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Each key's calls are priced at its own rate: two keys of one relay
|
||||
// count one model's list price apart, a key without a rate and a call
|
||||
// whose key isn't known at the provider's, and a price the user set for
|
||||
// the model stands as set for every key.
|
||||
func TestKeyPriceRatePrices(t *testing.T) {
|
||||
priceHome(t)
|
||||
priceCatalog(t)
|
||||
half, premium := keyID("sk-half"), keyID("sk-premium")
|
||||
if err := Save(Provider{ID: "openai", Name: "OpenAI", Chat: "https://api.openai.com/v1", Key: "sk-half", Models: []string{"sol"}, PriceRate: 0.8,
|
||||
Keys: []KeyAccount{{Name: "Premium", Key: "sk-premium"}, {Name: "Plain", Key: "sk-plain"}},
|
||||
KeyPriceRates: map[string]float64{half: 0.5, premium: 1.5}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := settings.Load()
|
||||
for _, c := range []struct {
|
||||
key string
|
||||
want float64
|
||||
}{{half, 1}, {premium, 3}, {keyID("sk-plain"), 1.6}, {"", 1.6}, {"0000000000", 1.6}} {
|
||||
pr, ok, _ := BaseKeyPriceIn(s, "openai", c.key, "sol")
|
||||
if !ok || pr.Input != c.want {
|
||||
t.Errorf("key %q: $%v in, want $%v (%v)", c.key, pr.Input, c.want, ok)
|
||||
}
|
||||
}
|
||||
// routing by price weighs a candidate at the rate of the key it holds
|
||||
p, _ := Find("openai")
|
||||
q := *p
|
||||
q.Key = "sk-premium"
|
||||
if pr, ok := q.PriceAt(s, "sol", time.Time{}); !ok || pr.Input != 3 {
|
||||
t.Fatalf("PriceAt with Premium: %+v %v", pr, ok)
|
||||
}
|
||||
if err := settings.Save(settings.Settings{ModelPrices: map[string]settings.ModelPrice{"openai/sol": statePrice(7)}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s = settings.Load()
|
||||
for _, k := range []string{half, premium, ""} {
|
||||
if pr, ok, _ := BaseKeyPriceIn(s, "openai", k, "sol"); !ok || pr.Input != 7 {
|
||||
t.Errorf("key %q: a price set for the model is not scaled: %+v %v", k, pr, ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -687,6 +687,7 @@ func ReplaceKey(id, keyRef, key string) (was, now string, err error) {
|
||||
moveKeyed(p.AccountWindowCaps, keyRef, now)
|
||||
moveKeyed(p.AccountWindowAmounts, keyRef, now)
|
||||
moveKeyed(p.KeyOwnBalances, keyRef, now)
|
||||
moveKeyed(p.KeyPriceRates, keyRef, now)
|
||||
return keyRef, now, Save(*p)
|
||||
}
|
||||
|
||||
|
||||
@@ -2872,11 +2872,19 @@ func priceIn(s settings.Settings, all []Provider, providerID, model string, at t
|
||||
// pricing many records holds both and multiplies the rates itself, as
|
||||
// the usage ledger's Pricer does, so one read serves every time of day.
|
||||
func BasePriceIn(s settings.Settings, providerID, model string) (catalog.Price, bool, []RateWindow) {
|
||||
return BaseKeyPriceIn(s, providerID, "", model)
|
||||
}
|
||||
|
||||
// BaseKeyPriceIn is BasePriceIn for a call the provider's key keyID sent:
|
||||
// at the key's own price rate when it has one (KeyPriceRates, @tnt12231
|
||||
// on X), else the provider's. An empty keyID, or one the provider doesn't
|
||||
// rate apart, is BasePriceIn.
|
||||
func BaseKeyPriceIn(s settings.Settings, providerID, keyID, model string) (catalog.Price, bool, []RateWindow) {
|
||||
p, known := byIDOrWas(providerID)
|
||||
if !known {
|
||||
p = Provider{ID: providerID}
|
||||
}
|
||||
pr, ok := priceOf(s, p, known, model, time.Time{})
|
||||
pr, ok := priceOf(s, p.atKeyRate(keyID), known, model, time.Time{})
|
||||
return pr, ok, p.RateWindows
|
||||
}
|
||||
|
||||
@@ -2918,13 +2926,17 @@ func priceOf(s settings.Settings, p Provider, known bool, model string, at time.
|
||||
|
||||
// PriceAt is what a call to model at p costs when made at at, as Usage
|
||||
// counts one made then: EffectivePriceAt for p as the caller holds it (a
|
||||
// routing group's member), its Peak still set, for the caller to apply
|
||||
// routing group's member, at the rate of the key it holds), its Peak still set, for the caller to apply
|
||||
// with Price.In and tell whether it did. A model served at no cost there
|
||||
// (FreeModel) costs nothing.
|
||||
func (p Provider) PriceAt(s settings.Settings, model string, at time.Time) (catalog.Price, bool) {
|
||||
if p.FreeModel(model) {
|
||||
return catalog.Price{}, true
|
||||
}
|
||||
// a key that bills at its own rate (KeyPriceRates) is priced at it
|
||||
if p.Account == nil && p.Key != "" {
|
||||
p = p.atKeyRate(keyID(p.Key))
|
||||
}
|
||||
return priceOf(s, p, true, model, at)
|
||||
}
|
||||
|
||||
|
||||
@@ -592,6 +592,11 @@ type Provider struct {
|
||||
// key's card shows it less what magpie priced its calls at since
|
||||
// (see key_balance_own.go).
|
||||
KeyOwnBalances map[string]OwnBalance `json:"keyOwnBalances,omitempty"`
|
||||
// KeyPriceRates is, for a provider of API keys, the price rate of each
|
||||
// key that bills at its own (@tnt12231 on X: one relay, keys in groups
|
||||
// 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"`
|
||||
|
||||
// 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
|
||||
@@ -999,6 +1004,7 @@ func (p Provider) clone() Provider {
|
||||
p.AccountNames = maps.Clone(p.AccountNames)
|
||||
p.KeySpendCaps = maps.Clone(p.KeySpendCaps)
|
||||
p.KeyOwnBalances = maps.Clone(p.KeyOwnBalances)
|
||||
p.KeyPriceRates = maps.Clone(p.KeyPriceRates)
|
||||
if p.AccountWindowCaps != nil {
|
||||
m := make(map[string]map[string]int, len(p.AccountWindowCaps))
|
||||
for k, v := range p.AccountWindowCaps {
|
||||
@@ -1863,6 +1869,7 @@ func normalize(p Provider) Provider {
|
||||
p.AccountNames = normalAccountNames(p.AccountNames)
|
||||
p.KeySpendCaps = normalKeySpendCaps(p.KeySpendCaps)
|
||||
p.KeyOwnBalances = normalKeyOwnBalances(p.KeyOwnBalances)
|
||||
p.KeyPriceRates = normalKeyPriceRates(p.KeyPriceRates)
|
||||
if len(p.Models) > 0 {
|
||||
p.NoModels = false // a pick is no longer Select none
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// One Pricer prices each call at the rate of the key that sent it
|
||||
// (@tnt12231 on X): a relay's two keys at 0.5× and 1.5× count the same
|
||||
// model apart within one page, a key without a rate of its own and a call
|
||||
// whose key wasn't recorded at the provider's 0.8, and the memo never
|
||||
// hands one key's price to another's call.
|
||||
func TestPricerKeyPriceRates(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
|
||||
// sol at $2 a million in
|
||||
os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755)
|
||||
os.WriteFile(catalog.CachePath(), []byte(`{"anthropic":{"id":"anthropic","models":{"sol":{"id":"sol","cost":{"input":2,"output":8}}}}}`), 0o644)
|
||||
catalog.Reset()
|
||||
t.Cleanup(catalog.Reset)
|
||||
half, premium := provider.KeyID("sk-half"), provider.KeyID("sk-premium")
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "sk-half", Chat: "https://relay.example/v1", PriceRate: 0.8,
|
||||
Keys: []provider.KeyAccount{{Name: "Premium", Key: "sk-premium"}, {Name: "Plain", Key: "sk-plain"}},
|
||||
KeyPriceRates: map[string]float64{half: 0.5, premium: 1.5}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
price := Pricer()
|
||||
now := time.Now()
|
||||
for _, c := range []struct {
|
||||
key string
|
||||
want float64
|
||||
}{{half, 1}, {premium, 3}, {provider.KeyID("sk-plain"), 1.6}, {"", 1.6}, {half, 1}} {
|
||||
pr := price(Record{Time: now, Agent: "codex", Provider: "relay", ProviderKeyID: c.key, Model: "sol", Input: 1e6, Status: 200})
|
||||
if pr == nil {
|
||||
t.Fatalf("key %q: no price", c.key)
|
||||
}
|
||||
if got := pr.Cost(1e6, 0, 0, 0); got != c.want {
|
||||
t.Errorf("key %q: $%v, want $%v", c.key, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -585,7 +585,7 @@ var ownPrice catalog.Price
|
||||
// one whose other models alone would stand for this call's, prices
|
||||
// nothing (#4278).
|
||||
func Pricer() func(Record) *catalog.Price {
|
||||
prices := map[[5]string]*catalog.Price{}
|
||||
prices := map[[6]string]*catalog.Price{}
|
||||
// each provider's rate windows as the same read of the prices saw
|
||||
// them: the windows are held once (BasePriceIn), each record's rate
|
||||
// read at its own time (provider.RateAt), so a window that opens
|
||||
@@ -602,7 +602,10 @@ func Pricer() func(Record) *catalog.Price {
|
||||
served = ""
|
||||
}
|
||||
id := r.priceID()
|
||||
k := [5]string{id, r.Model, served, r.SessionProvider, r.Effort}
|
||||
// a key that bills at its own rate (provider.KeyPriceRates) prices
|
||||
// its calls apart from the provider's other keys
|
||||
key := r.ProviderKeyID
|
||||
k := [6]string{id, r.Model, served, r.SessionProvider, r.Effort, key}
|
||||
if pr, ok := prices[k]; ok {
|
||||
return atWindow(pr, windows[id], r.Time)
|
||||
}
|
||||
@@ -618,15 +621,15 @@ func Pricer() func(Record) *catalog.Price {
|
||||
if v, ok, ws = provider.UserBasePriceIn(s, id, r.Model); !ok {
|
||||
// the model that ran is priced as itself, what the vendor
|
||||
// billed; with none, the asked-for one's price stands
|
||||
if v, ok, ws = provider.BasePriceIn(s, id, served); !ok {
|
||||
v, ok, ws = provider.BasePriceIn(s, id, r.Model)
|
||||
if v, ok, ws = provider.BaseKeyPriceIn(s, id, key, served); !ok {
|
||||
v, ok, ws = provider.BaseKeyPriceIn(s, id, key, r.Model)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
v, ok, ws = provider.BasePriceIn(s, id, r.Model)
|
||||
v, ok, ws = provider.BaseKeyPriceIn(s, id, key, r.Model)
|
||||
}
|
||||
if !ok && served != "" {
|
||||
v, ok, ws = provider.BasePriceIn(s, id, served)
|
||||
v, ok, ws = provider.BaseKeyPriceIn(s, id, key, served)
|
||||
}
|
||||
if ok {
|
||||
pr = &v
|
||||
|
||||
Reference in New Issue
Block a user