Files
magpie/internal/usage/ledger.go
T
Comic Chang 901ee08280 Count usage at the configured provider/model price (#278)
Magpie reports models.dev's list price for every call. That is the right
number for a vendor's own key and the wrong one for a provider that
resells or exposes a model at a different tariff, and it leaves a model the
catalogue does not list with no cost at all — a provider's own /models
gives ids, not economics.

  magpie model price relay-a/gpt-5.5 0.12,1.20,0.01,0.15
  magpie model price relay-a/* 0.12,1.20,0.01,0.15
  magpie model price relay-a/gpt-5.5 --reset
  magpie model prices

Absolute USD per million tokens. All four parts are required: a price
missing one would understate the rest of every call, and a hand-edited file
that left a part out would bill it at zero, so each part is a pointer and
the setter refuses a price that is negative, NaN or infinite, naming the
part at fault. Zero stays distinct throughout — a model served at no cost
has a price, not the absence of one. A `<provider>/*` entry covers every
model of that provider and an exact entry wins over it; --reset removes
only the exact entry and says so when a provider-wide one is still in
force.

The order a price is looked for in is the price for this model, then
`<provider>/*`, then the provider's own catalogue, then models.dev for the
maker. A price is a provider's tariff, not the model's: the same model
through two providers has two prices, and each keeps its own. A provider is
resolved by its id, or by an id it was renamed from, and never by its
display name — Find answers those too, and a record naming one was counted
at another provider's price.

provider.EffectivePrice is the one lookup every cost caller shares, so the
usage ledger and a session's totals both go through it, and a session
naming a model bare is still priced at its maker's list price, which is a
different question from what one provider charges. catalog.PriceOf and
PricedBy keep returning the models.dev price for anything wanting an
unbiased number. The background-task pickers (draw, search, vision) still
rank by catalogue price: they choose which model answers, not what a call
is reported to cost.

Unlike every other per-model preference this does not call
catalog.Touched. What a call costs is not what an agent picks a model by,
and the model lists magpie keeps in the agents' own files are not its to
rewrite over a number in a cost report. A rename moves the prices with it
through the walk #288 adds, so nothing here has to say so, and an id
recorded before a rename still resolves.

Validation happens where the entry is written, not in Save: one hand-edited
bad price in the file must not make saving a theme or a window size fail. A
price for a model the provider does not serve is refused the way
`magpie model name` refuses the same id, since it is a price that never
applies and nothing reports it as dead; a removal is exempt, so an entry
left for a model that has since gone can still be taken away.
2026-09-30 20:31:11 +08:00

156 lines
4.7 KiB
Go

package usage
// The ledger: every call of a period, one row each, newest first — what
// the agent asked for, where it went, what model answered, the tokens and
// what they cost at the effective price — to set beside a vendor's own bill.
import (
"encoding/csv"
"io"
"slices"
"strconv"
"strings"
"time"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
// Row is one call as the ledger lists it.
type Row struct {
Record
// Cost is the call's price in USD, when its model's is known
// (Priced); Swapped: the reply named another model than Model
Cost float64 `json:"cost"`
Priced bool `json:"priced"`
Swapped bool `json:"swapped,omitempty"`
}
// Filter narrows the ledger: to one agent (its id, as AgentOf gives it),
// to the failed calls, and to the rows whose models, provider, host or
// session hold Query (any case).
type Filter struct {
Agent string
Failed bool
Query string
}
func (f Filter) keeps(r Record) bool {
if f.Agent != "" && AgentOf(r.Agent) != f.Agent {
return false
}
if f.Failed && r.Status < 400 {
return false
}
if q := strings.ToLower(strings.TrimSpace(f.Query)); q != "" {
return slices.ContainsFunc([]string{r.Requested, r.Model, r.Served, r.Provider, r.Host, r.Session, r.Effort}, func(s string) bool {
return strings.Contains(strings.ToLower(s), q)
})
}
return true
}
// Since is when the period began, as of now; zero for all.
func (p Period) Since(now time.Time) time.Time {
day := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
switch p {
case Today:
return day
case Week:
return day.AddDate(0, 0, -6)
case Month:
return day.AddDate(0, 0, -29)
}
return time.Time{}
}
// Ledger is the calls of a period that the filter keeps, newest first,
// with their sum, and the agents that made any call in the period (their
// ids, for a filter to offer).
func Ledger(p Period, f Filter) (rows []Row, sum Totals, agents []string) {
return ledger(p.Since(time.Now()), f, Load(time.Time{}))
}
func ledger(since time.Time, f Filter, recs []Record) (rows []Row, sum Totals, agents []string) {
renamed := provider.Renamed()
priceOf := pricer()
rows = []Row{}
agents = []string{}
for i := len(recs) - 1; i >= 0; i-- {
r := recs[i]
if !since.IsZero() && r.Time.Before(since) {
continue
}
if id, ok := renamed[r.Provider]; ok {
r.Provider = id
}
if a := AgentOf(r.Agent); !slices.Contains(agents, a) {
agents = append(agents, a)
}
if !f.keeps(r) {
continue
}
pr := priceOf(r)
sum.add(r, pr)
row := Row{Record: r, Swapped: r.Served != "" && Swapped(r.Model, r.Served)}
if pr != nil && r.Input+r.Output > 0 {
row.Cost, row.Priced = pr.Cost(r.Input, r.Output, r.CacheRead, r.CacheWrite), true
}
row.Agent = AgentOf(r.Agent)
rows = append(rows, row)
}
slices.Sort(agents)
return rows, sum, agents
}
// pricer looks up what each call cost the user, once per provider and model:
// the price they set for it, else its provider's models.dev entry's, else its
// maker's (a subscription's, #224).
func pricer() func(Record) *catalog.Price {
prices := map[string]*catalog.Price{}
return func(r Record) *catalog.Price {
k := r.Provider + "/" + r.Model
if pr, ok := prices[k]; ok {
return pr
}
var pr *catalog.Price
v, ok := provider.EffectivePrice(r.Provider, r.Model)
if ok {
pr = &v
} else {
catalog.Missing() // models.dev may list it by now
}
prices[k] = pr
return pr
}
}
// CSVHeader is the ledger's columns, as WriteCSV writes them.
var CSVHeader = []string{"time", "agent", "requested_model", "provider", "host", "model", "served_model", "swapped",
"effort", "input_tokens", "output_tokens", "cache_write_tokens", "cache_read_tokens", "reasoning_tokens",
"cost_usd", "duration_ms", "ttft_ms", "status", "error", "session", "kind"}
// WriteCSV writes rows as CSV, a header first: times in RFC 3339 with
// their offset, the cost in USD at the effective price (empty when unknown), error
// "true" for a call answered with a status of 400 or more.
func WriteCSV(w io.Writer, rows []Row) error {
cw := csv.NewWriter(w)
cw.Write(CSVHeader)
n := strconv.Itoa
for _, r := range rows {
cost := ""
if r.Priced {
cost = strconv.FormatFloat(r.Cost, 'f', 6, 64)
}
ttft := ""
if r.TTFT > 0 {
ttft = strconv.FormatInt(r.TTFT, 10)
}
cw.Write([]string{r.Time.Format(time.RFC3339), r.Agent, r.Requested, r.Provider, r.Host, r.Model, r.Served,
strconv.FormatBool(r.Swapped), r.Effort, n(r.Input), n(r.Output), n(r.CacheWrite), n(r.CacheRead), n(r.Reasoning),
cost, strconv.FormatInt(r.Millis, 10), ttft, n(r.Status), strconv.FormatBool(r.Status >= 400), r.Session, r.Kind})
}
cw.Flush()
return cw.Error()
}