quota: what is left of every subscription, plan and key balance, for scripts and agents — magpie quota [<provider>] [--json] prints each window's use and remaining percent and when it starts again, and each key's balance; the gateway answers the same at GET /v1/magpie/quotas (only to this machine, as it names the accounts), so an agent can pick where to send its work (#85)
This commit is contained in:
+1
-7
@@ -161,13 +161,7 @@ type accountRow struct {
|
||||
Lapsed string `json:"lapsed,omitempty"` // its sign-in has to be made again
|
||||
}
|
||||
|
||||
type quotaSpan struct {
|
||||
Name string `json:"name"`
|
||||
Used float64 `json:"used"` // percent
|
||||
Remaining float64 `json:"remaining"` // percent
|
||||
ResetsAt *time.Time `json:"resetsAt,omitempty"`
|
||||
Display string `json:"display,omitempty"`
|
||||
}
|
||||
type quotaSpan = provider.QuotaSpan
|
||||
|
||||
// accountRows asks each agent's accounts for their allowance at once; what
|
||||
// was asked less than a minute ago comes from magpie's cache.
|
||||
|
||||
@@ -168,6 +168,7 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("GET /v1/models", s.models)
|
||||
mux.HandleFunc("GET /models", s.models)
|
||||
mux.HandleFunc("GET /v1/models/{id}", s.model)
|
||||
mux.HandleFunc("GET /v1/magpie/quotas", s.quotas)
|
||||
mux.HandleFunc("POST /v1/chat/completions", s.handle(provider.Chat))
|
||||
mux.HandleFunc("POST /chat/completions", s.handle(provider.Chat))
|
||||
mux.HandleFunc("POST /v1/responses", s.handle(provider.Responses))
|
||||
@@ -187,7 +188,22 @@ func (s *Server) Handler() http.Handler {
|
||||
|
||||
func (s *Server) info(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]any{"name": "magpie", "version": Version, "models": len(provider.Catalog()),
|
||||
"apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1beta/models/{model}:generateContent"}})
|
||||
"apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1beta/models/{model}:generateContent", "/v1/magpie/quotas"}})
|
||||
}
|
||||
|
||||
// quotas is what is left of every subscription, plan and key magpie has,
|
||||
// for an agent choosing where to send its work (magpie quota --json is the
|
||||
// same). It names the accounts and their balances, so it answers only on
|
||||
// this machine, when the gateway listens beyond it too.
|
||||
func (s *Server) quotas(w http.ResponseWriter, r *http.Request) {
|
||||
host, _, _ := net.SplitHostPort(r.RemoteAddr)
|
||||
if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() {
|
||||
writeError(w, provider.Chat, http.StatusForbidden, "magpie's quotas are only told to this machine")
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second)
|
||||
defer cancel()
|
||||
writeJSON(w, 200, map[string]any{"object": "list", "data": provider.QuotaReport(ctx, time.Now())})
|
||||
}
|
||||
|
||||
func modelObject(e provider.Entry) map[string]any {
|
||||
|
||||
@@ -73,11 +73,6 @@ func usageRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/usage/quotas", func(rw http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second)
|
||||
defer cancel()
|
||||
balances := make(chan []provider.SubscriptionQuota, 1)
|
||||
plans := make(chan []provider.SubscriptionQuota, 1)
|
||||
go func() { balances <- provider.KeyBalances(ctx) }()
|
||||
go func() { plans <- provider.PlanQuotas(ctx) }()
|
||||
out := append(provider.SubscriptionUsage(ctx), <-plans...)
|
||||
writeJSON(rw, append(out, <-balances...))
|
||||
writeJSON(rw, provider.Quotas(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Quotas is what is left everywhere magpie can ask: the signed-in
|
||||
// subscriptions' windows, the plans bought with a key, and the keys'
|
||||
// balances, as the Usage page shows them. The vendors are asked at once;
|
||||
// what doesn't answer before ctx ends comes back with an error.
|
||||
func Quotas(ctx context.Context) []SubscriptionQuota {
|
||||
subs, plans, balances := quotas(ctx)
|
||||
return append(append(subs, plans...), balances...)
|
||||
}
|
||||
|
||||
func quotas(ctx context.Context) (subs, plans, balances []SubscriptionQuota) {
|
||||
b := make(chan []SubscriptionQuota, 1)
|
||||
p := make(chan []SubscriptionQuota, 1)
|
||||
go func() { b <- KeyBalances(ctx) }()
|
||||
go func() { p <- PlanQuotas(ctx) }()
|
||||
subs = SubscriptionUsage(ctx)
|
||||
return subs, <-p, <-b
|
||||
}
|
||||
|
||||
// Quota is one account's or key's allowance as magpie quota --json and
|
||||
// the gateway's GET /v1/magpie/quotas tell it, for an agent choosing
|
||||
// where to send its work: Provider is the first part of the models'
|
||||
// ids (provider/model) for a key's plan or balance, the agent for a
|
||||
// subscription.
|
||||
type Quota struct {
|
||||
Provider string `json:"provider"`
|
||||
Name string `json:"name"`
|
||||
Kind string `json:"kind"` // subscription, plan (bought with a key) or balance (a key's money)
|
||||
Plan string `json:"plan,omitempty"`
|
||||
User string `json:"user,omitempty"`
|
||||
Windows []QuotaSpan `json:"windows"`
|
||||
Balance string `json:"balance,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// QuotaSpan is one window of an allowance: how much of it is used and
|
||||
// left, in percent, and when it starts again.
|
||||
type QuotaSpan struct {
|
||||
Name string `json:"name"`
|
||||
Used float64 `json:"used"`
|
||||
Remaining float64 `json:"remaining"`
|
||||
ResetsAt *time.Time `json:"resetsAt,omitempty"`
|
||||
Display string `json:"display,omitempty"` // the vendor's own count, "1.2k / 3k"
|
||||
}
|
||||
|
||||
// QuotaReport is Quotas as Quota, the reset times made absolute from now.
|
||||
func QuotaReport(ctx context.Context, now time.Time) []Quota {
|
||||
subs, plans, balances := quotas(ctx)
|
||||
out := []Quota{}
|
||||
for _, g := range []struct {
|
||||
kind string
|
||||
qs []SubscriptionQuota
|
||||
}{{"subscription", subs}, {"plan", plans}, {"balance", balances}} {
|
||||
for _, q := range g.qs {
|
||||
r := Quota{Provider: q.Provider, Name: q.Name, Kind: g.kind, Plan: q.Plan, User: q.User,
|
||||
Windows: []QuotaSpan{}, Balance: q.Balance, Error: q.Error}
|
||||
for _, w := range q.Windows {
|
||||
s := QuotaSpan{Name: w.Name, Used: w.Used, Remaining: max(0, 100-w.Used), ResetsAt: w.ResetsAt, Display: w.Display}
|
||||
if s.ResetsAt == nil && w.ResetSecs > 0 {
|
||||
t := now.Add(time.Duration(w.ResetSecs) * time.Second)
|
||||
s.ResetsAt = &t
|
||||
}
|
||||
r.Windows = append(r.Windows, s)
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -67,6 +67,7 @@ const usage = `magpie — one place to pick every agent's model
|
||||
|
||||
magpie serve run the gateway alone (the app runs it too)
|
||||
magpie usage [today|7d|30d|all] tokens and cost per agent and model (30d)
|
||||
magpie quota [<provider>] [--json] what is left of every subscription, plan and key balance
|
||||
magpie sync refresh the model catalog and vendor model lists
|
||||
magpie agents list every supported agent
|
||||
magpie update [check] install the newest release (check: only say if there is one)
|
||||
@@ -170,6 +171,8 @@ func run(args []string) error {
|
||||
return accountsCmd(args)
|
||||
case "usage":
|
||||
return usageCmd(args)
|
||||
case "quota", "quotas":
|
||||
return quotaCmd(args)
|
||||
case "update":
|
||||
return updateCmd(args)
|
||||
case "library", "lib":
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
const quotaUsage = `usage: magpie quota [<provider>…] [--json]
|
||||
what is left of every subscription, plan and key magpie has: each window's use and
|
||||
when it starts again, and each key's balance, asked of the vendors now (or less than
|
||||
a minute ago). --json is for scripts and agents; the gateway answers the same at
|
||||
GET http://127.0.0.1:3425/v1/magpie/quotas`
|
||||
|
||||
// quotaCmd: magpie quota [<provider>…] [--json]
|
||||
func quotaCmd(args []string) error {
|
||||
asJSON := false
|
||||
var only []string
|
||||
for _, a := range args[1:] {
|
||||
switch a {
|
||||
case "--json", "-j":
|
||||
asJSON = true
|
||||
case "help", "-h", "--help":
|
||||
fmt.Println(quotaUsage)
|
||||
return nil
|
||||
default:
|
||||
only = append(only, strings.ToLower(a))
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
qs := []provider.Quota{}
|
||||
for _, q := range provider.QuotaReport(ctx, time.Now()) {
|
||||
if len(only) == 0 || quotaMatches(q, only) {
|
||||
qs = append(qs, q)
|
||||
}
|
||||
}
|
||||
if asJSON {
|
||||
b, _ := json.MarshalIndent(qs, "", " ")
|
||||
fmt.Println(string(b))
|
||||
return nil
|
||||
}
|
||||
if len(qs) == 0 {
|
||||
if len(only) > 0 {
|
||||
return fmt.Errorf("no subscription, plan or key balance of %s", strings.Join(only, ", "))
|
||||
}
|
||||
fmt.Println(muted.Render("nothing to tell ·"), "a signed-in subscription, a coding plan or a key whose vendor tells its balance shows up here")
|
||||
return nil
|
||||
}
|
||||
width := 0
|
||||
for _, q := range qs {
|
||||
width = max(width, len([]rune(quotaTitle(q))))
|
||||
}
|
||||
for _, q := range qs {
|
||||
line := fmt.Sprintf("%-*s %s", width, quotaTitle(q), muted.Render(fmt.Sprintf("%-12s", q.Kind)))
|
||||
for _, w := range q.Windows {
|
||||
line += " " + quotaCell(w)
|
||||
}
|
||||
if q.Balance != "" {
|
||||
line += " " + bold.Render(q.Balance) + muted.Render(" left")
|
||||
}
|
||||
if q.Error != "" {
|
||||
line += " " + muted.Render(q.Error)
|
||||
}
|
||||
fmt.Println(line)
|
||||
}
|
||||
fmt.Println(faint.Render(" % is how much of a window is used · ↻ when it starts again · --json for scripts, or GET /v1/magpie/quotas on the gateway"))
|
||||
return nil
|
||||
}
|
||||
|
||||
// quotaTitle is a quota's line head: its provider, plan and account.
|
||||
func quotaTitle(q provider.Quota) string {
|
||||
t := q.Provider
|
||||
if q.Plan != "" {
|
||||
t += " · " + q.Plan
|
||||
}
|
||||
if q.User != "" {
|
||||
t += " · " + q.User
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func quotaMatches(q provider.Quota, only []string) bool {
|
||||
for _, o := range only {
|
||||
if strings.EqualFold(q.Provider, o) || strings.EqualFold(q.Name, o) || strings.EqualFold(q.Kind, o) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
Reference in New Issue
Block a user