Documentation
¶
Overview ¶
Package pricing owns model rates and the arithmetic that turns tokens into dollars. Before it, rates lived in two plugins' configs — 16 fields between them — and dollars were computed in four places, which is how a stale "understates by 4x" comment survived a gateway repricing.
Cost is the only implementation of that arithmetic now. One multiplication survives outside it, in tool-prune's metrics (tokens x rate for its own $ saved counter), which therefore skips this package's micro quantization and can disagree with the rendered figure in the last digit.
The package holds no I/O and no provider knowledge. A rate table is built once at startup and swapped atomically; resolution is a pure function of (endpoint, model, prompt size).
Index ¶
- Constants
- func AvoidedUsage(u Usage, tokens int) (Usage, Tier)
- func Cost(r Rates, u Usage) (int64, bool)
- func EndpointKey(endpoint string) string
- func EstimateTokensFromBytes(bytesRemoved, promptTokens, bodyBytes int) int
- func IncompleteReason(inf *pipeline.InferenceExtension) string
- func MicrosFromUSD(usd float64) (int64, bool)
- func MicrosOrZero(usd float64) int64
- func PlausibleRequestCostUSD(usd float64) bool
- func PlausibleUsage(u Usage) bool
- type Config
- type ContextThreshold
- type Description
- type Effective
- type EffectiveRates
- type EndpointConfig
- type Entry
- type ModelConfig
- type MultiplierRule
- type MultiplierView
- type Provenance
- type Rates
- type Refusal
- type Registry
- func (r *Registry) Cost(endpoint, model string, u Usage) (micros int64, prov Provenance, ok bool)
- func (r *Registry) Describe() Description
- func (r *Registry) EffectiveFor(host string) Effective
- func (r *Registry) Handler() http.HandlerFunc
- func (r *Registry) Resolve(endpoint, model string, promptTotal int) (Rates, Provenance)
- func (r *Registry) Swap(t *Table)
- type Resolver
- type ResolverConsumer
- type RowView
- type Table
- type ThresholdConfig
- type ThresholdView
- type Tier
- type TierRates
- type Usage
Constants ¶
const ( // ReasonOutputUncounted: the prompt was counted and whatever was generated never // was, so the figure is a FLOOR — the real cost is this plus an unknown completion. // // The case it exists for is a truncated Anthropic stream: prompt counts land on // message_start and the output count only on message_delta, so a stream dying in between // finalizes with real prompt tokens and output at zero. // // KNOWN BOUNDARY, deliberately not closed. The discriminator is the stop reason (see // outputUncounted), so a response carrying a stop_reason but no usage block reads as EXACT // even though its output was never tallied. Closing that would flag every response whose // output legitimately WAS zero — an immediate refusal, a max_tokens of zero — because those // are indistinguishable by counters alone, and a false caveat on ordinary traffic is how an // operator learns to ignore the real signal. A test row pins it ("stop reason with zero // output is exact"). If the omitted-usage shape is ever OBSERVED, the fix is a new reason // keyed on something that distinguishes it, not a weakening of this one. ReasonOutputUncounted = "output-uncounted" // ReasonSplitUnreported: the provider reported a total and no per-kind split, so the figure // is APPROXIMATE rather than low. UsageFromInference attributes such a total wholly to // uncached input, which over-prices a cache-heavy request (a cache read bills at ~0.1x) and // under-prices a generation-heavy one (~5x), with no way to say which from one number. // // A property of the gateway rather than the request, so a consumer presents it as a standing // caveat on precision, never as an incident. ReasonSplitUnreported = "split-unreported" // ReasonCountersBelowTotal: the response's OWN total exceeds the counters that were priced, // so tokens were reported and attributed to no tier. A floor, like ReasonOutputUncounted, on // different evidence — there a stop reason is missing, here the parts do not add up to the // stated total. // // NAMED FOR THE EVIDENCE, not the tier, because the tier is what is unknown: a // short-reported prompt produces identical arithmetic, and a wrong tier in the label sends // an operator to the wrong side of the request. ReasonCountersBelowTotal = "counters-below-total" )
Reasons a figure modelled from an inference extension's counters is not an exact total. Returned by IncompleteReason and carried per-request on the cost record.
Separate reasons rather than one "incomplete" boolean because a consumer acts on them differently: a floor is known-LOW and bounded on one side, an approximation has no known direction. Collapsed, a totals-only gateway — a permanent property of that gateway — would be indistinguishable from a truncated stream, which is a transient failure worth chasing.
Wire strings, travelling on costevent.Event.IncompleteReason: hyphenated lowercase, like Provenance.
const BundledUpstreamCommit = "ee7c7e14f3dd7c4c3930a423440ec26427e2c554"
BundledUpstreamCommit is the BerriAI/litellm commit this table was generated from. Pinned so "refresh the rates" is a scripted diff against a known base rather than a measurement exercise, and so the golden test can prove the checked-in table still matches its snapshot.
const MaxCostMicros = 1 << 53
MaxCostMicros bounds ONE request's conversion into the micros unit. It is a REPRESENTABILITY bound and nothing more — see "what it does not bound" below, which is the half that is easy to overstate.
float64 counts every integer exactly only up to 2^53, so a total beyond that cannot round-trip through int64 meaningfully even when it fits. $9 billion for one request is unreachable by any legitimate traffic and is the point past which a figure is a bug rather than a bill.
EXPORTED so the one bound serves every producer of a micros figure. costevent's header path accepts any finite non-negative float, and its Micros() conversion was unguarded — so a header of 1e13 saturated to MaxInt64 and put a garbage figure where a ledger row was expected. A second bound declared over there would be free to drift from this one; there is only ever one answer to "past which figure is this a bug".
WHAT IT DOES NOT BOUND: THE ACCUMULATED SUM. 1,024 requests at this bound wrap usage.Counts.Add to a large negative total, and NO per-request bound can close that — for any bound C the sum wraps after MaxInt64/C requests, so a smaller C buys distance, not closure. Closing it takes a checked accumulate where the sum is kept, which the aggregate PR in this series does. TestNoPerRequestBoundClosesTheAccumulationWrap pins the reasoning; until that PR lands this is an open defect and not history, reachable through a header on a parsed path.
EXCLUSIVE: exactly MaxCostMicros is out of range. 2^53 is the first integer whose successor float64 cannot represent, so 2^53+1 rounds back onto it — at that one value an out-of-range figure is indistinguishable from an in-range one. Excluding it makes "accepted" mean "exactly representable and distinct from its neighbours".
const MaxPlausibleRequestCostMicros int64 = maxPlausibleTokens * maxPlausibleMicrosPerToken
MaxPlausibleRequestCostMicros is the most ONE inference request could plausibly cost: maxPlausibleTokens at maxPlausibleMicrosPerToken, which is 1e10 micros — $10,000.
A BLAST-RADIUS CAP, NOT AUTHENTICATION. It says nothing about who reported the figure and cannot: a gateway's cost header is an unauthenticated string on a response, and any host a client is proxied to can put any number in it. What the cap does is bound what a figure this process could not corroborate is allowed to contribute, so that one forged header cannot exhaust a daily budget, poison a thirty-day ledger row, or push an aggregate towards the int64 wrap that MaxCostMicros documents. What it does NOT do: stop a forgery UNDER the cap (that is spend an operator has to reconcile against the gateway's own accounting), authenticate the reporting host (a host allowlist would, and remains the stronger fix), or bound the accumulated sum (see MaxCostMicros).
COARSE ON PURPOSE. The worst real call anyone can construct — a 1M-token opus-5 prompt plus a 64k completion — is about $7, so this leaves three orders of magnitude of headroom. The cap exists to make a forged figure merely wrong rather than catastrophic; set near real traffic it would refuse real bills the first time a vendor reprices, which is a coverage gap that looks exactly like the defect it guards.
INCLUSIVE, unlike MaxCostMicros: 1e10 micros is exactly representable with representable neighbours, so there is no ambiguous edge to exclude, and "the most a request could plausibly cost" is by construction still plausible.
const MaxPlausibleTokens = maxPlausibleTokens
MaxPlausibleTokens is the largest token count one request could plausibly report, per field. See maxPlausibleTokens for the derivation — this is that constant, exported.
It exists because authlib/usage refuses an implausible token report and needs the same bound: the token fields arrive as a provider-controlled `int` on the wire, so without one a forged response that cannot move the dollar total past $10,000 could still move the token total by 9.2e18, and a client renders the two side by side.
NO IMPORTER ON THIS BRANCH: the consumers are usage.maxPlausibleRequestTokens (#1013 of this stack) and the ledger writer's admission guard (#1014), so a grep at this commit finds only the declaration. Exported anyway because the split put the derivation here and its readers in the next two PRs — and because two literals that must agree is the shape that let config's retention floor drift from the window it protects.
const NumTiers = numTiers
NumTiers is numTiers for callers outside this package, so a consumer sizing a per-tier array names the constant instead of writing 4 — a literal that would go stale silently if a tier were ever added, which is the failure numTiers' own doc says arrays exist to prevent.
Variables ¶
This section is empty.
Functions ¶
func AvoidedUsage ¶
AvoidedUsage places an estimated prompt-token saving into the single tier the request's prompt actually landed in.
One tier, not spread across them: the removed bytes were part of one prompt, and that prompt was billed as cache-write, cache-read or fresh input. Which one changes the answer by up to 12.5x, so the choice is the whole substance of the figure and belongs beside PromptTier rather than in a caller.
A deliberate simplification: a prompt can straddle tiers — some cached, some fresh — and PromptTier picks the dominant one. Attributing the saving to the dominant tier is the best available answer without knowing WHERE in the prompt the removal happened.
func Cost ¶
Cost prices u at r, returning integer micros — millionths of a dollar.
Micros because usage.Counts.CostMicros is already that unit, and integer addition across ring buckets is exact where repeated float addition is not.
ok is false when the request is UNPRICED, which is a different answer from a cost of zero. Four ways to be unpriced:
- A tier that carried tokens has no rate. The invariant: a request is priced only if every tier it used had a rate, so a partial table produces a named gap rather than a total that is quietly too low. toolprune holds the same rule on the counting side (metrics.unpriced): name the gap rather than charge one model's tokens at another model's rate.
- No tokens were reported at all. That is unknown usage, not a free request; counting it as priced-zero would dilute the coverage denominator.
- A negative count, which is a parser bug or a hostile body. A negative cost would corrode a running total that nothing re-derives.
- A count above maxPlausibleTokens, on the same reasoning and from the same wire. THE MODELLED FIGURE WAS THE UNBOUNDED ONE: headerCost refuses a gateway's figure past MaxPlausibleRequestCostMicros ($10,000), and the aggregate PR in this series WILL refuse an implausible token report and count it (usage.plausibleTokenReport, Counts.RefusedTokenRequests — neither exists at this commit) — while the money derived from those same counts arrived here and was believed, bounded only by MaxCostMicros, which is $9 billion. So one response could have its tokens called impossible and its dollars kept, in the same aggregate, side by side in the same client.
- A modelled figure past MaxPlausibleRequestCostMicros ($10,000), which is the ceiling a gateway's own figure is already held to. Bounding the counts does NOT make this bound follow arithmetically, tempting as that reading is: the token check is per TIER, so a request can carry maxPlausibleTokens several times over, and a base rate has no magnitude bound at all. The two are checked separately because neither implies the other.
- No rates at all, which is the ProvNone case reaching here directly.
- A rate that is negative or non-finite, wherever it came from. Trusting the rate while checking the count would let a hostile or buggy producer emit negative money or MaxInt64 micros.
A tier with no rate but no tokens is fine: toolprune's table has no output rate at all, and refusing there would unprice every request it measures.
func EndpointKey ¶
EndpointKey normalizes a request's target host the way rate resolution normalizes it: lower-cased, port stripped.
Exported so callers that key their own state on an endpoint — the drift reporter's dedup set, for one — agree with matchHost about what counts as the same endpoint. Keeping a private copy of this rule is how "GW.internal:443" and "gw.internal" came to occupy two entries for one gateway.
func EstimateTokensFromBytes ¶
EstimateTokensFromBytes converts a byte-level body reduction into an estimated prompt token reduction, calibrated on the request it came from.
ESTIMATE, and named so. The calibration is this request's own measured ratio — promptTokens over the body size actually sent — which is sound when the removed span had the same token density as what remained, and wrong when it did not. A tool manifest is denser in punctuation than prose, so a prune measured against a prompt of mostly prose overstates its own saving. The output gets quoted in dollars, so that has to be said out loud rather than left for a reader to infer.
bodyBytes must be the size of the body ACTUALLY SENT upstream, which is not the pruned size when a plugin measured a saving without applying it: dividing by the smaller counterfactual size would inflate tokens-per-byte and overstate the saving.
Returns 0 when any input is non-positive, which covers "nothing was removed", "no response yet" and "no body" without the caller distinguishing them — there is no estimate to make in any of those cases.
func IncompleteReason ¶
func IncompleteReason(inf *pipeline.InferenceExtension) string
IncompleteReason names why a figure modelled from inf's counters is not an exact total, or "" when the counters support one.
Only ever consulted for a MODELLED figure. A gateway's own cost header is what the call actually charged whatever our counters managed to observe, so completeness there is the gateway's assertion and not an inference from a token tally — costing.Settle gates this call on the usage-fallback arm for that reason.
The reasons are decided by DIFFERENT instruments, and that asymmetry is what to read before changing anything here: the presence mask is the right test for ReasonSplitUnreported and the wrong one for ReasonOutputUncounted, because the mask's reliability is DIALECT-specific — OpenAI gates each bit on a pointer, Anthropic asserts Input|Output unconditionally. See the block comment at the discriminator.
Takes the extension rather than a Usage because none of the signals it needs — the stop reason, the legacy aggregates, the presence mask — is inside Usage's four tiers.
func MicrosFromUSD ¶
MicrosFromUSD converts a dollar figure to integer micros — millionths of a dollar — reporting false when the result is not a usable ledger figure.
The one conversion, because there is one bound. `int64(math.Round(usd * 1e6))` written by hand at a call site is the shape this replaces — unchecked, it saturates to MaxInt64 and puts a garbage figure where a ledger row is expected; see MaxCostMicros.
ok is false for NaN, an infinity, a negative figure, or anything AT OR ABOVE MaxCostMicros. A caller must treat that as UNPRICED and not as a large number: a clamped figure is a wrong number wearing a right label, and the ring forgets it in six hours while the durable ledger keeps it for thirty days with no repair path.
The SIGN IS CHECKED ON THE INPUT, before rounding, because it does not survive the rounding. math.Round(-1e-07 * 1e6) is math.Round(-0.1), which is NEGATIVE ZERO, and `-0.0 < 0` is false in Go — so this returned (0, true) for every figure in (-5e-07, 0), calling a wrong-signed figure a priced zero and contradicting the paragraph above. Anything at or beyond -5e-07 rounded to -1 and was caught, which is why the hole was only ever the tiny end.
An input of exactly -0.0 IS ZERO and stays priced: `-0.0 < 0` is false here too, and that is correct rather than incidental — negative zero is a value of zero, a settled zero is a producer saying the call was free, and refusing it would report a genuine free call as unpriced traffic.
NaN does not reach this guard (every comparison against NaN is false) and is still caught below, where it always was.
func MicrosOrZero ¶
MicrosOrZero is MicrosFromUSD for a caller with nothing useful to do with a refusal.
For figures that are a RATIO rather than a total: an unrepresentable component makes the ratio less complete and nothing else, where the same failure in a total would be a garbage ledger figure. Do not use it for money anyone is charged.
func PlausibleRequestCostUSD ¶
PlausibleRequestCostUSD reports whether usd could be what ONE inference request cost.
The predicate lives beside the bound so no caller re-derives the comparison, and so the out-of-range case cannot be forgotten: a figure too large for MicrosFromUSD is not plausible either, and reading `micros <= MaxPlausibleRequestCostMicros` off a conversion that failed would compare against a zero and call 1e300 plausible.
func PlausibleUsage ¶
PlausibleUsage reports whether every counter in u could be a real report: non-negative, and no larger than one request could bill for.
EXPORTED BECAUSE THE QUESTION IS ASKED IN TWO PLACES AND MUST HAVE ONE ANSWER. Cost asks it while pricing; costing.Settle asks it BEFORE deriving anything, because a figure derived from an impossible count has to be refused whole — and inferring that from Cost's refusal reason does not work: Cost returns the FIRST problem it meets, so a missing rate on an earlier tier masks the count entirely. Measured with a table that has no input rate: {Input: 1000, CacheRead: -1, Output: 50} refused as "no-rate", and the output half — which zeroes the offending tier along with the prompt — came back priced at $0.0005 on a record disclosing nothing.
These counters are provider-controlled integers on the wire, which is why the bound exists at all; see maxPlausibleTokens for where the ceiling comes from.
Types ¶
type Config ¶
type Config struct {
// Bundled controls whether the shipped price table participates. Default TRUE:
// covering internal usage with no manual setup is the point, and LiteLLM's
// public rates are not a secret. Set false to price only what you configure.
Bundled *bool `yaml:"bundled" json:"bundled,omitempty"`
// Endpoints scopes rates per target. This is what lets one process price
// several gateways and the vendor endpoint differently, which a single global
// rate table cannot: the choice is per REQUEST, not per deployment.
Endpoints []EndpointConfig `yaml:"endpoints" json:"endpoints,omitempty"`
}
Config is the top-level `pricing:` section of an AuthBridge config.
One section for the whole process, not a knob per plugin. Before this, rates lived in two plugins' configs — 12 on tool-prune and 4 on litellm-budget-track — and a deployment that wanted consistent cost had to keep them in agreement by hand.
func (*Config) BundledEnabled ¶
BundledEnabled reports whether the shipped table participates, defaulting to true for a nil Config or an unset field.
func (*Config) WarnIfUnpinned ¶
WarnIfUnpinned logs once at startup when the process will price every endpoint from the bundled table.
The bundled rates are VENDOR LIST. A deployment behind a gateway that bills below list is overstated — measurably so: the gateway these rates replaced billed at 0.76x vendor list, making every figure 1.32x high. Nothing in the running system says so, because an overstated figure looks exactly like an accurate one.
Deliberately a WARN and not an error: pricing from list is a reasonable default and the correct answer for anyone talking straight to the vendor. It is only wrong silently, which is what this fixes.
type ContextThreshold ¶
ContextThreshold is a long-context rate override: above AbovePromptTokens the tiers it Sets replace the base ones.
Tiers it does not set keep their base rate rather than becoming unset. A table that prices only long-context input would otherwise unset output above the threshold, and Cost's per-tier invariant would flip the whole request to unpriced — turning a partial price list into a coverage hole.
type Description ¶
type Description struct {
// UpstreamCommit is the LiteLLM commit the bundled rates were generated from, so a
// figure can be traced to its source without reading the binary.
UpstreamCommit string `json:"upstreamCommit,omitempty"`
Rows []RowView `json:"rows"`
Multipliers []MultiplierView `json:"multipliers,omitempty"`
}
Description is the whole table, unresolved.
type Effective ¶
type Effective struct {
Host string `json:"host"`
// Multiplier and MultiplierFrom are surfaced separately from the scaled rates so an
// operator can see WHY their figures differ from vendor list, rather than being
// handed numbers that match no published price list.
Multiplier float64 `json:"multiplier"`
MultiplierFrom string `json:"multiplierFrom,omitempty"`
Models []EffectiveRates `json:"models"`
}
Effective is the resolved answer for one endpoint.
type EffectiveRates ¶
type EffectiveRates struct {
Model string `json:"model"`
Provenance string `json:"provenance"`
Unpriced bool `json:"unpriced,omitempty"`
// LongContextAbove is the prompt-token count past which DIFFERENT rates apply, or
// 0 when this model has none.
//
// The rates below are the below-threshold ones, because that is what a request of
// unknown size is charged and EffectiveFor resolves at prompt size 0. Without this
// field the view quotes a figure a long-context request will not be charged — the
// same silent-wrong-number failure this package exists to remove, reintroduced by
// the tool built to inspect it. The bundled table ships four such models.
LongContextAbove int `json:"longContextAbove,omitempty"`
// Above* are the rates once LongContextAbove is exceeded, resolved the same way and
// with the same multiplier applied. Present only when LongContextAbove is.
//
// Naming the breakpoint without its prices told an operator that their long sessions
// cost something other than the figures above, and left them to find out what by
// reading the raw table and applying the discount by hand — which is the arithmetic
// this endpoint exists to do for them.
AboveInputPerMillion float64 `json:"aboveInputPerMillion,omitempty"`
AboveCacheWritePerMillion float64 `json:"aboveCacheWritePerMillion,omitempty"`
AboveCacheReadPerMillion float64 `json:"aboveCacheReadPerMillion,omitempty"`
AboveOutputPerMillion float64 `json:"aboveOutputPerMillion,omitempty"`
InputPerMillion float64 `json:"inputPerMillion,omitempty"`
CacheWritePerMillion float64 `json:"cacheWritePerMillion,omitempty"`
CacheReadPerMillion float64 `json:"cacheReadPerMillion,omitempty"`
OutputPerMillion float64 `json:"outputPerMillion,omitempty"`
}
EffectiveRates is what one model actually costs at one endpoint, multiplier included.
type EndpointConfig ¶
type EndpointConfig struct {
// Hosts are globs matched against the request's target host, port stripped.
// An empty list, or any entry of "*", means any endpoint.
//
// A list rather than a single glob because gateways commonly share a rate card:
// two replicas, or a service name and its external alias, bill identically, and
// repeating the whole models block per host invites the two copies to drift.
// Each host becomes its own table row.
Hosts []string `yaml:"hosts" json:"hosts,omitempty"`
// Models maps a model glob to its rates. Keys are matched
// case-insensitively, and an exact key beats a glob.
Models map[string]ModelConfig `yaml:"models" json:"models,omitempty"`
// Multiplier scales every rate that resolves for these hosts. Absent means 1.0.
//
// A FRACTION of the resolved rate, so a 24% discount is 0.76. This is the whole
// configuration most deployments need: a gateway discount is one scalar, and
// stating it once tracks upstream repricing instead of freezing last quarter's
// numbers into a copied rate card. See MultiplierRule.
//
// An endpoint with a multiplier needs no models block — it scales what already
// resolves, including models no entry names.
Multiplier *float64 `yaml:"multiplier" json:"multiplier,omitempty"`
}
EndpointConfig prices the models reached through one endpoint.
func (*EndpointConfig) UnmarshalYAML ¶
func (e *EndpointConfig) UnmarshalYAML(node *yaml.Node) error
type Entry ¶
type Entry struct {
Host string
Model string
Rates Rates
Prov Provenance
}
Entry is one row of a rate table: rates for the models matching Model on the endpoints matching Host.
Host "" and "*" both mean any endpoint — how the bundled slice is scoped, since a shipped table cannot know an operator's gateway names. Model is a glob matched case-insensitively.
func Bundled ¶
func Bundled() []Entry
Bundled returns the price table shipped in the binary.
Deeply copied, thresholds included. The rows are package state shared by every Registry, so a caller that appended to the slice — or wrote through a row's Thresholds, which a shallow copy would still alias — would corrupt every later NewTable in the process.
type ModelConfig ¶
type ModelConfig struct {
TierRates `yaml:",inline"`
// Above overrides the base rates once a request's prompt exceeds a token
// count. Crossing 200k prompt tokens is what a long agent session IS, and
// pricing that traffic at the base rate understates it.
Above []ThresholdConfig `yaml:"above" json:"above,omitempty"`
}
ModelConfig is one model pattern's rates, optionally with long-context overrides.
func (*ModelConfig) UnmarshalYAML ¶
func (m *ModelConfig) UnmarshalYAML(node *yaml.Node) error
type MultiplierRule ¶
type MultiplierRule struct {
// Host is a glob matched against the request's target host, port stripped. Empty
// or "*" scales every endpoint.
Host string
// Factor multiplies each resolved rate. 1.0 means list.
Factor float64
// Prov records where the factor came from. A scaled figure reports the STRONGER of
// its two sources, and it also ranks these rules against each other — an operator's
// factor for an endpoint beats the shipped one. See Resolve for why stronger.
Prov Provenance
}
MultiplierRule scales every rate that resolves for an endpoint.
It exists because a gateway discount is a SCALAR, not a rate card. Some gateways bill a uniform fraction of vendor list — one was measured at exactly 0.7600 across three models and all four tiers, twelve figures agreeing to four decimal places. Expressing that as twelve copied numbers has two costs a multiplier does not:
- Twelve chances to fumble a decimal place, in a file nothing validates against the gateway.
- It goes stale silently the moment Anthropic reprices. The gateway's price is DERIVED from list, so a multiplier tracks a repricing automatically once the bundled table is refreshed, while copied rates keep reporting last quarter's numbers with no indication they are wrong.
type MultiplierView ¶
type MultiplierView struct {
Host string `json:"host,omitempty"`
Factor float64 `json:"factor"`
Provenance string `json:"provenance"`
}
MultiplierView is one endpoint discount rule.
type Provenance ¶
type Provenance int
Provenance says where a rate came from, so every reported figure carries its own credibility instead of looking equally authoritative either way.
Ordered by precedence: a higher value wins a resolution. That is the whole reason these are ranked rather than named — see Table.Resolve.
const ( // ProvNone means no rate was found. The request is unpriced, which is not the // same as free. ProvNone Provenance = iota // ProvBundled is the price table shipped in the binary. A starting point that // needs no configuration, not a fact about the operator's account. ProvBundled // ProvDiscovered is a rate learned from the gateway itself rather than configured. // // NOTHING PRODUCES THIS TODAY. Fetching rates from LiteLLM's /model/info was // designed and prototyped, then dropped: it would have bought avoiding the // transcription of three numbers that change on the order of months, and cost a // virtual key to mint and mount, an outbound dependency, and a refresh loop. // Pinning a gateway in `pricing:` does the same job in eight lines of YAML. // // The level remains because the precedence is the durable part — a rate learned // from a gateway should beat the shipped table and lose to an operator's explicit // override — so anything that later learns rates from one has a defined place to // land. See provenance_ordering_test.go. ProvDiscovered // ProvConfigured is an explicit pricing.endpoints[].models entry. An override // is an override, so it outranks a fetched value. ProvConfigured // ProvAuthoritative is a real observed cost for one request — LiteLLM's // X-Litellm-Response-Cost or its -Original variant. Not a rate but a settled // figure, so it never appears in a rate table and bypasses Cost entirely. // NewTable rejects it. ProvAuthoritative )
func ProvenanceFromString ¶
func ProvenanceFromString(s string) (Provenance, bool)
ProvenanceFromString is the inverse of String, for a level that has been through JSON.
False for anything unrecognized rather than defaulting: provenance decides precedence and drives WarnIfUnpinned, so a silent fallback to a valid-looking level would either suppress a warning an operator needs or outrank a rate they configured.
func (Provenance) String ¶
func (p Provenance) String() string
type Rates ¶
type Rates struct {
Base [numTiers]float64
Set [numTiers]bool
Thresholds []ContextThreshold
}
Rates is one (endpoint, model) pair's rates, in USD per token.
Set exists because a zero rate and an absent rate are different answers. Zero means free; absent means unknown, and Cost refuses to price a request whose tokens land on an absent tier (see Cost).
func (Rates) At ¶
At flattens Rates for a prompt of promptTotal tokens: the highest threshold strictly exceeded, overlaid on Base, with Thresholds cleared.
Strictly exceeded, not met — "$X above 200k tokens" means the premium starts at token 200,001, so a request of exactly 200k pays base.
The scan takes the maximum exceeded threshold rather than the first, so At does not depend on slice order. Order-dependence here would be a footgun with no visible symptom: a config or test that happened to list thresholds ascending would price long context at the lower premium and look plausible.
Idempotent: the result carries no thresholds, so flattening it again returns it unchanged. Resolve hands out flattened rates and Cost flattens again.
func (Rates) For ¶
For returns the rate for one tier and whether a rate is actually available.
The bool is the per-tier invariant in accessor form, and it is the whole reason this is not a plain field read: Set is per tier, so a model priced only for cache reads must report "no rate" for a cache write rather than the zero value. Cost enforces the same rule across a whole request; consumers that publish individual rates (tool-prune's per-request event) use this.
Call it on rates from Resolve or At, which are already flattened for the request's prompt size. On unflattened rates it reads the BASE tier and ignores thresholds — correct for "what is this model's list rate", wrong for pricing a specific request.
type Refusal ¶
type Refusal string
Refusal names WHY Cost declined to price a request, for the one caller that has to tell the causes apart.
A wire-shaped string like IncompleteReason, but this one is NOT a wire value: it exists so costing.Settle can decide whether a refusal is worth DISCLOSING on the published record. Two of these are claims about impossible input and belong in front of an operator; the rest are ordinary coverage gaps — no rates configured for a model, no counters in the response — which a client already renders as unpriced and which would be noise as a disclosure.
const ( // RefusalNone: nothing was refused. RefusalNone Refusal = "" // RefusalNoTokens: the response reported no counters at all, so there is nothing to // price. Unknown usage, not a free request. RefusalNoTokens Refusal = "no-tokens" // RefusalImpossibleCount: a count no request could have reported — negative, or past // maxPlausibleTokens. DISCLOSED, because it is a statement about the response's own // numbers rather than about our configuration. RefusalImpossibleCount Refusal = "impossible-count" // RefusalNoRate: a tier that carried tokens had no rate, or the rate was negative or // non-finite. A configuration gap, and the reason a partial total is never presented as // a whole one. RefusalNoRate Refusal = "no-rate" // RefusalUnrepresentable: the arithmetic left the micros unit, which MicrosFromUSD // refuses rather than return a garbage ledger figure. RefusalUnrepresentable Refusal = "unrepresentable" // RefusalImplausibleTotal: a figure past MaxPlausibleRequestCostMicros ($10,000), the // same ceiling a gateway's own header is held to. DISCLOSED, because the cause is on our // side — an operator's typo in a rate, or a rate discovered from a gateway — and it // unprices every request that rate touches while looking like traffic nobody had rates // for. RefusalImplausibleTotal Refusal = "implausible-total" )
func CostByTier ¶
CostByTier is Cost's arithmetic with the per-tier amounts kept instead of summed away.
ONE PASS, ONE `eff`. The alternative is what Settle does for its prompt and output halves: call Cost again with the other tiers zeroed. That re-resolves the rate table against a MODIFIED prompt total on each call and re-applies the per-request plausibility ceiling to each fragment, which is forty lines of guard reasoning in costing.go. This returns a decomposition of the same float sum the total is built from, so the tiers are mutually consistent by construction and no fragment can pass or fail a bound the whole did not.
THE TIERS NEED NOT SUM EXACTLY TO total. Each is converted to micros independently, so four truncations can differ from one by a few micros. Callers use them as a RATIO — see usage.Counts.ApportionTiers — where truncation is invisible. Nothing may present this array as a total.
The refusals below are Cost's own, unchanged: this function IS Cost's body, and CostWithReason now delegates to it.
func CostWithReason ¶
CostWithReason is Cost, and says why when it refuses.
Split out rather than folded into Cost's signature because three call sites want the figure and one wants the cause: costing.Settle publishes a refusal an operator can act on, and telling "this rate table is wrong" from "this model has no rates" is the whole difference between a signal and a shrug. Every refusal below is one of Cost's documented four-plus ways to be unpriced, named rather than collapsed into a bare false.
A two-line delegation to CostByTier, which holds the arithmetic and every refusal above. Signature unchanged: three call sites want the figure and one wants the cause, and none of them needs the split.
func (Refusal) ImpossibleFigure ¶
ImpossibleFigure reports whether a refusal was about the SIZE of the derived figure rather than a missing or unusable input.
EXPORTED FOR THE SAME REASON AS PlausibleUsage: the question is asked in two places and must have one answer. costing.Settle asks it to refuse both HALVES of a request whose whole was refused, and again to disclose that refusal on the record.
TWO REFUSALS SAY IT, AND WHICH ONE APPEARS IS DECIDED BY CHECK ORDER, NOT BY MAGNITUDE. Cost tests MicrosFromUSD before MaxPlausibleRequestCostMicros, so a figure is RefusalImplausibleTotal only while it stays under MaxCostMicros (~$9.007e9); past that it is RefusalUnrepresentable, which is the LARGER and more obviously broken case. Keying a caller on the plausibility label alone therefore covers the smaller half of the range and silently drops the rest — measured at $1e6 per input token: the whole and the prompt half were refused as unrepresentable, the $5,000 output half came back priced, and because the disclosure keyed on the same label the record carried NO RejectedReason at all. An unnameable coverage gap is the failure refusing-rather-than-clamping exists to prevent, so both labels are named here, once.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry is the long-lived Resolver every consumer holds.
It exists because of a lifetime mismatch in the proxy. buildPipelines is a closure the config reloader re-invokes on every change (cmd/authbridge-proxy/main.go:296,300), so plugins are reconstructed; but the usage aggregator that shares the same rates is created once, outside that closure (main.go:370), and outlives every rebuild. A resolver reconstructed per build would leave the aggregator holding a stale table forever, and pricing would silently diverge between /v1/usage and the plugins.
So the table is swapped in place and the Registry pointer never changes. Readers hold the Registry; the reloader hands it a new Table.
func NewRegistry ¶
NewRegistry returns a Registry serving t. A nil t is legal and prices nothing — an operator with no pricing config and the bundled slice disabled.
func (*Registry) Cost ¶
Cost resolves and prices in one call — the shape every consumer actually wants.
Provenance collapses to ProvNone whenever ok is false, including when a row DID match but its tiers do not cover the request. Reporting "bundled" alongside a figure of zero would label an absent answer as a sourced one, which is the mislabelling this package's provenance exists to prevent.
func (*Registry) Describe ¶
func (r *Registry) Describe() Description
Describe on the Registry reads the live table. Nil-safe, matching Resolve: a binary with no pricing wired reports an empty table rather than crashing a status handler.
func (*Registry) EffectiveFor ¶
EffectiveFor on the Registry reads the live table.
func (*Registry) Handler ¶
func (r *Registry) Handler() http.HandlerFunc
Handler serves the pricing table for inspection on the diagnostic listener, beside /config and /reload/status.
GET /pricing/table the raw table: every row and multiplier, unscaled GET /pricing/table?host=H what H actually charges, multiplier applied
The host form is the one worth having. "Which rows exist" is answerable from the source; "what will this gateway charge me" requires host scoping, specificity, provenance precedence and the discount to be applied together, which is not something a reader can carry out by eye — and is exactly the gap that let a 0.76x gateway be reported at vendor list for months.
func (*Registry) Resolve ¶
func (r *Registry) Resolve(endpoint, model string, promptTotal int) (Rates, Provenance)
Resolve implements Resolver.
A nil Registry resolves to ProvNone rather than panicking: a binary built without pricing wiring must report its traffic as unpriced, not crash on the response path. Same posture as a nil Table.
type Resolver ¶
type Resolver interface {
Resolve(endpoint, model string, promptTotal int) (Rates, Provenance)
}
Resolver hands out rates for a request. An interface so a plugin can be tested against a fixed table, and so discovery (phase 7) can wrap a Table rather than reach inside it.
promptTotal is the request's prompt-side token count: the returned Rates are already flattened through Rates.At for that size, so a caller cannot forget to apply a long-context premium.
type ResolverConsumer ¶
type ResolverConsumer interface {
SetPricingResolver(Resolver)
}
ResolverConsumer is implemented by plugins that need to turn tokens into dollars. plugins.BuildWithDeps injects the process Resolver before Configure runs, so a plugin's configuration code can reach it.
This mirrors spiffe.ProviderConsumer exactly, and for the same reason: plugin factories take no construction arguments (see plugins.PluginFactory), so a process-wide dependency has to arrive by injection rather than through the plugin's own config. Sharing the shape means the registry's injection path and its need-detection probe work the same way for both.
A plugin must tolerate never being called — a build that opted out of pricing passes nothing, and the plugin's zero-value Resolver must then report traffic as unpriced rather than panicking. Holding a *Registry satisfies that for free, since a nil *Registry resolves to ProvNone.
type RowView ¶
type RowView struct {
Host string `json:"host,omitempty"`
Model string `json:"model"`
Provenance string `json:"provenance"`
InputPerMillion float64 `json:"inputPerMillion,omitempty"`
CacheWritePerMillion float64 `json:"cacheWritePerMillion,omitempty"`
CacheReadPerMillion float64 `json:"cacheReadPerMillion,omitempty"`
OutputPerMillion float64 `json:"outputPerMillion,omitempty"`
Thresholds []ThresholdView `json:"thresholds,omitempty"`
}
RowView is one rate-table row, in the unit providers publish.
A zero rate means UNSET, not free: config rejects a zero and the generator drops it, so nothing legitimate produces one. Rendered with omitempty so an absent tier reads as absent rather than as a price of nothing.
type Table ¶
type Table struct {
// contains filtered or unexported fields
}
Table is an immutable resolved rate table. Build one with NewTable; never mutate one that is live, because a Registry hands the same pointer to every concurrent reader.
func Build ¶
Build assembles a Table from config plus, unless disabled, the bundled slice.
A nil Config is legal and yields the bundled table alone — the no-configuration case, which is meant to work.
Configured rows are emitted at ProvConfigured so they outrank anything bundled at equal specificity: an override is an override.
func NewTable ¶
func NewTable(entries []Entry, mults ...MultiplierRule) (*Table, error)
NewTable compiles entries into a table, rejecting rows that cannot mean anything useful.
func (*Table) Describe ¶
func (t *Table) Describe() Description
Describe renders the raw table: every row as configured or shipped, unscaled.
func (*Table) EffectiveFor ¶
EffectiveFor resolves every model the table names, for one endpoint.
This is the question worth answering: not "what rows exist" but "what will this gateway charge me". Resolution applies host scoping, specificity, provenance precedence and the multiplier — none of which a reader can carry out by eye.
Glob rows are resolved under their own pattern, which is the honest rendering: a pattern's rate is what any model matching it gets, and inventing a concrete model name to stand for it would imply a row that does not exist.
func (*Table) Resolve ¶
func (t *Table) Resolve(endpoint, model string, promptTotal int) (Rates, Provenance)
Resolve returns the rates for one (endpoint, model) pair and where they came from, already flattened for a prompt of promptTotal tokens.
Provenance decides first, specificity only within a level — see the specificity type for why the endpoint axis outranks the model axis. A nil Table resolves to ProvNone rather than panicking: a binary built without pricing wiring must report traffic as unpriced, not crash on the response path.
type ThresholdConfig ¶
type ThresholdConfig struct {
// PromptTokens is the count the prompt must EXCEED for these rates to apply.
PromptTokens int `yaml:"prompt_tokens" json:"prompt_tokens"`
TierRates `yaml:",inline"`
}
ThresholdConfig is one long-context breakpoint.
func (*ThresholdConfig) UnmarshalYAML ¶
func (t *ThresholdConfig) UnmarshalYAML(node *yaml.Node) error
type ThresholdView ¶
type ThresholdView struct {
AbovePromptTokens int `json:"abovePromptTokens"`
InputPerMillion float64 `json:"inputPerMillion,omitempty"`
CacheWritePerMillion float64 `json:"cacheWritePerMillion,omitempty"`
CacheReadPerMillion float64 `json:"cacheReadPerMillion,omitempty"`
OutputPerMillion float64 `json:"outputPerMillion,omitempty"`
}
ThresholdView is one long-context override.
type Tier ¶
type Tier int
Tier names which kind of token is being priced.
Four tiers, because that is what every provider on a Claude path bills separately and prompt-cache tiers differ by more than 12x: a cache write is 1.25x input and a cache read 0.1x, so one flat rate misprices cache-heavy traffic (Claude Code) by up to ~10x.
Deliberately absent: service-tier variants (flex / priority / ultrafast) and the 1-hour-TTL cache-write premium. Both are real fields in LiteLLM's ModelInfoBase, neither is on a path we run, and an unpopulated tier is an untested tier. Adding one later is a field plus a threshold row, not a reshape.
func PromptTier ¶
PromptTier picks which prompt tier a saving on the cached prefix came out of.
A write-dominant request wrote the prefix, a read-dominant one read it, and one reporting no cache tokens at all sent it as plain input. That distinction is worth more than it looks: a cache write bills at 1.25x the input rate and a read at 0.1x, so identical saved tokens are worth over 12x more on a miss than a hit, and reporting one blended figure would hide a factor of twelve.
Lives here rather than in a consumer because two of them need it — the plugin that measures the saving and the UI that renders it — and a second copy of this rule would be a second place for it to drift.
This assumes the saving sits inside the cached prefix, which holds for a client that puts cache_control on its tool block (Claude Code does). It is the one assumption to revisit for a client that lays its prompt out differently.
func TierFromString ¶
TierFromString is the inverse of Tier.String, for a tier that has been through JSON.
Reports false for anything unrecognized rather than defaulting to input: a saving attributed to the wrong tier is off by up to 12.5x, and silently picking the cheapest interpretation would understate it.
type TierRates ¶
type TierRates struct {
InputCostPerMillion float64 `yaml:"input_cost_per_million" json:"input_cost_per_million,omitempty"`
CacheWriteCostPerMillion float64 `yaml:"cache_write_cost_per_million" json:"cache_write_cost_per_million,omitempty"`
CacheReadCostPerMillion float64 `yaml:"cache_read_cost_per_million" json:"cache_read_cost_per_million,omitempty"`
OutputCostPerMillion float64 `yaml:"output_cost_per_million" json:"output_cost_per_million,omitempty"`
InputCostPerToken float64 `yaml:"input_cost_per_token" json:"input_cost_per_token,omitempty"`
CacheWriteCostPerToken float64 `yaml:"cache_write_cost_per_token" json:"cache_write_cost_per_token,omitempty"`
CacheReadCostPerToken float64 `yaml:"cache_read_cost_per_token" json:"cache_read_cost_per_token,omitempty"`
OutputCostPerToken float64 `yaml:"output_cost_per_token" json:"output_cost_per_token,omitempty"`
}
TierRates is the operator-facing rate block: every tier expressible in either unit.
The per-million fields are the ones to reach for. Providers publish prices per million tokens ("$3.80 / Mtok"), so that is the unit an operator already has in hand — no dividing by a million by hand, and no 0.0000038-vs-0.000038 typo that misprices by 10x and looks plausible either way.
The per-token fields stay accepted because LiteLLM's own model_prices_and_context_window.json is per-token, and rates get copied straight out of it.
type Usage ¶
type Usage struct {
Input int // uncached prompt tokens
CacheWrite int // prompt tokens written to cache
CacheRead int // prompt tokens served from cache
Output int // generated completion tokens
}
Usage is one request's token count, split by tier.
This mirrors parsercommon.TokenUsage, which is what the inference parsers already publish — but parsercommon sits under authlib/plugins/internal/, so Go's internal rule puts it out of reach here. Reasoning is omitted (a subset of Output, already counted) and so is ReportedTotal (an aggregate no tier prices).
func UsageFromInference ¶
func UsageFromInference(inf *pipeline.InferenceExtension) Usage
UsageFromInference reads the per-tier token split that the inference parsers publish onto pctx.Extensions.Inference.
This is the one conversion between the parsers' vocabulary and this package's, and it lives here so both consumers share it rather than each writing their own — the D3 duplication this consolidation exists to remove.
The split counters are preferred over the legacy PromptTokens / CompletionTokens aggregates, never the reverse: parsercommon.TokenUsage.Fill derives PromptTokens FROM the split, so reading the aggregate would fold the cache tiers into uncached input and price cache reads at up to 10x their real rate on cache-heavy traffic (which is what Claude Code produces).
The aggregates are the fallback for a provider that reports only totals. Without it such traffic has a zero split, and Cost treats zero usage as UNPRICED — so the requests would drop out of the dollar total silently instead of being priced approximately. Attributing the aggregate to uncached input is the same fallback toolprune's OnFinish already makes (plugins/toolprune/plugin.go:705-709): it over-prices a cache-heavy request, but a provider that hides its cache split has given us no way to do better, and being visibly approximate beats being invisibly absent.
The two fallbacks are independent because a provider can report a prompt split and only a legacy completion total.
func (Usage) PromptTotal ¶
PromptTotal is the prompt-side total, which is what a context threshold is measured against. Output is excluded: a long-context premium is priced on how much prompt was sent, not on what came back.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
gen
command
Command gen regenerates the bundled price table from LiteLLM's public price map.
|
Command gen regenerates the bundled price table from LiteLLM's public price map. |
|
pricegen
Package pricegen turns LiteLLM's public model_prices_and_context_window.json into pricing.Entry rows and renders them as Go source.
|
Package pricegen turns LiteLLM's public model_prices_and_context_window.json into pricing.Entry rows and renders them as Go source. |