Files
magpie/internal/provider/key_rate_test.go
T
yetone a95a7a1cd8 providers: each API key can bill at a price rate of its own (tnt12231 on X)
A relay sells keys in groups that bill at different rates against the
official price (0.5x on one, 1.2x on another) under one endpoint, and
magpie had only the provider's price rate. Now a key can have its own:

- provider.KeyPriceRates, keyed by key id like KeySpendCaps: cloned,
  normalized on save, carried when a key is replaced. A key without one
  bills at the provider's PriceRate. A price the user set for a model
  stands as set, as it does under the provider's rate.
- Usage prices each call at its key's rate (usage.Pricer memoizes per
  key id, BaseKeyPriceIn), so the Usage page, a key's spend cap and its
  typed balance follow it. PriceAt, used to route by price, takes the
  rate of the key the provider holds.
- GUI: the provider editor's Advanced has "Price rate per key" under
  Price rate, shown only with two or more keys, folded past 8 keys like
  the per-key proxies. An empty line shows the provider's rate as its
  placeholder. Save sends keyPriceRates ({} clears, left out keeps).
  The lines, the check and the placeholder live in keyrates.js,
  imported when a provider with two or more keys opens. The core's
  budget goes up 397 for what is left in app.js (the import, the
  draft's copy, Advanced opening for it, the save's line, proxyLines
  drawing another kind of line); app.js stays under its own.
- CLI: magpie provider key-rate <id> [key [rate|default]].
- docs/subsystems/providers-accounts.md: a Key price rates row.

Run, at this head (rebased on 287a1ffa2) through mote-run:
- go test ./internal/usage ./internal/cli ./internal/gui: ok.
  ./internal/provider: ok but TestHostBuildsNoList, red the same on
  origin/main 51b98b1a8 (3 of 3), filed as #6479 (likely 16b8c300f).
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build: ok.
- GUI: key-price-rate.test.cjs (chromium and webkit x en, zh, zh-TW,
  ja, de: own rates saved, provider rate as placeholder, bad values
  refused, comma decimals, {} on clear, a folded key keeps its rate,
  one key shows no lines and posts none), i18n-keys and
  provider-many-keys-proxy (it shares proxyLines): ok. old-webkit:
  keyrates.js added to its on-demand list; its two reds (compat.js
  first, Safari 15.0 styles) fail the same on origin/main 51b98b1a8
  (#5919 and the on-demand list's #6467 family).
- Earlier, at 92bce5c72: the GUI files that reach the provider editor
  (134 tests). The 6 provider-many-keys reds fail the same on that base
  (#6209); proxy-login-fields' chromium zh timeout passes 12/12 alone on
  base and branch (#6374).

Broken by hand: atKeyRate leaving PriceRate as the provider's made
TestKeyPriceRatePrices and TestPricerKeyPriceRates red; the save not
sending keyPriceRates made 20 of 30 key-price-rate GUI tests red, and
keyrates.js dropping each parsed rate made them red again after the
move.

Not tried: a real relay with several keys at different rates; the real
Linux WebKitGTK app. The budget estimate and the Sessions page's costs
still use the provider's rate.
2026-11-13 16:31:24 +08:00

150 lines
5.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package provider
import (
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/settings"
)
// A key's own price rate (@tnt12231 on X) is set by the key's id or name,
// kept by its fingerprint in lower case, and taken off with nil; a key
// without one bills at the provider's PriceRate. A rate of 0 or out of
// range and a key the provider hasn't are refused, a subscription has no
// keys to rate, and a key's value replaced keeps its rate.
func TestKeyPriceRateSet(t *testing.T) {
priceHome(t)
if err := Save(Provider{ID: "relay", Name: "Relay", Chat: "https://relay.test/v1", Key: "sk-half", KeyName: "Half", PriceRate: 0.8,
Keys: []KeyAccount{{Name: "Premium", Key: "sk-premium"}, {Name: "Plain", Key: "sk-plain"}}}); err != nil {
t.Fatal(err)
}
half, premium, plain := keyID("sk-half"), keyID("sk-premium"), keyID("sk-plain")
rateOf := func(ref string) (float64, bool) {
t.Helper()
p, err := Find("relay")
if err != nil {
t.Fatal(err)
}
return p.KeyPriceRate(ref)
}
if r, own := rateOf(half); own || r != 0.8 {
t.Fatalf("no rate of its own, the provider's: %v %v", r, own)
}
if err := SetKeyPriceRate("relay", "Half", new(0.5)); err != nil {
t.Fatal(err)
}
if err := SetKeyPriceRate("relay", strings.ToUpper(premium), new(1.2)); err != nil {
t.Fatal(err)
}
if r, own := rateOf(strings.ToUpper(half)); !own || r != 0.5 {
t.Fatalf("Half: %v %v", r, own)
}
if r, own := rateOf(premium); !own || r != 1.2 {
t.Fatalf("Premium: %v %v", r, own)
}
if r, own := rateOf(plain); own || r != 0.8 {
t.Fatalf("Plain follows the provider: %v %v", r, own)
}
if p, _ := Find("relay"); p.PriceRate != 0.8 {
t.Fatalf("the provider's own rate changed: %v", p.PriceRate)
}
for _, bad := range []float64{0, -1, 1001, 0.1234} {
if err := SetKeyPriceRate("relay", "Plain", new(bad)); err == nil {
t.Fatalf("%v was taken", bad)
}
}
if err := SetKeyPriceRate("relay", "nobody", new(1.0)); err == nil {
t.Fatal("a key the provider hasn't got a rate")
}
// the value replaced, the rate goes with the key
if _, _, err := ReplaceKey("relay", half, "sk-half-2"); err != nil {
t.Fatal(err)
}
if r, own := rateOf(keyID("sk-half-2")); !own || r != 0.5 {
t.Fatalf("replaced, Half's rate %v %v", r, own)
}
if err := SetKeyPriceRate("relay", "Half", nil); err != nil {
t.Fatal(err)
}
if r, own := rateOf(keyID("sk-half-2")); own || r != 0.8 {
t.Fatalf("taken off, the provider's again: %v %v", r, own)
}
// a rate kept wrong in the file (typed by hand) is left out on Save
p, _ := Find("relay")
p.KeyPriceRates = map[string]float64{strings.ToUpper(plain): 2, premium: 0, "": 3}
if err := Save(*p); err != nil {
t.Fatal(err)
}
if p, _ := Find("relay"); len(p.KeyPriceRates) != 1 || p.KeyPriceRates[plain] != 2 {
t.Fatalf("kept: %v", p.KeyPriceRates)
}
}
func TestKeyPriceRateOnASubscription(t *testing.T) {
user := signIn(t)
if err := SetKeyPriceRate("codex", user, new(0.5)); err == nil {
t.Fatal("a subscription's account got a key's rate")
}
}
func TestParseKeyPriceRate(t *testing.T) {
for in, want := range map[string]float64{"0.8": 0.8, "1.5x": 1.5, "×1.2": 1.2, " 2 ": 2, "X0.5": 0.5} {
r, err := ParseKeyPriceRate(in)
if err != nil || r == nil || *r != want {
t.Errorf("%q: %v %v", in, r, err)
}
}
for _, in := range []string{"default", "Provider", "off", "-"} {
if r, err := ParseKeyPriceRate(in); err != nil || r != nil {
t.Errorf("%q: %v %v", in, r, err)
}
}
for _, in := range []string{"0", "abc", "1001", "0.1234", ""} {
if _, err := ParseKeyPriceRate(in); err == nil {
t.Errorf("%q taken", in)
}
}
}
// Each key's calls are priced at its own rate: two keys of one relay
// count one model's list price apart, a key without a rate and a call
// whose key isn't known at the provider's, and a price the user set for
// the model stands as set for every key.
func TestKeyPriceRatePrices(t *testing.T) {
priceHome(t)
priceCatalog(t)
half, premium := keyID("sk-half"), keyID("sk-premium")
if err := Save(Provider{ID: "openai", Name: "OpenAI", Chat: "https://api.openai.com/v1", Key: "sk-half", Models: []string{"sol"}, PriceRate: 0.8,
Keys: []KeyAccount{{Name: "Premium", Key: "sk-premium"}, {Name: "Plain", Key: "sk-plain"}},
KeyPriceRates: map[string]float64{half: 0.5, premium: 1.5}}); err != nil {
t.Fatal(err)
}
s := settings.Load()
for _, c := range []struct {
key string
want float64
}{{half, 1}, {premium, 3}, {keyID("sk-plain"), 1.6}, {"", 1.6}, {"0000000000", 1.6}} {
pr, ok, _ := BaseKeyPriceIn(s, "openai", c.key, "sol")
if !ok || pr.Input != c.want {
t.Errorf("key %q: $%v in, want $%v (%v)", c.key, pr.Input, c.want, ok)
}
}
// routing by price weighs a candidate at the rate of the key it holds
p, _ := Find("openai")
q := *p
q.Key = "sk-premium"
if pr, ok := q.PriceAt(s, "sol", time.Time{}); !ok || pr.Input != 3 {
t.Fatalf("PriceAt with Premium: %+v %v", pr, ok)
}
if err := settings.Save(settings.Settings{ModelPrices: map[string]settings.ModelPrice{"openai/sol": statePrice(7)}}); err != nil {
t.Fatal(err)
}
s = settings.Load()
for _, k := range []string{half, premium, ""} {
if pr, ok, _ := BaseKeyPriceIn(s, "openai", k, "sol"); !ok || pr.Input != 7 {
t.Errorf("key %q: a price set for the model is not scaled: %+v %v", k, pr, ok)
}
}
}