diff --git a/docs/reference.md b/docs/reference.md index f80ebad4c..6e5305326 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -656,6 +656,7 @@ magpie gateway-key limit list # each limit, used, left and reset magpie gateway-key limit 10d --tokens 5m # every 10 days, from now magpie gateway-key limit 5h --tokens 200k # every 5 hours, from now magpie gateway-key limit add week --cost 20 # one more limit; all must pass +magpie gateway-key limit add month --cost 20 --model openai/* # a limit of only OpenAI's models magpie gateway-key limit remove 2 # take off the 2nd limit magpie gateway-key limit reset # count its usage from 0 again (reset 2: only the 2nd) magpie gateway-key limit off # no limit @@ -720,6 +721,25 @@ Usage page this way (#1547). Requests from this computer that send no gateway key are not limited; a gateway key used from this computer is. +A limit can count **only some models** (zola_xynb on X): pick them under +**Models** in the limit's editor, or `--model` (again, or a comma list) on +`magpie gateway-key limit`, as `/` or `/*`, such +as $20 a month on `openai/*` beside $50 a month on the whole key. Such a +limit counts only the calls those models answered, by the provider and +model in the usage log. Once it is spent, a request naming one of them is +refused with the same 429 (it names the models, and sets no +`X-Magpie-Limit-Reset`, so a magpie using this one as a remote rests only +the model), and a routing group, a model's fallbacks, `count_tokens`, +embeddings, images, videos, the decision groups and magpie's own calls for +the key leave its models out and go on to the others, from the next +request on, midway through a conversation too. Its spent models stay in +the key's model lists. A limit without models is the whole key's, as every +limit before this was; two limits of the same window can share it only +when they count different models. A request through a group holds no +reservation in a model's limit, so requests sent at once through groups +can go over it by about a call each. A magpie from before this reads such +a limit, if it is a key's first, as the whole key's. + A key's holder can also open **`/me`** in a browser at the address they reach the gateway at (for example `http://192.168.1.10:3999/me`), type their key, and see its own limits, its usage over today, 7 and 30 days, the diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index d11b0857c..a99e66dd8 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -606,7 +606,29 @@ the spent limit that resets last). The saved key keeps the first limit in clients read, and `limits` is each of them (`budget.All`). Holding a key to its limits is the Key limits plugin's, on the gateway's budget point ([Plugin runtime](plugin-runtime.md#gateway-extension-points-p3-budget)): -with it off, a key held to a limit gets 503 and nothing is sent. A local magpie +with it off, a key held to a limit gets 503 and nothing is sent. A limit can count +only some models (`access.Limit.Models`, zola_xynb on X), `/` +or `/*`: its sums are kept per window and scope (`sums.scope`, +`window.scope`), and count a call only when the provider and model in the +usage log match (`scopeModels` adds a model's other ids). `budget.reserve` +holds a request to it only when the model it names resolves to one of them +(`servedAs`; a group, `auto/` or unknown name holds nothing there). Before +the reservation, `keyLimited` puts the key's spent ones on the caller +(`withSpent`, `budget.Spent` through `gwbudget.Spender`, its issuer's too, +`access.Identity.Spent`), `count_tokens` included. Then `keyHolds` holds the +request, magpie's own calls for the key too; `modelAllowed` refuses a spent +model by any of its ids (`spentFor`); `groupAllowed` ignores them, so a group +stays the key's; `groupKeeps` and so `allowedCandidates`, `drawingTries`, +the decision groups and embeddings' group tries leave them out, so a group +goes on to the members left from the next request on, midway through a +conversation too. Where nothing is left, `keyModelRefusal` (`keyGroupRefusal` +with a media group's own members, `spentAmong` on the chat route) answers 429 with the limit's message and +`Retry-After`, not 403, and no `X-Magpie-Limit-Reset`, so a remote magpie +rests the model only; `keyLimited`'s own scoped refusal skips that header +too. The model lists (`keyListHolds`) don't change, `budget.Binding` +prefers a whole-key limit, and a remote's key card leaves such limits out +(`keyLimitCard`). Tests: `TestKeyModelLimit*` in `key_model_limit_test.go`, +`TestScoped*` in `internal/budget`. A local magpie asks it with each of its remote-magpie keys for that key's card on its Usage page (#1547), a window per limit's cap. diff --git a/internal/access/access.go b/internal/access/access.go index 419b94fcc..50d0e5a7e 100644 --- a/internal/access/access.go +++ b/internal/access/access.go @@ -204,7 +204,35 @@ type Identity struct { // Group is the routing group, by name, whose own accounts hold the // request as well (HeldToGroup); "" when none does. Group string + // Spent are the key's limits of some models (Limit.Models) with + // nothing left, as the gateway found them for this request: their + // models are left out of its candidates, a routing group's members + // too, and a request naming one is refused with Why. + Spent []SpentScope } + +// SpentScope is a limit of some models with nothing left until Reset. +type SpentScope struct { + // Models are the limit's models, with the other ids each goes by + Models []string + Reset time.Time + // Why is what a request for one of them is told + Why string +} + +// SpentOn is the spent limit that counts model ("/"), +// the one that resets last when several do. +func (who Identity) SpentOn(model string) (SpentScope, bool) { + var out SpentScope + found := false + for _, s := range who.Spent { + if ModelAllowed(s.Models, model) && (!found || s.Reset.After(out.Reset)) { + out, found = s, true + } + } + return out, found +} + type contextKey struct{} func WithIdentity(ctx context.Context, who Identity) context.Context { @@ -474,7 +502,10 @@ func Update(action string, in Change) (string, error) { } for a := range ls { for b := a + 1; b < len(ls); b++ { - if ls[a].sameWindow(&ls[b]) { + if ls[a].sameLimit(&ls[b]) { + if ls[a].Scoped() { + return "", fmt.Errorf("This key already has a limit %s for %s: change that one instead", ls[a].Per(), strings.Join(ls[a].Models, ", ")) + } return "", fmt.Errorf("This key already has a limit %s: change that one instead", ls[a].Per()) } } diff --git a/internal/access/limit.go b/internal/access/limit.go index 95ae12e44..ce6cef56c 100644 --- a/internal/access/limit.go +++ b/internal/access/limit.go @@ -5,6 +5,7 @@ import ( "fmt" "math" "slices" + "strings" "time" ) @@ -33,11 +34,39 @@ type Limit struct { // the same window doesn't count. Zero for a calendar limit never // reset, as every limit from before #1509 is. Since time.Time `json:"since,omitzero"` + // Models scope the limit to some models (zola_xynb on X: a cap for + // one model or one provider under one key): "/" or + // "/*", as a key's models are written. The limit counts + // only the key's calls a model of them answered, and holds only + // requests that would go to one: a routing group goes on to its + // members outside it. None, the whole key, as every limit from + // before this. + Models []string `json:"models,omitempty"` +} + +// Scoped: l counts only some models' calls (Limit.Models). +func (l *Limit) Scoped() bool { return l != nil && len(l.Models) > 0 } + +// Scope is l's models as one string, the same for the same models in any +// order or letter case; "" for the whole key. +func (l *Limit) Scope() string { + if !l.Scoped() { + return "" + } + ms := make([]string, len(l.Models)) + for i, m := range l.Models { + ms[i] = strings.ToLower(m) + } + slices.Sort(ms) + return strings.Join(ms, ",") } // MaxLimits is how many limits one key can have (#2227). const MaxLimits = 5 +// MaxLimitModels is how many models one limit can count. +const MaxLimitModels = 50 + // Limits are k's limits, its Limit first; none for a key with no limit. // Each holds the key on its own: a request passes only while all of them // have something left. @@ -88,6 +117,13 @@ func (l *Limit) sameWindow(o *Limit) bool { return l.Period == o.Period && l.Days == o.Days && l.Hours == o.Hours } +// sameLimit: l and o count the same calls in the same window, so a key +// with both would have one limit twice. Limits of other models in one +// window are each their own. +func (l *Limit) sameLimit(o *Limit) bool { + return l.sameWindow(o) && l.Scope() == o.Scope() +} + // Periods are the windows a limit can be set for. var Periods = []string{"day", "week", "month", "days", "hours"} @@ -145,6 +181,19 @@ func (l *Limit) Valid() (*Limit, error) { return nil, errors.New("A limit's period is day, week, month, every N days or every N hours") } v.Cost = math.Round(v.Cost*1e4) / 1e4 + ms, err := CleanModels(v.Models) + if err != nil { + return nil, err + } + for _, m := range ms { + if strings.HasPrefix(strings.ToLower(m), "group/") || strings.HasPrefix(strings.ToLower(m), "auto/") { + return nil, errors.New("A limit counts models or providers, like openai/* or openai/gpt-5, not a routing group: " + m) + } + } + if len(ms) > MaxLimitModels { + return nil, fmt.Errorf("A limit can count at most %d models", MaxLimitModels) + } + v.Models = ms return &v, nil } @@ -160,6 +209,12 @@ func (l *Limit) Per() string { return l.Period } +// Counts says a call model answered ("/") counts toward +// l: every call for a limit of the whole key. +func (l *Limit) Counts(model string) bool { + return !l.Scoped() || ModelAllowed(l.Models, model) +} + // sinceOf is the Since a limit set as next keeps, with prev the key's // limit before: its own while the period and cycle stay the same (a new // cap doesn't restart the window), else a new cycle from now for "days" diff --git a/internal/access/limit_models_test.go b/internal/access/limit_models_test.go new file mode 100644 index 000000000..af877cb39 --- /dev/null +++ b/internal/access/limit_models_test.go @@ -0,0 +1,62 @@ +package access + +import ( + "strings" + "testing" + "time" +) + +// A limit of some models (zola_xynb on X) keeps its models cleaned, never +// a routing group, and sits beside a limit of the whole key in the same +// window: two limits in one window are the same only for the same models. +func TestScopedLimitValidAndBeside(t *testing.T) { + l, err := (&Limit{Period: "month", Cost: 20, Models: []string{" openai/* ", "OpenAI/*", "anthropic/claude-opus"}}).Valid() + if err != nil || len(l.Models) != 2 || l.Models[0] != "openai/*" { + t.Fatalf("cleaned as %+v %v", l, err) + } + for _, bad := range []string{"group/coding", "Auto/x", "gpt-5"} { + if _, err := (&Limit{Period: "day", Tokens: 5, Models: []string{bad}}).Valid(); err == nil { + t.Errorf("%s was taken", bad) + } + } + many := make([]string, MaxLimitModels+1) + for i := range many { + many[i] = "p/m" + strings.Repeat("x", i) + } + if _, err := (&Limit{Period: "day", Tokens: 5, Models: many}).Valid(); err == nil { + t.Error("more models than a limit counts were taken") + } + if (&Limit{Models: []string{"b/*", "A/x"}}).Scope() != (&Limit{Models: []string{"a/X", "b/*"}}).Scope() { + t.Error("the same models in another order or case are another scope") + } + + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + Now = func() time.Time { return time.Date(2026, 11, 6, 8, 0, 0, 0, time.UTC) } + t.Cleanup(func() { Now = time.Now }) + if _, err := Update("add-key", Change{Name: "Shared"}); err != nil { + t.Fatal(err) + } + keys, _ := List() + id := keys[0].ID + at := func(n int, l *Limit) error { + _, err := Update("limit-key", Change{Key: id, Limit: l, Index: &n}) + return err + } + if err := at(0, &Limit{Period: "month", Cost: 100}); err != nil { + t.Fatal(err) + } + if err := at(1, &Limit{Period: "month", Cost: 20, Models: []string{"openai/*"}}); err != nil { + t.Fatal("a month of OpenAI beside a month of the key:", err) + } + if err := at(2, &Limit{Period: "month", Cost: 5, Models: []string{"OpenAI/*"}}); err == nil || !strings.Contains(err.Error(), "openai/*") { + t.Fatalf("a second month of OpenAI: %v", err) + } + if err := at(2, &Limit{Period: "month", Cost: 5}); err == nil { + t.Fatal("a second month of the whole key was taken") + } + keys, _ = List() + ls := keys[0].Limits() + if len(ls) != 2 || ls[0].Scoped() || !ls[1].Scoped() || ls[1].Models[0] != "openai/*" { + t.Fatalf("kept as %+v", ls) + } +} diff --git a/internal/budget/budget.go b/internal/budget/budget.go index 96b980460..f741a953a 100644 --- a/internal/budget/budget.go +++ b/internal/budget/budget.go @@ -25,6 +25,15 @@ // hours and a week, as a subscription's): a request is let in only // while every one has something left, and its reservation is held // in each window. +// - A limit can count only some models' calls (access.Limit.Models, +// zola_xynb on X): "/" or "/*", matched +// against the provider and model that answered each call. A request +// that names such a model is refused here once that limit is spent, +// and holds its reservation there; a routing group's, or a fallback's, +// goes on to the models outside it, as the gateway leaves a spent +// limit's models out of every route's candidates (Spent). A group's +// request holds no reservation in a model's limit, so parallel +// requests through groups can go over it by about one call each. // - Only requests that came with a gateway key are limited: from // another computer one is required; on this one a request without one // (or with a token that is no key) isn't limited. @@ -47,7 +56,11 @@ import ( // sums is what a key's calls came to in a window. type sums struct { - start time.Time + start time.Time + // scope is the limit's access.Limit.Scope, "" for the whole key, and + // models its patterns with each model's other ids (scopeModels) + scope string + models []string calls int input, output, cacheRead, cacheWrite int64 cost float64 @@ -66,6 +79,38 @@ func (s *sums) add(r usage.Record, cost float64, priced bool) { } } +// counts says r is a call of the models s counts: every call, for the +// whole key. +func (s *sums) counts(r usage.Record) bool { + return s.scope == "" || access.ModelAllowed(s.models, r.Provider+"/"+r.Model) +} + +// scopeModels is the patterns l counts by: its own, and for a model the +// user lists by an id of their own (provider.SetModelID) the provider's +// id of it and back, as calls are recorded by the provider's. +func scopeModels(l *access.Limit) []string { + out := slices.Clone(l.Models) + for _, m := range l.Models { + if strings.Contains(m, "*") { + continue + } + pid, model, ok := strings.Cut(m, "/") + if !ok { + continue + } + p, err := provider.Find(pid) + if err != nil { + continue + } + for _, o := range []string{p.OwnModelID(model), p.ListedModelID(model)} { + if o != model { + out = append(out, pid+"/"+o) + } + } + } + return out +} + func (s *sums) tokens(l *access.Limit) int64 { n := s.input + s.output + s.cacheWrite if l != nil && l.CacheReads { @@ -84,7 +129,8 @@ type held struct { // finishes after the next one has started. type window struct { key string - start int64 // the window's start as Unix seconds + start int64 // the window's start as Unix seconds + scope string // the limit's models (access.Limit.Scope), "" for the whole key } var state = struct { @@ -103,28 +149,30 @@ func counts(r usage.Record) bool { return !r.IsRejected() && !r.IsReported() && !r.IsProbe() && r.Computer == "" } -// sumsFor is keyID's sums for each window starting at starts, read from -// usage.jsonl the first time; those of windows no limit counts in now -// are let go. A window two limits share (a day and a week on a Monday, -// a day and a month on the 1st) is kept once, as Append adds a call to -// each one kept (#2942). Called with state held. -func sumsFor(keyID string, starts []time.Time) []*sums { +// sumsFor is keyID's sums for each of its limits ls, in the window each +// starts at starts, read from usage.jsonl the first time; those of +// windows no limit counts in now are let go. A window two limits of the +// same models share (a day and a week on a Monday, a day and a month on +// the 1st) is kept once, as Append adds a call to each one kept (#2942). +// Called with state held. +func sumsFor(keyID string, ls []*access.Limit, starts []time.Time) []*sums { k := slot(keyID) kept := state.sums[k] out := make([]*sums, len(starts)) var next []*sums - at := func(ss []*sums, start time.Time) int { - return slices.IndexFunc(ss, func(s *sums) bool { return s.start.Equal(start) }) + at := func(ss []*sums, start time.Time, scope string) int { + return slices.IndexFunc(ss, func(s *sums) bool { return s.start.Equal(start) && s.scope == scope }) } for i, start := range starts { - if j := at(next, start); j >= 0 { + scope := ls[i].Scope() + if j := at(next, start, scope); j >= 0 { out[i] = next[j] continue } - if j := at(kept, start); j >= 0 { + if j := at(kept, start, scope); j >= 0 { out[i] = kept[j] } else { - out[i] = read(keyID, start) + out[i] = read(keyID, start, ls[i]) } next = append(next, out[i]) } @@ -132,12 +180,16 @@ func sumsFor(keyID string, starts []time.Time) []*sums { return out } -func read(keyID string, start time.Time) *sums { - s := &sums{start: start} +// read is what keyID's calls of l's models came to from start. +func read(keyID string, start time.Time, l *access.Limit) *sums { + s := &sums{start: start, scope: l.Scope()} + if l.Scoped() { + s.models = scopeModels(l) + } cost := usage.NewCoster() usage.Visit(start, func(r usage.Record) { // a key issued under keyID spends from its limits too - if (r.CallerKeyID == keyID || r.CallerIssuerID == keyID) && counts(r) && !r.Time.Before(start) { + if (r.CallerKeyID == keyID || r.CallerIssuerID == keyID) && counts(r) && !r.Time.Before(start) && s.counts(r) { c, ok := cost(r) s.add(r, c, ok) } @@ -182,7 +234,7 @@ func Append(rec usage.Record) { } c, ok := cost(rec) for _, s := range kept { - if !rec.Time.Before(s.start) { + if !rec.Time.Before(s.start) && s.counts(rec) { s.add(rec, c, ok) } } @@ -208,6 +260,8 @@ type Status struct { TokenLimit int64 `json:"tokenLimit,omitempty"` CostLimit float64 `json:"costLimit,omitempty"` CacheReads bool `json:"cacheReads,omitempty"` + // Models are the models the limit counts, none for the whole key + Models []string `json:"models,omitempty"` // TokensLeft and CostLeft are what is left of each cap, 0 at most TokensLeft int64 `json:"tokensLeft"` CostLeft float64 `json:"costLeft"` @@ -217,7 +271,7 @@ type Status struct { func status(keyID string, l *access.Limit, s *sums, h *held, reset time.Time) Status { st := Status{Period: l.Period, Days: l.Days, Hours: l.Hours, Start: s.start, Reset: reset, Calls: s.calls, Tokens: s.tokens(l), Cost: s.cost, Unpriced: s.unpriced, - TokenLimit: l.Tokens, CostLimit: l.Cost, CacheReads: l.CacheReads} + TokenLimit: l.Tokens, CostLimit: l.Cost, CacheReads: l.CacheReads, Models: l.Models} if h != nil { st.InFlight, st.Reserved, st.ReservedCost = h.n, h.tokens, h.cost } @@ -249,16 +303,17 @@ func Of(k access.Key, now time.Time) *Status { func All(k access.Key, now time.Time) []Status { ls := k.Limits() var out []Status - read1 := map[int64]*sums{} + read1 := map[window]*sums{} for _, l := range ls { start, reset := l.Window(now) - s := read1[start.Unix()] + w := window{slot(k.ID), start.Unix(), l.Scope()} + s := read1[w] if s == nil { - s = read(k.ID, start) - read1[start.Unix()] = s + s = read(k.ID, start, l) + read1[w] = s } state.Lock() - h := state.held[window{slot(k.ID), start.Unix()}] + h := state.held[w] out = append(out, status(k.ID, l, s, h, reset)) state.Unlock() } @@ -267,12 +322,17 @@ func All(k access.Key, now time.Time) []Status { // Binding is the one of a key's statuses that holds it most: of those // spent, the one that resets last, as the key is refused until then; -// else the one with the most of a cap used. Nil for none. +// else the one with the most of a cap used. Nil for none. A limit of +// some models holds the key only when it has no limit of the whole key: +// one spent leaves the key's other models served, and a magpie using this +// one as a remote reads this one as the key's. func Binding(all []Status) *Status { + whole := slices.ContainsFunc(all, func(st Status) bool { return len(st.Models) == 0 }) var b *Status for i := range all { st := &all[i] switch { + case whole && len(st.Models) > 0: case b == nil: b = st case st.Spent != b.Spent: @@ -324,8 +384,12 @@ func (r *Refusal) Error() string { if !r.Spent { what += fmt.Sprintf(", with %d requests in flight holding the rest", r.InFlight) } - return fmt.Sprintf("magpie gateway key %q has used %s for this %s; it resets at %s", - r.Key, what, (&access.Limit{Period: r.Period, Days: r.Days, Hours: r.Hours}).Per(), r.Reset.Format("2006-01-02 15:04 MST")) + on := "" + if len(r.Models) > 0 { + on = " on " + strings.Join(r.Models, ", ") + } + return fmt.Sprintf("magpie gateway key %q has used %s%s for this %s; it resets at %s", + r.Key, what, on, (&access.Limit{Period: r.Period, Days: r.Days, Hours: r.Hours}).Per(), r.Reset.Format("2006-01-02 15:04 MST")) } // RetryAfter is how long until the window resets, in whole seconds. @@ -348,6 +412,8 @@ func (Limiter) Reserve(who access.Identity, body int64, model string, now time.T return release, nil } +func (Limiter) Spent(who access.Identity, now time.Time) []access.SpentScope { return Spent(who, now) } + // Reserve lets a request of who's in, holding a reservation for it until // the release it returns is called, or refuses it. body is the request's // size in bytes (-1 unknown) and model the model it named, for a cost cap @@ -371,23 +437,24 @@ func Reserve(who access.Identity, body int64, model string, now time.Time) (rele } func reserve(who access.Identity, body int64, model string, now time.Time) (release func(), refused *Refusal) { - ls := who.Limits() - if who.KeyID == "" || len(ls) == 0 { + // a limit of some models holds a request only when it names one of + // them; one through a routing group is held by the gateway leaving + // the spent ones' models out of its candidates (Spent) + served := servedAs(model) + if who.KeyID == "" || len(who.Limits()) == 0 { return func() {}, nil } - starts := make([]time.Time, len(ls)) - resets := make([]time.Time, len(ls)) - for i, l := range ls { - starts[i], resets[i] = l.Window(now) - } state.Lock() defer state.Unlock() - ss := sumsFor(who.KeyID, starts) - heldAt := func(start time.Time) *held { return state.held[window{slot(who.KeyID), start.Unix()}] } + ls, starts, resets, ss := windowsOf(who, now, func(l *access.Limit) bool { return !l.Scoped() || scopeHas(l, served) }) + if len(ls) == 0 { + return func() {}, nil + } + heldAt := func(i int) *held { return state.held[window{slot(who.KeyID), starts[i].Unix(), ls[i].Scope()}] } // every limit is asked: of those with nothing left, the one that // resets last is the one the client is told, as it is refused until then for i, l := range ls { - s, h := ss[i], heldAt(starts[i]) + s, h := ss[i], heldAt(i) var ht int64 var hc float64 if h != nil { @@ -412,7 +479,7 @@ func reserve(who access.Identity, body int64, model string, now time.Time) (rele } var holds []hold for i, l := range ls { - k := window{slot(who.KeyID), starts[i].Unix()} + k := window{slot(who.KeyID), starts[i].Unix(), l.Scope()} j := slices.IndexFunc(holds, func(x hold) bool { return x.k == k }) if j < 0 { s := ss[i] @@ -461,6 +528,102 @@ func reserve(who access.Identity, body int64, model string, now time.Time) (rele }, nil } +// servedAs is the ids a request for model would be answered by, as +// "/" with the provider's id of it and the user's own: +// none for a routing group, an auto/ model or a name magpie doesn't serve, +// whose models routing decides. +func servedAs(model string) []string { + if model == "" || provider.IsGroupRef(model) { + return nil + } + if _, ok := provider.GroupFor(model); ok { + return nil + } + if _, ok := provider.AutoStandIn(model); ok { + return nil + } + p, m, ok := provider.Resolve(model) + if !ok { + return nil + } + out := []string{p.ID + "/" + m} + for _, o := range []string{p.OwnModelID(m), p.ListedModelID(m)} { + if o != m { + out = append(out, p.ID+"/"+o) + } + } + return out +} + +// scopeHas says one of ids is among l's models. +func scopeHas(l *access.Limit, ids []string) bool { + for _, id := range ids { + if access.ModelAllowed(l.Models, id) { + return true + } + } + return false +} + +// Spent is who's limits of some models that have nothing left now, its +// own key's and the one it was issued under's: the gateway leaves their +// models out of every route's candidates for the request (access.Identity +// .Spent), each said with the refusal a request naming one is told. +func Spent(who access.Identity, now time.Time) []access.SpentScope { + out := spentOf(who, now) + if who.Issuer != nil { + out = append(out, spentOf(*who.Issuer, now)...) + } + return out +} + +func spentOf(who access.Identity, now time.Time) []access.SpentScope { + if who.KeyID == "" || !slices.ContainsFunc(who.Limits(), (*access.Limit).Scoped) { + return nil + } + state.Lock() + defer state.Unlock() + ls, starts, resets, ss := windowsOf(who, now, (*access.Limit).Scoped) + var out []access.SpentScope + for i, l := range ls { + s, h := ss[i], state.held[window{slot(who.KeyID), starts[i].Unix(), l.Scope()}] + var ht int64 + var hc float64 + if h != nil { + ht, hc = h.tokens, h.cost + } + if (l.Tokens > 0 && s.tokens(l)+ht >= l.Tokens) || (l.Cost > 0 && s.cost+hc >= l.Cost) { + r := &Refusal{Status: status(who.KeyID, l, s, h, resets[i]), Key: who.KeyName} + out = append(out, access.SpentScope{Models: s.models, Reset: resets[i], Why: r.Error()}) + } + } + return out +} + +// windowsOf is who's limits that keep holds, each with its window's start +// and reset and its sums. The sums of every limit are asked for, the ones +// left out too: sumsFor lets go of a window no limit asked for counts in, +// and a request of one model would read another's limit's again from the +// ledger on the next. Called with state held. +func windowsOf(who access.Identity, now time.Time, keep func(*access.Limit) bool) (ls []*access.Limit, starts, resets []time.Time, ss []*sums) { + all := who.Limits() + allStarts := make([]time.Time, len(all)) + allResets := make([]time.Time, len(all)) + for i, l := range all { + allStarts[i], allResets[i] = l.Window(now) + } + allSums := sumsFor(who.KeyID, all, allStarts) + for i, l := range all { + if keep(l) { + ls = append(ls, l) + starts = append(starts, allStarts[i]) + resets = append(resets, allResets[i]) + ss = append(ss, allSums[i]) + } + } + return ls, starts, resets, ss +} + // priceOf is the input price per token of model when it names its // provider ("provider/model"). func priceOf(model string) (float64, bool) { diff --git a/internal/budget/scoped_test.go b/internal/budget/scoped_test.go new file mode 100644 index 000000000..3449a3af3 --- /dev/null +++ b/internal/budget/scoped_test.go @@ -0,0 +1,145 @@ +package budget + +import ( + "path/filepath" + "strings" + "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/usage" +) + +// scopedKey is a key in a sandbox HOME with limits ls, and the provider +// "plan" serving m1 and m2. +func scopedKey(t *testing.T, ls ...access.Limit) access.Identity { + t.Helper() + 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) + Forget() + t.Cleanup(Forget) + if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "k", Chat: "https://plan.example/v1", Models: []string{"m1", "m2"}}); err != nil { + t.Fatal(err) + } + if _, err := access.Update("add-key", access.Change{Name: "Shared"}); err != nil { + t.Fatal(err) + } + ks, _ := access.List() + for i := range ls { + n := i + if _, err := access.Update("limit-key", access.Change{Key: ks[0].ID, Limit: &ls[i], Index: &n}); err != nil { + t.Fatal(err) + } + } + ks, _ = access.List() + k := ks[0] + return access.Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More} +} + +// A limit of some models counts only their calls, from the ledger after a +// restart too, and holds only a request for one of them: the key's other +// models are still served, and Spent names the spent ones for a group. +func TestScopedLimitCountsItsModels(t *testing.T) { + who := scopedKey(t, access.Limit{Period: "day", Tokens: 1000, Models: []string{"plan/m1"}}) + now := time.Now() + call := func(model string, n int) { + t.Helper() + Append(usage.Record{Time: now, Provider: "plan", Model: model, Input: n, Status: 200, CallerKeyID: who.KeyID}) + } + refused := func(model string) *Refusal { + t.Helper() + release, r := Reserve(who, -1, model, now) + if release != nil { + release() + } + return r + } + // the key's limit is read once before the calls, as the gateway does + if r := refused("plan/m1"); r != nil { + t.Fatal(r) + } + call("m2", 5000) + if r := refused("plan/m1"); r != nil { + t.Fatal("another model's call spent it:", r) + } + call("m1", 1200) + for _, restart := range []bool{false, true} { + if restart { + Forget() + } + r := refused("plan/m1") + if r == nil || !strings.Contains(r.Error(), "plan/m1") { + t.Fatalf("restart %v: plan/m1 refused as %v", restart, r) + } + if r := refused("plan/m2"); r != nil { + t.Fatalf("restart %v: plan/m2 refused: %v", restart, r) + } + sp := Spent(who, now) + if len(sp) != 1 || !access.ModelAllowed(sp[0].Models, "plan/m1") || access.ModelAllowed(sp[0].Models, "plan/m2") || sp[0].Reset.IsZero() { + t.Fatalf("restart %v: spent %+v", restart, sp) + } + all := All(access.Key{ID: who.KeyID, Limit: who.Limit, More: who.More}, now) + if len(all) != 1 || all[0].Tokens != 1200 || !all[0].Spent || all[0].Models[0] != "plan/m1" { + t.Fatalf("restart %v: status %+v", restart, all) + } + } + // a routing group's request isn't held by it: the gateway leaves + // plan/m1 out of the group's members + if r := refused("group/any"); r != nil { + t.Fatal("a group's request was refused:", r) + } +} + +// A key with a limit of the whole key and one of a provider: the whole +// key's counts every call, the provider's only its own, and a request of +// another model doesn't let go of the provider's sums, which would read +// the ledger again on every request. +func TestScopedBesideTheWholeKey(t *testing.T) { + who := scopedKey(t, + access.Limit{Period: "day", Tokens: 10_000}, + access.Limit{Period: "day", Tokens: 1000, Models: []string{"plan/m1"}}) + now := time.Now() + if _, r := Reserve(who, -1, "plan/m2", now); r != nil { + t.Fatal(r) + } + Append(usage.Record{Time: now, Provider: "plan", Model: "m1", Input: 800, Status: 200, CallerKeyID: who.KeyID}) + Append(usage.Record{Time: now, Provider: "plan", Model: "m2", Input: 800, Status: 200, CallerKeyID: who.KeyID}) + if sp := Spent(who, now); len(sp) != 0 { + t.Fatal("spent before its cap:", sp) + } + release, r := Reserve(who, -1, "plan/m2", now) + if r != nil { + t.Fatal(r) + } + release() + state.Lock() + kept := len(state.sums[slot(who.KeyID)]) + state.Unlock() + if kept != 2 { + t.Fatalf("%d windows kept after another model's request, want 2", kept) + } + all := All(access.Key{ID: who.KeyID, Limit: who.Limit, More: who.More}, now) + if len(all) != 2 || all[0].Tokens != 1600 || all[1].Tokens != 800 { + t.Fatalf("status %+v", all) + } + // the binding one is the whole key's, though the provider's is fuller + if b := Binding(all); b == nil || len(b.Models) != 0 { + t.Fatalf("binding %+v", b) + } + Append(usage.Record{Time: now, Provider: "plan", Model: "m1", Input: 300, Status: 200, CallerKeyID: who.KeyID}) + if _, r := Reserve(who, -1, "plan/m1", now); r == nil { + t.Fatal("plan/m1 past its cap was let in") + } + if release, r := Reserve(who, -1, "plan/m2", now); r != nil { + t.Fatal("plan/m2 refused for plan/m1's cap:", r) + } else { + release() + } +} diff --git a/internal/cli/gateway_keys_cli.go b/internal/cli/gateway_keys_cli.go index 69dd066b3..b3afb747c 100644 --- a/internal/cli/gateway_keys_cli.go +++ b/internal/cli/gateway_keys_cli.go @@ -92,7 +92,7 @@ func gatewayKeysTo(out io.Writer, args []string) error { args = args[:2] } if (action == "list" && len(args) != 1) || (action != "list" && len(args) != 2) { - return fmt.Errorf("usage: magpie gateway-key list | add [--key | --key -] [--read-only] | rotate [--key | --key -] | remove | limit [list | off | reset [] | remove | [add] day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads]] | models [all | /|/* ...] | accounts [all | /|/ ...] | quotas [on | off] | access [read-only | full] | move | issue --ttl [--name ] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from ] | issuer [on | off] | oidc [list | add --key --repo owner/name … | remove ]") + return fmt.Errorf("usage: magpie gateway-key list | add [--key | --key -] [--read-only] | rotate [--key | --key -] | remove | limit [list | off | reset [] | remove | [add] day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads] [--model /|/* ...]] | models [all | /|/* ...] | accounts [all | /|/ ...] | quotas [on | off] | access [read-only | full] | move | issue --ttl [--name ] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from ] | issuer [on | off] | oidc [list | add --key --repo owner/name … | remove ]") } switch action { case "list", "add", "rotate", "remove": @@ -173,12 +173,17 @@ func gatewayKeysTo(out io.Writer, args []string) error { // magpie gateway-key limit off no limit // magpie gateway-key limit day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads] // its only limit, or the one of several with that window -// magpie gateway-key limit add [--tokens N] [--cost USD] [--cache-reads] +// magpie gateway-key limit add [--tokens N] [--cost USD] [--cache-reads] [--model openai/*] // one more limit; a request passes only while every one has something left // magpie gateway-key limit remove take off the nth limit // magpie gateway-key limit reset [] count from 0 again, every limit or the nth; a new N-day or N-hour cycle from now (#1509) +// +// --model (again, or a comma list) makes a limit count only those models' +// calls, "/" or "/*" (zola_xynb on X): a cap for +// one model or provider under one key, the key's other models served once +// it is spent. func gatewayKeyLimit(out io.Writer, args []string) error { - usage := fmt.Errorf("usage: magpie gateway-key limit [off | reset [] | remove | [add] day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads]]") + usage := fmt.Errorf("usage: magpie gateway-key limit [off | reset [] | remove | [add] day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads] [--model /|/* ...]]") if len(args) == 0 { return usage } @@ -264,10 +269,10 @@ func gatewayKeyLimit(out io.Writer, args []string) error { if len(have) > 1 { v, _ := lim.Valid() n := slices.IndexFunc(have, func(l *access.Limit) bool { - return v != nil && l.Period == v.Period && l.Days == v.Days && l.Hours == v.Hours + return v != nil && l.Period == v.Period && l.Days == v.Days && l.Hours == v.Hours && l.Scope() == v.Scope() }) if n < 0 { - return fmt.Errorf("%s has %d limits and none %s: add one with `magpie gateway-key limit %s add %s ...`, or take one off with `remove `", keys[i].Name, len(have), perPhrase(v), id, args[1]) + return fmt.Errorf("%s has %d limits and none %s%s: add one with `magpie gateway-key limit %s add %s ...`, or take one off with `remove `", keys[i].Name, len(have), perPhrase(v), onModels(v), id, args[1]) } in.Index = &n } @@ -297,6 +302,9 @@ func gatewayKeyLimit(out io.Writer, args []string) error { fmt.Fprintf(w, "\t\n") fmt.Fprintf(w, "Limit %d\t%s, all must have something left\n", n+1, perPhrase(&access.Limit{Period: st.Period, Days: st.Days, Hours: st.Hours})) } + if len(st.Models) > 0 { + fmt.Fprintf(w, "Models\t%s: only their calls count, and only requests for them are refused once it is spent\n", strings.Join(st.Models, ", ")) + } fmt.Fprintf(w, "Window\tthis %s, %s – %s (local time)\n", (&access.Limit{Period: st.Period, Days: st.Days, Hours: st.Hours}).Per(), st.Start.Format("2006-01-02 15:04"), st.Reset.Format("2006-01-02 15:04")) if st.TokenLimit > 0 { counted := "input, output and cache writes" @@ -319,6 +327,9 @@ func gatewayKeyLimit(out io.Writer, args []string) error { state := "open" if st.Spent { state = "spent: requests are refused until " + st.Reset.Format("2006-01-02 15:04") + if len(st.Models) > 0 { + state = "spent: requests for these models are refused until " + st.Reset.Format("2006-01-02 15:04") + } } fmt.Fprintf(w, "State\t%s\n", state) } @@ -340,6 +351,15 @@ func perPhrase(l *access.Limit) string { return "per " + l.Period } +// onModels is " on " for a limit of some models, "" for one of the +// whole key. +func onModels(l *access.Limit) string { + if !l.Scoped() { + return "" + } + return " on " + strings.Join(l.Models, ", ") +} + // parseKeyLimit reads a limit as typed: its window, then --tokens, // --cost and --cache-reads. func parseKeyLimit(window string, rest []string, usage error) (*access.Limit, error) { @@ -395,6 +415,16 @@ func parseKeyLimit(window string, rest []string, usage error) (*access.Limit, er } case "--cache-reads": lim.CacheReads = true + case "--model", "--models": + v, err := next() + if err != nil { + return nil, err + } + for _, m := range strings.Split(v, ",") { + if m = strings.TrimSpace(m); m != "" { + lim.Models = append(lim.Models, m) + } + } default: return nil, usage } @@ -461,7 +491,7 @@ func limitWords(k access.Key, now time.Time) string { if st.CostLimit > 0 { parts = append(parts, fmt.Sprintf("$%.2f/$%.2f", st.Cost, st.CostLimit)) } - s := strings.Join(parts, " ") + " " + perPhrase(&access.Limit{Period: st.Period, Days: st.Days, Hours: st.Hours}) + s := strings.Join(parts, " ") + " " + perPhrase(&access.Limit{Period: st.Period, Days: st.Days, Hours: st.Hours}) + onModels(&access.Limit{Models: st.Models}) if st.Spent { s += " (spent until " + st.Reset.Format("01-02 15:04") + ")" } diff --git a/internal/cli/gateway_keys_cli_test.go b/internal/cli/gateway_keys_cli_test.go index 907d6cfac..8c2439207 100644 --- a/internal/cli/gateway_keys_cli_test.go +++ b/internal/cli/gateway_keys_cli_test.go @@ -488,3 +488,63 @@ func TestGatewayKeyCLIMove(t *testing.T) { t.Fatal("no place") } } + +// --model makes a limit count only some models (zola_xynb on X), beside +// one of the whole key in the same window; the plain form changes the one +// of those models, and the list says which models each counts. +func TestGatewayKeyScopedLimitCLI(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", os.Getenv("HOME")) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + call := func(args ...string) (string, error) { + var out bytes.Buffer + err := gatewayKeysTo(&out, append([]string{"gateway-key"}, args...)) + return out.String(), err + } + if _, err := call("add", "Team"); err != nil { + t.Fatal(err) + } + keys, _ := access.List() + id := keys[0].ID + limits := func() []*access.Limit { + keys, _ := access.List() + return keys[0].Limits() + } + if _, err := call("limit", id, "month", "--cost", "100"); err != nil { + t.Fatal(err) + } + got, err := call("limit", id, "add", "month", "--cost", "20", "--model", "openai/*") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(got, "openai/*") { + t.Fatalf("the list says %q", got) + } + if _, err := call("limit", id, "add", "month", "--cost", "5", "--models", "anthropic/claude-opus,zai/*", "--model", "kimi/k2"); err != nil { + t.Fatal(err) + } + ls := limits() + if len(ls) != 3 || ls[0].Scoped() || strings.Join(ls[1].Models, " ") != "openai/*" || strings.Join(ls[2].Models, " ") != "anthropic/claude-opus zai/* kimi/k2" { + t.Fatalf("kept as %+v %+v %+v", ls[0], ls[1], ls[2]) + } + // the plain form changes the month of OpenAI, not the key's + if _, err := call("limit", id, "month", "--cost", "30", "--model", "openai/*"); err != nil { + t.Fatal(err) + } + if ls := limits(); ls[0].Cost != 100 || ls[1].Cost != 30 { + t.Fatalf("after changing OpenAI's month: %+v %+v", ls[0], ls[1]) + } + for _, args := range [][]string{ + {"limit", id, "add", "month", "--cost", "5", "--model", "openai/*"}, // the same window and models again + {"limit", id, "add", "day", "--cost", "5", "--model", "group/coding"}, + {"limit", id, "add", "day", "--cost", "5", "--model"}, + {"limit", id, "add", "day", "--cost", "5", "--model", "gpt-5"}, + } { + if _, err := call(args...); err == nil { + t.Fatal("accepted", args) + } + } + if ls := limits(); len(ls) != 3 { + t.Fatalf("a refused command left %d limits", len(ls)) + } +} diff --git a/internal/cli/main.go b/internal/cli/main.go index 134e89ef0..8ddf9f8b6 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -132,7 +132,7 @@ const usage = `magpie — one place to pick every agent's model magpie goroutines [] every goroutine of the running magpie, its stack and how long it waited, for a report of it stuck at something magpie log [--path] [-n N] [-f] where magpie's logs are, to send with a report: the app's (app.log), the service's; -n prints the app log's last N lines, -f follows it magpie gateway-key list|add [--read-only]|rotate [--key -]|remove manage the keys clients use to call a shared gateway - magpie gateway-key limit [list|off|reset [n]|remove |[add] day|week|month|d|h --tokens N --cost USD --cache-reads] a key's own limits, and what it used + magpie gateway-key limit [list|off|reset [n]|remove |[add] day|week|month|d|h --tokens N --cost USD --cache-reads --model openai/*] a key's own limits, and what it used; --model counts only those models magpie gateway-key models [all|/|/* ...] the models a key may use, every one unless it names some magpie gateway-key quotas [on|off] whether a key held to a budget, models or accounts is told the quotas of what it may use magpie gateway-key access [read-only|full] read-only: the key reads quotas and usage (GET /, /v1/magpie/quotas, /v1/magpie/usage) and uses no model, MCP server or write diff --git a/internal/gateway/decide.go b/internal/gateway/decide.go index 432dd06b1..7598763e6 100644 --- a/internal/gateway/decide.go +++ b/internal/gateway/decide.go @@ -611,7 +611,8 @@ func (s *Server) serveSystemOne(w http.ResponseWriter, r *http.Request) { // a gateway key held to some models (#882) is refused another; a // decision model is a model, and System One asks one directly if keyWho, held := keyHolds(r); held && !modelAllowed(keyWho, p, model) { - writeError(w, provider.Chat, http.StatusForbidden, keyModelError(keyWho, asked)) + st, msg := keyModelRefusal(w, keyWho, p.ID+"/"+model) + writeError(w, provider.Chat, st, msg) return } // its keys or accounts in its routing's order, each asked until one diff --git a/internal/gateway/decide_group.go b/internal/gateway/decide_group.go index bd965d881..865ec9e03 100644 --- a/internal/gateway/decide_group.go +++ b/internal/gateway/decide_group.go @@ -124,6 +124,13 @@ func (s *Server) serveDecisionGroup(w http.ResponseWriter, r *http.Request, body writeError(w, provider.Chat, http.StatusForbidden, keyAccountsError(who, asked)) return } + // every member left is one a spent limit of the key's counts + if len(cs) == 0 && keyHeld && len(members) == 0 { + if st, msg := keyGroupRefusal(w, keyWho, asked, ms); st == http.StatusTooManyRequests { + writeError(w, provider.Chat, st, msg) + return + } + } } cs = probeOne(cs) // of those resting, only the one back soonest (#1799) if len(cs) == 0 { diff --git a/internal/gateway/draw.go b/internal/gateway/draw.go index 4da515381..d083a3ae1 100644 --- a/internal/gateway/draw.go +++ b/internal/gateway/draw.go @@ -698,7 +698,7 @@ func (s *Server) images(edit bool) http.HandlerFunc { } keyWho, keyHeld := keyHolds(r) if keyHeld && named && (isGroup && !groupAllowed(keyWho, g, ms) || !isGroup && !modelAllowed(keyWho, p, model)) { - fail(403, keyModelError(keyWho, d.Model)) + fail(keyModelRefusal(w, keyWho, d.Model)) return } if msg, off := modelOff(p, model, d.Model); off { // disabled by the user (#1867) @@ -720,7 +720,7 @@ func (s *Server) images(edit bool) http.HandlerFunc { } t := s.drawingTries(g, ms, keeps, drawsModel) if len(t) == 0 && keeps != nil { - fail(403, keyModelError(keyWho, d.Model)) + fail(keyGroupRefusal(w, keyWho, d.Model, ms)) return } if len(t) > 0 { diff --git a/internal/gateway/embeddings.go b/internal/gateway/embeddings.go index 6a40fc7d9..7c9631b79 100644 --- a/internal/gateway/embeddings.go +++ b/internal/gateway/embeddings.go @@ -121,10 +121,11 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op if isGroup { r = heldByGroup(r, g) // held to the group's accounts, if it is } - if keyWho, held := keyHolds(r); held && (isGroup && !groupAllowed(keyWho, g, ms) || !isGroup && !modelAllowed(keyWho, p, model)) { - msg := keyModelError(keyWho, asked) - call.Status, call.Error = 403, msg - writeError(w, provider.Chat, 403, msg) + keyWho, keyHeld := keyHolds(r) + if keyHeld && (isGroup && !groupAllowed(keyWho, g, ms) || !isGroup && !modelAllowed(keyWho, p, model)) { + st, msg := keyModelRefusal(w, keyWho, asked) + call.Status, call.Error = st, msg + writeError(w, provider.Chat, st, msg) s.record(call) return } @@ -172,6 +173,19 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op } tries = cs } + // a group's members the key may not go to through it are left out + // (groupKeeps): those a spent limit of the key's counts + if keyHeld && isGroup { + keeps := groupKeeps(keyWho, g, ms) + tries = slices.DeleteFunc(tries, func(c candidate) bool { return !keeps[c.p.ID+"/"+c.model] }) + if len(tries) == 0 { + st, msg := keyGroupRefusal(w, keyWho, asked, ms) + call.Status, call.Error = st, msg + writeError(w, provider.Chat, st, msg) + s.record(call) + return + } + } // the accounts or keys the calling key may not use are left out of // the tries too (#905): a group's members through it no less if keyWho, held := accountHolds(r); held { diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index be57d55f1..52c47d3bf 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1431,7 +1431,7 @@ func cursorLocalModel(m map[string]any, e provider.Entry) { // with. A gateway key held to some models is told of those alone, as its // chat list is: models it names that an account it may use serves (#2579). func drawerObjects(r *http.Request) []map[string]any { - who, held := keyHolds(r) + who, held := keyListHolds(r) var out []map[string]any for _, p := range provider.All() { if !p.On() || p.DecideOnly() { @@ -1461,7 +1461,7 @@ func drawerObjects(r *http.Request) []map[string]any { // A gateway key held to some models or accounts is told of those alone, // as its chat list is (#2579). func videomakerObjects(r *http.Request) []map[string]any { - who, held := keyHolds(r) + who, held := keyListHolds(r) var out []map[string]any for _, p := range provider.All() { if !p.On() || p.DecideOnly() { @@ -2283,7 +2283,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro logged := func() { rec := usage.Record{RouteID: call.Route, Time: start, Agent: call.Agent, Via: call.Via, Provider: call.Provider, Model: call.Model, Requested: call.Model, Millis: call.Millis, Status: call.Status, Rejected: true, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind, Endpoint: endpointOf(r, from, "", provider.Provider{}, ""), Archive: call.archiveName()} - failedWith(&rec, call.Status, call.Error, "") + failedWith(&rec, call.Status, call.Error, call.Usage.ErrType) withBodies(&rec, &call) appendUsage(r, rec) } @@ -2508,7 +2508,6 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro _, accHeld := accountHolds(r) chose, _ := r.Context().Value(magpieChoseKey{}).(bool) if keyHeld && (isGroup && !groupAllowed(keyWho, g, ms) || !isGroup && !modelAllowed(keyWho, p, model)) { - call.Status, call.Error = 403, "model not allowed for the gateway key" // the model the key was checked against is named, not the one the // client sent: an agent that stands a request on another model // (Desktop's check on its list's first, a stand-in, a tier) was @@ -2519,7 +2518,12 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro if isGroup { checked = g.Ref() } - writeError(w, from, 403, keyModelError(keyWho, checked)) + st, msg := keyModelRefusal(w, keyWho, checked) + call.Status, call.Error = st, "model not allowed for the gateway key" + if st == http.StatusTooManyRequests { + call.Error, call.Usage.ErrType = msg, "gateway_key_limit" + } + writeError(w, from, st, msg) turnedAway() return } @@ -2810,7 +2814,17 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } else if isGroup { members = groupKeeps(keyWho, g, ms) } + spent, anySpent := spentAmong(keyWho, cands) cands, pl, accountHeld = allowedCandidates(who, cands, pl, members) + if len(cands) == 0 && anySpent { + // every model left is one a spent limit of the key's counts + // (zola_xynb): said as the limit, not as a model gone + st, msg := spentRefusal(w, spent) + call.Status, call.Error, call.Usage.ErrType = st, msg, "gateway_key_limit" + writeError(w, from, st, msg) + turnedAway() + return + } } // a conversation that stays strictly where it is goes on on its // account past the usage cap set on it, and is refused there, not diff --git a/internal/gateway/image_mcp_models.go b/internal/gateway/image_mcp_models.go index a1ce8e1c5..9359b4894 100644 --- a/internal/gateway/image_mcp_models.go +++ b/internal/gateway/image_mcp_models.go @@ -106,7 +106,7 @@ func ImageModels() []ImageModel { // mediaModelsFor is mediaModels less those r's gateway key may not use. func mediaModelsFor(r *http.Request, video bool) (all, shown []string, def string) { all, def = mediaModels(video) - who, held := keyHolds(r) + who, held := keyListHolds(r) if !held { return all, all, def } diff --git a/internal/gateway/key_limit.go b/internal/gateway/key_limit.go index 2ecfea7ee..450368e63 100644 --- a/internal/gateway/key_limit.go +++ b/internal/gateway/key_limit.go @@ -33,6 +33,12 @@ const remoteKeyLimitHeader = "X-Magpie-Limit-Reset" // resets; one let in holds a reservation until it ends. A key with a limit // while plugins/budget is off is refused with a 503, and nothing is sent. Reads, the // bridge's tool callbacks and counting tokens cost nothing and pass. +// +// A limit of some models (access.Limit.Models) holds a request that names +// one of them here, and its spent ones are put on the request's caller +// (access.Identity.Spent), for every route to leave their models out of +// its candidates: a routing group's request goes on to the others, and +// counting tokens on a spent one is refused as serving it would be. func keyLimited(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { who := access.Caller(r.Context()) @@ -40,14 +46,22 @@ func keyLimited(next http.Handler) http.Handler { if who.Issuer != nil { limits = append(slices.Clone(limits), who.Issuer.Limits()...) } - if !who.Limited() || r.Method != http.MethodPost || strings.HasPrefix(r.URL.Path, "/_magpie/") || strings.HasPrefix(r.URL.Path, "/mcp/") || strings.HasSuffix(r.URL.Path, "/count_tokens") || r.URL.Path == KeysPath { + if !who.Limited() || r.Method != http.MethodPost || strings.HasPrefix(r.URL.Path, "/_magpie/") || strings.HasPrefix(r.URL.Path, "/mcp/") || r.URL.Path == KeysPath { + next.ServeHTTP(w, r) + return + } + scoped := slices.ContainsFunc(limits, (*access.Limit).Scoped) + if strings.HasSuffix(r.URL.Path, "/count_tokens") { + if scoped { + r = withSpent(r, who, limitClock()) + } next.ServeHTTP(w, r) return } size, model := r.ContentLength, "" // a compressed body (#1223) is reserved at its decoded size and model costCap := slices.ContainsFunc(limits, func(l *access.Limit) bool { return l.Cost > 0 }) - if enc := r.Header.Get("Content-Encoding"); costCap || size < 0 || (enc != "" && !strings.EqualFold(enc, "identity")) { + if enc := r.Header.Get("Content-Encoding"); costCap || scoped || size < 0 || (enc != "" && !strings.EqualFold(enc, "identity")) { // a turn on Codex's own path reads to its own limit (codexBackend) var most int64 if strings.HasPrefix(r.URL.Path, CodexPath+"/") { @@ -62,6 +76,11 @@ func keyLimited(next http.Handler) http.Handler { size, model = int64(len(b)), budget.ModelOf(b) } now := limitClock() + if scoped { + // before the request's own reservation, which would count it + // spent on the model it holds + r = withSpent(r, who, now) + } release, err := reserveFor(who, size, model, now) if err != nil { status, errType := http.StatusServiceUnavailable, "gateway_key_limit_off" @@ -69,7 +88,10 @@ func keyLimited(next http.Handler) http.Handler { if errors.As(err, &refused) { status, errType = http.StatusTooManyRequests, "gateway_key_limit" w.Header().Set("Retry-After", strconv.Itoa(refused.RetryAfter(now))) - w.Header().Set(remoteKeyLimitHeader, refused.ResetAt().Format(time.RFC3339)) + // a limit of some models rests a remote's model, not its key + if b, ok := refused.(*budget.Refusal); !ok || len(b.Models) == 0 { + w.Header().Set(remoteKeyLimitHeader, refused.ResetAt().Format(time.RFC3339)) + } } // the Anthropic and OpenAI SDKs would otherwise retry a 429 or 503 w.Header().Set("X-Should-Retry", "false") @@ -84,6 +106,24 @@ func keyLimited(next http.Handler) http.Handler { }) } +// withSpent is r with its caller's spent limits of some models on it +// (access.Identity.Spent), as the limiter serving who tells them; r as it +// is when none serves (a request it holds is refused by reserveFor). +func withSpent(r *http.Request, who access.Identity, now time.Time) *http.Request { + l, err := gwbudget.Limiting(who) + if err != nil || l == nil { + return r + } + sp, ok := l.(gwbudget.Spender) + if !ok { + return r + } + if who.Spent = sp.Spent(who, now); len(who.Spent) == 0 { + return r + } + return r.WithContext(access.WithIdentity(r.Context(), who)) +} + // reserveFor holds a request of who's to its key's limits through the // gateway's budget point (gwbudget): its release, or why it isn't let in, // a gwbudget.Refusal or, for a key held to a limit while no limiter serves diff --git a/internal/gateway/key_model_limit_test.go b/internal/gateway/key_model_limit_test.go new file mode 100644 index 000000000..d2e0093bb --- /dev/null +++ b/internal/gateway/key_model_limit_test.go @@ -0,0 +1,249 @@ +package gateway + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/budget" + "github.com/yetone/magpie/internal/provider" +) + +// usedReply is a chat answer of 350 tokens, which the key's limits count. +func usedReply(id string) string { + return `{"id":"` + id + `","choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":300,"completion_tokens":50}}` +} + +// keyCall sends body to path with secret as the gateway key. +func keyCall(h http.Handler, secret, path, body string) *httptest.ResponseRecorder { + r := httptest.NewRequest("POST", path, strings.NewReader(body)) + r.Header.Set("Authorization", "Bearer "+secret) + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w +} + +// spentSaid fails t unless w is the 429 of a spent limit of some models: +// it names the key and the models, says when it resets, and leaves the +// key's reset header out, as the key's other models are still served. +func spentSaid(t *testing.T, w *httptest.ResponseRecorder, scope string) { + t.Helper() + var e struct { + Error struct{ Message, Type string } + } + json.Unmarshal(w.Body.Bytes(), &e) + if w.Code != http.StatusTooManyRequests || e.Error.Type != "rate_limit_error" || !strings.Contains(e.Error.Message, `"Capped"`) || !strings.Contains(e.Error.Message, scope) { + t.Fatalf("refusal: %d %s", w.Code, w.Body.String()) + } + if w.Header().Get("Retry-After") == "" || w.Header().Get("X-Should-Retry") != "false" || w.Header().Get(remoteKeyLimitHeader) != "" { + t.Fatalf("headers %v", w.Header()) + } +} + +// zola_xynb on X: a key's limit of some models counts their calls alone +// and refuses them alone once spent, said as a limit; the key's other +// models go on, a routing group goes on to its members outside it (and +// is refused only when none is left), counting tokens on a spent model is +// refused as serving it would be, the list is unchanged, another key is +// free, and a restart reads what was spent back from the ledger. +func TestKeyModelLimitHoldsItsModelsAlone(t *testing.T) { + fresh(t) + budget.Forget() + pinLimitClock(t) + plan := &fake{t: t, ctype: "application/json", reply: usedReply("from-plan")} + spare := &fake{t: t, ctype: "application/json", reply: usedReply("from-spare")} + twoProviders(t, plan, spare) + for _, g := range []provider.Group{ + {Name: "Both", Members: []string{"plan/m1", "spare/m2"}, Routing: provider.Ordered}, + {Name: "Solo", Members: []string{"plan/m1"}, Routing: provider.Ordered}, + } { + if err := provider.SaveGroup(g); err != nil { + t.Fatal(err) + } + } + keys, secrets := newCaller(t, "Capped", "Other") + setLimit(t, keys[0].ID, &access.Limit{Period: "day", Tokens: 700, Models: []string{"plan/*"}}) + h := New().Handler() + chat := func(secret, model string) *httptest.ResponseRecorder { + return keyCall(h, secret, "/v1/chat/completions", `{"model":"`+model+`","messages":[{"role":"user","content":"hi"}]}`) + } + // spare's calls don't count in it + for range 3 { + if w := chat(secrets[0], "spare/m2"); w.Code != 200 { + t.Fatal("another provider's model", w.Code, w.Body.String()) + } + } + for i := range 2 { + if w := chat(secrets[0], "plan/m1"); w.Code != 200 { + t.Fatal("within the limit", i, w.Code, w.Body.String()) + } + } + if plan.calls != 2 { + t.Fatal(plan.calls) + } + for _, model := range []string{"plan/m1", "m1", "group/solo"} { + spentSaid(t, chat(secrets[0], model), "plan/*") + } + if plan.calls != 2 { + t.Fatal("a spent model's request reached its provider", plan.calls) + } + if rec := lastUsage(t); !rec.Rejected || rec.CallerKeyID != keys[0].ID || rec.ErrType != "gateway_key_limit" || rec.Status != 429 { + t.Fatalf("refusal recorded as %+v", rec) + } + // the key's other models go on, and a group to its member outside it + spareCalls := spare.calls + if w := chat(secrets[0], "spare/m2"); w.Code != 200 || !strings.Contains(w.Body.String(), "from-spare") { + t.Fatal("a model outside the limit", w.Code, w.Body.String()) + } + if w := chat(secrets[0], "group/both"); w.Code != 200 || !strings.Contains(w.Body.String(), "from-spare") || plan.calls != 2 || spare.calls != spareCalls+2 { + t.Fatal("a group didn't go on past its spent member", w.Code, w.Body.String(), plan.calls) + } + // counting tokens on a spent model is refused, on another counted + count := func(model string) *httptest.ResponseRecorder { + return keyCall(h, secrets[0], "/v1/messages/count_tokens", `{"model":"`+model+`","messages":[{"role":"user","content":"hi"}]}`) + } + spentSaid(t, count("plan/m1"), "plan/*") + if w := count("spare/m2"); w.Code != 200 || !strings.Contains(w.Body.String(), "input_tokens") { + t.Fatal("counting another model", w.Code, w.Body.String()) + } + // the list still has it, as a spent key's has every model + r := httptest.NewRequest("GET", "/v1/models", nil) + r.Header.Set("Authorization", "Bearer "+secrets[0]) + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + if !strings.Contains(w.Body.String(), `"plan/m1"`) { + t.Fatal("a spent model left the list", w.Body.String()) + } + if w := chat(secrets[1], "plan/m1"); w.Code != 200 { + t.Fatal("another key held to the spent one's limit", w.Code) + } + budget.Forget() + spentSaid(t, chat(secrets[0], "plan/m1"), "plan/*") + if w := chat(secrets[0], "spare/m2"); w.Code != 200 { + t.Fatal("after a restart, a model outside the limit", w.Code) + } +} + +// A request that moves to another model midway — a provider's fallback +// when it is out of quota — doesn't move onto a model a spent limit of +// the key's counts: that one is never asked, and the refusal says why. +func TestKeyModelLimitHoldsAFallback(t *testing.T) { + fresh(t) + budget.Forget() + pinLimitClock(t) + plan := &fake{t: t, ctype: "application/json", reply: usedReply("from-plan")} + spare := &fake{t: t, ctype: "application/json", reply: usedReply("from-spare")} + twoProviders(t, plan, spare) + keys, secrets := newCaller(t, "Capped") + setLimit(t, keys[0].ID, &access.Limit{Period: "day", Tokens: 350, Models: []string{"spare/*"}}) + h := New().Handler() + if w := keyCall(h, secrets[0], "/v1/chat/completions", `{"model":"spare/m2","messages":[{"role":"user","content":"hi"}]}`); w.Code != 200 { + t.Fatal(w.Code, w.Body.String()) + } + plan.code, plan.reply = 429, `{"error":{"message":"slow down"}}` + w := keyCall(h, secrets[0], "/v1/chat/completions", chatReq) + if spare.calls != 1 || strings.Contains(w.Body.String(), "from-spare") { + t.Fatal("the fallback went to a spent model", spare.calls, w.Code, w.Body.String()) + } + if plan.calls == 0 { + t.Fatal("the model asked wasn't tried") + } +} + +// System One's decision model is held by a spent limit that counts it. +func TestKeyModelLimitHoldsSystemOne(t *testing.T) { + fresh(t) + budget.Forget() + pinLimitClock(t) + var decided int + jev := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + decided++ + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"answers":{"intent":{"choice":"bug"}},"usage":{"input_tokens":300,"output_tokens":50}}`)) + })) + t.Cleanup(jev.Close) + if err := provider.Save(provider.Provider{ID: "jev", Name: "Jev", Key: "k", Decide: jev.URL + "/v1"}); err != nil { + t.Fatal(err) + } + keys, secrets := newCaller(t, "Capped") + setLimit(t, keys[0].ID, &access.Limit{Period: "day", Tokens: 300, Models: []string{"jev/*"}}) + h := New().Handler() + const ask = `{"model":"jev/jev-latest","state":{"message":"hi"},"questions":{"intent":{"type":"choice"}}}` + if w := keyCall(h, secrets[0], "/v1/systemone", ask); w.Code != 200 || decided != 1 { + t.Fatal("within the limit", w.Code, w.Body.String()) + } + spentSaid(t, keyCall(h, secrets[0], "/v1/systemone", ask), "jev/*") + if decided != 1 { + t.Fatal("a spent decider was asked", decided) + } +} + +// A routing group of embedding or image models goes on past a member a +// spent limit of the key's counts, and is refused when it has no other. +func TestKeyModelLimitHoldsMediaGroups(t *testing.T) { + s, e := easeled(t) + budget.Forget() + pinLimitClock(t) + spent := &fake{t: t, ctype: "application/json", reply: usedReply("from-spent")} + up := httptest.NewServer(spent) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "flare", Name: "Flare", Chat: up.URL + "/v1", Key: "k", Models: []string{"chat", "gpt-image-1"}}); err != nil { + t.Fatal(err) + } + for _, g := range []provider.Group{ + {ID: "pics", Name: "pics", Members: []string{"flare/gpt-image-1", "art/gpt-image-1"}, Routing: provider.Ordered}, + {ID: "lone", Name: "lone", Members: []string{"flare/gpt-image-1"}, Routing: provider.Ordered}, + {ID: "emb", Name: "emb", Members: []string{"flare/embed-1"}, Routing: provider.Ordered}, + } { + if err := provider.SaveGroup(g); err != nil { + t.Fatal(err) + } + } + keys, secrets := newCaller(t, "Capped") + setLimit(t, keys[0].ID, &access.Limit{Period: "day", Tokens: 350, Models: []string{"flare/*"}}) + h := s.Handler() + if w := keyCall(h, secrets[0], "/v1/chat/completions", `{"model":"flare/chat","messages":[{"role":"user","content":"hi"}]}`); w.Code != 200 { + t.Fatal(w.Code, w.Body.String()) + } + w := keyCall(h, secrets[0], "/v1/images/generations", `{"model":"group/pics","prompt":"a magpie"}`) + if w.Code != 200 || spent.calls != 1 || len(e.got("/v1/images/generations")) != 1 { + t.Fatal("a drawing group didn't go on past its spent member", w.Code, w.Body.String(), spent.calls) + } + spentSaid(t, keyCall(h, secrets[0], "/v1/images/generations", `{"model":"group/lone","prompt":"a magpie"}`), "flare/*") + spentSaid(t, keyCall(h, secrets[0], "/v1/embeddings", `{"model":"group/emb","input":"hi"}`), "flare/*") + if spent.calls != 1 { + t.Fatal("a spent member was asked", spent.calls) + } +} + +// A limit of the whole key, as every one from before, is untouched by +// limits of some models beside it: it counts every model, and says its +// reset to a remote magpie. +func TestKeyModelLimitBesideTheWholeKey(t *testing.T) { + fresh(t) + budget.Forget() + pinLimitClock(t) + plan := &fake{t: t, ctype: "application/json", reply: usedReply("from-plan")} + spare := &fake{t: t, ctype: "application/json", reply: usedReply("from-spare")} + twoProviders(t, plan, spare) + keys, secrets := newCaller(t, "Capped") + if _, err := access.Update("limit-key", access.Change{Key: keys[0].ID, Limit: &access.Limit{Period: "day", Tokens: 1050}}); err != nil { + t.Fatal(err) + } + if _, err := access.Update("limit-key", access.Change{Key: keys[0].ID, Index: new(1), Limit: &access.Limit{Period: "day", Tokens: 10000, Models: []string{"plan/*"}}}); err != nil { + t.Fatal(err) + } + h := New().Handler() + for _, model := range []string{"spare/m2", "spare/m2", "plan/m1"} { + if w := keyCall(h, secrets[0], "/v1/chat/completions", `{"model":"`+model+`","messages":[{"role":"user","content":"hi"}]}`); w.Code != 200 { + t.Fatal(model, w.Code, w.Body.String()) + } + } + w := keyCall(h, secrets[0], "/v1/chat/completions", `{"model":"spare/m2","messages":[{"role":"user","content":"hi"}]}`) + if w.Code != 429 || w.Header().Get(remoteKeyLimitHeader) == "" { + t.Fatal("the whole key's limit", w.Code, w.Header(), w.Body.String()) + } +} diff --git a/internal/gateway/key_models.go b/internal/gateway/key_models.go index 464ea9041..9ef273a05 100644 --- a/internal/gateway/key_models.go +++ b/internal/gateway/key_models.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "slices" + "strconv" "strings" "github.com/yetone/magpie/internal/access" @@ -36,9 +37,28 @@ func magpieChose(ctx context.Context) context.Context { return context.WithValue(ctx, magpieChoseKey{}, true) } -// keyHolds is the calling key's models, when they hold this request. +// keyHolds is the calling key's models, when they hold this request: the +// models it lists, and those a limit of some models it has spent counts +// (access.Identity.Spent, zola_xynb on X), which hold magpie's own calls +// for the key too, as their spend counts in it. func keyHolds(r *http.Request) (access.Identity, bool) { who := access.Caller(r.Context()) + if chose, _ := r.Context().Value(magpieChoseKey{}).(bool); chose { + if len(who.Spent) == 0 { + return who, false + } + who.Models, who.AccountModels = nil, false + return who, true + } + return who, who.Restricted() || len(who.Spent) > 0 +} + +// keyListHolds is keyHolds for a list of models shown to the key: a +// spent limit leaves its models listed, as a spent limit of the whole key +// does, and a request for one is told why it is refused. +func keyListHolds(r *http.Request) (access.Identity, bool) { + who := access.Caller(r.Context()) + who.Spent = nil if !who.Restricted() { return who, false } @@ -48,6 +68,109 @@ func keyHolds(r *http.Request) (access.Identity, bool) { return who, true } +// spentFor is the key's spent limit that counts provider p's model, by +// any id the model goes by, the one that resets last when several do. +func spentFor(who access.Identity, p provider.Provider, model string) (access.SpentScope, bool) { + if len(who.Spent) == 0 { + return access.SpentScope{}, false + } + ids := []string{p.ID + "/" + model} + if own := p.OwnModelID(model); own != model { + ids = append(ids, p.ID+"/"+own) + } + if local := p.ListedModelID(model); local != model { + ids = append(ids, p.ID+"/"+local) + } + var out access.SpentScope + found := false + for _, id := range ids { + if s, ok := who.SpentOn(id); ok && (!found || s.Reset.After(out.Reset)) { + out, found = s, true + } + } + return out, found +} + +// spentRef is the spent limit a request for ref is refused by: a model's +// that counts it, or for a routing group the key may use, the one of its +// members' that resets last, when each member is spent or not the key's. +func spentRef(who access.Identity, ref string) (access.SpentScope, bool) { + if len(who.Spent) == 0 { + return access.SpentScope{}, false + } + if g, ms, isGroup := provider.FindGroup(ref); isGroup { + if !groupAllowed(who, g, ms) { + return access.SpentScope{}, false + } + return spentOfMembers(who, ms) + } + if sid, ok := provider.AutoStandIn(ref); ok { + ref = sid + } + p, model, ok := provider.Resolve(ref) + if !ok { + return access.SpentScope{}, false + } + return spentFor(who, p, model) +} + +// spentOfMembers is the spent limit of the key's that counts one of a +// routing group's members ms, the one that resets last when several do. +func spentOfMembers(who access.Identity, ms []provider.Member) (access.SpentScope, bool) { + var out access.SpentScope + found := false + for _, m := range ms { + if s, ok := spentFor(who, m.Provider, m.Model); ok && (!found || s.Reset.After(out.Reset)) { + out, found = s, true + } + } + return out, found +} + +// keyGroupRefusal is keyModelRefusal for a routing group whose members ms +// a route found itself (an embedding, image or video group's, which +// provider.FindGroup's chat members leave out): its 429 when a spent limit +// counts one of them. +func keyGroupRefusal(w http.ResponseWriter, who access.Identity, ref string, ms []provider.Member) (int, string) { + if s, ok := spentOfMembers(who, ms); ok { + return spentRefusal(w, s) + } + return keyModelRefusal(w, who, ref) +} + +// keyModelRefusal is the status and message a request for ref its key may not +// use is answered with: a 429 saying the limit and when it resets, with +// Retry-After, when a limit of the key's spent on it is why, else +// keyModelError's 403. It names no reset in remoteKeyLimitHeader: a +// magpie using this one as a remote rests only the model on it, as the +// key's other models are still served. +func keyModelRefusal(w http.ResponseWriter, who access.Identity, ref string) (int, string) { + if s, ok := spentRef(who, ref); ok { + return spentRefusal(w, s) + } + return http.StatusForbidden, keyModelError(who, ref) +} + +// spentRefusal is keyModelRefusal's 429 for the spent limit s. +func spentRefusal(w http.ResponseWriter, s access.SpentScope) (int, string) { + w.Header().Set("Retry-After", strconv.Itoa(max(1, int(s.Reset.Sub(limitClock()).Seconds()+0.999)))) + w.Header().Set("X-Should-Retry", "false") + return http.StatusTooManyRequests, s.Why +} + +// spentAmong is the spent limit of the key's that counts one of cs, the +// one that resets last when several do. +func spentAmong(who access.Identity, cs []candidate) (access.SpentScope, bool) { + var out access.SpentScope + found := false + for _, c := range cs { + if s, ok := spentFor(who, c.p, c.model); ok && (!found || s.Reset.After(out.Reset)) { + out, found = s, true + } + } + return out, found +} + // accountHolds is the calling key's accounts, when they hold this // request: magpie's own calls for the key — a web search, a picture // described, a Codex title — are of the models the user picked, so the @@ -89,6 +212,14 @@ func allows(who access.Identity, ids ...string) bool { // one written before the id was given, or an agent's old ref to the // provider's own id. func modelAllowed(who access.Identity, p provider.Provider, model string) bool { + if _, spent := spentFor(who, p, model); spent { + return false // a limit of the key's that counts it is spent + } + return modelListed(who, p, model) +} + +// modelListed is modelAllowed by the key's models alone. +func modelListed(who access.Identity, p provider.Provider, model string) bool { if allows(who, p.ID+"/"+model) { return true } @@ -122,7 +253,10 @@ func groupNamed(who access.Identity, g provider.Group) bool { // Every route asks this: the model lists (entryAllowed), a request on // each API, count_tokens, embeddings, images, videos, the decision // groups, a subagent's and masking's route. +// A member a spent limit counts doesn't take the group away from the key: +// the request goes on to the others (groupKeeps). func groupAllowed(who access.Identity, g provider.Group, ms []provider.Member) bool { + who.Spent = nil return groupNamed(who, g) || (foundGroup(g) || who.AccountModels) && membersAllowed(who, ms) } @@ -157,11 +291,16 @@ func keyGroupFor(r *http.Request, id string) (string, bool) { } // groupKeeps is the members of g a request through it may go to for the -// key: every one when it names g, else those it may use. +// key: every one when it names g, else those it may use; neither one a +// spent limit of the key's counts (zola_xynb: a group goes on to the +// models left, midway too, as the next request finds the limit spent). func groupKeeps(who access.Identity, g provider.Group, ms []provider.Member) map[string]bool { out := map[string]bool{} named := groupNamed(who, g) for _, m := range ms { + if _, spent := spentFor(who, m.Provider, m.Model); spent { + continue + } if named || memberAllowed(who, m) { out[m.Provider.ID+"/"+m.Model] = true } @@ -277,7 +416,7 @@ func accountServesOn(who access.Identity, p provider.Provider, model string, ref // keyAllowed filters the catalog to what the calling key may use. func keyAllowed(r *http.Request, es []provider.Entry) []provider.Entry { - who, held := keyHolds(r) + who, held := keyListHolds(r) if !held { return es } @@ -302,7 +441,7 @@ func keyAllowed(r *http.Request, es []provider.Entry) []provider.Entry { // his listed alone). off is the list's own picks (ModelOff), nil for // none; a model they leave out stays out. func keyListed(r *http.Request, shown []provider.Entry, off func(string) bool) []provider.Entry { - who, held := keyHolds(r) + who, held := keyListHolds(r) if !held { return shown } @@ -575,7 +714,8 @@ func countHeld(w http.ResponseWriter, r *http.Request, proto provider.Protocol, } g, ms, isGroup := provider.FindGroup(id) if isGroup && !groupAllowed(keyWho, g, ms) || !isGroup && !modelAllowed(keyWho, p, model) { - writeError(w, proto, http.StatusForbidden, keyModelError(keyWho, id)) + st, msg := keyModelRefusal(w, keyWho, id) + writeError(w, proto, st, msg) return true } return false diff --git a/internal/gateway/video.go b/internal/gateway/video.go index a901e8fa7..1373d2939 100644 --- a/internal/gateway/video.go +++ b/internal/gateway/video.go @@ -1050,7 +1050,7 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) { } keyWho, keyHeld := keyHolds(r) if keyHeld && named && (isGroup && !groupAllowed(keyWho, g, ms) || !isGroup && !modelAllowed(keyWho, p, model)) { - fail(403, keyModelError(keyWho, f.Model)) + fail(keyModelRefusal(w, keyWho, f.Model)) return } if msg, off := modelOff(p, model, f.Model); off { // disabled by the user (#1867) @@ -1073,7 +1073,7 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) { } t := s.drawingTries(g, ms, keeps, servesKind(provider.KindVideo)) if len(t) == 0 && keeps != nil { - fail(403, keyModelError(keyWho, f.Model)) + fail(keyGroupRefusal(w, keyWho, f.Model, ms)) return } if len(t) > 0 { diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 7fdeaba60..59f682420 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2979,9 +2979,11 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } #gatewayKeys .klf input { width: 100%; min-width: 0; height: 28px; padding: 0 8px; border: 1px solid var(--line); border-radius: 7px; background: var(--card); color: var(--fg); font: inherit; font-size: 12px; } #gatewayKeys .klf-check { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--fg-2); } #gatewayKeys .klf-err { color: var(--red); } -#gatewayKeys .klf .klf-period { width: 100%; max-width: none; height: 28px; justify-content: space-between; color: var(--fg); } +#gatewayKeys .klf .klf-period, #gatewayKeys .klf .klf-pick { width: 100%; max-width: none; height: 28px; justify-content: space-between; color: var(--fg); } #gatewayKeys .klf.with-days { grid-template-columns: minmax(0, 1fr) minmax(0, 0.6fr) minmax(0, 1fr) minmax(0, 1fr); } #gatewayKeys .klf-days[hidden] { display: none; } +#gatewayKeys .klf-models { grid-column: 1 / -1; } +#gatewayKeys .klf .klf-pick > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } #gatewayKeys .klf-used { display: flex; align-items: center; gap: 8px; min-width: 0; } #gatewayKeys .klf-used .key-limit { flex: 1 1 auto; } #gatewayKeys .klf-used .klf-reset { flex: none; } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 45b592b0c..966d8a9e8 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -478,6 +478,7 @@ const I18N = { "Estimated cost limit, US$": "估算费用限额(美元)", "Estimated cost, US$": "估算费用(美元)", "Count cache reads too": "缓存读取也计入", + "Models this limit counts": "此额度计入的模型", "Tokens are each call's uncached input, output and cache writes. The cost is an estimate at the Usage page's prices, not a bill. Windows are calendar ones in this computer's time (a week from Monday), or every N days or N hours from when the limit is set or reset. Requests from this computer without a key aren't limited.": "Token 计未命中缓存的输入、输出和缓存写入。费用按用量页价格估算,非账单。周期按本机时间的自然日、周、月(每周从周一起),或从设置或重置额度时起每 N 天或每 N 小时。本机无密钥的请求不受限额。", "Tokens is a count, like 2000000 or 2M": "Token 应为数量,例如 2000000、2M 或 200万", "The cost is US dollars, like 5 or 2.50": "费用以美元计,例如 5 或 2.50", @@ -5127,6 +5128,7 @@ const I18N = { "Estimated cost limit, US$": "估算費用限額(美元)", "Estimated cost, US$": "估算費用(美元)", "Count cache reads too": "快取讀取也計入", + "Models this limit counts": "此額度計入的模型", "Tokens are each call's uncached input, output and cache writes. The cost is an estimate at the Usage page's prices, not a bill. Windows are calendar ones in this computer's time (a week from Monday), or every N days or N hours from when the limit is set or reset. Requests from this computer without a key aren't limited.": "Token 計未命中快取的輸入、輸出和快取寫入。費用按用量頁價格估算,非帳單。週期按本機時間的自然日、週、月(每週從週一起),或從設定或重置額度時起每 N 天或每 N 小時。本機無金鑰的請求不受限額。", "Tokens is a count, like 2000000 or 2M": "Token 應為數量,例如 2000000、2M 或 200萬", "The cost is US dollars, like 5 or 2.50": "費用以美元計,例如 5 或 2.50", @@ -9737,6 +9739,7 @@ const I18N = { "Estimated cost limit, US$": "推定費用の上限(米ドル)", "Estimated cost, US$": "推定費用(米ドル)", "Count cache reads too": "キャッシュ読み取りも数える", + "Models this limit counts": "この上限に数えるモデル", "Tokens are each call's uncached input, output and cache writes. The cost is an estimate at the Usage page's prices, not a bill. Windows are calendar ones in this computer's time (a week from Monday), or every N days or N hours from when the limit is set or reset. Requests from this computer without a key aren't limited.": "トークンは各呼び出しのキャッシュされない入力、出力、キャッシュ書き込みの合計です。費用は使用量ページの価格による推定で、請求額ではありません。期間はこのコンピュータの時刻によるカレンダー単位(週は月曜日から)か、上限を設定またはリセットした時から N 日ごとか N 時間ごとです。このコンピュータからのキーなしのリクエストは制限されません。", "Tokens is a count, like 2000000 or 2M": "トークンは数で指定します(例:2000000 や 2M)", "The cost is US dollars, like 5 or 2.50": "費用は米ドルで指定します(例:5 や 2.50)", @@ -14365,6 +14368,7 @@ const I18N = { "Estimated cost limit, US$": "Limit geschätzte Kosten, US$", "Estimated cost, US$": "Geschätzte Kosten, US$", "Count cache reads too": "Cache-Lesen mitzählen", + "Models this limit counts": "Modelle, die dieses Limit zählt", "Tokens are each call's uncached input, output and cache writes. The cost is an estimate at the Usage page's prices, not a bill. Windows are calendar ones in this computer's time (a week from Monday), or every N days or N hours from when the limit is set or reset. Requests from this computer without a key aren't limited.": "Token sind je Aufruf die nicht gecachte Eingabe, die Ausgabe und das Cache-Schreiben. Die Kosten sind eine Schätzung zu den Preisen der Seite „Nutzung“, keine Rechnung. Zeitfenster sind Kalenderzeiträume in der Zeit dieses Computers (eine Woche ab Montag) oder alle N Tage bzw. alle N Stunden ab dem Setzen oder Zurücksetzen des Limits. Anfragen von diesem Computer ohne Schlüssel werden nicht begrenzt.", "Tokens is a count, like 2000000 or 2M": "Token ist eine Anzahl, z. B. 2000000 oder 2M", "The cost is US dollars, like 5 or 2.50": "Die Kosten sind US-Dollar, z. B. 5 oder 2.50", diff --git a/internal/gui/assets/plugins/gateway/keys.js b/internal/gui/assets/plugins/gateway/keys.js index b89330ff9..3230abac3 100644 --- a/internal/gui/assets/plugins/gateway/keys.js +++ b/internal/gui/assets/plugins/gateway/keys.js @@ -594,6 +594,10 @@ function limitCost(v) { return /^\d+(\.\d+)?$/.test(s) ? parseFloat(s) : NaN; } const usd = (n) => "$" + (n >= 100 ? n.toFixed(0) : n.toFixed(2)); +// limitModels names the models a limit counts (zola_xynb on X), "" when +// it counts every call of the key +const limitModels = (ms) => !ms?.length ? "" : ms.length === 1 ? ms[0] : t("{n} models", { n: ms.length }); +const sameModels = (a, b) => (a || []).length === (b || []).length && (a || []).every((m) => (b || []).includes(m)); // keyLimits are a key's limits, its first and the rest (#2227), and // keyUsed what it has used of each, in the same order. @@ -606,7 +610,7 @@ function limitDraft(k, n) { const taken = keyLimits(k).map((x) => x.period); // a new one in a window the key has no limit in yet: a week beside 5 hours const period = l.period || (n ? ["week", "hours", "day", "month"].find((p) => !taken.includes(p)) || "days" : "day"); - return { id: k.id, n, period, days: l.days ? String(l.days) : "", hours: l.hours ? String(l.hours) : (n && period === "hours" ? "5" : ""), tokens: l.tokens ? String(l.tokens) : "", cost: l.cost ? String(l.cost) : "", cacheReads: !!l.cacheReads }; + return { id: k.id, n, period, days: l.days ? String(l.days) : "", hours: l.hours ? String(l.hours) : (n && period === "hours" ? "5" : ""), tokens: l.tokens ? String(l.tokens) : "", cost: l.cost ? String(l.cost) : "", cacheReads: !!l.cacheReads, models: [...(l.models || [])] }; } // bindingUsed is the limit holding a key most: of those spent, the one // that resets last, as it is refused until then; else the first @@ -628,6 +632,7 @@ function gatewayLimitBadge(k) { if (u.tokenLimit) parts.push(fmtN(u.tokens) + " / " + fmtN(u.tokenLimit)); if (u.costLimit) parts.push(usd(u.cost) + " / " + usd(u.costLimit)); b.textContent = (u.spent ? t("Spent") + " · " : "") + parts.join(" · ") + " · " + perWords(u.period, u.days, u.hours) + + (u.models?.length ? " · " + limitModels(u.models) : "") + (more > 0 ? " · " + t(more === 1 ? "+1 limit" : "+{n} limits", { n: more }) : ""); } b.title = t(u ? "Change this key's limit" : "Set a limit for this key"); @@ -649,13 +654,15 @@ function gatewayLimitLine(k, u) { const line = el("div", "key-limit" + (u.spent ? " spent" : "")); const parts = []; if (keyUsed(k).length > 1) parts.push(perWords(u.period, u.days, u.hours)); + if (u.models?.length) parts.push(limitModels(u.models)); if (u.tokenLimit) parts.push(t("{used} of {limit} tokens · {left} left", { used: fmtN(u.tokens), limit: fmtN(u.tokenLimit), left: fmtN(u.tokensLeft) })); if (u.costLimit) parts.push(t("{used} of {limit} estimated · {left} left", { used: usd(u.cost), limit: usd(u.costLimit), left: usd(u.costLeft) })); const at = new Date(u.reset); parts.push(t(u.spent ? "refused until {when}" : "resets {when}", { when: resetClock(at) })); if (u.inFlight) parts.push(t(u.inFlight === 1 ? "1 in flight" : "{n} in flight", { n: u.inFlight })); line.textContent = parts.join(" · "); - line.title = t("Counted from {start}; resets {when}", { start: new Date(u.start).toLocaleString(intlLang()), when: at.toLocaleString(intlLang()) }) + line.title = (u.models?.length ? u.models.join(", ") + "\n" : "") + + t("Counted from {start}; resets {when}", { start: new Date(u.start).toLocaleString(intlLang()), when: at.toLocaleString(intlLang()) }) + (u.unpriced ? "\n" + t("{n} calls without a known price aren't in the cost", { n: u.unpriced }) : ""); return line; } @@ -670,7 +677,8 @@ function gatewayLimitEditor(k) { const changed = () => d.period !== (kept.period || "day") || limitTokens(d.tokens) !== (kept.tokens || 0) || limitCost(d.cost) !== (kept.cost || 0) || d.cacheReads !== !!kept.cacheReads || (d.period === "days" && limitDays(d.days) !== kept.days) - || (d.period === "hours" && limitHours(d.hours) !== kept.hours); + || (d.period === "hours" && limitHours(d.hours) !== kept.hours) + || !sameModels(d.models, kept.models); const fields = el("div", "klf"); // the app's own menu, not a native select const period = el("button", "sess-pick klf-period"); @@ -710,7 +718,21 @@ function gatewayLimitEditor(k) { cl.append(el("span", "klf-name", t("Estimated cost, US$")), cost); const pl = el("label", "klf-field"); pl.append(el("span", "klf-name", t("Window")), period); - fields.append(pl, dl, hl, tl, cl); + // the models the limit counts (zola_xynb on X): none picked is every + // call of the key, as a limit set before there was a pick + const models = el("button", "sess-pick klf-pick klf-models-pick"); + models.type = "button"; + models.setAttribute("aria-label", t("Models this limit counts")); + models.setAttribute("aria-haspopup", "menu"); + models.setAttribute("aria-expanded", "false"); + const paintModels = () => { + models.title = d.models.join(", "); + models.replaceChildren(el("span", "", limitModels(d.models) || t("All models")), svg(CHEV, 11, 1.6)); + }; + paintModels(); + const ml = el("label", "klf-field klf-models"); + ml.append(el("span", "klf-name", t("Models")), models); + fields.append(pl, dl, hl, tl, cl, ml); // a key's limits (#2227), each a tab, when it has more than one or one // is being added: the editor is of one at a time let which = null; @@ -718,7 +740,7 @@ function gatewayLimitEditor(k) { which = el("div", "klf-which"); which.setAttribute("role", "tablist"); which.setAttribute("aria-label", t("This key's limits")); - const tabs = limits.map((l, i) => ({ i, name: perWords(l.period, l.days, l.hours) })); + const tabs = limits.map((l, i) => ({ i, name: perWords(l.period, l.days, l.hours) + (l.models?.length ? " · " + limitModels(l.models) : "") })); if (n >= limits.length) tabs.push({ i: n, name: t("New limit") }); for (const x of tabs) { const tab = el("button", "klf-tab" + (x.i === n ? " on" : ""), x.name); @@ -767,6 +789,32 @@ function gatewayLimitEditor(k) { if (v === "hours") hours.focus({ preventScroll: true }); }, "Limit window", "sess-menu"); }; + models.onclick = async (e) => { + e.preventDefault(); + e.stopPropagation(); + if (models.classList.contains("open")) return closeProtoMenu(); + let list = []; + try { ({ models: list } = await api("caller-keys/models")); } catch (err) { status(t(err.message), "err"); return; } + if (!models.isConnected || gatewayLimit !== d) return; + const opts = [{ v: "", name: "All models", note: "" }]; + const seen = new Set(); + // a routing group isn't one: what it picks is counted by the model + // that served the call + for (const m of list || []) { + if (m.group) continue; + if (!seen.has(m.provider)) { + seen.add(m.provider); + opts.push({ v: m.provider + "/*", name: t("Every {provider} model", { provider: m.providerName }), note: m.provider + "/*", literalName: true }); + } + opts.push({ v: m.id, name: m.name, note: m.id, literalName: true }); + } + for (const v of d.models) if (!opts.some((o) => o.v === v)) opts.push({ v, name: v, note: "Not served now", literalName: true }); + openProtoMenu(models, opts, [...d.models], (picked) => { + d.models = picked; + paintModels(); + update(); + }, "Models this limit counts", "sess-menu"); + }; days.oninput = () => { d.days = days.value; update(); }; hours.oninput = () => { d.hours = hours.value; update(); }; tokens.oninput = () => { d.tokens = tokens.value; update(); }; @@ -785,6 +833,7 @@ function gatewayLimitEditor(k) { save.disabled = true; const tk = limitTokens(d.tokens), c = limitCost(d.cost); const limit = tk || c ? { period: d.period, tokens: tk, cost: c, cacheReads: d.cacheReads } : null; + if (limit && d.models.length) limit.models = d.models; if (limit && d.period === "days") limit.days = limitDays(d.days); if (limit && d.period === "hours") limit.hours = limitHours(d.hours); // which one only when there are several: one is the key's only limit diff --git a/internal/gui/tests/fixtures/caller-keys.cjs b/internal/gui/tests/fixtures/caller-keys.cjs index b8292aa25..c01ad6676 100644 --- a/internal/gui/tests/fixtures/caller-keys.cjs +++ b/internal/gui/tests/fixtures/caller-keys.cjs @@ -154,7 +154,8 @@ function fixture(lang, theme, events, options = {}) { const usedOf = (l) => { const span = l.period === "hours" ? l.hours * 36e5 : (l.days || 1) * 864e5; return { period: l.period, days: l.days, hours: l.hours, start: new Date().toISOString(), reset: new Date(Date.now() + span).toISOString(), - calls: 0, tokens: 0, cost: 0, tokenLimit: l.tokens, costLimit: l.cost, tokensLeft: l.tokens, costLeft: l.cost, spent: false }; + calls: 0, tokens: 0, cost: 0, tokenLimit: l.tokens, costLimit: l.cost, tokensLeft: l.tokens, costLeft: l.cost, spent: false, + ...(l.models ? { models: l.models } : {}) }; }; // one of several by its index (#2227), as access.Update keeps them; // without one, the key's only limit diff --git a/internal/gui/tests/gateway-key-model-limit.test.cjs b/internal/gui/tests/gateway-key-model-limit.test.cjs new file mode 100644 index 000000000..7214b3a88 --- /dev/null +++ b/internal/gui/tests/gateway-key-model-limit.test.cjs @@ -0,0 +1,108 @@ +// A gateway key's limit on some models (zola_xynb on X): the limit +// editor's Models picks them in the app's menu, every model of a provider +// at once or one by one, and none picked is the whole key, as a limit set +// before there was a pick. The badge, the line and the tabs name what a +// limit counts. In every language, both engines, wide and narrow. +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { fixture } = require("./fixtures/caller-keys.cjs"); + +const src = fs.readFileSync(path.resolve(__dirname, "../assets/i18n.js"), "utf8"); +const I18N = new Function(src.slice(0, src.indexOf("\n};") + 3) + "; return I18N;")(); + +const day = 864e5; +const limits = () => ({ + laptop: { + limit: { period: "month", cost: 20, models: ["openai/*"] }, + used: { period: "month", start: new Date(Date.now() - 3 * day).toISOString(), reset: new Date(Date.now() + 20 * day).toISOString(), calls: 8, + tokens: 300000, cost: 4, costLimit: 20, tokensLeft: 0, costLeft: 16, spent: false, models: ["openai/*"] }, + }, +}); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of [1100, 420]) { + test(`${engine} ${lang} ${width}: a key's limit on some models`, async (t) => { + const tr = (k, vars = {}) => { + const s = lang === "en" ? k : I18N[lang][k]; + assert.equal(typeof s, "string", `${lang} has ${k}`); + return s.replace(/\{(\w+)\}/g, (_, v) => String(vars[v])); + }; + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(6000); + page.setDefaultNavigationTimeout(60000); + const events = [], errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", fixture(lang, "light", events, { lan: true, limits: limits(), groups: true })); + await page.goto("http://magpie.test/?view=gateway"); + await page.locator("#gatewayKeys .acc[data-key]").last().waitFor(); + const row = (id) => page.locator(`#gatewayKeys .acc[data-key="${id}"]`); + const sent = (action) => events.filter((e) => e.action === action); + const fits = async (what) => assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > window.innerWidth), false, what + " scrolls sideways"); + const tap = async (loc) => { + await page.mouse.move(width / 2, 400); + for (let i = 0; i < 20 && !(await loc.evaluate((e) => { const r = e.getBoundingClientRect(); return r.top >= 0 && r.bottom <= (document.querySelector("footer.foot")?.getBoundingClientRect().top ?? innerHeight); })); i++) { + await page.mouse.wheel(0, 120); + await page.waitForTimeout(50); + } + await loc.click(); + }; + + // the badge and the line name the models the limit counts + const badge = row("laptop").locator(".amodels.limit"); + assert((await badge.textContent()).includes("openai/*"), "badge says " + await badge.textContent()); + const line = row("laptop").locator(".key-limit"); + assert((await line.textContent()).startsWith("openai/*"), "line says " + await line.textContent()); + await fits("the rows"); + + // the editor's Models, the app's menu, never a native select + await badge.click(); + const ed = row("laptop").locator(".key-limit-ed"); + await ed.waitFor(); + assert.equal(await ed.locator("select").count(), 0); + const pick = ed.getByRole("button", { name: tr("Models this limit counts"), exact: true }); + assert.equal((await pick.textContent()).trim(), "openai/*"); + assert.equal(await pick.evaluate((e) => getComputedStyle(e).borderLeftStyle === getComputedStyle(e).borderRightStyle), true); + await fits("the editor"); + await tap(pick); + const menu = page.locator(".proto-menu"); + await menu.waitFor(); + assert.equal((await menu.locator(".pm-head").textContent()).trim(), tr("Models this limit counts")); + // a routing group isn't offered: a call is counted by the model that served it + assert.equal(await menu.getByText("group/coding", { exact: true }).count(), 0); + const item = (name) => menu.locator(".pm-item").filter({ has: page.getByText(name, { exact: true }) }); + assert.equal(await item(tr("Every {provider} model", { provider: "OpenAI" })).getAttribute("aria-checked"), "true"); + // one Relay model more, and the window as it was + await item("relay/m-mini").click(); + await page.keyboard.press("Escape"); + await menu.waitFor({ state: "detached" }); + assert.equal((await pick.textContent()).trim(), tr("{n} models", { n: 2 })); + assert.equal(await ed.locator(".munsaved").isHidden(), false, "a pick is unsaved until Save"); + await tap(ed.getByRole("button", { name: tr("Save"), exact: true })); + await ed.waitFor({ state: "detached" }); + assert.deepEqual(sent("limit-key").map((e) => e.body), [{ key: "laptop", limit: { period: "month", tokens: 0, cost: 20, cacheReads: false, models: ["relay/m-mini", "openai/*"] } }]); + assert((await badge.textContent()).includes(tr("{n} models", { n: 2 }))); + + // All models: the whole key again, sent with no models + await badge.click(); + await ed.waitFor(); + await tap(pick); + await menu.waitFor(); + await item(tr("All models")).click(); + await menu.waitFor({ state: "detached" }); + assert.equal((await pick.textContent()).trim(), tr("All models")); + await tap(ed.getByRole("button", { name: tr("Save"), exact: true })); + await ed.waitFor({ state: "detached" }); + assert.deepEqual(sent("limit-key").at(-1).body, { key: "laptop", limit: { period: "month", tokens: 0, cost: 20, cacheReads: false } }); + assert.equal((await badge.textContent()).includes("openai/*"), false); + assert.equal((await line.textContent()).includes(tr("{n} models", { n: 2 })), false); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/gwbudget/gwbudget.go b/internal/gwbudget/gwbudget.go index 3f1b587a4..eb97f7e57 100644 --- a/internal/gwbudget/gwbudget.go +++ b/internal/gwbudget/gwbudget.go @@ -34,6 +34,13 @@ type Limiter interface { Reserve(who access.Identity, body int64, model string, now time.Time) (release func(), refused Refusal) } +// Spender is a Limiter that can tell which of a key's limits of some +// models (access.Limit.Models) have nothing left: the gateway leaves +// their models out of the request's candidates (access.Identity.Spent). +type Spender interface { + Spent(who access.Identity, now time.Time) []access.SpentScope +} + var ( mu sync.Mutex limiters []*Limiter diff --git a/internal/provider/remote_key_limits.go b/internal/provider/remote_key_limits.go index 5770a8b53..a4a3dc093 100644 --- a/internal/provider/remote_key_limits.go +++ b/internal/provider/remote_key_limits.go @@ -82,6 +82,8 @@ type remoteKeyLimit struct { TokensLeft int64 `json:"tokensLeft"` CostLeft float64 `json:"costLeft"` Spent bool `json:"spent"` + // Models are the models a limit counts, none for the whole key + Models []string `json:"models"` } type remoteKeyRead struct { @@ -192,6 +194,13 @@ func keyLimitCard(a *remoteKeyAnswer) (*GatewayKeyLimit, []QuotaWindow) { var ws []QuotaWindow share := func(used, limit float64) float64 { return math.Min(100, math.Round(used/limit*1000)/10) } for _, x := range all { + if len(x.Models) > 0 { + // a limit of some models: a request for one of them is + // refused with a 429 that rests that model here, and the + // key's others are served; as a window it would read as the + // key's + continue + } reset := x.Reset if x.TokenLimit > 0 { ws = append(ws, QuotaWindow{Name: keyWindowName("Tokens", x.Period), Used: share(float64(x.Tokens), float64(x.TokenLimit)), ResetsAt: &reset,