providers: rate windows bill a provider's hours at its own rate (#2463)
A provider can have up to 8 rate windows: days, a span that may cross midnight (on this computer's clock), and a rate. Inside a window a call costs the base price times the rate. The base is the user's model price as set, or the list price times PriceRate with the vendor's own peak (DeepSeek, Command Code, OpenCode Go) already in it. The author gave this order as the spec: a 0.8 window on a shared DeepSeek key takes 0.8 off the peak price at peak. The editor's hint says not to set the official peak hours again as a window, in every language. Each call is priced at its own time on the Usage page and its CSV, in the Requests tab's rows, and against a gateway key's cost limit. The Sessions page, group templates and the model list written into an agent's own config use the base price. /v1/models prices at now. Ported from YangHonghang's 2c9d459ff (rate-windows-2463-v2). The Go pricing, its tests and the translations are theirs. Changed here: - No budget raised. Their commit raised appScriptBudget and coreScriptBudget; core_budget_test.go is main's again. The editor's window rows, time menus, validation and hint moved to ratewindows.js, which app.js imports when the field is drawn (as signsheets.js is). The sliding-thumb and modalDepth comments were cut down to make room. The core is 1,535,528 of 1,536,586 and app.js 1,312,242 of 1,315,316. Until the script has loaded, a save leaves rateWindows out, and the server keeps the saved ones. - Their unrelated TestAssetsHaveNoConflictMarkers is dropped (one commit, one goal). - The row badge shows only for a provider with windows. Before, every provider with a price rate alone got a new ×badge. Its title is shorter, and so are its translations. - AgentPricer (agent model files: Pi, omp, OpenCode cost) uses the base price. Nothing rewrites those files when a window opens or closes, so a price taken at Sync stayed on outside the window. - internal/budget gets a TestMain through testenv, so the new test runs in a home of its own. - old-webkit's list of lazily loaded scripts names ratewindows.js. - The draft keeps each window as a shallow copy, and a day chip replaces its days array, so the saved provider is never changed. - The GUI test waits for the lazy script's hint, not a fixed 300ms. It also checks the peak note in each language. Run first on2f5a3f1c0, then again after rebasing on70d9996c5,8acb0d3a7andd609729cf. The rebase onto70d9996c5met main's ruleedit.js in old-webkit's list, and both are listed. - gofmt -l internal: clean at8acb0d3a7(129578c3dgofmt'd main's pi_api_test.go). - mote, on8acb0d3a7: go vet on usage, provider and gui ok; GOOS=linux and GOOS=windows go vet -tags nogui ./... ok. go test -tags nogui for internal/usage, provider, gui, budget and sessions: ok. The five internal/agent tests that are red on WSL (below) pass on mote there. Ond609729cf(a one-line mover min in internal/provider), internal/provider again: ok. - On2f5a3f1c0: internal/provider, usage, budget and sessions, and the gui RateNow|PriceRate|CoreScript|Budget tests, each under TZ=UTC, Asia/Shanghai and America/Los_Angeles: all ok. - wsl-run (magpie-desktop, Playwright chromium and webkit) on70d9996c5: provider-rate-windows, old-webkit, i18n-keys, provider-price-rate, provider-advanced-fold, agent-hides-editor, key-box-once, provider-many-keys, nokey-editor and editor-short-window: 200/200. On2f5a3f1c0the first five and model-price-edit: 132/132. On mote the same files hit WebKit launch timeouts (180s) under another session's full GUI suite (load 30), and that run was stopped. - Full suite, wsl-run (mote was running another session's full suite), go test -tags nogui -count=1 -timeout 45m ./... at 6e534f546 (this change on70d9996c5): every package ok except internal/agent. internal/agent fails TestInstalledVersion, TestGrokInstalled, TestCursorFolderFromTheEditorIsNotTheCLI, TestOmpDetectedWithPiDir and TestZedAppPath. This change doesn't touch internal/agent. At origin/main8acb0d3a7on the same box, TestInstalledVersion, TestGrokInstalled and TestOmpDetectedWithPiDir fail too: a fake CLI in /tmp exec'd with "Invalid argument". That is #4033 and #3548 (WSL2 binfmt interop). - Broken by hand, red each time: - Pricer without the window: TestPricerRateWindows, TestBlockRowsTakeTheirRateWindow, TestCostLimitCountsTheRateWindow. - Block rows without atWindow: TestBlockRowsTakeTheirRateWindow. - AgentPricer at now: TestAgentPricerLeavesTheRateWindowOut. - Badge for a price rate alone: TestRateNowOf. - Peak note removed: provider-rate-windows, 10 of 10 chromium layouts. - ratewindows.js not in old-webkit's list: old-webkit. Not tried: - A real relay billed by the hour. - The real desktop app (WebKitGTK, WKWebView). - The full GUI suite (mote was running another session's). Known limits: - No rate is stored per record, so changing the windows reprices history, as a changed PriceRate does. - Windows follow this computer's zone, with no zone of their own. - The Sessions page uses the base price. Co-authored-by: YangHonghang <honghang.yang@qq.com>
This commit is contained in:
@@ -18,6 +18,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| Part | Responsibility | Source |
|
||||
| --- | --- | --- |
|
||||
| Provider | `Provider` holds the endpoint bases for each `Protocol` (Chat, Responses, Anthropic, Gemini), the keys, `Fallback`, `Routing`, `Sink`, `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. 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 (…/v1beta added to a bare host, a pasted endpoint or model list cut back), requests go 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 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 list them, beside its `PriceRate`, or the editor's Save would quietly drop what it shows. | [`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`) |
|
||||
| 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) |
|
||||
| Zhipu's 200 refusals | Zhipu's and Z.ai's `/api/v1` (the GLM Coding Plan's Responses API, from their Codex pages) and `/api/monitor` answer a refusal 200 in the platform's envelope, `{"code":1000,"msg":"身份验证失败。","success":false}`, where their OpenAI and Anthropic endpoints answer the same key 401 (@xanahopper on X: a refused key tested green on the Responses row only). `ZhipuEnveloped` turns a 2xx JSON body from `open.bigmodel.cn` or `api.z.ai` with `success: false` into `{"error":{"code","message"}}` at the status Zhipu's error-code table gives (1000–1005 → 401, 1113 and 1302–1399 → 429, 1220 → 403, 1210–1229, 1261 and 1301 → 400, anything else → 502), in the provider test's `probe` (endpoint tests, model tests, Detect APIs) and the gateway's `forwardOnce`. A stream, a compressed body, a body over 64 KB and every other host pass as they came. The plan's quota card for a key refused there (1000–1005, or a 401) says `<Zhipu or Z.ai> didn't take this key (<their words>): …` with the vendor's API-keys page (`zhipuRefused`), not asked again as a team's key, and the GUI shows it as that (`quotaError`) rather than "Allowance unavailable". | [`zhipu_envelope.go`](../../internal/provider/zhipu_envelope.go), [`planquota.go`](../../internal/provider/planquota.go), [`test.go`](../../internal/provider/test.go) |
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package budget
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
// A call inside one of its provider's rate windows (#2463) costs its rate
|
||||
// against a gateway key's cost limit, so the same tokens spend the cap in
|
||||
// fewer calls than outside the window: the records are priced at their
|
||||
// own time, by the same Pricer the Usage page prices with.
|
||||
func TestCostLimitCountsTheRateWindow(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"))
|
||||
catalog.Reset()
|
||||
t.Cleanup(catalog.Reset)
|
||||
// $1000 a million input: 300 tokens of input a call costs $0.30
|
||||
// outside the window, $0.90 inside it
|
||||
in, zero := 1000.0, 0.0
|
||||
if err := settings.Save(settings.Settings{ModelPrices: map[string]settings.ModelPrice{
|
||||
"plan/m1": {Input: &in, Output: &zero, CacheRead: &zero, CacheWrite: &zero},
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "k", Chat: "https://plan.example/v1",
|
||||
RateWindows: []provider.RateWindow{{Start: "10:00", End: "14:00", Rate: 3}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newKey := func(name string) access.Key {
|
||||
t.Helper()
|
||||
if _, err := access.Update("add-key", access.Change{Name: name}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ks, err := access.List()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, k := range ks {
|
||||
if k.Name == name {
|
||||
if _, err := access.Update("limit-key", access.Change{Key: k.ID, Limit: &access.Limit{Period: "day", Cost: 1.0}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ks, err := access.List()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, k := range ks {
|
||||
if k.Name == name {
|
||||
return k
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
t.Fatal("the key is not there")
|
||||
return access.Key{}
|
||||
}
|
||||
day := time.Now()
|
||||
at := func(h, m int) time.Time {
|
||||
return time.Date(day.Year(), day.Month(), day.Day(), h, m, 0, 0, time.Local)
|
||||
}
|
||||
spent := func(k access.Key, when time.Time) bool {
|
||||
t.Helper()
|
||||
who := access.Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More}
|
||||
_, refused := Reserve(who, -1, "", when)
|
||||
return refused != nil
|
||||
}
|
||||
call := func(k access.Key, h, m int) {
|
||||
t.Helper()
|
||||
Append(usage.Record{Time: at(h, m), Provider: "plan", Model: "m1", Input: 300, Status: 200, CallerKeyID: k.ID})
|
||||
}
|
||||
|
||||
// two calls at the peak's 3×, $0.90 each: $1.80 of a $1 cap, the next
|
||||
// is out; the same two off the peak are $0.60 and leave room
|
||||
peak := newKey("Peak")
|
||||
call(peak, 11, 0)
|
||||
call(peak, 11, 30)
|
||||
if !spent(peak, at(11, 40)) {
|
||||
t.Fatal("a key over $1 of peak calls is let in")
|
||||
}
|
||||
off := newKey("Off")
|
||||
call(off, 15, 0)
|
||||
call(off, 15, 10)
|
||||
if spent(off, at(15, 20)) {
|
||||
t.Fatal("two off-peak calls spent a $1 cap")
|
||||
}
|
||||
call(off, 15, 30)
|
||||
if spent(off, at(15, 40)) {
|
||||
t.Fatal("three off-peak calls, $0.90 of a $1 cap, are spent")
|
||||
}
|
||||
call(off, 15, 50)
|
||||
if !spent(off, at(16, 0)) {
|
||||
t.Fatal("four off-peak calls, $1.20 of a $1 cap, are let in")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package budget
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
// The tests run in a home of their own, never the user's real files.
|
||||
func TestMain(m *testing.M) { testenv.Main(m) }
|
||||
@@ -4539,6 +4539,21 @@ body .row.agent .ag-prefs .row.pref .who { display: block; }
|
||||
:is(.ag-prefs, .agent-prefs) .compact-at { flex: 0 1 auto; min-width: 0; flex-wrap: wrap; row-gap: 6px; }
|
||||
/* Settings' search finds them; not searching, the links stay out */
|
||||
#view-settings:not(.set-searching) #agentPrefLinks { display: none; }
|
||||
|
||||
/* a provider's rate windows (#2463): the editor's rows, a day chip each,
|
||||
a span and a rate beside them */
|
||||
.rate-windows > .rate-win:last-child + button { align-self: start; }
|
||||
.rate-win { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
|
||||
.rate-win .day-chips { display: flex; gap: 2px; }
|
||||
.rate-win .day-chip { min-width: 24px; height: 24px; padding: 0 4px; border: 1px solid var(--line); border-radius: 6px; background: var(--card); color: var(--muted); font: inherit; font-size: 11px; }
|
||||
.rate-win .day-chip.on { color: var(--fg); background: var(--seg-thumb); box-shadow: var(--seg-edge); }
|
||||
.rate-win input { width: 64px; height: 28px; padding: 0 8px; border: 1px solid var(--line); border-radius: 7px; background: var(--card); color: var(--fg); font: inherit; font-size: 12px; }
|
||||
.rate-win .rate-rate { width: 56px; }
|
||||
.rate-win .rate-dash { color: var(--muted); }
|
||||
.rate-win .rate-win-del { flex: none; padding: 0 6px; color: var(--muted); }
|
||||
.rate-win .rate-win-del:hover { color: var(--red); }
|
||||
.rate-win .rate-time { width: 86px; height: 28px; justify-content: space-between; padding: 0 8px; flex: none; }
|
||||
.rate-win .rate-time[data-value=""] span { color: var(--muted); }
|
||||
.sess-pick.led-more { padding: 0 6px; }
|
||||
.sess-pick.led-more svg { transform: none; }
|
||||
.sess-tools .led-rename { flex: none; width: 180px; height: 26px; padding: 0 8px; border-radius: 7px; font-size: 12px; }
|
||||
|
||||
+29
-23
@@ -6320,6 +6320,11 @@ function renderProviders() {
|
||||
if (p.off) name.append(el("span", "badge off", t("Switched off")));
|
||||
if (p.move && p.move.state !== "plugin") name.append(deprecatedBadge());
|
||||
const n = p.models.filter((m) => m.on).length;
|
||||
// rate windows: what it bills at now (#2463)
|
||||
if (p.rateNow > 0) {
|
||||
const rate = "×" + (p.rateNow < 0.01 ? "<0.01" : +p.rateNow.toFixed(2));
|
||||
name.append(Object.assign(el("span", "badge rate-now", rate), { title: t("Bills at {rate} now: the price rate times this hour's window", { rate }) }));
|
||||
}
|
||||
// a provider that only draws images (Settings → Image generation) says so
|
||||
const models = n ? t(n === 1 ? "{n} model" : "{n} models", { n })
|
||||
: p.draws ? t(p.draws === 1 ? "{n} image model" : "{n} image models", { n: p.draws }) : t(p.noModels ? "usage only" : "no models exposed");
|
||||
@@ -7907,6 +7912,12 @@ function priceRateField() {
|
||||
box.oninput = () => { draft.priceRate = box.value; };
|
||||
return field(t("Price rate"), box, t("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"));
|
||||
}
|
||||
// a provider's hours at its own rate (#2463), drawn by ratewindows.js
|
||||
function rateWindowsField() {
|
||||
const box = el("div", "stack rate-windows"), d = draft;
|
||||
import("./ratewindows.js").then(() => rateWindowsPaint(box, d), statusErr);
|
||||
return field(t("Rate windows"), box);
|
||||
}
|
||||
// pluginOptionsField: the switches a plugin declares for its provider
|
||||
// (auth.options, #2038, Vocllum), each an Off/On beside the plugin's own
|
||||
// words for it, put in as text. One the plugin asks to confirm is asked
|
||||
@@ -8038,6 +8049,7 @@ function advancedSet(d, p) {
|
||||
return (d.headers || []).some(([k]) => (k || "").trim()) || !!(d.extraBody || "").trim() || !!(d.replyHeaders || "").trim() ||
|
||||
!!d.proxyMode || Object.values(d.accountProxies || {}).some((x) => x?.mode) ||
|
||||
[d.concurrency, 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 || d.unredacted || d.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff) ||
|
||||
!!d.fallback?.length || !!p?.balanceToken?.set;
|
||||
}
|
||||
@@ -8822,13 +8834,11 @@ $("#modal").addEventListener("keydown", (e) => {
|
||||
// relative top and a cap on its height. A change made in the page is held
|
||||
// before it is drawn (a mutation's microtask); a resize a frame later.
|
||||
const modalHold = { off: 0, at: null, y: 0, cap: null, capSet: "", touched: false };
|
||||
// how far down the dialog an element sits, to the fraction of a pixel,
|
||||
// what moves it in an animation (a row coming in) left out. An element
|
||||
// that scales (a Copy button's pop, a segment pressed) is measured by its
|
||||
// own top as drawn unscaled, round its transform-origin: measured by what
|
||||
// holds it, a pressed segment read 2px above where it was marked, and the
|
||||
// dialog went 2px down at every click (the owner, 10-23). One that turns
|
||||
// or skews is measured by what holds it.
|
||||
// how far down the dialog an element sits, its animation (a row coming
|
||||
// in) left out. One that scales (a Copy pop, a pressed segment) counts by
|
||||
// its own unscaled top: by its holder's, a pressed segment read 2px high
|
||||
// and the dialog crept down at each click (the owner, 10-23). One that
|
||||
// turns or skews counts by its holder.
|
||||
function modalDepth(a, d) {
|
||||
if (!a?.isConnected || !d.contains(a) || a === d || !a.offsetParent) return null;
|
||||
if (getComputedStyle(d).transform === "none") {
|
||||
@@ -9047,18 +9057,10 @@ const modalBackdrop = backdropClick($("#modal"));
|
||||
$("#modal").onclick = (e) => { if (modalBackdrop(e)) cancelEdit(); };
|
||||
|
||||
// ---------- sliding thumb ----------
|
||||
// Pills (the nav, every segmented control) have one thumb that glides to the
|
||||
// selected option instead of each option lighting up on its own.
|
||||
//
|
||||
// A thumb glides only when the option picked changes, and only from where
|
||||
// it is on the screen. Most controls are drawn again on every save (all of
|
||||
// Settings is), and a redrawn control takes the thumb of the one it
|
||||
// replaces, the glide under way with it: the same element, so nothing about
|
||||
// its motion is worked out again. It glides on to the option picked if that
|
||||
// is another (a save refused puts one back), and otherwise is left as it
|
||||
// is. A thumb is placed only where the control is laid out: one drawn
|
||||
// hidden (Settings at start, a tab not shown) is put under its option,
|
||||
// still, when it is shown or sized again (thumbFit).
|
||||
// Pills (the nav, every segmented control) have one thumb that glides to
|
||||
// the selected option, only when the pick changes and from where it is on
|
||||
// screen: a control redrawn on save (all of Settings is) takes the old one's
|
||||
// thumb, glide and all. One drawn hidden is placed once shown (thumbFit).
|
||||
const thumbs = new Map(); // control position → { th, pick, to }: its thumb, the option it is under or going to, and where that is
|
||||
const THUMB_MS = 280, THUMB_EASE = "cubic-bezier(.2, .8, .2, 1)"; // --ease
|
||||
const thumbKeys = new WeakMap(); // box → its key, for thumbFit
|
||||
@@ -9206,7 +9208,7 @@ function baseAPIOf(p) {
|
||||
|
||||
// draftOf is a saved provider as its editor's form holds it.
|
||||
function draftOf(p) {
|
||||
return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), icon: p.icon || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], searches: !!p.searches, unredacted: !!p.unredacted, insecureTLS: !!p.insecureTLS, limitRestOff: !!p.limitRestOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p) };
|
||||
return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), icon: p.icon || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], searches: !!p.searches, unredacted: !!p.unredacted, insecureTLS: !!p.insecureTLS, limitRestOff: !!p.limitRestOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) };
|
||||
}
|
||||
|
||||
// duplicateProvider opens the Add form on a copy of p (#268): its URLs,
|
||||
@@ -9512,7 +9514,7 @@ function drawEditor(p, presetID) {
|
||||
if (perAccount) proxies.append(perAccount);
|
||||
advIn.append(...field(t("Proxy"), proxies));
|
||||
advIn.append(...concurrencyField(p));
|
||||
advIn.append(...priceRateField());
|
||||
advIn.append(...priceRateField(), ...rateWindowsField());
|
||||
if (p.cline) advIn.append(...upstreamField());
|
||||
ed.append(...pluginOptionsField(subOf(a.agent)));
|
||||
// a plugin's provider is reached inside magpie: its plugin:// URLs go
|
||||
@@ -9550,10 +9552,12 @@ function drawEditor(p, presetID) {
|
||||
if (queue.bad) return queueError(ed, queue.bad);
|
||||
const priceRate = priceRateOfDraft();
|
||||
if (priceRate === undefined) return priceRateError(ed);
|
||||
const rateWindows = self.rateWindowsOfDraft?.();
|
||||
if (rateWindows === false) return rateWindowsError(ed);
|
||||
if (priceTypedError(ed)) return;
|
||||
const picked = accountModelsDraft(p);
|
||||
if (picked === false) return pickError();
|
||||
const body = { id: p.id, models: chosenIds(), noModels: noneChosen(), bestInFamily: bestChosen(), unlisted: draft.unlisted, hiddenDrawers: draft.hiddenDrawers, fallback: draft.fallback, contexts: cx.map, outputs: ox.map, compacts: cpx.map, proxy, accountProxies: own.map, maxConcurrency, ...queue, priceRate, modelPrefs: modelPrefsOfDraft(), pinUpstream: !!draft.pinUpstream, ...(p.carriesCompaction ? { nativeCompaction: !!draft.nativeCompaction } : {}), ...routingOfDraft(p) };
|
||||
const body = { id: p.id, models: chosenIds(), noModels: noneChosen(), bestInFamily: bestChosen(), unlisted: draft.unlisted, hiddenDrawers: draft.hiddenDrawers, fallback: draft.fallback, contexts: cx.map, outputs: ox.map, compacts: cpx.map, proxy, accountProxies: own.map, maxConcurrency, ...queue, priceRate, rateWindows, modelPrefs: modelPrefsOfDraft(), pinUpstream: !!draft.pinUpstream, ...(p.carriesCompaction ? { nativeCompaction: !!draft.nativeCompaction } : {}), ...routingOfDraft(p) };
|
||||
saving(saveBtn, t("Saving…"));
|
||||
saveAccountModelsDraft(picked).then(() => savePluginOptions(subOf(a.agent))).then(() => providerAction("save", body, t("{name} saved", { name: p.name })), (e) => { doneSaving(saveBtn); editorError(e.message || String(e)); }); };
|
||||
bar.append(cancel, saveBtn);
|
||||
@@ -9736,7 +9740,7 @@ function drawEditor(p, presetID) {
|
||||
if (perKey) proxies.append(perKey);
|
||||
advIn.append(...field(t("Proxy"), proxies));
|
||||
advIn.append(...concurrencyField(p));
|
||||
advIn.append(...priceRateField());
|
||||
advIn.append(...priceRateField(), ...rateWindowsField());
|
||||
|
||||
if (p?.cline || (isNew && pr?.id === "clinepass")) advIn.append(...upstreamField());
|
||||
|
||||
@@ -10206,6 +10210,8 @@ function drawEditor(p, presetID) {
|
||||
Object.assign(body, queue);
|
||||
body.priceRate = priceRateOfDraft();
|
||||
if (body.priceRate === undefined) return priceRateError(ed);
|
||||
body.rateWindows = self.rateWindowsOfDraft?.();
|
||||
if (body.rateWindows === false) return rateWindowsError(ed);
|
||||
if (p && priceTypedError(ed)) return;
|
||||
if (draft.balanceToken) body.balanceToken = draft.balanceToken;
|
||||
else if (draft.clearBalanceToken) body.clearBalanceToken = true;
|
||||
|
||||
@@ -4165,6 +4165,16 @@ const I18N = {
|
||||
"System One": "System One",
|
||||
"Embeddings": "向量嵌入",
|
||||
"Audio": "音频",
|
||||
"Rate windows": "时段倍率",
|
||||
"Add a window": "添加时段",
|
||||
"Inside a window a call costs the official price times its rate, on top of the price rate; outside every window the price rate alone counts. The first window that holds a call wins. Times are on the clock of the computer magpie runs on, and 22:00–6:00 crosses midnight. No day ticked is every day. A price you set for a model is scaled by the window too. Changing the windows prices the calls already counted again, as a changed price rate does.": "时段内的调用按官方价乘以该时段的倍率计费,叠加在价格倍率之上;时段之外只按价格倍率。调用命中第一个满足的时段。时间按运行 magpie 的那台电脑的时钟,22:00–6:00 表示跨零点。不勾任何星期表示每天。为模型单独设的价格同样按该倍率缩放。修改时段后,已记录的调用也按新时段重算,与修改价格倍率相同。",
|
||||
"DeepSeek's own API, Command Code and OpenCode Go already count their DeepSeek models' peak hours at double: don't add those hours as a window, or they count twice.": "DeepSeek 官方 API、Command Code 和 OpenCode Go 的 DeepSeek 模型已按官方高峰时段双倍计价:不要再把这些时段设为时段倍率,否则会重复计算。",
|
||||
"Window starts at": "时段开始于",
|
||||
"Window ends at": "时段结束于",
|
||||
"Rate in this window": "该时段的倍率",
|
||||
"Remove this window": "删除这个时段",
|
||||
"Rate windows: every window is days, a time like 09:00, another time for it to end, and a rate from 0 to 1000 with at most three decimals": "时段倍率:每个时段是星期、一个如 09:00 的时间、另一个结束时间,以及一个 0 到 1000、至多三位小数的倍率",
|
||||
"Bills at {rate} now: the price rate times this hour's window": "现在按 {rate} 计费:价格倍率乘以当前时段的倍率",
|
||||
// Insights › Masking (plugins/redact), words said elsewhere too
|
||||
"Masking": "脱敏",
|
||||
"Each request masking changed, what the vendor saw, and how, on Insights › Masking": "每条被脱敏的请求、厂商看到的样子和遮法,都在 观测 › 脱敏",
|
||||
@@ -8330,6 +8340,16 @@ const I18N = {
|
||||
"System One": "System One",
|
||||
"Embeddings": "向量嵌入",
|
||||
"Audio": "音訊",
|
||||
"Rate windows": "時段倍率",
|
||||
"Add a window": "新增時段",
|
||||
"Inside a window a call costs the official price times its rate, on top of the price rate; outside every window the price rate alone counts. The first window that holds a call wins. Times are on the clock of the computer magpie runs on, and 22:00–6:00 crosses midnight. No day ticked is every day. A price you set for a model is scaled by the window too. Changing the windows prices the calls already counted again, as a changed price rate does.": "時段內的呼叫以官方價乘上該時段的倍率計費,疊加在價格倍率之上;時段之外只按價格倍率。呼叫命中第一個符合的時段。時間按執行 magpie 的那台電腦的時鐘,22:00–6:00 表示跨午夜。不勾任何星期表示每天。為模型單獨設的價格同樣按該倍率縮放。修改時段後,已記錄的呼叫也依新時段重新計算,與修改價格倍率相同。",
|
||||
"DeepSeek's own API, Command Code and OpenCode Go already count their DeepSeek models' peak hours at double: don't add those hours as a window, or they count twice.": "DeepSeek 官方 API、Command Code 和 OpenCode Go 的 DeepSeek 模型已按官方尖峰時段雙倍計價:不要再把這些時段設為時段倍率,否則會重複計算。",
|
||||
"Window starts at": "時段開始於",
|
||||
"Window ends at": "時段結束於",
|
||||
"Rate in this window": "該時段的倍率",
|
||||
"Remove this window": "刪除這個時段",
|
||||
"Rate windows: every window is days, a time like 09:00, another time for it to end, and a rate from 0 to 1000 with at most three decimals": "時段倍率:每個時段是星期、一個如 09:00 的時間、另一個結束時間,以及一個 0 到 1000、至多三位小數的倍率",
|
||||
"Bills at {rate} now: the price rate times this hour's window": "現在以 {rate} 計費:價格倍率乘上目前時段的倍率",
|
||||
// Insights › Masking (plugins/redact), words said elsewhere too
|
||||
"Masking": "脫敏",
|
||||
"Each request masking changed, what the vendor saw, and how, on Insights › Masking": "每則被脫敏的請求、廠商看到的樣子和遮法,都在 觀測 › 脫敏",
|
||||
@@ -12497,6 +12517,16 @@ const I18N = {
|
||||
"System One": "System One",
|
||||
"Embeddings": "埋め込み",
|
||||
"Audio": "音声",
|
||||
"Rate windows": "時間帯倍率",
|
||||
"Add a window": "時間帯を追加",
|
||||
"Inside a window a call costs the official price times its rate, on top of the price rate; outside every window the price rate alone counts. The first window that holds a call wins. Times are on the clock of the computer magpie runs on, and 22:00–6:00 crosses midnight. No day ticked is every day. A price you set for a model is scaled by the window too. Changing the windows prices the calls already counted again, as a changed price rate does.": "時間帯内の呼び出しは公式価格にその時間帯の倍率を掛けた額で計上され、価格倍率にさらに重ねられます。時間帯の外では価格倍率のみが適用されます。呼び出しは最初に一致した時間帯の倍率です。時刻は magpie が動いているコンピュータの時計で、22:00–6:00 は深夜0時をまたぎます。曜日を1つも選ばない場合は毎日です。モデルに個別に設定した価格も同様にその倍率が掛かります。時間帯を変更すると、記録済みの呼び出しも新しい時間帯で計算し直されます(価格倍率の変更と同じです)。",
|
||||
"DeepSeek's own API, Command Code and OpenCode Go already count their DeepSeek models' peak hours at double: don't add those hours as a window, or they count twice.": "DeepSeek 公式 API、Command Code、OpenCode Go の DeepSeek モデルは公式のピーク時間帯をすでに 2 倍で計上しています。その時間帯を時間帯倍率として追加しないでください。二重に計上されます。",
|
||||
"Window starts at": "時間帯の開始時刻",
|
||||
"Window ends at": "時間帯の終了時刻",
|
||||
"Rate in this window": "この時間帯の倍率",
|
||||
"Remove this window": "この時間帯を削除",
|
||||
"Rate windows: every window is days, a time like 09:00, another time for it to end, and a rate from 0 to 1000 with at most three decimals": "時間帯倍率:各時間帯は曜日、09:00 のような時刻、終了する別の時刻、そして小数3位までの 0 から 1000 の倍率で指定します",
|
||||
"Bills at {rate} now: the price rate times this hour's window": "現在は {rate} で計上:価格倍率×現在の時間帯の倍率",
|
||||
// Insights › Masking (plugins/redact), words said elsewhere too
|
||||
"Masking": "マスク",
|
||||
"Each request masking changed, what the vendor saw, and how, on Insights › Masking": "マスクしたリクエストごとに、ベンダーに届いた姿とマスクの仕方を 観測 › マスク で見られます",
|
||||
@@ -16664,6 +16694,16 @@ const I18N = {
|
||||
"System One": "System One",
|
||||
"Embeddings": "Embeddings",
|
||||
"Audio": "Audio",
|
||||
"Rate windows": "Zeitfenster",
|
||||
"Add a window": "Zeitfenster hinzufügen",
|
||||
"Inside a window a call costs the official price times its rate, on top of the price rate; outside every window the price rate alone counts. The first window that holds a call wins. Times are on the clock of the computer magpie runs on, and 22:00–6:00 crosses midnight. No day ticked is every day. A price you set for a model is scaled by the window too. Changing the windows prices the calls already counted again, as a changed price rate does.": "Innerhalb eines Zeitfensters kostet ein Aufruf den offiziellen Preis mal dessen Rate, zusätzlich zum Preisfaktor; außerhalb aller Zeitfenster zählt nur der Preisfaktor. Das erste Zeitfenster, das den Aufruf hält, gewinnt. Zeiten gelten nach der Uhr des Computers, auf dem magpie läuft; 22:00–6:00 geht über Mitternacht. Kein Wochentag angehakt heißt jeder Tag. Ein selbst gesetzter Modellpreis wird ebenfalls mit der Rate skaliert. Werden die Zeitfenster geändert, werden auch bereits gezählte Aufrufe neu berechnet, wie bei einem geänderten Preisfaktor.",
|
||||
"DeepSeek's own API, Command Code and OpenCode Go already count their DeepSeek models' peak hours at double: don't add those hours as a window, or they count twice.": "DeepSeeks eigene API, Command Code und OpenCode Go rechnen ihre DeepSeek-Modelle in den Spitzenzeiten schon doppelt: diese Stunden nicht noch einmal als Zeitfenster eintragen, sonst zählen sie zweifach.",
|
||||
"Window starts at": "Zeitfenster beginnt um",
|
||||
"Window ends at": "Zeitfenster endet um",
|
||||
"Rate in this window": "Rate in diesem Zeitfenster",
|
||||
"Remove this window": "Dieses Zeitfenster entfernen",
|
||||
"Rate windows: every window is days, a time like 09:00, another time for it to end, and a rate from 0 to 1000 with at most three decimals": "Zeitfenster: jedes Zeitfenster besteht aus Wirktagen, einer Zeit wie 09:00, einer anderen Endzeit und einer Rate von 0 bis 1000 mit höchstens drei Dezimalstellen",
|
||||
"Bills at {rate} now: the price rate times this hour's window": "Rechnet gerade mit {rate} ab: der Preisfaktor mal das Zeitfenster dieser Stunde",
|
||||
// Insights › Masking (plugins/redact), words said elsewhere too
|
||||
"Masking": "Maskierung",
|
||||
"Each request masking changed, what the vendor saw, and how, on Insights › Masking": "Jede maskierte Anfrage, was der Anbieter sah und wie, unter Einblick › Maskierung",
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
// A provider's rate windows (#2463) in its editor: the hours it bills at
|
||||
// its own rate, a peak at 2x or a discount off peak. app.js imports this
|
||||
// when an editor draws the field (rateWindowsField), so it weighs nothing
|
||||
// on the core. Each window is its days (none ticked: every day), a span
|
||||
// that may cross midnight, and the rate the price is times inside it, on
|
||||
// top of the price rate; the first window holding a call wins.
|
||||
|
||||
// rateWindowsPaint draws d's windows into box, and Add a window under
|
||||
// them while there is room for one more.
|
||||
window.rateWindowsPaint = function paint(box, d) {
|
||||
box.replaceChildren();
|
||||
if (!box.nextElementSibling) {
|
||||
const help = el("div", "hint", t("Inside a window a call costs the official price times its rate, on top of the price rate; outside every window the price rate alone counts. The first window that holds a call wins. Times are on the clock of the computer magpie runs on, and 22:00–6:00 crosses midnight. No day ticked is every day. A price you set for a model is scaled by the window too. Changing the windows prices the calls already counted again, as a changed price rate does."));
|
||||
// a list price with the vendor's own peak has it already (#2463,
|
||||
// the author): a window over the same hours would double it again
|
||||
help.append(el("div", "", t("DeepSeek's own API, Command Code and OpenCode Go already count their DeepSeek models' peak hours at double: don't add those hours as a window, or they count twice.")));
|
||||
help.id = "rate-windows-help";
|
||||
box.after(help);
|
||||
box.setAttribute("role", "group");
|
||||
box.setAttribute("aria-describedby", help.id);
|
||||
}
|
||||
for (const w of d.rateWindows || []) box.append(rateWindowRow(w, d, () => paint(box, d)));
|
||||
if ((d.rateWindows || []).length < 8) {
|
||||
const add = el("button", "text", t("Add a window"));
|
||||
add.type = "button";
|
||||
add.onclick = () => { (d.rateWindows ??= []).push({ days: [], start: "", end: "", rate: "" }); paint(box, d); };
|
||||
box.append(add);
|
||||
}
|
||||
};
|
||||
|
||||
// rateWindowRow is one window of the editor, its draft w kept as typed.
|
||||
function rateWindowRow(w, d, repaint) {
|
||||
const row = el("div", "rate-win"), chips = el("div", "day-chips");
|
||||
const names = [t("Sun"), t("Mon"), t("Tue"), t("Wed"), t("Thu"), t("Fri"), t("Sat")];
|
||||
for (let i = 0; i < 7; i++) {
|
||||
// a new array each press: the draft's window is a shallow copy of the
|
||||
// saved one, which keeps its own days
|
||||
const mark = () => {
|
||||
const on = (w.days || []).includes(i);
|
||||
b.classList.toggle("on", on);
|
||||
b.setAttribute("aria-pressed", String(on));
|
||||
};
|
||||
const b = el("button", "day-chip", names[i]);
|
||||
b.type = "button";
|
||||
mark();
|
||||
b.onclick = () => {
|
||||
const days = (w.days || []).filter((x) => x !== i);
|
||||
w.days = days.length < (w.days || []).length ? days : [...days, i].sort((a, z) => a - z);
|
||||
mark();
|
||||
};
|
||||
chips.append(b);
|
||||
}
|
||||
const rate = input(w.rate, "3");
|
||||
rate.classList.add("rate-rate");
|
||||
rate.inputMode = "decimal";
|
||||
rate.setAttribute("aria-label", t("Rate in this window"));
|
||||
rate.oninput = () => { w.rate = rate.value; };
|
||||
const del = el("button", "text rate-win-del", "×");
|
||||
del.type = "button";
|
||||
del.title = t("Remove this window");
|
||||
del.setAttribute("aria-label", del.title);
|
||||
del.onclick = () => {
|
||||
const at = (d.rateWindows || []).indexOf(w);
|
||||
if (at >= 0) d.rateWindows.splice(at, 1);
|
||||
repaint();
|
||||
};
|
||||
row.append(chips, timePick(w, "start", t("Window starts at")), el("span", "rate-dash", "–"),
|
||||
timePick(w, "end", t("Window ends at")), rate, del);
|
||||
return row;
|
||||
}
|
||||
|
||||
// timePick is a window's start or end as the app's own menu of half
|
||||
// hours, not typed; only an end may be 24:00.
|
||||
function timePick(w, key, label) {
|
||||
const b = el("button", "sess-pick rate-time");
|
||||
b.type = "button";
|
||||
b.setAttribute("aria-haspopup", "menu");
|
||||
b.setAttribute("aria-expanded", "false");
|
||||
b.setAttribute("aria-label", label);
|
||||
const paint = () => {
|
||||
b.dataset.value = w[key] || "";
|
||||
b.replaceChildren(el("span", "", w[key] || "--:--"), svg(CHEV, 11, 1.6));
|
||||
};
|
||||
b.onclick = (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (b.classList.contains("open")) return closeProtoMenu();
|
||||
const times = [];
|
||||
for (let m = 0; m < 1440; m += 30) times.push(String(Math.floor(m / 60)).padStart(2, "0") + ":" + String(m % 60).padStart(2, "0"));
|
||||
if (key === "end") times.push("24:00");
|
||||
openProtoMenu(b, times.map((v) => ({ v, name: v, note: "", literalName: true })), w[key], (v) => { w[key] = v; paint(); }, label, "sess-menu");
|
||||
};
|
||||
paint();
|
||||
return b;
|
||||
}
|
||||
|
||||
// clockOf reads "H:MM" or "HH:MM", 24:00 included; null for what isn't one.
|
||||
function clockOf(v) {
|
||||
const m = String(v ?? "").trim().match(/^(\d{1,2}):(\d{2})$/);
|
||||
if (!m) return null;
|
||||
const min = +m[1] * 60 + +m[2];
|
||||
return +m[1] > 24 || +m[2] > 59 || min > 1440 ? null : min;
|
||||
}
|
||||
|
||||
// rateWindowsOfDraft is the draft's windows as saved, null for none, or
|
||||
// false when one is typed wrong (provider.CheckRateWindows' rules). Not
|
||||
// loaded yet, the save leaves them out, which keeps them as they are.
|
||||
window.rateWindowsOfDraft = function () {
|
||||
const out = [];
|
||||
for (const w of draft.rateWindows || []) {
|
||||
const start = clockOf(w.start), end = clockOf(w.end);
|
||||
if (start === null || start === 1440 || end === null || start === end) return false;
|
||||
const n = decimalOf(String(w.rate ?? "").trim());
|
||||
if (!(n > 0 && n <= 1000) || Math.abs(n * 1000 - Math.round(n * 1000)) > 1e-6) return false;
|
||||
out.push({ days: [...(w.days || [])], start: String(w.start).trim(), end: String(w.end).trim(), rate: n });
|
||||
}
|
||||
return out.length ? out : null;
|
||||
};
|
||||
|
||||
window.rateWindowsError = function (ed) {
|
||||
shown(ed.querySelector(".rate-windows input"))?.focus({ preventScroll: true });
|
||||
return editorError(t("Rate windows: every window is days, a time like 09:00, another time for it to end, and a rate from 0 to 1000 with at most three decimals"), "warn");
|
||||
};
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A save's priceRate (#819): left out keeps the rate, null clears it, a
|
||||
@@ -95,3 +97,34 @@ func TestAccountSaveKeepsPriceRate(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// What a provider row says it bills at now (#2463) is the price rate times
|
||||
// the window holding the time on this computer's clock, 0 for 1×, and
|
||||
// /api/providers carries it: the browser's clock may be another zone's.
|
||||
func TestRateNowOf(t *testing.T) {
|
||||
ws := []provider.RateWindow{{Start: "10:00", End: "14:00", Rate: 3}}
|
||||
peak := time.Date(2026, 10, 20, 11, 0, 0, 0, time.Local)
|
||||
off := time.Date(2026, 10, 20, 15, 0, 0, 0, time.Local)
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
p provider.Provider
|
||||
at time.Time
|
||||
want float64
|
||||
}{
|
||||
{"price rate and window", provider.Provider{PriceRate: 2, RateWindows: ws}, peak, 6},
|
||||
{"price rate off the window", provider.Provider{PriceRate: 2, RateWindows: ws}, off, 2},
|
||||
{"window alone", provider.Provider{RateWindows: ws}, peak, 3},
|
||||
{"the peak written in UTC", provider.Provider{RateWindows: ws}, peak.UTC(), 3},
|
||||
{"nothing", provider.Provider{RateWindows: ws}, off, 0},
|
||||
{"a price rate with no window", provider.Provider{PriceRate: 2}, peak, 0},
|
||||
{"a window at 1×", provider.Provider{RateWindows: []provider.RateWindow{{Start: "10:00", End: "14:00", Rate: 1}}}, peak, 0},
|
||||
} {
|
||||
if got := rateNowOf(c.p, c.at); got != c.want {
|
||||
t.Errorf("%s: %v, want %v", c.name, got, c.want)
|
||||
}
|
||||
}
|
||||
allDay := []provider.RateWindow{{Start: "00:00", End: "24:00", Rate: 3}}
|
||||
if got := providerInfo(provider.Provider{ID: "relay", RateWindows: allDay}, nil).RateNow; got != 3 {
|
||||
t.Errorf("/api/providers' rateNow under an all-day 3× window: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -244,6 +244,13 @@ type providerJSON struct {
|
||||
// how many requests each key or account sends the vendor in any
|
||||
// minute, 0 for no limit (coeo91 on Discord)
|
||||
MaxRPM int `json:"maxRPM,omitempty"`
|
||||
// RateWindows are the time-of-day windows it bills at its own rate
|
||||
// (#2463), as the editor opens on them
|
||||
RateWindows []provider.RateWindow `json:"rateWindows,omitempty"`
|
||||
// RateNow is what it bills at now, the price rate times the window
|
||||
// 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"`
|
||||
// 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
|
||||
@@ -631,6 +638,7 @@ func providerInfoWith(p provider.Provider, agents []agentUse, desktop map[string
|
||||
Ready: p.Ready(), Chosen: p.Picks(), Models: []modelJSON{}, Agents: []providerAgent{},
|
||||
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts,
|
||||
MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), PriceRate: p.PriceRate,
|
||||
RateWindows: p.RateWindows, RateNow: rateNowOf(p, time.Now()),
|
||||
AccountConcurrency: p.AccountConcurrency, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM,
|
||||
Outputs: provider.OutputsOf(p.ID), Compacts: provider.CompactsOf(p.ID),
|
||||
}
|
||||
@@ -1237,6 +1245,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
// Limit, for accountconcurrency: the account's or key's own
|
||||
// limit, 0 for none, null for the provider's (#892)
|
||||
Limit *int `json:"limit"`
|
||||
// RateWindows are the time-of-day windows it bills at its own
|
||||
// rate (#2463); a list as checked (CheckRateWindows), null or
|
||||
// [] for none; left out, they are kept
|
||||
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"`
|
||||
@@ -1526,6 +1538,14 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
return
|
||||
}
|
||||
in.PriceRate = rate
|
||||
wins, keepWins, err := rateWindowsOf(req.RateWindows)
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
if !keepWins {
|
||||
in.RateWindows = wins
|
||||
}
|
||||
// many keys pasted into the key field (361 on Discord: a provider
|
||||
// added with hundreds): the first is the key, the others its
|
||||
// accounts, as Paste several adds them
|
||||
@@ -1612,6 +1632,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
if keepRate && old != nil {
|
||||
in.PriceRate = old.PriceRate
|
||||
}
|
||||
if keepWins && old != nil {
|
||||
in.RateWindows = old.RateWindows
|
||||
}
|
||||
// how long its keys rest out of quota is set in
|
||||
// providers.json or with `magpie provider quota-rest`,
|
||||
// which the form doesn't show: kept as it was (#1772)
|
||||
@@ -2587,6 +2610,46 @@ func priceRateOf(raw json.RawMessage) (r float64, keep bool, err error) {
|
||||
return *n, false, nil
|
||||
}
|
||||
|
||||
// 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).
|
||||
func rateWindowsOf(raw json.RawMessage) (ws []provider.RateWindow, keep bool, err error) {
|
||||
if len(raw) == 0 {
|
||||
return nil, true, nil
|
||||
}
|
||||
var list *[]provider.RateWindow
|
||||
if err := json.Unmarshal(raw, &list); err != nil {
|
||||
return nil, false, fmt.Errorf("rate windows are a list of windows, not %s", raw)
|
||||
}
|
||||
if list == nil || len(*list) == 0 {
|
||||
return nil, false, nil
|
||||
}
|
||||
if bad := provider.CheckRateWindows(*list); bad != "" {
|
||||
return nil, false, errors.New(bad)
|
||||
}
|
||||
return *list, false, nil
|
||||
}
|
||||
|
||||
// rateNowOf is what p bills at at t (#2463): its price rate times the
|
||||
// rate of the window holding t, 0 when that comes to 1× or p has no
|
||||
// windows (a price rate alone is the editor's to show).
|
||||
func rateNowOf(p provider.Provider, t time.Time) float64 {
|
||||
if len(p.RateWindows) == 0 {
|
||||
return 0
|
||||
}
|
||||
r := 1.0
|
||||
if p.PriceRate > 0 {
|
||||
r = p.PriceRate
|
||||
}
|
||||
if w := p.RateAt(t); w > 0 {
|
||||
r *= w
|
||||
}
|
||||
if r == 1 {
|
||||
return 0
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// concurrencyOf is a save's maxConcurrency: keep when the save left it
|
||||
// out, nil for null (the plugin's, or none), else the number, 0 for none.
|
||||
func concurrencyOf(raw json.RawMessage) (n *int, keep bool, err error) {
|
||||
|
||||
@@ -143,9 +143,10 @@ test("compat.js is the first of the page's own scripts", async () => {
|
||||
assert.equal(srcs[0], "compat.js", "loaded first: " + srcs.join(", "));
|
||||
// webfonts.js is imported by app.js in a browser tab only, cfgblocked.js
|
||||
// when magpie can't write its folder, signsheets.js when a sign-in asks a
|
||||
// value first, ruleedit.js on a masking rule's Edit; the checks above
|
||||
// still read them
|
||||
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
|
||||
// value first, ruleedit.js on a masking rule's Edit, ratewindows.js when
|
||||
// a provider editor draws its rate windows; the checks above still read
|
||||
// them
|
||||
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.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,189 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A provider's rate windows (#2463): the editor's Advanced has the field,
|
||||
// empty for none; Add a window gives a row of days, a span and a rate;
|
||||
// Save posts the windows typed, null when none are left, and refuses a
|
||||
// window with a bad time or rate before anything is posted. A provider
|
||||
// saved with windows opens on them, its row inside the editor at a
|
||||
// phone's width too. A row's ×rate is the server's rateNow, never worked
|
||||
// out on the browser's clock. In every language, wide and narrow.
|
||||
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");
|
||||
// the editor folds what few need under Advanced, this field among them:
|
||||
// opened as a reader would, unless something set in it opened it already
|
||||
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 windows = [{ days: [1, 2, 3, 4, 5], start: "09:00", end: "18:00", rate: 3 }];
|
||||
const relay = {
|
||||
id: "relay", name: "Relay", 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" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", maxConcurrency: null,
|
||||
};
|
||||
const codex = {
|
||||
id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "",
|
||||
models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [],
|
||||
account: { agent: "codex", agentName: "Codex", user: "me@example.com", plan: "PLUS", logins: [{ user: "me@example.com", plan: "PLUS", active: true, on: true }] },
|
||||
proxy: "", maxConcurrency: null, rateWindows: windows,
|
||||
};
|
||||
|
||||
function serve(lang, posts, list = [relay, codex]) {
|
||||
const providers = { providers: list, 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 words = {
|
||||
en: { label: "Rate windows", save: "Save", add: "Add a window" },
|
||||
zh: { label: "时段倍率", save: "保存", add: "添加时段" },
|
||||
"zh-TW": { label: "時段倍率", save: "儲存", add: "新增時段" },
|
||||
ja: { label: "時間帯倍率", save: "保存", add: "時間帯を追加" },
|
||||
de: { label: "Zeitfenster", save: "Speichern", add: "Zeitfenster hinzufügen" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of Object.keys(words)) for (const width of [900, 420]) {
|
||||
const w = words[lang];
|
||||
const launch = async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
return (await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" })).newPage();
|
||||
};
|
||||
const open = async (t, name) => {
|
||||
const page = await launch(t);
|
||||
page.setDefaultTimeout(5000);
|
||||
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 unfold(page);
|
||||
// ratewindows.js is imported as the field is drawn: its hint is there
|
||||
// once the rows can be
|
||||
await page.locator(".editor .rate-windows + .hint").waitFor();
|
||||
await page.waitForTimeout(300);
|
||||
return { page, errors, posts };
|
||||
};
|
||||
const save = async (page, posts) => {
|
||||
const n = posts.length;
|
||||
await page.locator(".editor .bar").getByRole("button", { name: w.save, exact: true }).click();
|
||||
for (let i = 0; i < 50 && posts.length === n; i++) await page.waitForTimeout(50);
|
||||
return posts.at(-1);
|
||||
};
|
||||
|
||||
test(`${engine} ${lang} ${width}: rate windows are added, saved and refused when wrong`, async (t) => {
|
||||
const { page, errors, posts } = await open(t, "Relay");
|
||||
const zh = await page.evaluate(() => ({
|
||||
label: I18N.zh["Rate windows"], add: I18N.zh["Add a window"],
|
||||
hint: I18N.zh["Inside a window a call costs the official price times its rate, on top of the price rate; outside every window the price rate alone counts. The first window that holds a call wins. Times are on the clock of the computer magpie runs on, and 22:00–6:00 crosses midnight. No day ticked is every day. A price you set for a model is scaled by the window too. Changing the windows prices the calls already counted again, as a changed price rate does."],
|
||||
bad: I18N.zh["Rate windows: every window is days, a time like 09:00, another time for it to end, and a rate from 0 to 1000 with at most three decimals"],
|
||||
}));
|
||||
assert(zh.label && zh.add && zh.hint && zh.bad, "every string has its Chinese");
|
||||
// the vendors whose list price has its peak already are named under
|
||||
// the windows, in the page's own language
|
||||
const peak = "DeepSeek's own API, Command Code and OpenCode Go already count their DeepSeek models' peak hours at double: don't add those hours as a window, or they count twice.";
|
||||
const peakText = await page.evaluate(([lang, k]) => lang === "en" ? k : I18N[lang]?.[k], [lang, peak]);
|
||||
assert(peakText, "the peak note has its " + lang);
|
||||
assert((await page.locator(".editor .rate-windows + .hint").innerText()).includes(peakText.trim()), "the peak note is shown");
|
||||
assert.equal(await page.locator(".editor .rate-win").count(), 0, "none set");
|
||||
|
||||
// a window is added, its days ticked, its span and rate typed
|
||||
await page.locator(".editor .rate-windows").getByRole("button", { name: w.add }).click();
|
||||
const row = page.locator(".editor .rate-win");
|
||||
assert.equal(await row.count(), 1);
|
||||
await row.locator(".day-chip").nth(1).click();
|
||||
await row.locator(".day-chip").nth(3).click();
|
||||
await row.locator("input.rate-rate").fill("3");
|
||||
|
||||
// a window with no times picked is refused before anything is posted
|
||||
await row.locator("input.rate-rate").fill("3");
|
||||
await page.locator(".editor .bar").getByRole("button", { name: w.save, exact: true }).click();
|
||||
await page.locator(".editor .editor-error").waitFor();
|
||||
assert.equal(posts.length, 0, "no time picked is not posted");
|
||||
await row.locator("button.rate-time").nth(0).click();
|
||||
await page.getByRole("menuitemradio", { name: "09:00" }).click();
|
||||
await row.locator("button.rate-time").nth(1).click();
|
||||
await page.getByRole("menuitemradio", { name: "18:00" }).click();
|
||||
await row.locator("input.rate-rate").fill("3000");
|
||||
await page.locator(".editor .bar").getByRole("button", { name: w.save, exact: true }).click();
|
||||
await page.locator(".editor .editor-error").waitFor();
|
||||
assert.equal(posts.length, 0, "a rate over 1000 is not posted");
|
||||
await row.locator("input.rate-rate").fill("3");
|
||||
|
||||
const saved = await save(page, posts);
|
||||
assert.equal(saved.action, "save");
|
||||
assert.equal(saved.body.id, "relay");
|
||||
assert.deepEqual(saved.body.rateWindows, [{ days: [1, 3], start: "09:00", end: "18:00", rate: 3 }]);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang} ${width}: a provider saved with windows opens on them`, async (t) => {
|
||||
const { page, errors, posts } = await open(t, "Codex");
|
||||
const row = page.locator(".editor .rate-win");
|
||||
assert.equal(await row.count(), 1);
|
||||
// the row wraps inside the editor rather than running past it
|
||||
const over = await row.evaluate((r) => {
|
||||
const box = r.closest(".editor").getBoundingClientRect();
|
||||
return [...r.querySelectorAll("*")].filter((c) => c.getBoundingClientRect().right > box.right + 1).map((c) => c.className);
|
||||
});
|
||||
assert.deepEqual(over, [], "nothing of the row past the editor's edge");
|
||||
assert.equal(await row.locator(".day-chip.on").count(), 5, "the five days ticked");
|
||||
assert.equal(await row.locator("button.rate-time").nth(0).textContent(), "09:00");
|
||||
assert.equal(await row.locator("button.rate-time").nth(1).textContent(), "18:00");
|
||||
assert.equal(await row.locator("input.rate-rate").inputValue(), "3");
|
||||
const saved = await save(page, posts);
|
||||
assert.deepEqual(saved.body.rateWindows, windows, "what it opens with is what it saves");
|
||||
|
||||
// none left is saved as none, not left out: the saved editor closed,
|
||||
// the row opens again on what it has
|
||||
await page.locator(".row.provider", { hasText: "Codex" }).click();
|
||||
await unfold(page);
|
||||
await page.locator(".editor .rate-win").waitFor();
|
||||
await page.locator(".editor .rate-win .rate-win-del").click();
|
||||
const cleared = await save(page, posts);
|
||||
assert(Object.hasOwn(cleared.body, "rateWindows"), "no window is saved as none, not left out");
|
||||
assert.equal(cleared.body.rateWindows, null);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang} ${width}: a row's rate is the server's, not the browser's clock`, async (t) => {
|
||||
// the server says Relay bills at 6× now; Codex has a window over
|
||||
// every hour of the browser's day but the server says 1× (its own
|
||||
// clock is elsewhere), so it shows none
|
||||
const page = await launch(t);
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const allDay = [{ days: [], start: "00:00", end: "24:00", rate: 3 }];
|
||||
await page.route("**/*", serve(lang, [], [{ ...relay, rateNow: 6 }, { ...codex, rateWindows: allDay }]));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
await page.locator(".row.provider", { hasText: "Relay" }).waitFor();
|
||||
assert.equal(await page.locator(".row.provider", { hasText: "Relay" }).locator(".badge.rate-now").textContent(), "×6");
|
||||
assert.equal(await page.locator(".row.provider", { hasText: "Codex" }).locator(".badge.rate-now").count(), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
@@ -131,7 +132,9 @@ func templateModels() []rated {
|
||||
r := rated{e: e}
|
||||
if pr, ok := MakerPrice(e.Model); ok {
|
||||
r.out, r.maker = pr.Output, true
|
||||
} else if pr, ok := priceOf(s, e.Provider, true, e.Model); ok {
|
||||
} else if pr, ok := priceOf(s, e.Provider, true, e.Model, time.Time{}); ok {
|
||||
// without a rate window's rate (#2463): a template weighs how
|
||||
// strong a model is, which the hour it is made in doesn't change
|
||||
r.out = pr.Output
|
||||
}
|
||||
r.small, r.tiny = sizeOf(e.Model)
|
||||
|
||||
+69
-11
@@ -2212,7 +2212,11 @@ func SamePriceIn(s settings.Settings, providerID, model string) (catalog.Price,
|
||||
// price they set for that model, or for every model of that provider, or for
|
||||
// that model from any provider (settings' ModelPrices), else the provider's own list price, else its
|
||||
// maker's, else the maker's of the model the user said it is the same as
|
||||
// (SamePriceIn), each at the provider's price rate (PriceRate). The second return is false only when no price is known at all,
|
||||
// (SamePriceIn), each at the provider's price rate (PriceRate), and again
|
||||
// at the rate of the time-of-day window the call falls in (RateWindows,
|
||||
// #2463) — the window's rate on a price the user set as well, the price
|
||||
// rate alone leaving it as set. The second return is false only when no
|
||||
// price is known at all,
|
||||
// which is not the same as a price of zero: that one is set, deliberately.
|
||||
//
|
||||
// A price here is the provider's tariff, not the model's: the same model
|
||||
@@ -2227,31 +2231,70 @@ func EffectivePrice(providerID, model string) (catalog.Price, bool) {
|
||||
// the list is one snapshot of the prices rather than a reading per row, and
|
||||
// a price changed while it is read takes effect in the next call.
|
||||
func EffectivePriceIn(s settings.Settings, providerID, model string) (catalog.Price, bool) {
|
||||
return EffectivePriceAt(s, providerID, model, time.Now())
|
||||
}
|
||||
|
||||
// EffectivePriceAt is EffectivePriceIn at the time given: a record's own
|
||||
// time when one is priced, now for a price shown before a call. A caller
|
||||
// pricing many records takes BasePriceIn once per model and multiplies
|
||||
// each record's window rate on itself, so one read of the prices serves
|
||||
// every time of day.
|
||||
func EffectivePriceAt(s settings.Settings, providerID, model string, at time.Time) (catalog.Price, bool) {
|
||||
// A price is keyed by the id the provider has now, so one written before
|
||||
// a rename is read under the id it has. Only an id, or one the provider
|
||||
// was renamed from, resolves; anything else is looked up as given, so a
|
||||
// key under a display name counts only for a caller naming that name
|
||||
// too. Nothing writes such a key — SetModelPrice re-keys the way
|
||||
// SetModelName does — which is what keeps the two from drifting.
|
||||
return priceIn(s, All(), providerID, model)
|
||||
return priceIn(s, All(), providerID, model, at)
|
||||
}
|
||||
|
||||
// priceIn is EffectivePriceIn with the providers read already, for a
|
||||
// caller pricing many models at once: All() copies every provider each
|
||||
// time it is read, so a list read it once a model, 30 providers' copies
|
||||
// for each of hundreds of models (EntryPricer).
|
||||
func priceIn(s settings.Settings, all []Provider, providerID, model string) (catalog.Price, bool) {
|
||||
func priceIn(s settings.Settings, all []Provider, providerID, model string, at time.Time) (catalog.Price, bool) {
|
||||
p, known := byIDOrWasIn(all, providerID)
|
||||
if !known {
|
||||
p = Provider{ID: providerID}
|
||||
}
|
||||
return priceOf(s, p, known, model)
|
||||
return priceOf(s, p, known, model, at)
|
||||
}
|
||||
|
||||
// priceOf is EffectivePriceIn for a provider already looked up, for a
|
||||
// BasePriceIn is EffectivePriceAt without a rate window's rate: what the
|
||||
// provider bills outside every window, and the third return is its
|
||||
// windows, for RateAt to read each record's time against. A caller
|
||||
// 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) {
|
||||
p, known := byIDOrWas(providerID)
|
||||
if !known {
|
||||
p = Provider{ID: providerID}
|
||||
}
|
||||
pr, ok := priceOf(s, p, known, model, time.Time{})
|
||||
return pr, ok, p.RateWindows
|
||||
}
|
||||
|
||||
// priceOf is EffectivePriceAt for a provider already looked up, for a
|
||||
// caller pricing many models at once: byIDOrWas reads every provider's
|
||||
// accounts each time.
|
||||
func priceOf(s settings.Settings, p Provider, known bool, model string) (catalog.Price, bool) {
|
||||
// accounts each time. The window's rate scales every price the call is
|
||||
// counted at, a price the user set for the model included (#2463); the
|
||||
// price rate alone leaves that price as set. A zero at prices without a
|
||||
// rate window's rate, as BasePriceIn asks for.
|
||||
func priceOf(s settings.Settings, p Provider, known bool, model string, at time.Time) (catalog.Price, bool) {
|
||||
pr, ok := tariffOf(s, p, known, model)
|
||||
if ok && !at.IsZero() {
|
||||
if w := p.RateAt(at); w > 0 && w != 1 {
|
||||
pr = pr.Times(w)
|
||||
}
|
||||
}
|
||||
return pr, ok
|
||||
}
|
||||
|
||||
// tariffOf is a price without a rate window's rate: what the user set
|
||||
// for the model as they set it, else the provider's list price, else its
|
||||
// maker's, each at the price rate.
|
||||
func tariffOf(s settings.Settings, p Provider, known bool, model string) (catalog.Price, bool) {
|
||||
id := p.ID
|
||||
// then what they said the model costs from any provider (*/model):
|
||||
// still the user's word, so before any list price
|
||||
@@ -2306,10 +2349,18 @@ func EntryPriceIn(st settings.Settings, find func(string) (Group, []Member, bool
|
||||
// read of the providers it makes: what a /v1/models or an agent's model
|
||||
// file prices row by row.
|
||||
func EntryPricer(st settings.Settings, find func(string) (Group, []Member, bool)) func(Entry) (catalog.Price, bool) {
|
||||
// one time for the whole list, as the providers are one read too:
|
||||
// a rate window (#2463) holds or not for every row alike
|
||||
return entryPricerAt(st, find, time.Now())
|
||||
}
|
||||
|
||||
// entryPricerAt is EntryPricer with a provider's rate window taken at
|
||||
// now, or left out for a zero now.
|
||||
func entryPricerAt(st settings.Settings, find func(string) (Group, []Member, bool), now time.Time) func(Entry) (catalog.Price, bool) {
|
||||
all := All()
|
||||
return func(e Entry) (catalog.Price, bool) {
|
||||
if e.Group == "" {
|
||||
return priceIn(st, all, e.Provider.ID, e.Model)
|
||||
return priceIn(st, all, e.Provider.ID, e.Model, now)
|
||||
}
|
||||
_, ms, ok := find(e.ID)
|
||||
if !ok || len(ms) == 0 {
|
||||
@@ -2317,7 +2368,7 @@ func EntryPricer(st settings.Settings, find func(string) (Group, []Member, bool)
|
||||
}
|
||||
var first catalog.Price
|
||||
for i, m := range ms {
|
||||
pr, ok := priceIn(st, all, m.Provider.ID, m.Model)
|
||||
pr, ok := priceIn(st, all, m.Provider.ID, m.Model, now)
|
||||
if !ok || m.Fast || i > 0 && !pr.Same(first) {
|
||||
return catalog.Price{}, false
|
||||
}
|
||||
@@ -2337,8 +2388,15 @@ func EntryPricer(st settings.Settings, find func(string) (Group, []Member, bool)
|
||||
// every call to the group at 0. A first member in a fast mode, or with no
|
||||
// known price, leaves the group unpriced, as before. The list is read
|
||||
// afresh at each Sync, so the price follows the group's members.
|
||||
//
|
||||
// A provider's rate window (#2463) is left out: the file holds whatever
|
||||
// was written at the last Sync, which nothing rewrites when a window
|
||||
// opens or closes, so a window's price taken then would stay on through
|
||||
// the hours outside it. magpie's own count (Usage, a key's budget) takes
|
||||
// each call's window.
|
||||
func AgentPricer(st settings.Settings, find func(string) (Group, []Member, bool)) func(Entry) (catalog.Price, bool) {
|
||||
same, all := EntryPricer(st, find), All()
|
||||
var base time.Time
|
||||
same, all := entryPricerAt(st, find, base), All()
|
||||
return func(e Entry) (catalog.Price, bool) {
|
||||
if pr, ok := same(e); ok || e.Group == "" {
|
||||
return pr, ok
|
||||
@@ -2347,7 +2405,7 @@ func AgentPricer(st settings.Settings, find func(string) (Group, []Member, bool)
|
||||
if !ok || len(ms) == 0 || ms[0].Fast {
|
||||
return catalog.Price{}, false
|
||||
}
|
||||
return priceIn(st, all, ms[0].Provider.ID, ms[0].Model)
|
||||
return priceIn(st, all, ms[0].Provider.ID, ms[0].Model, base)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -100,7 +100,7 @@ func TestPriceOfPeak(t *testing.T) {
|
||||
}
|
||||
at := func(s settings.Settings, p Provider, model string, tm time.Time) float64 {
|
||||
t.Helper()
|
||||
pr, ok := priceOf(s, p, true, model)
|
||||
pr, ok := priceOf(s, p, true, model, time.Time{})
|
||||
if !ok {
|
||||
t.Fatalf("%s %s: unpriced", p.ID, model)
|
||||
}
|
||||
@@ -137,7 +137,7 @@ func TestPriceOfPeak(t *testing.T) {
|
||||
}
|
||||
}
|
||||
// a provider gone since, priced at its maker's
|
||||
if pr, ok := priceOf(none, Provider{ID: "deepseek"}, false, "deepseek-flash"); !ok || pr.In(peak).Input != 0.3 {
|
||||
if pr, ok := priceOf(none, Provider{ID: "deepseek"}, false, "deepseek-flash", time.Time{}); !ok || pr.In(peak).Input != 0.3 {
|
||||
t.Errorf("removed deepseek: %+v %v", pr, ok)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,6 +212,12 @@ type Provider struct {
|
||||
// a price the user set for one of its models stands as set. 0 is the
|
||||
// price as listed; at most three decimals (PriceRateOK).
|
||||
PriceRate float64 `json:"priceRate,omitempty"`
|
||||
// RateWindows are the time-of-day windows it bills at its own rate
|
||||
// (#2463): a peak at 2× or 3×, a discount off peak. The first window
|
||||
// that holds a call's time multiplies the price again, on top of
|
||||
// PriceRate; outside every window the price rate alone counts. At
|
||||
// most RateWindowsMax of them (CheckRateWindows).
|
||||
RateWindows []RateWindow `json:"rateWindows,omitempty"`
|
||||
|
||||
// Headers are extra HTTP request headers sent to the vendor, as the user
|
||||
// typed them but for ${sessionId} and ${threadId} in a value, the
|
||||
@@ -785,9 +791,12 @@ func withPicks(a, pk Provider) Provider {
|
||||
a.MaxConcurrency, a.PinUpstream = pk.MaxConcurrency, pk.PinUpstream
|
||||
a.AccountConcurrency, a.QueueLimit, a.QueueWait = pk.AccountConcurrency, pk.QueueLimit, pk.QueueWait
|
||||
a.MaxRPM = pk.MaxRPM
|
||||
// and what it bills against the official price (#819): an account's
|
||||
// editor sets it as a key provider's does (PaulT on Discord, Codex)
|
||||
// what it bills against the official price (#819): an account's editor
|
||||
// sets it as a key provider's does (PaulT on Discord, Codex)
|
||||
a.PriceRate = pk.PriceRate
|
||||
// the hours the provider bills at its own rate (#2463), as the editor
|
||||
// keeps them for the account like the rest of these
|
||||
a.RateWindows = pk.RateWindows
|
||||
// the extra body fields written for it, which a ChatGPT account's
|
||||
// requests take (WithExtraBody, magpie-releases#18)
|
||||
a.ExtraBody = pk.ExtraBody
|
||||
@@ -922,7 +931,7 @@ func Save(p Provider) error {
|
||||
if p.ID == "kiro" {
|
||||
key = p.Key
|
||||
}
|
||||
p = Provider{ID: p.ID, Key: key, Models: p.Models, NoModels: p.NoModels, BestInFamily: p.BestInFamily, PickedFrom: p.PickedFrom, Delisted: p.Delisted, Unlisted: p.Unlisted, HiddenDrawers: p.HiddenDrawers, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, CapStop: p.CapStop, CapCareful: p.CapCareful, AccountNames: p.AccountNames, MaxConcurrency: p.MaxConcurrency, AccountConcurrency: p.AccountConcurrency, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, PriceRate: p.PriceRate, QuotaRest: p.QuotaRest, QuotaResetAt: p.QuotaResetAt, RestCap: p.RestCap, PinUpstream: p.PinUpstream, NativeCompaction: p.NativeCompaction, PromptAsWritten: p.PromptAsWritten, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID), Tucked: tuckedAccount(p.ID)}
|
||||
p = Provider{ID: p.ID, Key: key, Models: p.Models, NoModels: p.NoModels, BestInFamily: p.BestInFamily, RateWindows: p.RateWindows, PickedFrom: p.PickedFrom, Delisted: p.Delisted, Unlisted: p.Unlisted, HiddenDrawers: p.HiddenDrawers, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, CapStop: p.CapStop, CapCareful: p.CapCareful, AccountNames: p.AccountNames, MaxConcurrency: p.MaxConcurrency, AccountConcurrency: p.AccountConcurrency, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, PriceRate: p.PriceRate, QuotaRest: p.QuotaRest, QuotaResetAt: p.QuotaResetAt, RestCap: p.RestCap, PinUpstream: p.PinUpstream, NativeCompaction: p.NativeCompaction, PromptAsWritten: p.PromptAsWritten, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID), Tucked: tuckedAccount(p.ID)}
|
||||
} else {
|
||||
p.AccountProxies = keyProxies(p) // a provider of keys proxies each key apart
|
||||
if subscriptionID(p.ID) && !stored(p.ID) {
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RateWindow is a time-of-day window a provider bills at its own rate
|
||||
// (#2463): a relay that charges 2× or 3× at peak and a discount off
|
||||
// peak. Start and End are "HH:MM" on this computer's clock, End may be
|
||||
// "24:00"; Start after End crosses midnight, and the window then belongs
|
||||
// to the day it starts on, its Days among them. Days are time.Weekday's
|
||||
// numbers (Sunday 0), empty for every day. Rate is what the provider
|
||||
// bills against the official price inside the window, on top of
|
||||
// PriceRate: from just over 0 to 1000, at most three decimals. The first
|
||||
// window that holds a call's time wins; outside every window the price
|
||||
// rate alone counts. The window's rate scales a price the user set for a
|
||||
// model too, which the price rate alone leaves as set.
|
||||
type RateWindow struct {
|
||||
Days []int `json:"days,omitempty"`
|
||||
Start string `json:"start"`
|
||||
End string `json:"end"`
|
||||
Rate float64 `json:"rate"`
|
||||
}
|
||||
|
||||
// RateWindowsMax is how many windows one provider can have (#2463).
|
||||
const RateWindowsMax = 8
|
||||
|
||||
// ParseClock reads "HH:MM" as minutes into the day: 0 for 00:00 through
|
||||
// 1440 for 24:00, which only an end may be. ok is false for anything
|
||||
// else.
|
||||
func ParseClock(s string) (min int, ok bool) {
|
||||
h, m, found := strings.Cut(strings.TrimSpace(s), ":")
|
||||
if !found || len(h) == 0 || len(h) > 2 || !isDigits(h) || len(m) != 2 || !isDigits(m) {
|
||||
return 0, false
|
||||
}
|
||||
hh, err := strconv.Atoi(h)
|
||||
if err != nil || hh > 24 {
|
||||
return 0, false
|
||||
}
|
||||
mm, err := strconv.Atoi(m)
|
||||
if err != nil || mm > 59 {
|
||||
return 0, false
|
||||
}
|
||||
if min = hh*60 + mm; min > 1440 {
|
||||
return 0, false
|
||||
}
|
||||
return min, true
|
||||
}
|
||||
|
||||
// isDigits says whether s is ASCII digits alone.
|
||||
func isDigits(s string) bool {
|
||||
for _, r := range s {
|
||||
if r < '0' || r > '9' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return len(s) > 0
|
||||
}
|
||||
|
||||
// CheckRateWindows says what is wrong with a set of a provider's rate
|
||||
// windows, "" when nothing. A window's rate stands to the same rule as a
|
||||
// price rate but is never 0: 0 would read as the price as listed, which
|
||||
// is what being outside every window already means.
|
||||
func CheckRateWindows(ws []RateWindow) string {
|
||||
if len(ws) > RateWindowsMax {
|
||||
return fmt.Sprintf("at most %d rate windows", RateWindowsMax)
|
||||
}
|
||||
for i, w := range ws {
|
||||
start, ok := ParseClock(w.Start)
|
||||
if !ok {
|
||||
return fmt.Sprintf("rate window %d: the start is a time like 09:00, not %s", i+1, w.Start)
|
||||
}
|
||||
end, ok := ParseClock(w.End)
|
||||
if !ok {
|
||||
return fmt.Sprintf("rate window %d: the end is a time like 18:00, not %s", i+1, w.End)
|
||||
}
|
||||
if start == 1440 {
|
||||
return fmt.Sprintf("rate window %d: the start is a time like 09:00, not %s", i+1, w.Start)
|
||||
}
|
||||
if start == end {
|
||||
return fmt.Sprintf("rate window %d: the start and the end are both %s", i+1, w.Start)
|
||||
}
|
||||
for _, d := range w.Days {
|
||||
if d < 0 || d > 6 {
|
||||
return fmt.Sprintf("rate window %d: a day is 0 (Sunday) to 6 (Saturday), not %d", i+1, d)
|
||||
}
|
||||
}
|
||||
if r := w.Rate; !(r > 0) || math.IsNaN(r) || r > 1000 {
|
||||
return fmt.Sprintf("rate window %d: the rate is a number from 0 to 1000, not %v", i+1, r)
|
||||
}
|
||||
if math.Abs(w.Rate*1000-math.Round(w.Rate*1000)) > 1e-6 {
|
||||
return fmt.Sprintf("rate window %d: the rate has at most three decimals, not %v", i+1, w.Rate)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// RateAt is the rate the windows bill at at t, on this computer's clock:
|
||||
// 0 when no window holds t, which means the price rate alone, and for a
|
||||
// zero t, a price asked for with no call's time (a memo of the price
|
||||
// shared by many calls) being the base. The first window that holds t
|
||||
// wins. A window's span is from its start in and to
|
||||
// its end out; one that crosses midnight belongs to the day it starts
|
||||
// on, so its early hours read as that day's.
|
||||
func RateAt(ws []RateWindow, t time.Time) float64 {
|
||||
if len(ws) == 0 || t.IsZero() {
|
||||
return 0
|
||||
}
|
||||
// t's own zone is whatever wrote it: a call reported to
|
||||
// /v1/magpie/usage as "…Z" parses in UTC, and its hour read there
|
||||
// missed a window by the zone's offset
|
||||
t = t.Local()
|
||||
m := t.Hour()*60 + t.Minute()
|
||||
day := int(t.Weekday())
|
||||
for _, w := range ws {
|
||||
start, ok1 := ParseClock(w.Start)
|
||||
end, ok2 := ParseClock(w.End)
|
||||
if !ok1 || !ok2 || start == end {
|
||||
continue
|
||||
}
|
||||
var in bool
|
||||
d := day
|
||||
if start < end {
|
||||
in = m >= start && m < end
|
||||
} else {
|
||||
in = m >= start || m < end
|
||||
if m < end {
|
||||
// past midnight: the window began yesterday
|
||||
d = (d + 6) % 7
|
||||
}
|
||||
}
|
||||
if !in || len(w.Days) > 0 && !slices.Contains(w.Days, d) {
|
||||
continue
|
||||
}
|
||||
return w.Rate
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// RateWindowsOf is the rate windows of the provider with id, or of the one
|
||||
// renamed from it, none for a provider not known: for a caller holding
|
||||
// a base price to read each call's time against (#2463).
|
||||
func RateWindowsOf(id string) []RateWindow {
|
||||
p, ok := byIDOrWas(id)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return p.RateWindows
|
||||
}
|
||||
|
||||
// RateAt is the rate the provider's windows bill at at t, 0 for none.
|
||||
func (p Provider) RateAt(t time.Time) float64 {
|
||||
return RateAt(p.RateWindows, t)
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// A rate window (#2463) holds a time of day, and a window that crosses
|
||||
// midnight belongs to the day it starts on.
|
||||
|
||||
// atLocal is a time on this computer's clock, so a window and the time
|
||||
// asked of it are always in one zone whatever the test runs under.
|
||||
func atLocal(y int, mo time.Month, d, h, mi int) time.Time {
|
||||
return time.Date(y, mo, d, h, mi, 0, 0, time.Local)
|
||||
}
|
||||
|
||||
func TestParseClock(t *testing.T) {
|
||||
good := map[string]int{
|
||||
"00:00": 0, "09:00": 540, "9:30": 570, "23:59": 1439, "24:00": 1440, " 8:05 ": 485,
|
||||
}
|
||||
for s, want := range good {
|
||||
if n, ok := ParseClock(s); !ok || n != want {
|
||||
t.Errorf("ParseClock(%q) = %d, %v; want %d, true", s, n, ok, want)
|
||||
}
|
||||
}
|
||||
for _, s := range []string{"", "9", "9:5", "09:60", "24:01", "25:00", "ab:cd", "-1:00", "1:2:3", "0900"} {
|
||||
if n, ok := ParseClock(s); ok {
|
||||
t.Errorf("ParseClock(%q) = %d taken", s, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckRateWindows(t *testing.T) {
|
||||
ok := []RateWindow{
|
||||
{Start: "09:00", End: "12:00", Rate: 3},
|
||||
{Days: []int{1, 2, 3, 4, 5}, Start: "22:00", End: "06:00", Rate: 0.5},
|
||||
{Start: "00:00", End: "24:00", Rate: 1000},
|
||||
}
|
||||
if bad := CheckRateWindows(ok); bad != "" {
|
||||
t.Fatalf("good windows: %s", bad)
|
||||
}
|
||||
bad := []struct {
|
||||
name string
|
||||
ws []RateWindow
|
||||
}{
|
||||
{"nine windows", make([]RateWindow, RateWindowsMax+1)},
|
||||
{"bad start", []RateWindow{{Start: "9", End: "12:00", Rate: 2}}},
|
||||
{"bad end", []RateWindow{{Start: "09:00", End: "24:01", Rate: 2}}},
|
||||
{"start 24:00", []RateWindow{{Start: "24:00", End: "06:00", Rate: 2}}},
|
||||
{"empty span", []RateWindow{{Start: "09:00", End: "09:00", Rate: 2}}},
|
||||
{"day 7", []RateWindow{{Days: []int{7}, Start: "09:00", End: "12:00", Rate: 2}}},
|
||||
{"rate 0", []RateWindow{{Start: "09:00", End: "12:00", Rate: 0}}},
|
||||
{"rate negative", []RateWindow{{Start: "09:00", End: "12:00", Rate: -1}}},
|
||||
{"rate over 1000", []RateWindow{{Start: "09:00", End: "12:00", Rate: 1000.5}}},
|
||||
{"rate four decimals", []RateWindow{{Start: "09:00", End: "12:00", Rate: 0.1234}}},
|
||||
}
|
||||
for _, x := range bad {
|
||||
if CheckRateWindows(x.ws) == "" {
|
||||
t.Errorf("%s taken", x.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRateAt(t *testing.T) {
|
||||
// any Tuesday; the days are taken from the day itself, so the test
|
||||
// stands in every zone and on every calendar
|
||||
day := atLocal(2026, 10, 20, 10, 0)
|
||||
if day.Weekday() != time.Tuesday {
|
||||
t.Fatalf("2026-10-20 is a %v", day.Weekday())
|
||||
}
|
||||
tue := []int{int(time.Tuesday)}
|
||||
|
||||
// in from the start, out at the end
|
||||
ws := []RateWindow{{Start: "09:00", End: "12:00", Rate: 3}}
|
||||
if r := RateAt(ws, atLocal(2026, 10, 20, 9, 0)); r != 3 {
|
||||
t.Errorf("at the start: %v", r)
|
||||
}
|
||||
if r := RateAt(ws, atLocal(2026, 10, 20, 11, 59)); r != 3 {
|
||||
t.Errorf("a minute before the end: %v", r)
|
||||
}
|
||||
if r := RateAt(ws, atLocal(2026, 10, 20, 12, 0)); r != 0 {
|
||||
t.Errorf("at the end: %v", r)
|
||||
}
|
||||
|
||||
// across midnight, every day: in before, in after
|
||||
ws = []RateWindow{{Start: "22:00", End: "06:00", Rate: 0.5}}
|
||||
for _, x := range []struct{ h, mi int }{{21, 59}, {6, 0}, {12, 0}} {
|
||||
if r := RateAt(ws, atLocal(2026, 10, 20, x.h, x.mi)); r != 0 {
|
||||
t.Errorf("outside 22:00-06:00 at %02d:%02d: %v", x.h, x.mi, r)
|
||||
}
|
||||
}
|
||||
for _, x := range []struct{ h, mi int }{{22, 0}, {23, 59}, {0, 0}, {5, 59}} {
|
||||
if r := RateAt(ws, atLocal(2026, 10, 20, x.h, x.mi)); r != 0.5 {
|
||||
t.Errorf("inside 22:00-06:00 at %02d:%02d: %v", x.h, x.mi, r)
|
||||
}
|
||||
}
|
||||
|
||||
// across midnight on Tuesdays only: the early hours read as Tuesday's,
|
||||
// so Tuesday 22:00 into Wednesday 06:00, not Wednesday's night
|
||||
ws = []RateWindow{{Days: tue, Start: "22:00", End: "06:00", Rate: 2}}
|
||||
if r := RateAt(ws, atLocal(2026, 10, 20, 23, 0)); r != 2 {
|
||||
t.Errorf("Tuesday 23:00: %v", r)
|
||||
}
|
||||
if r := RateAt(ws, atLocal(2026, 10, 21, 5, 0)); r != 2 {
|
||||
t.Errorf("Wednesday 05:00, still Tuesday's window: %v", r)
|
||||
}
|
||||
if r := RateAt(ws, atLocal(2026, 10, 21, 22, 30)); r != 0 {
|
||||
t.Errorf("Wednesday 22:30, a Wednesday night: %v", r)
|
||||
}
|
||||
|
||||
// the first window that holds the time wins
|
||||
ws = []RateWindow{
|
||||
{Start: "09:00", End: "12:00", Rate: 3},
|
||||
{Start: "00:00", End: "24:00", Rate: 0.5},
|
||||
}
|
||||
if r := RateAt(ws, atLocal(2026, 10, 20, 10, 0)); r != 3 {
|
||||
t.Errorf("the first of two: %v", r)
|
||||
}
|
||||
if r := RateAt(ws, atLocal(2026, 10, 20, 15, 0)); r != 0.5 {
|
||||
t.Errorf("the second of two: %v", r)
|
||||
}
|
||||
|
||||
// a time written in another zone is read on this computer's clock: a
|
||||
// call reported as "…Z" is the same instant as the local one
|
||||
ws = []RateWindow{{Start: "10:00", End: "14:00", Rate: 3}}
|
||||
in := atLocal(2026, 10, 20, 11, 0)
|
||||
for _, z := range []*time.Location{time.UTC, time.FixedZone("far", -11*3600), time.FixedZone("east", 14*3600)} {
|
||||
if r := RateAt(ws, in.In(z)); r != 3 {
|
||||
t.Errorf("local 11:00 written in %s (%v): %v", z, in.In(z), r)
|
||||
}
|
||||
}
|
||||
|
||||
// a window that can't be read stands aside, and none at all is 0
|
||||
if r := RateAt([]RateWindow{{Start: "bad", End: "12:00", Rate: 3}}, atLocal(2026, 10, 20, 10, 0)); r != 0 {
|
||||
t.Errorf("an unreadable window: %v", r)
|
||||
}
|
||||
if r := RateAt(nil, atLocal(2026, 10, 20, 10, 0)); r != 0 {
|
||||
t.Errorf("no window: %v", r)
|
||||
}
|
||||
}
|
||||
|
||||
// A provider's windows multiply the price a call is counted at, at the
|
||||
// call's own time, on top of the price rate; BasePriceIn gives the price
|
||||
// without them and the windows to read a time against.
|
||||
func TestRateWindowsPrice(t *testing.T) {
|
||||
priceHome(t)
|
||||
priceCatalog(t)
|
||||
p := Provider{ID: "relay", Name: "Relay", Chat: "https://relay.example.com/v1", Key: "k",
|
||||
Models: []string{"sol"}, PriceRate: 2,
|
||||
RateWindows: []RateWindow{{Start: "09:00", End: "12:00", Rate: 3}}}
|
||||
if err := Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
peak := atLocal(2026, 10, 20, 10, 0)
|
||||
off := atLocal(2026, 10, 20, 15, 0)
|
||||
// the list price is 2 in, 10 out; PriceRate 2 makes 4 and 20, the
|
||||
// peak window's 3 makes 12 and, outside, 20 again
|
||||
pr, ok := EffectivePriceAt(settings.Load(), "relay", "sol", peak)
|
||||
if !ok || pr.Input != 12 || pr.Output != 60 {
|
||||
t.Fatalf("at the peak of a 2× relay: %+v %v", pr, ok)
|
||||
}
|
||||
pr, ok = EffectivePriceAt(settings.Load(), "relay", "sol", off)
|
||||
if !ok || pr.Input != 4 || pr.Output != 20 {
|
||||
t.Fatalf("off peak: %+v %v", pr, ok)
|
||||
}
|
||||
// EffectivePriceIn prices a call now, whatever that is: one of the two
|
||||
now, ok := EffectivePriceIn(settings.Load(), "relay", "sol")
|
||||
if !ok {
|
||||
t.Fatal("a price now is known")
|
||||
}
|
||||
if now.Input != 4 && now.Input != 12 {
|
||||
t.Fatalf("a price now is one of the window's: %+v", now)
|
||||
}
|
||||
// the base price and the windows apart, as the ledger's Pricer holds them
|
||||
base, ok, ws := BasePriceIn(settings.Load(), "relay", "sol")
|
||||
if !ok || base.Input != 4 || len(ws) != 1 || ws[0].Rate != 3 {
|
||||
t.Fatalf("the base price and the windows: %+v %v %+v", base, ok, ws)
|
||||
}
|
||||
// a rate of 1 changes nothing, and a model priced by the user is
|
||||
// scaled by the window all the same: the window is when the vendor
|
||||
// bills more, whatever the price is set from
|
||||
p.RateWindows = []RateWindow{{Start: "09:00", End: "12:00", Rate: 1}}
|
||||
if err := Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if pr, _ := EffectivePriceAt(settings.Load(), "relay", "sol", peak); pr.Input != 4 {
|
||||
t.Fatalf("a rate of 1: %+v", pr)
|
||||
}
|
||||
if err := settings.Save(settings.Settings{ModelPrices: map[string]settings.ModelPrice{"relay/sol": statePrice(3)}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.RateWindows = []RateWindow{{Start: "09:00", End: "12:00", Rate: 3}}
|
||||
if err := Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if pr, _ := EffectivePriceAt(settings.Load(), "relay", "sol", peak); pr.Input != 9 {
|
||||
t.Fatalf("a price the user set is scaled by the window too: %+v", pr)
|
||||
}
|
||||
if pr, _ := EffectivePriceAt(settings.Load(), "relay", "sol", off); pr.Input != 3 {
|
||||
t.Fatalf("a price the user set off peak: %+v", pr)
|
||||
}
|
||||
}
|
||||
|
||||
// A signed-in account's windows survive its Save: the account branch of
|
||||
// Save keeps only what it lists, and the windows are listed there — a
|
||||
// plugin provider is an account, and the editor's Save would otherwise
|
||||
// quietly drop what it shows, as it once did the account's PriceRate.
|
||||
func TestAccountSaveKeepsTheRateWindows(t *testing.T) {
|
||||
signIn(t) // a codex account, so Save takes the account branch
|
||||
ws := []RateWindow{{Days: []int{1}, Start: "09:00", End: "18:00", Rate: 3}}
|
||||
if err := Save(Provider{ID: "codex", RateWindows: ws}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, err := Find("codex")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(p.RateWindows) != 1 || p.RateWindows[0].Rate != 3 {
|
||||
t.Fatalf("the account's windows are gone: %+v", p.RateWindows)
|
||||
}
|
||||
}
|
||||
|
||||
// A template weighs a model by its price without the provider's rate
|
||||
// windows (#2463): the hour a template is made in says nothing about how
|
||||
// strong a model is, so a peak window never makes a relay's model read
|
||||
// as a flagship.
|
||||
func TestTemplateModelsLeaveTheRateWindowOut(t *testing.T) {
|
||||
priceHome(t)
|
||||
if err := settings.Save(settings.Settings{ModelPrices: map[string]settings.ModelPrice{"relay/obscure-lab-ultra": statePrice(5)}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := Save(Provider{ID: "relay", Name: "Relay", Chat: "https://relay.example.com/v1", Key: "k",
|
||||
Models: []string{"obscure-lab-ultra"},
|
||||
RateWindows: []RateWindow{{Start: "00:00", End: "24:00", Rate: 3}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var seen bool
|
||||
for _, r := range templateModels() {
|
||||
if r.e.Provider.ID == "relay" && r.e.Model == "obscure-lab-ultra" {
|
||||
seen = true
|
||||
if r.out != 5 {
|
||||
t.Errorf("the template weighs it at %v out, want the set 5, not the window's 3×", r.out)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !seen {
|
||||
t.Fatal("the relay's model is not among the template's")
|
||||
}
|
||||
}
|
||||
|
||||
// A zero time is a price asked with no call's time, a memo many calls
|
||||
// share (the Requests tab's gateway blocks): no window holds it, however
|
||||
// wide, so the memo is the base and each call's own time is read after.
|
||||
func TestRateAtZeroTimeIsTheBase(t *testing.T) {
|
||||
all := []RateWindow{{Start: "00:00", End: "24:00", Rate: 3}}
|
||||
if r := RateAt(all, time.Time{}); r != 0 {
|
||||
t.Fatalf("zero time: %v, want 0", r)
|
||||
}
|
||||
if r := RateAt(all, time.Now()); r != 3 {
|
||||
t.Fatalf("now in an all-day window: %v, want 3", r)
|
||||
}
|
||||
}
|
||||
|
||||
// The prices magpie writes into an agent's own model file (Pi's, omp's)
|
||||
// leave a rate window out: nothing rewrites the file as a window opens or
|
||||
// closes, so a price taken in one would stay on outside it. /v1/models,
|
||||
// read at each request, prices now.
|
||||
func TestAgentPricerLeavesTheRateWindowOut(t *testing.T) {
|
||||
priceHome(t)
|
||||
priceCatalog(t)
|
||||
p := Provider{ID: "relay", Name: "Relay", Chat: "https://relay.example.com/v1", Key: "k",
|
||||
Models: []string{"sol"}, PriceRate: 2,
|
||||
RateWindows: []RateWindow{{Start: "00:00", End: "24:00", Rate: 3}}}
|
||||
if err := Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
none := func(string) (Group, []Member, bool) { return Group{}, nil, false }
|
||||
e := Entry{ID: "relay/sol", Model: "sol", Provider: p}
|
||||
if pr, ok := AgentPricer(settings.Load(), none)(e); !ok || pr.Input != 4 || pr.Output != 20 {
|
||||
t.Fatalf("an agent file's price under an all-day 3× window: %+v %v, want the 2× relay's 4 and 20", pr, ok)
|
||||
}
|
||||
if pr, ok := EntryPricer(settings.Load(), none)(e); !ok || pr.Input != 12 || pr.Output != 60 {
|
||||
t.Fatalf("/v1/models' price now: %+v %v, want 12 and 60", pr, ok)
|
||||
}
|
||||
// a group whose members differ is priced at its first member, base too
|
||||
q := Provider{ID: "other", Name: "Other", Chat: "https://other.example.com/v1", Key: "k", Models: []string{"sol"}}
|
||||
if err := Save(q); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
group := func(string) (Group, []Member, bool) {
|
||||
return Group{}, []Member{{Provider: p, Model: "sol"}, {Provider: q, Model: "sol"}}, true
|
||||
}
|
||||
g := Entry{ID: "auto/sol", Model: "sol", Group: "auto", Provider: p}
|
||||
if pr, ok := AgentPricer(settings.Load(), group)(g); !ok || pr.Input != 4 {
|
||||
t.Fatalf("a mixed group's first member in an agent file: %+v %v, want 4", pr, ok)
|
||||
}
|
||||
}
|
||||
@@ -174,3 +174,30 @@ func TestListingPricesEveryModelAtTheSettingsItReadOnce(t *testing.T) {
|
||||
t.Errorf("the next listing prices the second at %v; want the $3 just written", p)
|
||||
}
|
||||
}
|
||||
|
||||
// A session is priced without its provider's rate windows (#2463): its
|
||||
// calls are summed by model, not by time, so the window open as it is
|
||||
// read would price every call at it, and the same session would read 3×
|
||||
// at the peak and 1× off it. A window that holds every hour shows it.
|
||||
func TestPriceOfLeavesTheRateWindowOut(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"))
|
||||
catalog.Reset()
|
||||
t.Cleanup(catalog.Reset)
|
||||
if err := settings.Save(settings.Settings{ModelPrices: map[string]settings.ModelPrice{
|
||||
"relay/gpt-5.5": {Input: new(float64(0.2)), Output: new(float64(1)),
|
||||
CacheRead: new(float64(0.05)), CacheWrite: new(float64(0.25))},
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Chat: "https://relay.example.com/v1",
|
||||
RateWindows: []provider.RateWindow{{Start: "00:00", End: "24:00", Rate: 3}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if pr, ok := priceOf(settings.Load(), "relay/gpt-5.5"); !ok || pr.Input != 0.2 || pr.Output != 1 {
|
||||
t.Errorf("priceOf(relay/gpt-5.5) = %+v, %v; want the set $0.2/$1, not the window's 3×", pr, ok)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2326,7 +2326,11 @@ func priceOf(s settings.Settings, model string) (catalog.Price, bool) {
|
||||
return catalog.Price{}, false
|
||||
}
|
||||
if pid, rest, ok := strings.Cut(m, "/"); ok {
|
||||
if pr, ok := provider.EffectivePriceIn(s, pid, rest); ok {
|
||||
// without a rate window's rate (#2463): a session sums its calls by
|
||||
// model, not by time, so the window of the hour it is read in
|
||||
// would price all of them at it, and the same session read 3× at
|
||||
// the peak and 1× off it
|
||||
if pr, ok, _ := provider.BasePriceIn(s, pid, rest); ok {
|
||||
return pr, true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,9 @@ type pricedAs struct {
|
||||
provider string
|
||||
flags uint16
|
||||
price *catalog.Price
|
||||
// windows are the provider's rate windows (#2463): price is asked
|
||||
// without a time, so each row's own time is read against them
|
||||
windows []provider.RateWindow
|
||||
}
|
||||
|
||||
// blockPricer prices the gateway's raw blocks as a query reads them. What a
|
||||
@@ -171,6 +174,7 @@ func (b *blockPricer) as(prov, model, served, effort string) pricedAs {
|
||||
a.flags |= 32
|
||||
}
|
||||
a.price = b.price(Record{Provider: prov, Model: model, Served: served, Effort: effort})
|
||||
a.windows = provider.RateWindowsOf(prov)
|
||||
b.by[k] = a
|
||||
return a
|
||||
}
|
||||
@@ -266,9 +270,10 @@ func (b *blockPricer) priceBlock(packed *rowChunk) (*rowChunk, *[]packedRow) {
|
||||
// make: the agent, the client and the provider are all a shape's
|
||||
c.Shapes, c.shapeIDs = slices.Clip(c.Shapes), nil
|
||||
type ids struct {
|
||||
id uint32 // the provider's string, or the row's shape
|
||||
flags uint16
|
||||
price *catalog.Price
|
||||
id uint32 // the provider's string, or the row's shape
|
||||
flags uint16
|
||||
price *catalog.Price
|
||||
windows []provider.RateWindow
|
||||
}
|
||||
names := map[[6]uint32]ids{}
|
||||
agents := map[uint32][2]uint32{}
|
||||
@@ -306,7 +311,7 @@ func (b *blockPricer) priceBlock(packed *rowChunk) (*rowChunk, *[]packedRow) {
|
||||
named, ok := names[k]
|
||||
if !ok {
|
||||
a := b.as(c.Strings[k[5]], c.Strings[k[1]], c.Strings[k[2]], c.Strings[k[3]])
|
||||
named = ids{k[4], a.flags, a.price}
|
||||
named = ids{k[4], a.flags, a.price, a.windows}
|
||||
names[k] = named
|
||||
}
|
||||
agent, ok := agents[t[0]]
|
||||
@@ -316,7 +321,7 @@ func (b *blockPricer) priceBlock(packed *rowChunk) (*rowChunk, *[]packedRow) {
|
||||
agents[t[0]] = agent
|
||||
}
|
||||
t[0], t[1], t[rowClient] = agent[0], named.id, agent[1]
|
||||
got = ids{c.shape(t), named.flags, named.price}
|
||||
got = ids{c.shape(t), named.flags, named.price, named.windows}
|
||||
shapes[sk] = got
|
||||
}
|
||||
p.Shape = got.id
|
||||
@@ -331,7 +336,7 @@ func (b *blockPricer) priceBlock(packed *rowChunk) (*rowChunk, *[]packedRow) {
|
||||
p.Cost = 0
|
||||
if got.price != nil && p.Tokens[0]+p.Tokens[1] > 0 {
|
||||
p.Flags |= 1
|
||||
p.Cost = got.price.In(p.Time).CostSplit(int(p.Tokens[0]), int(p.Tokens[1]), int(p.Tokens[2]), int(p.Tokens[3]), int(p.Tokens[5]))
|
||||
p.Cost = atWindow(got.price, got.windows, p.Time).In(p.Time).CostSplit(int(p.Tokens[0]), int(p.Tokens[1]), int(p.Tokens[2]), int(p.Tokens[3]), int(p.Tokens[5]))
|
||||
}
|
||||
}
|
||||
return &c, pooled
|
||||
|
||||
@@ -522,9 +522,16 @@ var ownPrice catalog.Price
|
||||
// a relay that sells kimi-k3 as moonshot-kimi-k3 answers as kimi-k3, which
|
||||
// is listed (#1498). The model asked for keeps its own price whenever it
|
||||
// has one, a zero set by the user included, so a ledger that matched the
|
||||
// vendor's bill still does.
|
||||
// vendor's bill still does. A record inside one of its provider's rate
|
||||
// windows (#2463) is priced at that window's rate, its own time read
|
||||
// against the windows, so calls either side of a boundary price apart.
|
||||
func Pricer() func(Record) *catalog.Price {
|
||||
prices := map[[3]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
|
||||
// mid-page prices only the calls inside it (#2463)
|
||||
windows := map[string][]provider.RateWindow{}
|
||||
s := settings.Load()
|
||||
return func(r Record) *catalog.Price {
|
||||
if r.OwnCost != nil {
|
||||
@@ -537,23 +544,38 @@ func Pricer() func(Record) *catalog.Price {
|
||||
id := r.priceID()
|
||||
k := [3]string{id, r.Model, served}
|
||||
if pr, ok := prices[k]; ok {
|
||||
return pr
|
||||
return atWindow(pr, windows[id], r.Time)
|
||||
}
|
||||
var pr *catalog.Price
|
||||
v, ok := provider.EffectivePriceIn(s, id, r.Model)
|
||||
v, ok, ws := provider.BasePriceIn(s, id, r.Model)
|
||||
if !ok && served != "" {
|
||||
v, ok = provider.EffectivePriceIn(s, id, served)
|
||||
v, ok, ws = provider.BasePriceIn(s, id, served)
|
||||
}
|
||||
if ok {
|
||||
pr = &v
|
||||
windows[id] = ws
|
||||
} else {
|
||||
catalog.Missing() // models.dev may list it by now
|
||||
}
|
||||
prices[k] = pr
|
||||
return pr
|
||||
return atWindow(pr, ws, r.Time)
|
||||
}
|
||||
}
|
||||
|
||||
// atWindow prices one record: the base price at the rate of the window
|
||||
// the record's time falls in (#2463), the price itself when none holds
|
||||
// or no price is known.
|
||||
func atWindow(pr *catalog.Price, ws []provider.RateWindow, at time.Time) *catalog.Price {
|
||||
if pr == nil {
|
||||
return nil
|
||||
}
|
||||
if r := provider.RateAt(ws, at); r > 0 && r != 1 {
|
||||
p := pr.Times(r)
|
||||
return &p
|
||||
}
|
||||
return pr
|
||||
}
|
||||
|
||||
// NewPricer totals requests' token-bearing attempts at one snapshot of the
|
||||
// effective prices used by the ledger. Reuse it for one page of routes;
|
||||
// make it again on the next read so a changed tariff re-prices history.
|
||||
|
||||
@@ -793,3 +793,99 @@ func TestLedgerPricesAModelListedUnderItsCanonicalID(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A record inside one of its provider's rate windows (#2463) is priced at
|
||||
// that window's rate at the record's own time, one outside at the base,
|
||||
// and one Pricer holds the base and the windows across the boundary: the
|
||||
// two sides of it price apart within one page.
|
||||
func TestPricerRateWindows(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, $8 out
|
||||
os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755)
|
||||
os.WriteFile(catalog.CachePath(), []byte(`{"anthropic":{"id":"anthropic","models":{"sol":{"id":"sol","cost":{"input":2,"output":8,"cache_read":0.5,"cache_write":2.5}}}}}`), 0o644)
|
||||
catalog.Reset()
|
||||
t.Cleanup(catalog.Reset)
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Chat: "https://relay.example/v1",
|
||||
RateWindows: []provider.RateWindow{{Start: "09:00", End: "12:00", Rate: 3}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
day := time.Now()
|
||||
in := func(h, m int) time.Time {
|
||||
return time.Date(day.Year(), day.Month(), day.Day(), h, m, 0, 0, time.Local)
|
||||
}
|
||||
rec := func(at time.Time) Record {
|
||||
return Record{Time: at, Agent: "codex", Provider: "relay", Model: "sol", Input: 1e6, Status: 200}
|
||||
}
|
||||
price := Pricer()
|
||||
peak, off := price(rec(in(10, 0))), price(rec(in(15, 0)))
|
||||
if peak == nil || off == nil {
|
||||
t.Fatal("both prices known")
|
||||
}
|
||||
// $2 a million in, the peak window's 3 makes $6, and the same base
|
||||
// price under the earlier call stays $2 after the later one: the rate
|
||||
// is the record's own, not the last one priced
|
||||
if c := peak.Cost(1e6, 0, 0, 0); c != 6 {
|
||||
t.Fatalf("inside 09:00-12:00: $%v", c)
|
||||
}
|
||||
if c := off.Cost(1e6, 0, 0, 0); c != 2 {
|
||||
t.Fatalf("outside the window, after one inside: $%v", c)
|
||||
}
|
||||
// the boundary itself: in at the start, out at the end
|
||||
if c := price(rec(in(9, 0))).Cost(1e6, 0, 0, 0); c != 6 {
|
||||
t.Fatalf("at the start: $%v", c)
|
||||
}
|
||||
if c := price(rec(in(12, 0))).Cost(1e6, 0, 0, 0); c != 2 {
|
||||
t.Fatalf("at the end: $%v", c)
|
||||
}
|
||||
}
|
||||
|
||||
// A gateway block's rows are priced from one memo per provider and model,
|
||||
// asked of the Pricer without a time: each row still takes the rate
|
||||
// window of its own time (#2463), as it takes DeepSeek's peak, so the
|
||||
// Requests tab prices a call at 10:00 inside 09:00-12:00 at 3x and one at
|
||||
// 15:00 at the list price, not every row at whatever the memo's zero time
|
||||
// fell in.
|
||||
func TestBlockRowsTakeTheirRateWindow(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"))
|
||||
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)
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Chat: "https://relay.example/v1",
|
||||
RateWindows: []provider.RateWindow{{Start: "09:00", End: "12:00", Rate: 3}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
day := time.Now()
|
||||
inside := time.Date(day.Year(), day.Month(), day.Day(), 10, 0, 0, 0, time.Local)
|
||||
outside := time.Date(day.Year(), day.Month(), day.Day(), 15, 0, 0, 0, time.Local)
|
||||
var raw rowChunk
|
||||
for i := 0; i < logBlockRows; i++ {
|
||||
at := inside
|
||||
if i%2 == 1 {
|
||||
at = outside
|
||||
}
|
||||
raw.add(Row{Record: Record{Time: at, Provider: "relay", Model: "sol", Input: 1_000_000}}, "", int64(i), false)
|
||||
}
|
||||
c, _ := newBlockPricer(provider.Renames{}, nil, Pricer()).priceBlock(raw.pack())
|
||||
if c == nil {
|
||||
t.Fatal("no block")
|
||||
}
|
||||
for i := range c.Rows {
|
||||
r := c.row(i)
|
||||
want := 2.0
|
||||
if r.Time.Equal(inside) {
|
||||
want = 6
|
||||
}
|
||||
if math.Abs(r.Cost-want) > 1e-9 {
|
||||
t.Fatalf("row %d at %v: $%v, want $%v", i, r.Time.Format("15:04"), r.Cost, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user