Files
magpie/internal/usage/ledger.go
T
yetone cf6b82f70d usage: a Codex, Copilot or catalog-less relay call is priced at its maker's list price, as a Claude account's is (#224 Koohoko: on the Usage page only Claude models show a cost; gpt-6-astra and gpt-6-luna through Codex's ChatGPT account and gemini-3.8-flash and gpt-6-luna through Copilot show tokens and no cost, and the Codex row reads ≈$153+) — the Usage page and the Requests list price a call by the models.dev ids of the provider it went to (Provider.Catalog), and only the Claude account had one (anthropic): Codex's and Copilot's accounts, like Grok's, WorkBuddy's and a relay added without a catalog, have none, so every call they served was counted unpriced although models.dev lists all these models (openai: gpt-6-astra $10/$50, gpt-6-luna $0.1/$0.5; google: gemini-3.8-flash $0.75/$3.75, per million, in the cached catalog). A call is now priced by its provider's catalogs first, as before, else by the first maker among the vendor presets that lists the model (the same makerCatalogs the reasoning levels borrow from), and a call whose provider has gone since is priced by its maker too. The model is matched by its own key first, then without a path or case (a relay's openai/gpt-6-astra is gpt-6-astra), a Bedrock geography, a (variant) or :tag, as the reasoning levels already are (new catalog.PricedBy, Provider.ListPrice, provider.MakerPrice); a model no maker lists (a Cursor or Kiro alias, a relay's own name) stays unpriced and keeps the + as before, no price is made up. Both the Usage summary and the Requests ledger go through the one pricer, so they agree. Tested with a new TestSubscriptionListPrice: calls to codex (gpt-6-astra, gpt-6-luna), copilot (gemini-3.8-flash, gpt-6-luna), claude (claude-opus-5-5) and a relay with no catalog (openai/gpt-6-astra, mystery-1) each get their maker's price in the ledger and the summary, mystery-1 alone unpriced (fails on main: all seven unpriced); TestLedger and TestSummarize unchanged. go build -tags nogui (and GOOS=linux, GOOS=windows), go test -tags nogui ./... pass (TestAddSecondOfPreset failed once in the full run with a fourth provider and passes on its own and in the package run; it doesn't touch pricing). Not tried against the reporter's usage log or in the GUI; the Sessions page's own pricing (internal/sessions) was not looked at.
2026-09-29 23:52:32 +08:00

160 lines
4.6 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 list 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 list 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 each call's list price, once per provider and model: 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{}
all := provider.All()
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.MakerPrice(r.Model)
for _, p := range all {
if p.ID == r.Provider {
v, ok = p.ListPrice(r.Model)
break
}
}
if ok {
pr = &v
}
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 list 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()
}