Documentation
¶
Overview ¶
Package usage keeps the token count of every call the gateway serves, so magpie can show what each agent and model consumed and roughly what it cost. Records go to one JSON-lines file next to providers.json. Metadata leaves the machine only when OTLP export is explicitly enabled.
Index ¶
- Constants
- Variables
- func AgentOf(ua string) string
- func Append(r Record)
- func CanceledBy(status int, err string) bool
- func ClineServing(sent, served string) bool
- func CodexModelEffort(p Period) map[string][]sessions.ModelEffort
- func CodexUsed() []string
- func CodexUsedBy(keyID string) []string
- func Computer() (id, name string)
- func CountsNoCache(provider string) bool
- func DecodeOf(out, reasoning int, ms, ttft, firstText, flow int64, firstReasoning ...int64) (tokens int, w int64)
- func DecodeWindow(out int, ms, ttft int64) int64
- func DropAllShared()
- func DropShared(computer, day string)
- func EachGatewaySession(nativeKeys map[string]bool, each func(GatewaySession) bool)
- func FeedPath() string
- func ForgetPages() bool
- func FormatCost(amountUSD float64, currency string, rate float64) string
- func FormatCredits(t Totals) string
- func GatewaySessionWindow(since time.Time) ([]GatewaySession, []GatewayDayUsage)
- func GatewaySessionWindowExcept(since time.Time, nativeKeys map[string]bool) ([]GatewaySession, []GatewayDayUsage)
- func GeminiServing(sent, served string) bool
- func GrokServing(sent, served string) bool
- func GroupRouted(sent, served string) bool
- func HistoricalWindowHolds(cards []provider.SubscriptionQuota, hist []provider.QuotaHistory, ...) []provider.SubscriptionQuota
- func HitPct(h float64) string
- func IngestReported(recs []Record) ([]bool, error)
- func IsAgent(id string) bool
- func IsLibrary(id string) bool
- func KeepOutsideCallsRead(ctx context.Context)
- func KeepShared(d SharedDay) error
- func KeySpent(keyID string, start time.Time) float64
- func LastSeen(agent string) time.Time
- func Ledger(p Period, f Filter) (rows []Row, sum Totals, agents []string)
- func ListedAs(prov, model, served string) bool
- func ListedForTest(lists map[string]map[string]string) (restore func())
- func LogBackup() ([]byte, int, error)
- func LogVersion() (uint64, bool)
- func MagpieAlias(id string) bool
- func MergeLog(gz []byte) (int, error)
- func ModelAtKey(provider, model string) string
- func NewCoster() func(Record) (float64, bool)
- func NewPricer() func([]Record) Totals
- func Observe(o Observer) (remove func())
- func OthersDir() string
- func OwnDays(since time.Time) map[string][]SharedCall
- func Path() string
- func Pricer() func(Record) *catalog.Price
- func PurposeKinds() map[string]PurposeKind
- func PurposeOf(kind string) string
- func ReadAhead()
- func ReadOutsideCalls(ctx context.Context)
- func RegionTail(sent, served string) bool
- func RelayRenamed(sent, served string) bool
- func ReleaseMatchScratch()
- func ReleaseScratch()
- func ReportedAs(ua string) string
- func ResetFeedForTest()
- func SameSpelled(sent, served string) bool
- func Saw(agent string)
- func ServeObservers() (stop func())
- func ServingName(sent, served string) bool
- func SharedKept() []string
- func SourceOf(r Row) string
- func Summaries(p Period) (Summary, Summary)
- func Swapped(sent, served string) bool
- func ValidComputer(id string) bool
- func VendorAlias(sent, served string) bool
- func Visit(since time.Time, fn func(Record))
- func VisitSessions(since time.Time, sessions []string, fn func(Record))
- func WithWindowHolds(qs []provider.SubscriptionQuota, now time.Time) []provider.SubscriptionQuota
- func WriteCSV(w io.Writer, rows []Row) error
- func Zone(name string) *time.Location
- type BigWrite
- type Bodies
- type Cursor
- type Day
- type FeedError
- type FeedItem
- type FeedPage
- type FeedRequest
- type Filter
- type GatewayDayUsage
- type GatewayModel
- type GatewaySession
- type Group
- type Heatmap
- type Known
- type Ledgered
- type ModelSpeed
- type Observer
- type OwnShare
- type Part
- type Period
- type Point
- type PurposeKind
- type Record
- func (r Record) Account() string
- func (r Record) Answered() bool
- func (r Record) ByMagpie() bool
- func (r Record) Canceled() bool
- func (r Record) CostAt(p catalog.Price) float64
- func (r Record) Decode() (tokens int, w int64)
- func (r Record) Failed() bool
- func (r Record) FailedTry() bool
- func (r Record) IsProbe() bool
- func (r Record) IsRejected() bool
- func (r Record) IsReported() bool
- func (r Record) LostRequest() bool
- func (r Record) RetriedRequest() bool
- type Request
- type RequestPage
- type Row
- type SeriesPoint
- type Share
- type SharedCall
- type SharedDay
- type Summary
- type Totals
- type UpParts
- type Via
- type ViaIndex
- type Watch
Constants ¶
const ( FeedStart = "start" FeedNow = "now" )
Cursor words that are no cursor: Start reads the whole ledger as it is now, Now reads nothing and gives the cursor to read what comes after.
const ( SourceGateway = "through" SourceSession = "direct" // SourceReported is the third: the calls a client reported through // POST /v1/magpie/usage/requests (#1874), which went straight to their // vendor. Record.Source and Row.Source spell it the same, as does via=. SourceReported = "reported" )
SourceGateway and SourceSession are the two sources a request row is of, which Row.Source spells "" and "log": the calls magpie's own gateway served, and the ones read from the agents' own session files, which it never saw. They are the requests page's source cells, and the values its via= takes.
const ( CodexWindowMs = 1000 CodexBodyTokens = 100 )
A Codex turn of one call read from its session file is timed by the turn's time_to_first_token_ms and its end, and that window can be one network push, not the writing: Fallmonkey on Discord had a reply whose first token came at 6.8 s, the model working, and the rest 0.2 s later in one go, read as thousands of tok/s. Such a row's window after the first token tells a speed only when it is CodexWindowMs or more and its tokens (its answer, for one that reasoned) CodexBodyTokens or more; else it tells the least it wrote at over the whole turn (Row.Floor). app.js's ledDecode and ledFloor_ have the same.
const ( KindAgentSummary = "agent_summary" KindAutoMode = "auto_mode_check" InferredSuffix = "_inferred" )
KindAgentSummary and KindAutoMode are the kinds of Claude Code's sub-agent progress summary and its auto mode classifier; InferredSuffix follows one that was told by the request's content.
const ( MinDecodeMs = 100 MaxDecodeSpeed = 10000 )
A reply's speed is its output tokens over its decode window, the ms from its first content to its end (#196; one that reasoned, DecodeOf); a window counts only when it timed the writing (#731). One that is shorter than MinDecodeMs, or over which the tokens would have come faster than MaxDecodeSpeed a second, didn't: the reply came in one burst at its end, written before the window opened — a turn that is one big tool call from Gemini, whose functionCall comes whole, has its first content a millisecond before its end, and 8264 tokens in 1 ms read 8,264,000 tok/s. Such a reply tells no speed and is left out of the summed one, where its tokens over next to no time would lift everyone's; its TTFT still counts. The bounds are wide of any real stream: the fastest vendors write a few thousand tokens a second, and a tenth of a second is the least a stream's timing tells anything by. routing/client.js's speedOf has the same.
const ( ThinkPace = 20 HeldWindowMs = 1000 )
HeldShare, ThinkPace and HeldWindowMs tell a reply held back and let go in a burst (DecodeOf): its content came in under a quarter of its window, its answer at over 20 times the pace its reasoning came, or its window was under a second and under a quarter of the wait before it. routing/client.js's decodeOf and usage/page.js's ledDecode have the same.
const AgentCanceled = "the agent canceled the request"
AgentCanceled is what the usage log says of a request the agent canceled before it was answered (the gateway's canceled), with the status StatusCanceled.
const BodyCut = "\n… (cut here by magpie)"
BodyCut ends a body the gateway captured only the start of.
const CanceledErrType = "agent_canceled"
CanceledErrType is the error type a call its agent canceled is logged with (CanceledBy), as LoopErrType is a looping reply's: the record keeps that it was the agent's cancel, whatever its message says.
const HeatmapWeeks = 53
HeatmapWeeks is how many weeks the heatmap shows, this one the last.
const KindKeepalive = "cache_keepalive"
KindKeepalive is the Kind of a cache keepalive ping a plugin sent on its own (Devin's, plugins#592): the conversation's request sent again with max_tokens 1 so the vendor's prompt cache outlives its 5 minutes.
const KindMCP = "mcp"
KindMCP is an MCP tool call's Kind, the purpose the request log picks them by.
const LoopErrType = "reply_loop"
LoopErrType is a record's ErrType for a reply magpie ended because the model was stuck in a loop (#1359), told apart from what vendors call their errors.
const MinRankTokens = 100
MinRankTokens is the fewest output tokens a request has to write to count in the model speed ranking: a short reply is nearly all wait, and its speed and first token say little about the model. The ranking's tooltip says the same number.
const NoCallerKey = "none"
NoCallerKey is the "callerKey" of a call that carried no gateway key: one that wasn't counted against any, as this computer's own agents' are, or that came before keys were recorded. As a filter it keeps only those.
const OtherComputers = "others"
OtherComputers is the Filter.Computer of every other computer's calls.
SharedDays is how many days of calls a computer keeps on the server.
const SourceMCP = "mcp"
SourceMCP is Record.Source for an agent's call to a tool of one of magpie's own MCP servers: the gateway's (image, vision, web search, plugin tools, the MCP hub) and the Magpie Image server an agent runs (ferock on Discord). Its Kind is KindMCP, Requested the tool's name as it was called, Host the server's, Provider and Model what the tool used when it used a model, Millis how long the call took and Error what a failed one said. Its arguments are never kept. It rides the probes' lane: listed on the request log, told apart there, counted nowhere, as the model requests the tool made are rows of their own that are.
const SourceProbe = "probe"
SourceProbe is Record.Source for a request magpie sent a provider on its own, outside any agent's turn (probelog): the editor's Test, Detect APIs, a model list's refresh. Its Kind says which (probelog.KindTest, KindDetect, KindList). Such a row is listed on the request log, told apart there, and counted nowhere: no total, cost, chart, group, budget, window hold or observer reads it. The log's index keeps it apart from the calls (logSnapshot.probes) so a reader of those never meets it.
const SourceSearch = "search"
SourceSearch is Record.Source for one ask of a search API (Tavily, Brave, …) by a web search magpie ran (cybercaius on Discord: which search API each search used couldn't be seen). Its Kind is "web_search", Agent the agent the search was for, Requested the API's name, Host where it was asked, ProviderKeyID and ProviderKeyName the key (by a hash and masked), Millis how long it took, Status the API's when it refused the key, and Error what a failed one said ("found nothing" for an answer with no page). The query is never kept. It rides the probes' lane as an MCP call does: listed on the request log and counted nowhere, since it has no tokens and is no model's.
const StatusCanceled = 499
StatusCanceled is the status a request the agent canceled is logged with: nginx's 499, the client closed the request.
const ThisComputer = "this"
ThisComputer is the Filter.Computer of the calls made here.
const UnknownProvider = "session-unknown"
UnknownProvider groups local session calls without claiming a supplier. Recorded provider IDs and matched creator identities stay in their own fields.
Variables ¶
var Agents func() []Known
Agents lists the agents magpie knows. Package agent sets it from each agent's own description, so they are listed in one place only.
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", "provider_key_id", "provider_key_name", "provider_account", "route_id",
"request_id", "endpoint", "error_message", "error_type", "source", "rejected", "session_provider", "session_account", "session_official_login", "caller_key_id", "caller_key_name", "response_id", "upstream",
"cache_write_5m_tokens", "cache_write_1h_tokens", "tries", "handed_on", "tier_asked", "tier_sent", "tier_served", "upstream_stop", "credits"}
CSVHeader is the ledger's columns, as WriteCSV writes them.
var Clock = time.Now
Clock is the time the periods are read by: when today began, the hours or days of the chart, the day a cached answer is for. A variable for the tests, which hold it still so that midnight never falls between a call they log and the period they ask for.
var Dimensions = []string{"provider", "agent", "model", "modelAt", "callerKey"}
Dimensions are what calls are told apart by: the provider they went to, the agent that made them, the model, the model at the provider it went to ("modelAt"), so one model's speed at each provider can be compared (inaction on Discord), and the gateway key that made them ("callerKey"), so the clients a shared gateway serves can be compared (#2521).
var FeedKeep = 30 * 24 * time.Hour
FeedKeep is how long a tombstone is kept, and so how long a client may be away and still resume. A var for the tests.
var FloorAgents = map[string]bool{"claude": true, "claude-desktop": true, "codex": true}
FloorAgents are the agents whose session files time a call from what asked for it to its reply's end, never from inside it: Claude Code's and Claude Desktop's from the line that asked, written before it was sent; Codex's call in a turn of several from what the model had last been given before the call's first output item, to its last (sessions' codexTiming). Their calls' tokens over that time are a floor of how fast the reply wrote. OpenCode's isn't checked against real sessions, so it tells none. app.js's LED_FLOOR_AGENTS has the same.
var LogCalls func(time.Time) []sessions.Call
LogCalls reads the calls the agents' own session files record, which the ledger adds to those the gateway logged. A variable for the tests.
Periods lists the windows in order.
var PluginAgents func() []Known
PluginAgents lists the agents plugins add, which come and go as plugins do; package agent sets it.
Functions ¶
func AgentOf ¶
AgentOf names the agent behind a client User-Agent. Known agents map to their magpie id; anything else keeps its product name.
func Append ¶
func Append(r Record)
Append writes one record. Errors are swallowed: accounting must never break a call.
func CanceledBy ¶ added in v0.1.3199
CanceledBy is whether a call that ended with status and error was canceled by its agent: a person stopped the reply, or sent the next message while it was coming and the agent asked again. Not magpie's own limit running out on a request it asked of itself ("magpie stopped waiting", #2318), which is logged 499 too and stays a failure.
func ClineServing ¶ added in v0.1.1372
ClineServing reports whether served is ClinePass's name for the virtual model config ("vmc/") serving the cline-pass/ model sent: the model's own name, its version's dot written as "p". ClinePass answers cline-pass/deepseek-v4.1-flash-1017 as vmc/deepseek-v4p1-flash-1017 whichever upstream served it, DeepSeek's own API included (finalProvider "deepseek": hy125245 on X, 10-23), and the swap it was marked read as the request going to another provider (zRain on Discord, 10-24). It holds for ClinePass's models only, and for the same model: vmc/deepseek-v4p1-flash for cline-pass/deepseek-v4-pro is still a swap, as is a vmc/ name for a model not asked of ClinePass.
func CodexModelEffort ¶ added in v0.1.1238
func CodexModelEffort(p Period) map[string][]sessions.ModelEffort
CodexModelEffort reports each Codex thread's own priced ledger consumption. The answer is the kept one, shared by every ask until the next build replaces it: callers read it and copy a thread's slice before keeping it, never write it. A copy of every thread's for each ask was ~230 MB every 80 s of a Sessions page open over a large history (#2278).
func CodexUsed ¶ added in v0.1.1727
func CodexUsed() []string
CodexUsed is the models Codex asked for in the last 30 days, as its records name them (a ChatGPT account's own as codex/<slug>), most recently used first, at most 100. Codex's model list puts these where the Codex app reads it (codexcat.Fit). It is read again at most once a minute, the list's ETag being on every reply Codex gets, or at once when Codex uses a model it hadn't (codexUsedNew). A call that failed counts: the user chose that model all the same.
func CodexUsedBy ¶ added in v0.1.1727
CodexUsedBy is CodexUsed for the Codex calls made with one gateway key alone: a key's holder is told nothing of what others used.
func Computer ¶ added in v0.1.653
func Computer() (id, name string)
Computer is this computer's id and name, the id made the first time and kept in usage-computer.json, which no backup or sync carries.
func CountsNoCache ¶ added in v0.1.1430
CountsNoCache is whether a provider's vendor never counts cache tokens, so a call of it with none recorded was not a miss: Kiro caches but tells only credits. Calls kept before its plugin said so (opencode-kiro-auth 0.1.16's magpie_cache_unknown) carry no CacheUnknown, and are read as having it (#3464). The provider is the built-in's id, or the plugin's own when it is signed in under that.
func DecodeOf ¶ added in v0.1.1088
func DecodeOf(out, reasoning int, ms, ttft, firstText, flow int64, firstReasoning ...int64) (tokens int, w int64)
DecodeOf is what a reply's speed is told by: the tokens it was seen to write and the ms it took (tony on Discord: gpt-6.1-sol read 163 tok/s, with a 14 s first token). A reply that reasoned counts only its answer — its output less the reasoning, from its first text — as most vendors keep the reasoning out of the stream (OpenAI's is encrypted, its summary sent when it's done; Claude's may come with no text): its tokens were written before the first content, over time the window from it doesn't hold, and counting them read a 2,000-token think and a 200-token answer in 1.5 s as 1,467 tok/s. Its time goes to the wait before the answer. With no answer text, paced visible reasoning can time all output from firstReasoning. Missing evidence (including older records), hidden reasoning and an unknown flow leave the speed untold. The window is DecodeWindow's: 0 for a reply that tells none.
A reply its vendor held back and let go in a burst at its end tells none either (John on Discord: Kimi Code answering OpenCode read 1,367, then 2,237 and 2,012 tok/s). The burst is told two ways, as the reply's text came before it or with it:
- flow, when known (Record.Flow), is how long its content took to come from where its window starts. A window HeldShare times longer had its content come in a small part of it: the rest was a wait while the vendor wrote and held it. The time it took to come is not the time it took to write (a burst let go over 236 ms read 528 tokens at 2,237 tok/s), and that time is not seen, so it tells no speed. A stream that came as it was written has a flow about its window.
- a reply that reasoned is timed from its first text, its reasoning written before. When the answer would have been written over ThinkPace times faster than its reasoning came before it, from the first content to the first text, its first text came with the burst and the wait before it was the answer being written and held (22 reasoning tokens over 10.5 s, then 528 answer tokens in 236 ms). A reasoning hidden from the stream (OpenAI's, Claude's omitted) comes before the first content and leaves this time short; one that streams comes at the pace its answer does.
- a window under HeldWindowMs after a wait HeldShare times longer: the reply came whole in a moment after a long silence, and what it was written over is not seen (pluviophile714 on Discord: gpt-6.1-sol, 392 tokens 0.25 s after an 8.2 s first token, read 1,539 tok/s where the vendor writes ~70). Its content can come spread over that moment (a relay replaying a held reply, OpenAI's answer let go after its hidden reasoning), so flow doesn't tell it. A stream as it is written takes a second or more to write a few hundred tokens; one that takes under a second is too short a sample to tell a speed by against such a wait, so a short answer after a long think tells none either.
func DecodeWindow ¶ added in v0.1.811
DecodeWindow is the ms a reply of out tokens, ms long with its first content at ttft, took to write them: 0 when it wasn't timed, wrote nothing, or came too fast to tell a speed by (above).
func DropAllShared ¶ added in v0.1.653
func DropAllShared()
DropAllShared lets every other computer's usage go: sync, or its sharing of usage, was turned off.
func DropShared ¶ added in v0.1.653
func DropShared(computer, day string)
DropShared lets another computer's day go, and its folder with its last.
func EachGatewaySession ¶ added in v0.1.2711
func EachGatewaySession(nativeKeys map[string]bool, each func(GatewaySession) bool)
EachGatewaySession calls each with every session GatewaySessions(time.Time{}, nativeKeys) gives, in its order (newest first, then by agent and id), until each returns false, without a copy of them all: the Sessions list shows sessions.All rows at most, and each of its polls while a session grew copied every one of ~10k more. A session's Models and Daily are the projection's own, as there.
func ForgetPages ¶
func ForgetPages() bool
ForgetPages lets go at once of what the Requests page and its heatmap keep for their next ask: the chunks (as requestForget does) and what is kept of each by its serial (as derivedIdle does). The app calls it once its page has gone away, closed or hidden, so that what a visit read goes in seconds, not the 7 minutes the idle timers take; the next visit reads the chunks back from the file of them. Says whether anything went.
func FormatCost ¶ added in v0.1.404
FormatCost renders an effective-price cost, kept in USD everywhere it's stored, as the CLI and TUI show it: at amountUSD's own price when currency isn't "cny", else converted at rate (CNY per one USD, from internal/fx; a rate of 0 or below also falls back to USD, a stale or missing rate being no reason to hide the number). Whole dollars or yuan above 100, cents above 1, else thousandths, so a fraction of a cent still shows as something.
func FormatCredits ¶ added in v0.1.1272
FormatCredits is what t's credited calls cost in their plans' credits, as their replies said (#2512): "" when none said.
func GatewaySessionWindow ¶ added in v0.1.1146
func GatewaySessionWindow(since time.Time) ([]GatewaySession, []GatewayDayUsage)
GatewaySessionWindow returns gateway sessions and their daily usage for a local-date range. It is kept separate from the GUI conversion so callers can use the same single usage-log snapshot for list and stats.
func GatewaySessionWindowExcept ¶ added in v0.1.1146
func GatewaySessionWindowExcept(since time.Time, nativeKeys map[string]bool) ([]GatewaySession, []GatewayDayUsage)
func GeminiServing ¶ added in v0.1.1113
GeminiServing reports whether served is the name Google's backend gives the deployment that serves the Gemini model sent: the model's own name with one letter after it (sessions.GeminiDeployment). Antigravity answers every level of gemini-3.8-flash (-low, -medium, -high) with modelVersion gemini-3.8-flash-n, an id no request can ask for (404) and fetchAvailableModels never lists, so it is that model, not another one swapped in (dumplings on Discord); gemini-4-argon's is gemini-4-argon-d (oioio on Discord). It holds for Gemini models only: gpt-5 answered as gpt-5-n is still a swap, as is gemini-3.8-flash answered as gemini-3.8-flash-lite or gemini-3.7-flash-n.
func GrokServing ¶ added in v0.1.1159
GrokServing reports whether served is xAI's name for the build serving the Grok model sent: the model's own name with "-build" after its version. xAI answers grok-4.7 as grok-4.7-build, and grok-4.6 as grok-4.6-build (#1455, cybershape; two relays' logs say the same), and its own list (SuperGrok's, 2026-10-02) offers grok-4.7 and its fast variant grok-4.7-build-fast, never a grok-4.7-build to ask for. It holds for Grok models only, and for the same variant: grok-4.7 answered as grok-4.7-build-fast (the fast one), grok-4.6-build or grok-4.7-mini is still a swap, as is gpt-5 answered as gpt-5-build.
func GroupRouted ¶ added in v0.1.563
GroupRouted reports whether sent is a routing group of another magpie (a remote magpie's "group/<id>", the one name only a magpie answers to) and served the model its reply named: the member the group routed the request to, which is the group doing its job, not the vendor serving another model than asked (莫 on Discord: group/auto-… answered by deepseek/deepseek-v4.1-flash, marked a swap).
func HistoricalWindowHolds ¶ added in v0.1.1258
func HistoricalWindowHolds(cards []provider.SubscriptionQuota, hist []provider.QuotaHistory, from, to time.Time) []provider.SubscriptionQuota
HistoricalWindowHolds reckons each window at its last reading in [from, to), not from today's percentage. cards supply the window's scope, never its current figures. Each returned card has one window, because the windows may have been sampled at different times. A shorter window is its last observed cycle, not all its cycles added.
func HitPct ¶
HitPct is a hit rate (0 to 1) as a percent, whole unless rounding would say 100% or 0% of a prompt not all or none cached, then to one or two decimals (ZhangXiaof48473 on X); the GUI's hitPct says it the same way.
func IngestReported ¶ added in v0.1.1220
IngestReported writes the calls a client reported (#1874) to the log the gateway writes its own to, under the same lock, each marked SourceReported. A call whose request id the log already has as reported, or that came earlier in recs, is skipped. It answers, for each record, whether it was written. The records must already be checked: each has a RequestID.
Nothing else the gateway does on a call happens: no observer sees it (the call is the client's, which can send its own), and no caller key's budget is spent, since the call didn't go through magpie.
func IsAgent ¶ added in v0.1.1196
IsAgent says whether id is an agent magpie knows, its own or a plugin's, rather than the product name of some other client (Python-urllib).
func IsLibrary ¶ added in v0.1.2182
IsLibrary says whether a client, by the name AgentOf gives it (a record's Agent, old records' too), is an HTTP library, a runtime or an API SDK rather than an agent: curl, Bun, python-httpx, Go-http-client, OpenAI/Python.
func KeepOutsideCallsRead ¶
KeepOutsideCallsRead reads the calls made outside magpie a minute after the start and every outsideEvery after, until ctx ends.
func KeepShared ¶ added in v0.1.653
KeepShared keeps another computer's day here, over the one kept before.
func KeySpent ¶ added in v0.1.2819
KeySpent is what the calls magpie sent on the API key keyID (its provider.KeyID) from start on cost, in USD at the Usage page's prices, under whichever provider sent them. A call with no known price counts nothing.
func LastSeen ¶ added in v0.1.91
LastSeen is when a request from the agent last reached the gateway: this process's own, else the newest in the log's last stretch. Zero if none.
func Ledger ¶ added in v0.1.408
Ledger is LedgerOf's rows, sum and agents.
A row's swapped is judged by the upstream names in force now, not by the one its call went out under: the names are read from the settings here, once, so a name given or changed since a call was recorded re-judges that call — one recorded under the name magpie knows the model by, and read after a name was set for it, reads as a swap although the vendor answered with the very model that was asked for. A record keeps the canonical id and the name the vendor's own reply gave (served_model) and not the name the request was sent under, so this is the only name there is to judge by — read as the name that went out, which the effort a record keeps of makes exact: an Antigravity account is asked for the variant of the model that level picks, so a reply naming that one is the model that was asked for and not another, whatever the family it is a level of. It is how ledgerWith's loop already treats the rest of a row: a provider renamed since is put back to the id it has now, and the names in force now are what the catalog lists the models under as well.
Storing the name that was sent would judge each call by what it was really sent under, and it is the better answer, but it is not this function's to make: it is a field on every record the gateway writes, and so a change to the file's format — a column a row written by an older magpie has no value for, and a decision about whether an empty one means "no upstream name" or "unknown" — rather than a row of a report. The rows here are what a reader sets beside a bill, and a name in force today is the one whose reply a bill's model column is read against.
The names are read here, once for the lot, rather than asked for a row at a time, so a caller already holding them — a report over the provider/model it was given — reads them the same way and reaches the same judgement: what a row says is the same however the rows were asked for.
func ListedAs ¶ added in v0.1.1733
ListedAs reports whether served is the name the provider's own model list gives the model asked for: Qoder's plugin lists its free Qwen model as qfmodel, named Qwen3.8-Flash, and since 0.2.38 (plugins#412) answers under that name, which was marked a swap to "actual Qwen3.8-Flash" (jzing.draw on Discord, 10-27). The list is the provider's word that the two are one model. It is asked only once a reply already reads as swapped, and each provider's list is read at most once a minute.
func ListedForTest ¶ added in v0.1.1733
ListedForTest gives ListedAs these lists, provider by model id, and forgets every list read before, until restore.
func LogBackup ¶
LogBackup is usage.jsonl's whole lines, gzipped, and how many there are: none (nil, 0) when there is no log. A line still being written when it is read is left for the next backup.
func LogVersion ¶ added in v0.1.2575
LogVersion is a number for the log as it stands, which changes when a call is written to it, and whether there is one: a synthetic log (LogCalls), or one not read to its end, has none; no log yet is one. The Sessions page keys an unchanged list on it.
func MagpieAlias ¶
MagpieAlias says id is one of magpie's own alias ids for a model, the names the gateway lists Claude Desktop, Claude Code under it and Claude Science by: anthropic/magpie-<number>, mythos-magpie-<number>, claude-magpie-<number> and magpie-<number>.anthropic.<Claude model>, with or without Claude Code's "[1m]", the number ten digits (gateway's aliasNumber). Only the gateway knows them, so a call that names one went through it. A test in the gateway keeps this in step with the ids it lists.
func MergeLog ¶
MergeLog adds the lines of a log LogBackup packed that usage.jsonl doesn't have, at its end, and says how many it added. A line the log has is passed over as often as the log has it, so a restore made twice adds nothing the second time, and two calls that were the same bytes both stay. A line that isn't a JSON object is passed over.
func ModelAtKey ¶ added in v0.1.996
ModelAtKey is a call's "modelAt": its provider's id and its model, as "provider/model" (a provider's id has no "/").
func NewCoster ¶ added in v0.1.675
NewCoster prices one record at a time at the effective prices the ledger uses, read once: its cost in USD, and false for a call with tokens but no known price.
func NewPricer ¶ added in v0.1.591
NewPricer totals requests' token-bearing attempts at one snapshot of the effective prices used by the ledger. Reuse it for one page of routes; make it again on the next read so a changed tariff re-prices history.
func Observe ¶ added in v0.1.1243
func Observe(o Observer) (remove func())
Observe registers o until remove is called. While this process serves the gateway it is started at once.
func OthersDir ¶ added in v0.1.653
func OthersDir() string
OthersDir is where the other computers' days are kept: one folder each.
func OwnDays ¶ added in v0.1.653
func OwnDays(since time.Time) map[string][]SharedCall
OwnDays are this computer's calls since the day of since, by day, as the Usage page lists them: a call another magpie passed on here is left to that computer, which counts it itself, and where the request archive keeps a call is this computer's own.
func Pricer ¶ added in v0.1.1243
Pricer uses the same effective price as the model CLI and session totals: explicit provider/model or provider-wide prices (including zero), then the provider catalog, then the maker catalog. Settings are read once per query.
A model no price is known for is priced as the model the vendor's reply said answered (Served), at the same provider, when that one has a price: a relay that sells kimi-k3 as moonshot-kimi-k3 answers as kimi-k3, which is listed (#1498). So is a call the vendor genuinely answered with another model than the one asked for — the swap the ledger marks, no rename in either name (#5340): the vendor billed for the one that ran, and the asked-for model's rate describes nothing that happened. A price the user set for the model asked for keeps its say either way, a zero included, so a ledger that matched the vendor's bill still does, and a served model with no price leaves the asked-for one's standing. A record inside one of its provider's rate windows (#2463) is priced at that window's rate, its own time read against the windows, so calls either side of a boundary price apart.
A local session's call has no provider of ours to price at (its billing provider is the unknown one) but its file names the route it went through; that name prices the call when the catalog lists the very model id under it, and never otherwise: a name models.dev doesn't know, or one whose other models alone would stand for this call's, prices nothing (#4278).
func PurposeKinds ¶ added in v0.1.969
func PurposeKinds() map[string]PurposeKind
PurposeKinds returns a copy of the catalog used to generate the UI's catalog. Add aliases here, then run go generate ./internal/usage from the repo root.
func PurposeOf ¶ added in v0.1.854
PurposeOf groups the agent's equivalent call-kind spellings for filtering. The recorded Kind stays untouched. Prefixing nonempty kinds keeps future names distinct from the unmarked bucket (which is not necessarily a chat).
func ReadAhead ¶ added in v0.1.1419
func ReadAhead()
ReadAhead parses the log into its index and works out today's summary in this computer's zone, for magpie to run as it starts: the first reader, the tray panel's line of today's calls, finds both done. Parsing the log cold took 0.33 s at 2 MB and 0.77 s at 40 MB on one core, and the panel's numbers waited for it on the first open after a start (CyberCaius on Discord). A reader that comes while it runs waits for the same parse, never a second.
func ReadOutsideCalls ¶
ReadOutsideCalls reads each such plugin's accounts' calls since the last reading and writes the new ones to the log. A reading that fails keeps its mark, so the next one asks again from there.
func RegionTail ¶ added in v0.1.2728
RegionTail reports whether one of sent and served is the other with a region after it: the same model at that region's deployment, not another model swapped in (plugins#628, chansee97). A region in both, or a name that differs besides it, is not this.
func RelayRenamed ¶ added in v0.1.1163
RelayRenamed reports whether sent is served's own name with a relay's word in front of it: a relay that sells kimi-k3 as moonshot-kimi-k3 is answered as kimi-k3 (#1498, liuweifeng), one that sells deepseek-v4.1-flash as claude-deepseek-v4.1-flash (#1383) as deepseek-v4.1-flash. What is left must name a version, so a bare word (flash, mini) is never taken for the model sent.
func ReleaseMatchScratch ¶ added in v0.1.2287
func ReleaseMatchScratch()
ReleaseMatchScratch is ReleaseScratch keeping the priced blocks.
func ReleaseScratch ¶ added in v0.1.1956
func ReleaseScratch()
ReleaseScratch lets go of what the request matching keeps between calls, and the priced blocks no query holds.
func ReportedAs ¶ added in v0.1.1227
ReportedAs is the agent the Usage and Sessions pages count a client's calls under: AgentOf's, unless the user counts that client as an agent of theirs (settings.ClientAgents). Only for what is reported: the gateway's own choices (routing, keys, caps) go by AgentOf, the client's own name.
func ResetFeedForTest ¶
func ResetFeedForTest()
ResetFeedForTest forgets what is loaded, as a restart does.
func SameSpelled ¶ added in v0.1.958
SameSpelled reports whether served is sent spelled with other separators or case: a row or route kept marked swapped before Swapped knew it is read as not swapped.
func ServeObservers ¶ added in v0.1.1243
func ServeObservers() (stop func())
ServeObservers starts every observer registered, and each one registered later, until stop: the gateway calls it as it starts serving.
func ServingName ¶ added in v0.1.1159
ServingName reports whether served is the vendor's own name for the deployment serving the model sent, which no request asks for by: Google's for a Gemini model (GeminiServing), xAI's for a Grok one (GrokServing), ClinePass's for one of its models (ClineServing).
func SharedKept ¶ added in v0.1.653
func SharedKept() []string
SharedKept are the other computers' days kept here, as "<id>/<day>".
func SourceOf ¶ added in v0.1.1104
SourceOf is the source a row is of, as the page's cells name them: the calls magpie's gateway served and the ones read from the agents' session files. A call the gateway turned away itself is neither — the page says under its totals that local rejections are not counted — so it is "" and picking either cell leaves it out, as the cells' own counts already do.
func Summaries ¶ added in v0.1.1093
Summaries is Summarize(p) and Direct(p) asked at one moment, for a page that shows the two together: asked one after the other, midnight could fall between them and set one day's calls through magpie beside the next day's calls not through it. The gateway's sessions are its top summaryCacheSessions (SummarizeTop), of its SessionCount: a page lists a few, and the summary of a long history is then kept rather than worked out again.
func Swapped ¶ added in v0.1.408
Swapped reports whether served is another model than sent: not the same name, however dated, pinned or prefixed. A call that went out as one level of a model (an Antigravity account's gemini-3.8-flash-medium) answered under the model's own name is that model at that level: Antigravity's reply names the family, not the variant (#462). Another level is another model, as AntigravitySentID has it. A vendor's "auto" (Copilot's, Cursor's) asked it to pick, so whichever answers wasn't swapped in, nor is the member another magpie's routing group sent it to (GroupRouted), nor a vendor's own name for the deployment serving the model (ServingName), nor the model a relay sold under a name of its own (RelayRenamed), nor the model at a region's deployment (RegionTail).
func ValidComputer ¶ added in v0.1.653
ValidComputer is whether id can be another computer's id: a folder name and a file name's first part, nothing else.
func VendorAlias ¶ added in v0.1.2497
VendorAlias reports whether served is the vendor's own alias for the model sent — an official name its docs give one of its models, not another model swapped in. Both ways: a request under the alias answered under the name it stands for is the same model too. A vendor may rename a model over time, and what its name stands for is its docs' word, so only pairs the docs state go here; catalog's SameModel keeps the two ids apart (the catalog lists deepseek-flash as an id of its own).
func Visit ¶ added in v0.1.675
Visit calls fn with each record from since on, as the ledger's index reads usage.jsonl: only its blocks that reach since are decoded. Each record is as it was recorded: a provider renamed since is named by the id it had then, which provider.UsageRenames tells (NewCoster does so itself).
func VisitSessions ¶ added in v0.1.2600
VisitSessions is Visit for the records whose Session or NativeSession is one of sessions, read without making a Record of any other.
func WithWindowHolds ¶ added in v0.1.1120
func WithWindowHolds(qs []provider.SubscriptionQuota, now time.Time) []provider.SubscriptionQuota
WithWindowHolds is qs with each window's Holds reckoned from the log, as it stood at now. qs itself, which the caller may share, is left as it is.
func WriteCSV ¶ added in v0.1.408
WriteCSV writes rows as CSV, a header first (cache_write_tokens is every cache write, as it always was, and the last two columns split it into 5-minute and 1-hour writes): times in RFC 3339 with their offset, the cost in USD at the effective price (empty when unknown), error "true" for a call that failed: answered with a status of 400 or more, or ended by an error a session file tells (not one its agent canceled, whose status is 499: Record.Failed). tries is how many tries the gateway made at the request the row ends, when more than one, and handed_on "true" for the row of a try that failed and handed the request on: the request's outcome is the row with the same route_id after it. tier_asked, tier_sent and tier_served are the service tier the client asked for, the one sent on the row's try and the one the reply said it ran at, each empty when there was none (Record.TierAsked). credits is what the reply said the call cost in its plan's credits, empty when it said none (Record.Credits).
func Zone ¶ added in v0.1.1330
Zone is the time zone a browser names (an IANA name such as "Asia/Shanghai"), the same *time.Location for every ask of one name, so that a Filter holding it is the same cache key each time. A zone that keeps this computer's clock, the page on this computer, is time.Local, whose answers the tray and the TUI share. An empty name or one this computer doesn't know is time.Local: the computer's days, as before.
With a day that starts after midnight (Settings' dayStart, ssharpcc on X), the zone is that zone moved so its midnight is that hour (dayzone): every day and hour the page cuts by it starts there.
Types ¶
type BigWrite ¶
type BigWrite struct {
N int `json:"n,omitempty"`
RouteID int64 `json:"route,omitempty"`
At time.Time `json:"at,omitzero"`
Model string `json:"model,omitempty"`
}
BigWrite is the request that wrote the most to the cache among a page's counted rows that the gateway served (RouteID is the request the Routing page keeps; a call read from an agent's own session file has none, so there is no request to jump to). A page's totals hide one request that rewrote a long conversation behind many that only read it (recih on X, #6199).
type Bodies ¶ added in v0.1.1243
type Bodies int
Bodies is how much of a request's and reply's bodies an observer wants.
func ObservedBodies ¶ added in v0.1.1243
func ObservedBodies() Bodies
ObservedBodies is the most of a request's bodies any observer wants now.
type Cursor ¶
type Cursor struct {
// contains filtered or unexported fields
}
Cursor is where a reader stopped in the log: the full blocks it has read, which the log keeps as they are while it only grows. The zero Cursor starts at the beginning.
func VisitFrom ¶
VisitFrom is Visit for a reader that keeps what it counted of the rows before cur: settled is called with each record of the full blocks after cur, which the reader keeps and the next call starts after; tail is called with the rows of the last, partial block, which it counts again each call. A cur the log has left behind (rewritten, cleared, another file) starts over: reset is called first, and settled gets every record. A reader of the Gateway page's key limits read a month of the log, row by row, for each poll.
type Day ¶ added in v0.1.1134
type Day struct {
Date string `json:"date"` // YYYY-MM-DD
Calls int `json:"calls"`
Tokens int `json:"tokens"` // in, out and through the cache, as the chart counts them
Cost float64 `json:"cost"` // of the priced calls, USD
// Unpriced: calls with tokens but no known price, not in Cost
Unpriced int `json:"unpriced,omitempty"`
}
Day is one day's calls, by the local calendar day they fell on.
type FeedError ¶
type FeedError struct{ Code, Message string }
FeedError is a cursor magpie can't resume from. Code is one of cursor_invalid, cursor_expired, cursor_reset and cursor_filter_changed.
type FeedItem ¶
FeedItem is one change: the row as it is now, or, Gone, the id that no longer is a row.
type FeedPage ¶
FeedPage is a read's answer.
func FeedRead ¶
func FeedRead(req FeedRequest) (FeedPage, error)
FeedRead answers one read of the feed.
type FeedRequest ¶
type FeedRequest struct {
Cursor string
Limit int // 100 when none, 500 at most
Filter Filter
// Key narrows the feed to one gateway key's calls, tombstones too
Key string
}
FeedRequest is one read.
type Filter ¶ added in v0.1.408
type Filter struct {
Day string // YYYY-MM-DD in Zone; "" is the whole period
// Zone is the reader's time zone (Zone gives it), which the period's
// days, the chart's hours and Day are read in; nil is this computer's
Zone *time.Location
CallerKey string
RouteID int64
Model string // exact model selected in the ranking
Agent string
Provider string // a provider's id, as the ledger's rows have it
Purpose string // PurposeOf's key; empty keeps every purpose
// Account narrows to the calls a subscription account answered, by its
// name as Record.Account gives it (#557)
Account string
// Failed keeps the rows of every request a try failed on
// (Record.FailedTry): those the agent got an error for, the tries
// handed on, and the requests a later try answered, as Routing shows
// them failed (maohy915 on X). Retried keeps only the requests answered
// after a try that failed first (Record.RetriedRequest). The Requests
// card still counts each request once, by how it ended.
Failed bool
Retried bool
Query string
// Computer narrows to the calls of one computer (#542): ThisComputer,
// OtherComputers, or another's id; "" is every computer's
Computer string
// Through narrows to one of the sources a row can be of
// (SourceGateway, SourceSession, SourceReported); "" keeps all. It is what the requests
// page's source cells filter by, and, as with the other dimensions, the
// cells themselves are counted with it cleared so all three stay
// switchable. Not Record.Via, which is the computer that forwarded the
// call (#542).
Through string
}
Filter narrows the ledger: to a route, one agent (its id, as AgentOf gives it), to one provider, to the failed calls, and to the rows whose models, provider, host or session hold Query (any case).
type GatewayDayUsage ¶ added in v0.1.1146
type GatewayModel ¶ added in v0.1.1146
type GatewaySession ¶ added in v0.1.1146
type GatewaySession struct {
Agent string `json:"agent"`
ID string `json:"id"`
Start time.Time `json:"start"`
Last time.Time `json:"last"`
Models []GatewayModel `json:"models"`
Daily []GatewayDayUsage `json:"-"`
sessions.Tokens
Cost float64 `json:"cost"`
Unpriced int `json:"unpriced"`
// Answered: calls of it the provider answered (a 2xx or 3xx). A
// session with none that spent nothing is no conversation of the
// reader's (SpentNothing).
Answered int `json:"-"`
}
GatewaySession is a read-only projection of requests served by this gateway. Its identity is the agent name and the session id supplied by the client. Unidentified requests and generated recording identities are left out.
func GatewaySessionByID ¶ added in v0.1.1146
func GatewaySessionByID(agent, id string, nativeKeys map[string]bool) (GatewaySession, bool)
func GatewaySessions ¶ added in v0.1.1146
func GatewaySessions(since time.Time, nativeKeys map[string]bool) []GatewaySession
GatewaySessions aggregates one usage snapshot without reading routing history or agent files. NativeKeys contains identities already represented by local session files and is used to suppress the duplicate projection.
A session's Models and Daily are the kept projection's own, shared by every caller, which reads them and never changes them: each ask cloned every session's days, and the start's first asks together held ~450 MB of copies over ~720k calls (#2776). They are clipped, so an append makes a slice of the caller's own.
func (GatewaySession) SpentNothing ¶
func (s GatewaySession) SpentNothing() bool
SpentNothing reports whether a gateway session has nothing to show: no call of it was answered and none spent a token. Codex's title and review threads do that when they fail — their ids are the thread's, no file of the agent's has them — and such a session was a row with nothing in it (flandern: three empty rows under "Seen through the gateway").
type Group ¶
type Group struct {
ID string `json:"id"`
Provider string `json:"provider,omitempty"` // models only
Model string `json:"model,omitempty"`
ProviderKeyID string `json:"providerKeyId,omitempty"`
ProviderKeyName string `json:"providerKeyName,omitempty"`
// Account is the subscription account of an Accounts group: "" for
// the calls of an account's provider whose record names none
Account string `json:"account,omitempty"`
CallerKeyID string `json:"callerKeyId,omitempty"`
CallerKeyName string `json:"callerKeyName,omitempty"`
// Host is where the calls went, when the provider's id has gone to
// more than one place, or elsewhere than the provider goes now: its
// calls are then told apart by it, not summed under the id.
Host string `json:"host,omitempty"`
// Agent is the agent a session is of (sessions only).
Agent string `json:"agent,omitempty"`
// Last is when the group's newest call in the period was made (agents
// only): the Usage page folds a small client idle for days into one
// "Other" row (WJaunita45604 on X: dozens of test clients).
Last time.Time `json:"last,omitzero"`
Totals
// Own is the share of these calls magpie made by itself (Record.ByMagpie):
// a routing classifier's, a web search's or an image description's,
// counted in Totals too, since they went to the same key or account
// (#1839). Filled for models, keys and accounts; a value, so a
// summary's copies share nothing.
Own OwnShare `json:"own,omitzero"`
}
Group is the share of one agent or model.
type Heatmap ¶ added in v0.1.1134
Heatmap is the days from From to To (today), both YYYY-MM-DD in the reader's time zone (Filter.Zone): only those with calls are listed, oldest first.
type Known ¶ added in v0.1.43
type Known struct {
ID string
Names []string // its id and aliases, which a record may already carry
UA []string // what its User-Agent begins with
}
Known is an agent as its requests name it.
type Ledgered ¶ added in v0.1.579
Ledgered is a period's calls that a filter keeps, newest first, with their sum, and the agents and providers that made any call in the period (their ids, for a filter to offer).
func LedgerOf ¶ added in v0.1.579
LedgerOf is the calls of a period that the filter keeps. The gateway's log comes with the calls the agents' session files record that the gateway did not see.
func LedgerOfAt ¶ added in v0.1.1093
LedgerOfAt is LedgerOf with the period read at now, for an answer that names that moment elsewhere too, as an exported CSV's name does.
type ModelSpeed ¶
type ModelSpeed struct {
Model string `json:"model"`
// Requests are the requests that counted: answered, streamed and timed,
// of MinRankTokens or more
Requests int `json:"requests"`
// Speed is the median tokens a second (Row.Decode's), over SpeedN
// requests whose speed was measured; 0 for none
Speed float64 `json:"tps,omitempty"`
SpeedN int `json:"tps_n,omitempty"`
// TTFT is the median ms to the first token, over Requests
TTFT int64 `json:"ttft_ms,omitempty"`
}
ModelSpeed is one model's place in the speed ranking: the median of its requests' output tokens a second after the first, and of the wait for the first token, over the requests that count. Median, so one stalled or one burst reply doesn't move it. Both are read off a histogram of 2% bins, so a median is within 1% of the exact one.
type Observer ¶ added in v0.1.1243
type Observer interface {
// Serve runs it while this process serves the gateway; stop ends it,
// after the calls in flight have finished
Serve() (stop func())
// Bodies is how much of a request's bodies it wants now
Bodies() Bodies
// Begin is asked as each gateway request starts; nil leaves the
// request unwatched by it
Begin(Request) Watch
// Ledger is each row Append writes. A row of a request some observer
// watched has Watched set.
Ledger(Record)
}
Observer is the gateway's observer point (P3 of docs/subsystems/plugin-runtime.md): it watches what the gateway serves and what the ledger is written, and never changes either. A plugin registers one with Observe while it is on (plugins/otel registers internal/otlp's exporter); with none registered the gateway does no observing work at all, not even keeping a reply's whole body.
It lives here, not in the gateway, because every row it sees is a usage Record and the ledger's other writers (budget, routing decisions) reach it too.
type OwnShare ¶ added in v0.1.1216
type OwnShare struct {
}
OwnShare is what magpie's own calls of a group came to.
type Part ¶ added in v0.1.579
type Part struct {
Calls int `json:"calls"`
Tokens int `json:"tokens"`
Cost float64 `json:"cost"`
// how fast its replies came, as Totals has it: a chart of speed says
// each one's at each point (#860)
Timed int `json:"timed,omitempty"`
TTFT int64 `json:"ttft_ms,omitempty"`
DecodeMs int64 `json:"decode_ms,omitempty"`
DecodeOut int `json:"decode_out,omitempty"`
// the bytes its requests sent up and read back (Totals.UpBytes), for
// a chart of the traffic over time
UpBytes int64 `json:"up_bytes,omitempty"`
DownBytes int64 `json:"down_bytes,omitempty"`
}
Part is what one provider, agent or model had of a point of the timeline.
type Period ¶
type Period string
Period is a window of time to sum over.
func LastOf ¶ added in v0.1.1233
LastOf is the rolling window of d ending now; ok is false when d is not positive.
func RangeOf ¶ added in v0.1.1162
RangeOf is the period from one date (YYYY-MM-DD), or one minute of a date (YYYY-MM-DDTHH:MM), to another, in either order; ok is false when either is neither, or when the two are the same minute.
func (Period) IsRange ¶ added in v0.1.1162
IsRange is whether p is days the reader picked rather than a preset.
func (Period) Known ¶ added in v0.1.1162
Known is whether p is a period the usage pages answer for: a preset, a picked range or a rolling window.
func (Period) Last ¶ added in v0.1.1233
Last is the length of a rolling window ("last:24h"), 0 when p is not one.
type PurposeKind ¶ added in v0.1.969
PurposeKind is the shared filtering key and untranslated display name of a kind.
type Record ¶
type Record struct {
Operation string `json:"operation,omitempty"`
RouteID int64 `json:"route_id,omitempty"` // the gateway Route, shared by its attempts
Time time.Time `json:"t"`
Agent string `json:"agent"` // magpie agent id, or the client's product name
Provider string `json:"provider"`
Host string `json:"host,omitempty"` // where the call went: provider.Where then
ProviderKeyID string `json:"providerKeyId,omitempty"` // fingerprint of the API key actually used
ProviderKeyName string `json:"providerKeyName,omitempty"`
// ProviderAccount is the subscription account that answered the call,
// as the Routing trace names it (provider.Account.User: an email, a
// login): the one that took over after a failover, the one pinned by
// X-Magpie-Account. Never a token. "" for a key or a provider without
// an account, and in a record written before it was kept (#557).
ProviderAccount string `json:"providerAccount,omitempty"`
CallerKeyID string `json:"callerKeyId,omitempty"`
CallerKeyName string `json:"callerKeyName,omitempty"`
// CallerIssuerID is the key CallerKeyID was issued under (an issued,
// short-lived key: access.IssueKey), whose limits count this call too.
CallerIssuerID string `json:"callerIssuerId,omitempty"`
// SessionProvider is the provider ID recorded by the agent. SessionAccount
// identifies the session's creator, not the account used for an API request.
// Neither field establishes an upstream route from today's configuration.
SessionProvider string `json:"session_provider,omitempty"`
SessionAccount string `json:"session_account,omitempty"`
// SessionOfficialLogin marks a matched account's explicit official login
// metadata, not this call's endpoint or billing authentication.
SessionOfficialLogin bool `json:"session_official_login,omitempty"`
Model string `json:"model"` // the provider's model id
// Requested is the model id the agent asked for (a magpie alias, a
// routing group, provider/model…), and Served the model the vendor's
// reply says answered, when it named one: a ledger to set beside the
// vendor's own bill. Neither is in a record written before they were.
Requested string `json:"req,omitempty"`
Served string `json:"served,omitempty"`
// Upstream: the provider an aggregator (OpenRouter …) said answered
// behind it — DeepInfra, Novita — when its reply named one
Upstream string `json:"upstream,omitempty"`
Input int `json:"in"`
Output int `json:"out"`
// CacheRead is the prompt tokens read from the vendor's cache, and
// CacheWrite those written to it (Anthropic's cache creation,
// cache_creation_input_tokens); neither is in Input. Both are written
// on every record, 0 too, as in and out are, so a call whose prompt
// missed the cache reads as that rather than as one whose cache wasn't
// kept (#1839). A record from before they were has neither: 0.
CacheRead int `json:"cache_read"`
CacheWrite int `json:"cache_write"`
// CacheWrite1h is how many of CacheWrite were written to be kept for
// an hour (Anthropic's 1-hour TTL, billed at 2× input where 5 minutes'
// is 1.25×); the rest were for 5 minutes. A record from before it was
// kept has none: all its writes are counted as 5-minute ones, as they
// were.
CacheWrite1h int `json:"cache_write_1h,omitempty"`
// CacheUnknown: the vendor counted no cache tokens for this call (a
// plugin's magpie_cache_unknown: Kiro caches but tells only credits),
// so its CacheRead of 0 is not a miss. A hit rate leaves its prompt
// out (Totals.CacheUnknown, #3464). A record from before it was kept
// has none: its 0 still reads as a miss.
CacheUnknown bool `json:"cache_unknown,omitempty"`
Reasoning int `json:"reasoning,omitempty"`
// Effort is the reasoning the model was asked for — a routing group's
// pick for the turn, or the agent's own — as it takes it; "" for none
Effort string `json:"effort,omitempty"`
// The service tier, as OpenAI's service_tier words it ("priority",
// "ultrafast", "flex", "default"; "fast" for Claude's speed "fast"):
// TierAsked what the client's request asked for, TierSent what went
// out to the vendor on this try, after a fast pick or a group member
// set Fast asked for priority and an account whose plan doesn't offer
// Ultrafast was asked for priority in its place, and TierServed what
// the vendor's reply said it ran at. Each is "" when there was none:
// TierServed is never taken from what was asked or sent, only from a
// reply that names it (#1784)
TierAsked string `json:"tier_asked,omitempty"`
TierSent string `json:"tier_sent,omitempty"`
TierServed string `json:"tier_served,omitempty"`
Millis int64 `json:"ms"`
// TTFT: ms from the request to its reply's first content — text,
// reasoning or a tool call — and FirstText to its first text, counted
// as Millis is, so Millis-TTFT is how long the reply took to write;
// none for a reply that wasn't streamed (#196)
TTFT int64 `json:"ttft_ms,omitempty"`
FirstText int64 `json:"first_text_ms,omitempty"`
// Compaction is Codex's explicit native marker. Nil means no matching
// native Codex call established whether a gateway row compacted.
Compaction *bool `json:"compaction,omitempty"`
// FirstReasoning is the start of paced visible reasoning, absent for hidden reasoning.
FirstReasoning int64 `json:"first_reasoning_ms,omitempty"`
// ReasoningHidden: the reply reasoned and its stream doesn't tell how
// much — sealed or summarised, or streamed with no reasoning count in
// its usage (#4545: Anthropic's usage never has one), when Reasoning is
// 0 for unknown, not for none. A reply of no text then tells no speed
// (Decode).
ReasoningHidden bool `json:"reasoning_hidden,omitempty"`
// Sent: ms from the request to its answering try going out to the
// vendor, its body written, as TTFT is counted: magpie's own time and
// the tries that failed first are before it, and TTFT-Sent is how
// long the vendor took to its first content. 0 where it isn't known
// (a reply not streamed, or a vendor magpie doesn't reach over HTTP).
Sent int64 `json:"sent_ms,omitempty"`
// Of Sent, what was magpie's: Own is magpie's own work on the request
// (reading it, translating it, choosing whom to ask), Retried the
// tries that failed first and the pauses after them, Queued the wait
// for a slot of a key's or account's MaxConcurrency or MaxRPM; the
// rest, Sent-Own-Retried-Queued, is connecting to the vendor and
// sending it the body. #1532: a vendor that held a try ~100 s and
// said 503 read as 104 s "In magpie". 0 in a record written before
// they were, where Sent is all that is known.
Own int64 `json:"own_ms,omitempty"`
// Masking: the ms of Own that went on masking the request (Settings
// → Privacy: the rules, and the local model with its wait for a
// turn), all of it where Own is unknown; 0 where nothing was masked,
// or in a record from before it was kept.
Masking int64 `json:"masking_ms,omitempty"`
Retried int64 `json:"retried_ms,omitempty"`
Queued int64 `json:"queued_ms,omitempty"`
// Flow: the ms the reply's content took to come, from where its speed
// is counted (DecodeOf): from a tenth of its content to nine tenths,
// spread over the whole. A reply a vendor held and let go in one burst
// has a flow of next to none, however long its end came after its
// first content, and so tells no speed (John on Discord: a Kimi Code
// reply read 1,367 tok/s). 0 where it isn't known.
Flow int64 `json:"flow_ms,omitempty"`
Status int `json:"status"`
// Error is why a call failed, in the vendor's words and cut short;
// ErrType what its body called the error (rate_limit_error,
// usage_limit_reached); RequestID the id the vendor gave the call; and
// Endpoint the path the agent called, with the one it was sent to when
// it went out in another protocol (/v1/messages → /v1/chat/completions)
Error string `json:"err,omitempty"`
ErrType string `json:"err_type,omitempty"`
RequestID string `json:"rid,omitempty"`
// ResponseID is the response object ID actually sent to the client.
ResponseID string `json:"response_id,omitempty"`
// MessageID is the id the agent's own session file gives the call's
// message (Claude Code's msg_…), on a call read from such a file. Not
// persisted: it is read back with the file, and told by the request
// feed (FeedOriginals).
MessageID string `json:"-"`
Endpoint string `json:"ep,omitempty"`
// Stop is why the upstream said its reply ended, in its own words
// (stop_reason, finish_reason …): "" when it said none, a stream that
// just stopped. Told apart by it, a reply that ended too soon is the
// upstream's own end_turn or a cut (蓝猫 on Discord).
Stop string `json:"stop,omitempty"`
// Session is the conversation the call was part of, as its agent names
// it (X-Magpie-Session, or the session header Claude Code, Codex or
// OpenCode sends): several sessions on one model told apart
Session string `json:"session,omitempty"`
// NativeSession retains the client header when X-Magpie-Session overrides it.
NativeSession string `json:"native_session,omitempty"`
// Subagent is the subagent that made the call, as its agent names it
// (Claude Code's x-claude-code-agent-id, the agentId of its
// subagents/agent-<id>.jsonl): Session stays the conversation it was
// spawned in, so its calls are counted there too. ParentAgent is the
// subagent that spawned it in turn (x-claude-code-parent-agent-id), ""
// when the conversation itself did or the agent doesn't say.
Subagent string `json:"subagent,omitempty"`
ParentAgent string `json:"parent_agent,omitempty"`
// Rejected is a request refused locally before an upstream was contacted.
Rejected bool `json:"rejected,omitempty"`
// Tries is how many tries the gateway made at the request this row
// ends, as its route lists them, when there was more than one: a
// request answered on a later try was answered, not failed (小一 on
// Discord). HandedOn marks the row of one try that failed and handed
// the request on to the next (a vendor's refusal kept for what it
// billed): it is not the request's outcome, which a later row with
// the same RouteID is, so it is neither a request nor a failure of
// its own. Neither is in a record written before they were; the log
// index tells HandedOn from such a record's route (handedOn).
Tries int `json:"tries,omitempty"`
HandedOn bool `json:"handed_on,omitempty"`
// UpBytes is how many bytes of this call's request actually went up to
// the vendor on the wire, its tries summed: the plain body where it
// goes as read, less where it went compressed (zstd to a ChatGPT
// backend, provider.CodexCompressed). A try gone over a connection
// that then failed still counts, as a connection's own counter would,
// and so does a single ask's second request (RetryOneAuth …). A
// record from before it was kept has none (#4456).
UpBytes int `json:"up_bytes,omitempty"`
// PlainBytes is the request's last try as it went into that ask,
// before compression, what UpBytes would have been without one: beside
// it, a compressed turn's discount and a retried request's re-sends
// both read off the row. None when no try went out.
PlainBytes int `json:"plain_bytes,omitempty"`
// DownBytes is how many bytes of the vendor's replies to this call's
// tries magpie read, tries summed as UpBytes is: a reply's body as it
// came, after the HTTP client undid a gzip the vendor sent it in, so
// more than the wire's for a gzipped reply. A record from before it was
// kept has none.
DownBytes int `json:"down_bytes,omitempty"`
// ImageFilesSaved is how many fewer bytes went up because DeepSeek's
// image files named the request's inline images by file id (#5407):
// the inline base64 its tries left out, less the images this request
// uploaded for it. Below 0 when an upload cost more than it saved this
// time. None where no image went by file.
ImageFilesSaved int `json:"image_files_saved,omitempty"`
// ImageFiles is how many of the request's inline images went by file
// instead, the most of any one try (a retry sends the same ones again):
// what ImageFilesSaved was saved on (matrix0487 on Discord). None in a
// row from before it was kept.
ImageFiles int `json:"image_files,omitempty"`
// UpParts is what UpBytes was made of, where the body was read to
// know (UpParts); nil where it wasn't: a socket's delta, a request
// whose images went by file, a row from before it was kept
// (theforeveriris on X: 8.6 GB up from plain-text projects).
UpParts *UpParts `json:"up_parts,omitempty"`
// Socket says the request went over the Responses WebSocket, its
// last try (provider.Socket, matrix0487 on Discord): UpBytes is then
// what the socket was sent, a delta on a kept socket.
Socket bool `json:"ws,omitempty"`
// Kind is what the agent made the call for when it isn't a turn of
// the conversation: a Codex subagent's (review, compact, guardian…)
Kind string `json:"kind,omitempty"`
// Via is the computer whose magpie passed the call on to this one (a
// Remote magpie provider there), Agent being the agent's on it; "" when
// no other magpie forwarded it (including direct LAN/container clients).
Via string `json:"via,omitempty"`
// Archive is where the request archive keeps the call, "<date>/<id>"
// (gateway/archive.go), when it was on: the Usage page reads it back
// by it long after Recent calls has let the call go (#447)
Archive string `json:"archive,omitempty"`
// Computer is the other computer the call was made on, by its id, for
// a call brought here by sync (#542); "" for one made here, as every
// call in usage.jsonl is
Computer string `json:"computer,omitempty"`
// Source is SourceReported for a call a client told magpie of through
// POST /v1/magpie/usage/requests (#1874), one that went straight to its
// vendor and that magpie never saw; "" for the gateway's own. Reported
// calls count in the totals and are told apart, and filtered, on the
// page.
Source string `json:"source,omitempty"`
// OwnCost is what such a client said the call cost, in USD. nil when it
// said nothing: the call is then priced at magpie's own prices, as the
// gateway's calls are, and priced again when those change.
OwnCost *float64 `json:"cost,omitempty"`
// Credits is what the vendor said the call cost in its plan's own
// credits (WorkBuddy's usage.credit, #2512), nil when it said none
Credits *float64 `json:"credits,omitempty"`
// Watched is a row of a request an Observer watched (observe.go): it
// has the request's attempts already, so it can pass the row over.
// Never persisted.
Watched bool `json:"-"`
// ClientIP is the address the request came to the gateway from, as the
// connection gave it (the gateway trusts no forwarding header, so behind
// a proxy it is the proxy's): a loopback address for this computer. It
// stays on this computer: sync (SharedCalls) and the gateway's
// /v1/magpie/usage/requests leave it out. "" for a row kept before it
// was recorded, a call a client reported, or magpie's own.
ClientIP string `json:"client_ip,omitempty"`
// Local is true only for verified loopback gateway requests. It is used
// for local-session deduplication, never persisted or exported.
Local bool `json:"-"`
// BodyIn and BodyOut are the request and reply as the gateway
// captured them, filled only while an Observer wants them (an OTLP
// export with bodies on, #538) and never written to usage.jsonl.
BodyIn string `json:"-"`
BodyOut string `json:"-"`
// contains filtered or unexported fields
}
Record is one call.
func Load ¶
Load streams complete records from the log. Historical request bodies are not retained by a global cache after the caller finishes with this snapshot.
func (Record) Account ¶ added in v0.1.660
Account is the subscription account that answered the call: the one the record names, or, in a record written before it named one, the account its Host said the call went out as then ("chatgpt.com as dee@example.com") — what the record itself says, never today's sign-in. "" when neither tells (#557).
func (Record) Answered ¶ added in v0.1.3199
Answered is whether the call ended with an answer: it neither failed nor was canceled, so how long it took to its first token and its speed tell something.
func (Record) ByMagpie ¶ added in v0.1.1216
ByMagpie is whether magpie made the call by itself rather than an agent: its routing classifier, System One's decision, a web search or an image description it asked for (#1839).
func (Record) Canceled ¶ added in v0.1.3199
Canceled is whether the agent canceled the call before it was answered: neither failed nor answered, counted apart (Totals.Canceled). A record logged before CanceledErrType was is told by its status and message.
func (Record) CostAt ¶ added in v0.1.1032
CostAt is what the call costs at a price: at the tier its input reaches, its 1-hour cache writes at theirs, and at the hour it was made (an off-peak price doubles at peak, Price.In). A reported call that said what it cost costs that, at any price.
func (Record) Failed ¶ added in v0.1.579
Failed is whether the call failed: the agent was answered an error status, or, for a call read from a session file, which has no status, the file says an error ended it. A call the agent canceled itself (Canceled) didn't fail: the agent left before an answer, and was told no error.
func (Record) FailedTry ¶
FailedTry is whether a try of r's request failed: r failed (whether the agent got the error or a later try took over), or r answered after a try that failed first. What Usage's Failed filter keeps: Routing shows those tries failed, and a request a fallback answered had none of its own failures listed under Failed (maohy915 on X).
func (Record) IsProbe ¶ added in v0.1.1446
IsProbe is a request magpie sent on its own (SourceProbe), an MCP tool call (SourceMCP) or a search API's (SourceSearch): a row listed and counted nowhere.
func (Record) IsRejected ¶ added in v0.1.579
IsRejected also recognizes local rejections written before the explicit flag.
func (Record) IsReported ¶ added in v0.1.1220
IsReported is a call an app reported itself (#1874), which never went through magpie. It is shown and counted on the Usage page only: nothing that acts on live traffic (a key's budget, a window's holds, the Sessions page's gateway sessions, what a session was routed to, Codex's sealed answers or remembered model) reads it, since it may be a backfill of calls long past and none of them were magpie's to route.
func (Record) LostRequest ¶ added in v0.1.1182
LostRequest is whether r ends a request the agent got an error for: a failed row that no later try took over from.
func (Record) RetriedRequest ¶ added in v0.1.1182
RetriedRequest is whether r ends a request that was answered after a try that failed first (not one its agent canceled after a failed try).
type Request ¶ added in v0.1.1243
type Request struct {
Header http.Header
// Agent the agent that sent it, Session its native session when it
// names one, else magpie's
Agent, Session string
// Kind its call kind ("web_search", "vision", …), "auxiliary" for
// Claude's tool-less small helper calls, "" for an agent's own turn
Kind string
// Plain is a loopback request with no gateway key, not passed on from
// another magpie: one the agent's own transcript can hold
Plain bool
}
Request is what an Observer is told of a request as it starts.
type RequestPage ¶ added in v0.1.579
type RequestPage struct {
Rows []Row
Sum Totals
Total int
Agents, Providers []string
Purposes []string // all purposes in the period, independent of the selected filter
CallerKeys []Group
// Through and Direct are the rows the gateway served and the rows read
// from the agents' own session files, which the gateway never saw. Sum
// is the two together; the page shows the three beside each other so a
// reader can tell what magpie carried from what it only read about.
Through, Direct Totals
// Reported are the calls a client told magpie of (#1874), which went
// straight to their vendor: counted in Sum, apart from both of those.
Reported Totals
// Accounts are the subscription accounts that answered calls in the
// period, by provider and account, for the Account filter (#557)
Accounts []Group
Bucket string
Series []SeriesPoint
By map[string][]Share
ChartBy map[string][]Share // the whole period's legend while a day is selected
// Computers are the rows told apart by the computer they were made on,
// ThisComputer's and each other's by id, of the rows without the
// filter's computer, and Names what the others are called: none when no
// other computer's calls were brought here by sync (#542)
Computers []Share
Names map[string]string
// Speeds are the models of the rows the filter keeps, ranked by the
// median speed of their requests (speed_rank.go)
Speeds []ModelSpeed
// Heat is the rows by day, as the chart's filter keeps them: only for
// the heatmap's own period (HeatmapOf)
Heat *Heatmap
// Big is the request that wrote the most to the cache, of the rows the
// filter keeps
Big BigWrite
}
type Row ¶ added in v0.1.408
type Row struct {
Record
// SessionRole is the query-time Codex actor classification. Unknown is
// explicit so a shared session header cannot make an unpaired call look
// like its root thread.
SessionRole string `json:"session_role,omitempty"`
// Cost is the call's effective 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"`
// Routed marks a remote magpie group answered by one of its members.
Routed bool `json:"routed,omitempty"`
// Source is "log" for a call read from an agent's own session file,
// which the gateway never saw: no status, no provider, no model asked
// for, but what the file says of the call. "" for one the gateway logged.
Source string `json:"source,omitempty"`
// Client is the client's own name when the user counts it as another
// agent (settings.ClientAgents, #1958): Agent is the one it is
// counted as, this what the ledger recorded it as
Client string `json:"client,omitempty"`
// contains filtered or unexported fields
}
Row is one call as the ledger lists it.
func (Row) Decode ¶ added in v0.1.1220
Decode is the row's DecodeOf, a Codex turn of one call from its session file held to CodexWindowMs and CodexBodyTokens.
func (Row) Floor ¶ added in v0.1.1180
Floor is the tokens and ms a row read from a session file tells the least its reply wrote at by, when its speed wasn't measured. 0, 0 when it tells none. app.js's ledFloorSpeed is the same rule for one row.
Mostly it is its output over its whole time, the wait for the first token in it, for a reply of 1,000 tokens or more over a second or more (a shorter one's wait is too much of it to tell anything; against Claude Code's own stream a floor read 2-5% under for 1,400 tokens or more, 11-33% for a shorter one) and no faster than MaxDecodeSpeed. A count of tokens is what bounds the share the wait can be, not a duration: a 5 s reply can be 4 s of wait (Fallmonkey on Discord asked for 5 s instead).
A Codex turn of one call that reasoned has its first token from the turn's end, but not its first text, so DecodeOf tells no speed. Its answer, its output less the reasoning, was all written after the first token, so the answer over the time from the first token to the end is a floor of the answer's speed, the reasoning written after the first token counted in its time. Its output over that time, as Fallmonkey asked, would count the reasoning written before the first token too and read high: a gateway reply of 496 tokens, 224 of them reasoning, 827 ms after a 10.2 s first token, reads 600 tok/s so, its measured answer 415, and this 329. That window is held to what a measured one is (CodexWindowMs, CodexBodyTokens): 827 ms can be one push as well.
A Codex turn of one call that tells neither, its window after the first token too short or its body too small, tells its output over the whole turn, the wait for the first token in it, by the same rule as any other such floor: 1,000 tokens or more over a second or more. It is the same formula, so it has the same gate: under 1,000 tokens the wait is too much of the time to tell anything (Fallmonkey on Discord: 11 tokens in 2.75 s read ≥4 tok/s while an 815-token Claude Code reply told nothing).
type SeriesPoint ¶ added in v0.1.579
SeriesPoint is a point of the timeline with its calls told apart, by each dimension, for a chart to stack them: the models of one point, say.
func LedgerSeries ¶ added in v0.1.579
func LedgerSeries(p Period, rows []Row) (bucket string, pts []SeriesPoint)
LedgerSeries is the rows of a period, the ledger's or a filter's, summed by hour, day or week, for the chart over them. A row is of the point its time falls in; the rows are in any order.
type Share ¶ added in v0.1.579
type Share struct {
}
Share is one provider's, agent's or model's part of some rows.
type SharedCall ¶ added in v0.1.653
type SharedCall struct {
}
SharedCall is a call as the ledger has it: Source "log" for one read from an agent's session file.
type SharedDay ¶ added in v0.1.653
type SharedDay struct {
}
SharedDay is one computer's calls of one day, as it puts them on the server.
type Summary ¶
type Summary struct {
Period Period `json:"period"`
Since time.Time `json:"since"`
Totals
Bucket string `json:"bucket"` // hour | day | week
Series []Point `json:"series"`
Agents []Group `json:"agents"`
Models []Group `json:"models"`
ProviderKeys []Group `json:"providerKeys"`
// Accounts are the subscription accounts' calls, by provider and the
// account that answered (#557)
Accounts []Group `json:"accounts"`
CallerKeys []Group `json:"callerKeys"`
// Sessions are the calls that named their session, by session, the
// most tokens first: all of them, or the top few of SessionCount where
// it was asked for that way (SummarizeTop).
Sessions []Group `json:"sessions"`
SessionCount int `json:"sessionCount"`
}
Summary is a period, summed up.
func Direct ¶ added in v0.1.869
Direct is a period's calls the agents made on their own, which the gateway never saw: those their session files record (Codex, Claude Code, Claude Desktop…), summed up as Summarize sums the gateway's, by agent, model and account. The Usage page's Requests tab and the tray panel count them beside the gateway's; magpie usage and the TUI show them in a part of their own (Kumo31 on Discord: Codex used outside magpie was on the window's Usage tab but not in magpie usage).
func Summarize ¶
Summarize caches the four periods over an indexed log snapshot. Callers receive their own result slices, without retaining historical Records.
func SummarizeTop ¶ added in v0.1.1173
SummarizeTop is Summarize with only the top n sessions by tokens (all of them for n < 0); SessionCount says how many the period has. It is what a page that shows a few of them or none asks for: a summary of more than summaryCacheSessions sessions is kept with those only, and Summarize, which gives every one, works it out again each time. Over a long history (Vantiboo1ean, ~750k requests in ~84k sessions) that was every refresh of the Usage page and the TUI, and the page was sent all 84k.
type Totals ¶
type Totals struct {
// Calls are the requests, Errors those the agent got an error for, and
// Retried those answered after a try that failed first (Record.Tries):
// a try handed on is in neither count, but its tokens are in the sums.
// Canceled are those the agent canceled before they were answered
// (Record.Canceled): neither an error nor answered
Calls int `json:"calls"`
Errors int `json:"errors"`
Retried int `json:"retried,omitempty"`
Canceled int `json:"canceled,omitempty"`
// Loops are those of Errors magpie ended for looping (LoopErrType):
// a model's count of them says how often it got stuck (#1858)
Loops int `json:"loops,omitempty"`
Input int `json:"input"`
Output int `json:"output"`
CacheRead int `json:"cache_read"`
CacheWrite int `json:"cache_write"`
// CacheWrite1h is how many of CacheWrite were 1-hour writes
CacheWrite1h int `json:"cache_write_1h,omitempty"`
// CacheUnknown is how many of the prompt's tokens (Input, CacheRead
// and CacheWrite) were of calls whose vendor counted no cache
// (Record.CacheUnknown), CacheUnknownCalls how many calls they were:
// a hit rate is CacheRead over the prompt less CacheUnknown, and none
// when nothing is left (#3464)
CacheUnknown int `json:"cache_unknown,omitempty"`
CacheUnknownCalls int `json:"cache_unknown_calls,omitempty"`
Reasoning int `json:"reasoning"`
Cost float64 `json:"cost"` // USD at the effective price, for the priced calls
Unpriced int `json:"unpriced"` // calls with tokens but no known price
// Credits are what the vendors said Credited of the calls cost in
// their plans' own credits (Record.Credits): the rest said nothing
Credits float64 `json:"credits,omitempty"`
Credited int `json:"credited,omitempty"`
// Timed: the answered calls whose first token was timed (streamed),
// TTFT the sum of their ttft_ms; DecodeMs the time from it to the end
// of those that wrote any, over which DecodeOut tokens came (a
// reasoning reply's answer, Record.Decode): their mean wait, and how
// fast they wrote (#196)
Timed int `json:"timed,omitempty"`
TTFT int64 `json:"ttft_ms,omitempty"`
DecodeMs int64 `json:"decode_ms,omitempty"`
DecodeOut int `json:"decode_out,omitempty"`
// DecodeN is how many replies DecodeMs and DecodeOut are of: the ones
// whose speed was measured, which a speed is shown with, so a group of
// 260 calls whose speed is one reply's says so (Fallmonkey on Discord)
DecodeN int `json:"decode_n,omitempty"`
// FloorOut tokens over FloorMs are the least FloorN replies read from a
// session file wrote at, those whose speed wasn't measured (Row.Floor):
// what a group shows, as "≥", beside how many it is of, after its
// measured speed when it has one. They are never in Speed.
FloorOut int `json:"floor_out,omitempty"`
FloorMs int64 `json:"floor_ms,omitempty"`
FloorN int `json:"floor_n,omitempty"`
// UpBytes, DownBytes and ImageFilesSaved are the rows' own summed
// (Record.UpBytes …): what went up to the vendors and came back, of
// the rows that kept it; none when no row did
UpBytes int64 `json:"up_bytes,omitempty"`
DownBytes int64 `json:"down_bytes,omitempty"`
ImageFilesSaved int64 `json:"image_files_saved,omitempty"`
// UpCalls is how many rows sent any bytes up, what UpBytes is spread
// over; UpMeasured the bytes of those whose parts were read
// (Record.UpParts), and UpSystem, UpTools and UpImages those parts
// summed: the conversation is UpMeasured less the three
UpCalls int `json:"up_calls,omitempty"`
UpMeasured int64 `json:"up_measured,omitempty"`
UpSystem int64 `json:"up_system,omitempty"`
UpTools int64 `json:"up_tools,omitempty"`
UpImages int64 `json:"up_images,omitempty"`
}
Totals is a sum of calls.
func (Totals) AllTokens ¶ added in v0.1.579
AllTokens is what went in and out and through the cache.
func (Totals) Floor ¶ added in v0.1.1180
Floor is the least the replies whose speed wasn't measured wrote at, in tokens a second (Row.Floor): 0 for none.
func (Totals) HitRate ¶ added in v0.1.1430
HitRate is the share of the prompt read from the cache, of the calls whose vendor counted it; false when none did (#3464).
func (Totals) MeanTTFT ¶ added in v0.1.392
MeanTTFT is the mean ms to the first token of the timed calls, 0 for none.
type UpParts ¶
type UpParts struct {
System int `json:"system,omitempty"`
Tools int `json:"tools,omitempty"`
Images int `json:"images,omitempty"`
}
UpParts is a request's bytes up by what they were: the agent's own prompt and instructions (system prompt, skills, memory), the tools' definitions, and the images and documents it sent inline, each scaled to the bytes that went up (Record.UpBytes). The rest is the conversation: the messages, the tool calls and their results, which an agent sends again whole on every request.
type Via ¶ added in v0.1.284
type Via struct {
Provider string `json:"provider"`
Model string `json:"model"`
Effort string `json:"effort,omitempty"`
Calls int `json:"calls"`
Tokens int `json:"tokens"` // in and out, as Totals counts them
Last time.Time `json:"last"`
// Credits are what Credited of the calls cost in the plan's own
// credits, as their replies said (Record.Credits)
Credits float64 `json:"credits,omitempty"`
Credited int `json:"credited,omitempty"`
}
Via is where the gateway sent a session's calls: one model at one reasoning effort, how often and how much.
type ViaIndex ¶ added in v0.1.1291
type ViaIndex struct {
// contains filtered or unexported fields
}
ViaIndex is Vias' answer: the one copy every caller shares, handed out whole and read only through Of, which gives each session's list as a copy of its own. Each ask cloned every session's list, ~66 MB a time over ~720k calls, where a page reads the few sessions it lists (#2776).
func Vias ¶ added in v0.1.284
Vias is what the gateway sent each session's calls to since a time, by agent id and the session's id ("codex|<id>"), the most calls first.
type Watch ¶ added in v0.1.1243
type Watch interface {
// Attempt is each routing attempt, unbilled failures and retries
// included, timed as the attempt and not the whole request
Attempt(Record)
// End is the request's end: its time, agent, model, status and length
End(Record)
}
Watch is one request an Observer watches.
Source Files
¶
- backup_log.go
- big_write.go
- block_price.go
- catalog_asks.go
- cleared.go
- client_agents.go
- codex_actors.go
- codex_identity.go
- codex_used.go
- cold_split.go
- derived_idle.go
- direct.go
- effort_split.go
- feed.go
- gateway_alias.go
- gateway_sessions.go
- heat_digest_disk.go
- heat_disk.go
- heatmap.go
- ledger.go
- log_change_linux.go
- log_disk.go
- log_file.go
- log_file_other.go
- log_index.go
- match_chunks.go
- observe.go
- page_split.go
- period_range.go
- plugin_calls.go
- plugin_outside.go
- probes.go
- purpose.go
- refset.go
- reported.go
- request_build_share.go
- request_cells.go
- request_disk.go
- request_disk_map_unix.go
- request_page.go
- request_pairs.go
- request_snapshot.go
- request_spill.go
- served.go
- session_provider.go
- shared.go
- speed_rank.go
- spend.go
- summary_cache.go
- summary_fold.go
- usage.go
- vias_cache.go
- visit_from.go
- window_holds.go
- window_holds_carry.go
- window_holds_history.go
- zone.go