usageapi

package
v0.1.4258 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 12 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package usageapi builds what magpie tells of its usage log: the Usage page's summary and its requests, a page at a time. The GUI's /api/usage and the gateway's /v1/magpie/usage answer the same JSON from here, so an app reading one reads the other.

Index

Constants

View Source
const (
	DayAgents = 12
	DayModels = 12
)

DayAgents is how many agents a day lists, the most tokens first, and DayModels how many of an agent's models: a page draws a card, not a table.

View Source
const PageSessions = 100

PageSessions is how many sessions Page lists: the Usage page draws none of them, and SessionCount says how many there are.

View Source
const SpanAll = "all"

SpanAll as SpanOf's from is every day there is a call for, up to date.

Variables

View Source
var Clients func() []Client

Clients are the agents magpie knows, for their names and logos: set by the GUI (internal/agent imports the gateway, which imports this). Unset, an agent is named by its id.

Functions

func FilterIn added in v0.1.1330

func FilterIn(r *http.Request) usage.Filter

FilterIn is FilterOf with the reader's zone, ZoneOf(r), which its Day and the period's days are read in.

func FilterOf

func FilterOf(q url.Values) usage.Filter

FilterOf is the filter a request's query names. A found routing group's model is taken as magpie keeps it (group/auto-…), as the menu offers it by its public auto/<model>, so either id picks the group's calls.

func PeriodOf

func PeriodOf(s string) usage.Period

PeriodOf is the period a ?period= names: a preset, or days picked as "2026-10-01..2026-10-07" (#1492); 30 days for anything else.

func Tilde

func Tilde(p string) string

Tilde is p with the home folder written ~.

func ZoneOf added in v0.1.1330

func ZoneOf(r *http.Request) *time.Location

ZoneOf is the reader's time zone, which the Usage page names in ?tz= (its browser's IANA name, as Intl gives it) for its days and hours to be the reader's: magpie web may be read from another zone than the computer's (Outvi V on Discord). This computer's when it names none or one unknown here.

Types

type Account

type Account struct {
	ID        string   `json:"id"`
	Name      string   `json:"name,omitempty"`
	Providers []string `json:"providers"`
}

Account is a subscription account the Account filter offers: its name, as the record keeps it and the filter asks by, the name the user gave it in magpie when there is one (plugins#310), and the providers it answered for, by name.

type Client

type Client struct{ ID, Name, Icon string }

Client is an agent as the usage JSON names it.

type Day

type Day struct {
	// From is the first day of the span asked for (SpanOf), the same as
	// Date for a day
	From  string `json:"from"`
	Date  string `json:"date"`  // YYYY-MM-DD, in the zone asked for; a span's last day
	Today string `json:"today"` // the zone's today
	DayTotals
	Agents     []DayAgent `json:"agents"`
	MoreAgents int        `json:"moreAgents,omitempty"`
	// Days are the days with calls up to Date, oldest first, over the
	// heatmap's span (usage.HeatmapWeeks)
	Days []DayCount `json:"days"`
}

Day is a day's usage.

func DayOf

func DayOf(date string, zone *time.Location) (Day, error)

DayOf is the day date (YYYY-MM-DD; "" for today) in zone (nil is this computer's). A day after today is an error.

func SpanOf

func SpanOf(from, date string, zone *time.Location) (Day, error)

SpanOf is the days from from to date, both included (YYYY-MM-DD; date "" is today, from "" is date alone and SpanAll the first day with calls), in zone (nil is this computer's), as DayOf is one day: a week's, a month's or all time's totals and the agents and models that made them. A day after today is an error, as is a from after date.

type DayAgent

type DayAgent struct {
	ID   string `json:"id"` // "" for calls that named no agent
	Name string `json:"name"`
	Icon string `json:"icon"`
	DayTotals
	Models []DayModel `json:"models"`
	// MoreModels is how many of its models DayModels left out; their
	// counts are in the agent's
	MoreModels int `json:"moreModels,omitempty"`
}

DayAgent is an agent's day, and its models'.

type DayCount

type DayCount struct {
	Date   string  `json:"date"`
	Calls  int     `json:"calls"`
	Tokens int     `json:"tokens"` // in, out and through the cache
	Cost   float64 `json:"cost"`
}

DayCount is a day that had calls.

type DayModel

type DayModel struct {
	Model        string `json:"model"`
	Provider     string `json:"provider"`     // its id
	ProviderName string `json:"providerName"` // as the Usage page names it
	Icon         string `json:"icon"`         // the provider's, as the Usage page draws it
	DayTotals
}

DayModel is a model's share of an agent's day.

type DayTotals

type DayTotals struct {
	Calls      int     `json:"calls"`
	Errors     int     `json:"errors"`
	Input      int     `json:"input"`
	Output     int     `json:"output"`
	CacheRead  int     `json:"cacheRead"`
	CacheWrite int     `json:"cacheWrite"`
	Reasoning  int     `json:"reasoning"`
	Cost       float64 `json:"cost"` // USD at the effective price, of the priced calls
	// Unpriced are calls with tokens but no known price, not in Cost
	Unpriced int `json:"unpriced"`
	// CacheUnknown is the prompt's tokens of calls whose vendor counts no
	// cache, which a hit rate leaves out (#3464)
	CacheUnknown int `json:"cacheUnknown"`
}

DayTotals are the counts of a day, an agent or a model.

type FeedResult

type FeedResult struct {
	Rows       []FeedRow `json:"rows"`
	Deleted    []Gone    `json:"deleted"`
	NextCursor string    `json:"next_cursor"`
	HasMore    bool      `json:"has_more"`
}

FeedResult is a read of the feed: the rows to upsert by id and the ids to drop (an id is in one of them), then the cursor to read on from.

func Feed

func Feed(cursor string, f usage.Filter, limit int, key string) (FeedResult, error)

Feed reads the feed. key narrows it to one gateway key's calls.

type FeedRow

type FeedRow struct {
	// ID is magpie's own, the same on every read and after a restart
	ID string `json:"id"`
	// Seq is the feed position of this version of the row
	Seq int64 `json:"seq"`
	// Origin: "gateway" (magpie served it), "session" (read from the agent's
	// own file; the gateway never saw it), "reported" (a client told
	// magpie), "" (a call magpie rejected itself, or its own test)
	Origin    string    `json:"origin"`
	Originals Originals `json:"original_ids"`
	Row
}

FeedRow is a row of the feed. Every row is one request: a call the gateway served, one read from an agent's file, one a client reported, or one another computer's magpie shared. None is a session or model summary.

func (FeedRow) Granularity

func (FeedRow) Granularity() string

Granularity is what one row is of. Always "request": the rows of the feed are single calls, never a session's or a model's total.

type Gone

type Gone struct {
	ID  string `json:"id"`
	Seq int64  `json:"seq"`
}

Gone is an id that is no row now: replaced by another row (a call from an agent's file the gateway turned out to have served) or taken out (a clear).

type Group

type Group struct {
	usage.Group
	Name string `json:"name"`
	Sub  string `json:"sub,omitempty"`  // models: the provider's name
	Icon string `json:"icon,omitempty"` // a real logo, or "generic" for an unknown client
}

Group is a usage.Group with what the UI needs to draw it.

type Ledger

type Ledger struct {
	CallerKeys []Group      `json:"callerKeys"`
	Period     usage.Period `json:"period"`
	Rows       []Row        `json:"rows"`
	Offset     int          `json:"offset"`
	Total      int          `json:"total"` // the rows the filter keeps, on every page
	// Series: the period by hour, day or week (Bucket), before the day filter
	Bucket string              `json:"bucket"`
	Series []usage.SeriesPoint `json:"series"`
	// By: the rows told apart by provider, agent, model and model at each
	// provider ("modelAt", named "model · provider"), the most tokens
	// first. The one by a dimension the filter has picked is of the rows
	// without that pick, so the others are still there to switch to.
	By      map[string][]Share `json:"by"`
	ChartBy map[string][]Share `json:"chartBy,omitempty"`
	Day     string             `json:"day,omitempty"`
	// Provider is the one provider the filter keeps, if any: every cost
	// of the page is of its calls alone, so a page whose currency is "by
	// provider" shows them in what that provider sells in
	Provider string `json:"provider,omitempty"`
	usage.Totals
	// Through and Direct: the rows the gateway served, and the rows read
	// from the agents' own session files, which it never saw. Totals is
	// the two together, so the page can show all three (#the usage report).
	Through usage.Totals `json:"through"`
	Direct  usage.Totals `json:"direct"`
	// Reported: the calls a client told magpie of through POST
	// /v1/magpie/usage/requests (#1874), which went straight to their vendor
	Reported usage.Totals `json:"reported"`
	// Agents, Providers and Purposes: those with calls in the period, for the filters
	Agents    []Named  `json:"agents"`
	Providers []Named  `json:"providers"`
	Purposes  []string `json:"purposes"`
	// Accounts: the subscription accounts that answered calls in the
	// period, for the Account filter (#557)
	Accounts []Account `json:"accounts"`
	// Computers: this one ("this", no name) and the others whose usage
	// sync brought (#542), for the filter; none while there are none
	Computers []Share `json:"computers,omitempty"`
	// Speeds: the models of the rows the filter keeps by the median speed
	// of their requests and of their wait for the first token (usage.ModelSpeed)
	Speeds []ModelSpeed `json:"speeds"`
	// SpeedMin is the fewest output tokens a request wrote to count in it
	SpeedMin int `json:"speed_min"`
	// BigWrite: the request that wrote the most to the cache, of the rows
	// the filter keeps
	BigWrite usage.BigWrite `json:"big_write"`
}

func LedgerPage

func LedgerPage(p usage.Period, f usage.Filter, offset, limit int) Ledger

LedgerPage is one page of the ledger: limit rows (100 when none is given, 500 at most) from offset.

func OwnPage

func OwnPage(l Ledger, key string) Ledger

OwnPage is l, a page filtered to the gateway key key's own calls, with its filter lists cut to what those calls had: they are drawn from every call in the period, and so would name the other keys, and the agents, providers and accounts only someone else's calls reached. The split by key is counted without the key's pick, so it is cut to the key's own share too, or it would tell a holder every other key's calls (#2521).

type Merged added in v0.1.1807

type Merged struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

Merged is a deleted provider merged into another.

type ModelSpeed

type ModelSpeed struct {
	usage.ModelSpeed
	Name string `json:"name"`
}

ModelSpeed is a usage.ModelSpeed with the name the page shows the model by.

type Named

type Named struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	Icon string `json:"icon"`
	// Deleted is when the provider was deleted, for one whose calls are
	// kept apart from a provider's added under its id since
	Deleted *time.Time `json:"deleted,omitempty"`
	// Merged are the deleted providers whose calls the user merged into
	// this one (provider.MergeDeleted), by the ids they are kept apart by
	Merged []Merged `json:"merged,omitempty"`
}

type Originals

type Originals struct {
	// RequestID: the id the vendor gave the request, or, in a row read from
	// an agent's file, the one the agent recorded (Claude Code's req_…)
	RequestID string `json:"request_id,omitempty"`
	// ResponseID: in a row read from an agent's file, the id of the response
	// object the agent recorded (Codex's resp_…). A call through the gateway
	// has ClientResponseID instead
	ResponseID string `json:"response_id,omitempty"`
	// ClientResponseID: the response object id the gateway sent its client,
	// which may be magpie's own when the reply was translated
	ClientResponseID string `json:"client_response_id,omitempty"`
	// MessageID: the id the agent's own file gives the call's message
	// (Claude Code's msg_…), in a row read from that file
	MessageID string `json:"message_id,omitempty"`
	// SessionID: the conversation, as the agent names it
	SessionID string `json:"session_id,omitempty"`
	// NativeSessionID: the agent's own session header when X-Magpie-Session
	// named the conversation instead
	NativeSessionID string `json:"native_session_id,omitempty"`
}

Originals are the ids the sources themselves gave a call, each told by who gave it. A key that is absent is one the source did not give: magpie invents none, and its own id of the row is FeedRow.ID.

type Row

type Row struct {
	usage.Row
	CallerKeyLabel string `json:"callerKeyLabel,omitempty"`
	AgentName      string `json:"agentName"`
	Icon           string `json:"icon"` // the agent's
	ProviderName   string `json:"providerName"`
	Access         string `json:"access,omitempty"` // known account/route type, independent of model maker
	PricingModel   string `json:"pricing_model,omitempty"`
	// ComputerName is the other computer a call was made on, shared through sync (#542)
	ComputerName string `json:"computerName,omitempty"`
	// Canceled: its agent canceled it before it was answered
	// (usage.Record.Canceled), which the page shows as no failure
	Canceled bool `json:"canceled,omitempty"`
}

Row is a usage.Row with the names the page shows it by.

type Share

type Share struct {
	usage.Share
	Name string `json:"name"`
	Icon string `json:"icon,omitempty"`
}

Share is a usage.Share with the name and logo the page shows it by.

type Usage

type Usage struct {
	usage.Summary
	Agents     []Group `json:"agents"`
	Models     []Group `json:"models"`
	Accounts   []Group `json:"accounts"`
	CallerKeys []Group `json:"callerKeys"`
	Path       string  `json:"path"`
}

func Page added in v0.1.1173

func Page(p usage.Period) Usage

Page is State with the top PageSessions sessions only, which is what the Usage page asks for: over a long history (Vantiboo1ean, ~750k requests) State sent the page every one of ~84k sessions (22 MB) and worked the summary out again for each refresh.

func PageIn added in v0.1.1330

func PageIn(p usage.Period, zone *time.Location) Usage

PageIn is Page with the period's days and the chart's hours in zone, the reader's (ZoneOf); nil is this computer's.

func State

func State(p usage.Period) Usage

State is the Usage page's summary of a period: what /api/usage and the gateway's GET /v1/magpie/usage answer.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL