modelinfo

package
v0.7.9 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 11 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package modelinfo resolves a model's context window (max input tokens) and per-token price, so context-guru's triggers can scale with the model rather than hard-coding thresholds. It does no I/O itself: Resolver, Pricer, Static, Table and Chain are pure lookups. The dynamic source — LiteLLM's community-maintained model_prices_and_context_window.json, fetched once and cached — is internal/modelinfo/litellm, a host-side sibling package: a host (proxy, cmd/) builds a litellm.LiteLLM and composes it into a Chain alongside this package's own Static fallback.

Every lookup fails OPEN: an unknown model returns ok=false and callers fall back to absolute thresholds.

READ THAT CAREFULLY, because an earlier version of this comment claimed more than the package delivers. "Any error just leaves the window unknown" is true of a single resolver in isolation and false of the chain it is normally used in: a Chain{litellm.LiteLLM, DefaultStatic()} answers an unreachable document from the embedded table, so a failed fetch does not produce "unknown", it produces a confident and possibly very wrong number. Callers that have been GIVEN an authoritative document — an explicit MODEL_INFO_URL — must not be silently answered from the fallback table; see modelWindows in cmd/context-guru-proxy, which probes such a URL at startup and refuses to run rather than guess past it.

Index

Constants

View Source
const (
	MinCacheableHaiku = 4096
	MinCacheableSmall = 1024
)

Prompt-cache minimums, MEASURED against the gateway rather than assumed.

A provider silently ignores a cache_control breakpoint that sits below its minimum cacheable prefix: no error, no cache entry, cache_creation_input_tokens: 0. The numbers differ per model family, so a single constant would either waste writes on one family or forgo caching on another.

~1.5k prefix, claude-haiku-4-5  => write=0 read=0   (inert)
~4.5k prefix, claude-haiku-4-5  => write=5401 then read=5401
~1.5k prefix, claude-sonnet-5   => write=2653 then read=2653
View Source
const (
	OpenAIMinimumCacheTTL      = 30 * time.Minute
	OpenAIDefaultKeepAliveIdle = OpenAIMinimumCacheTTL - 2*time.Minute
)

The GPT-5.6+ minimum is refreshed by a cache read. Keep-alive leaves two minutes for scheduling and upstream latency before that guarantee ends.

View Source
const (
	AnthropicCacheLifetime5m = AnthropicCacheTTL5m
	AnthropicCacheLifetime1h = AnthropicCacheTTL1h
)

The provider's cache lifetimes. They run from the START of the previous request. Every cap on a ping time reads these two. They are the SAME two values as AnthropicCacheTTL5m and AnthropicCacheTTL1h (cachelifetime.go), the one place they are written: these names only stay for the callers that read them as a cap on a ping time (#1350).

View Source
const (
	AnthropicDefaultKeepAliveIdle1h     = 59 * time.Minute
	AnthropicDefaultKeepAliveMaxPings1h = 1
	// AnthropicMaxKeepAliveMaxPings1h caps K for a 1-hour thread. The credential hold is
	// (K+1) x 59 min, so 3 bounds it at 236 min; it matches the manager-strategy band.
	AnthropicMaxKeepAliveMaxPings1h = 3
)

The Anthropic one-hour tier. This is the ONE place the one-hour ping time lives: 59 minutes after the previous request STARTED, one minute inside the lifetime, and one ping. Tune it here. The five-minute pair (240 s, 2 pings) stays in config.

View Source
const (
	// AnthropicCacheReadFrac is the standard cache-READ multiple. Four models have a lower one:
	// see CacheReadFracFor. Use that function when the model is known.
	AnthropicCacheReadFrac = 0.1
	// AnthropicCacheReadFracOpusSonnet55 is the cache-READ multiple of Claude Opus 5.5 and
	// Claude Sonnet 5.5.
	AnthropicCacheReadFracOpusSonnet55 = 0.05
	// AnthropicCacheReadFracFableMythos51 is the cache-READ multiple of Claude Fable 5.1 and
	// Claude Mythos 5.1.
	AnthropicCacheReadFracFableMythos51 = 0.025
	// AnthropicCacheWrite5mFrac is the 5-minute cache-WRITE multiple.
	AnthropicCacheWrite5mFrac = 1.25
	// AnthropicCacheWrite1hFrac is the 1-hour cache-WRITE multiple. It is taken from the fresh
	// input rate, not from the 5-minute write rate, because that is how the provider documents it.
	AnthropicCacheWrite1hFrac = 2.0
)

The Anthropic family's published cache multiples of the fresh input rate. This is the ONE place they are written. kvcache, dash, components/offload, cheapmodel and proxy all read them.

View Source
const (
	AnthropicCacheTTL5m = 5 * time.Minute
	AnthropicCacheTTL1h = time.Hour
)

The Anthropic cache tiers. These are the ONE place the two lifetimes live.

View Source
const (
	FamilyOpus   = "opus"
	FamilySonnet = "sonnet"
	FamilyHaiku  = "haiku"
	FamilyFable  = "fable"
)

The Claude tiers Family can name.

View Source
const MaxTiers = 3

MaxTiers is how many tiers a Price holds. The array keeps Price comparable with ==, which the packages that alias Price rely on. The live feed has at most 2 lines per model.

View Source
const RealTokensPerO200k = 1.20

RealTokensPerO200k converts our own token count into the count the provider will bill.

THE FLOORS ABOVE ARE IN THE PROVIDER'S TOKENS; internal/tokens counts o200k_base. Comparing the two directly is a unit error, and it was silently costing every haiku call its cache. MEASURED 2026-08-19 against the gateway, same bytes both sides:

preamble+context, claude-haiku-4-5:  3,673 o200k  ->  4,217 billed  (1.148x)
same shape, re-measured 2026-08-20:   6,143 o200k  ->  7,077 billed  (1.152x)
preamble only,    aws/claude-sonnet-5: 1,893 o200k ->  2,956 billed  (1.56x)

The 3,682-o200k prefix CACHED (write=4,412 then read=4,412) while the unconverted comparison (3,682 < 4,096) withheld the breakpoint — a cache the provider was willing to grant, declined on arithmetic. 1.20x is kept as the DIVISOR deliberately: it is looser than the 1.148-1.152x actually measured, so the derived floor (4096/1.20 = 3413 o200k) sits below the true one (4096/1.152 = 3555) and the breakpoint is offered slightly early rather than withheld. A too-tight divisor would reintroduce the bug this comment exists to explain. haiku-class is the family carrying the 4,096 floor, so it is the right conversion here; it is also the smaller of the two, so it never claims a cache we have evidence would be refused.

Being wrong in the LOOSE direction is nearly free: a breakpoint below the provider's real minimum is ignored, not charged (measured: write=0, read=0, input_tokens identical with and without the mark), and claimCacheWrite's release() records that and retries later. Being wrong in the TIGHT direction forgoes the cache permanently, which is what happened here.

View Source
const USD = "USD"

USD is the unit of every price that does not name one: the public map, the built-in table, and a price file without a currency key.

Variables

This section is empty.

Functions

func CacheLifetime added in v0.6.5

func CacheLifetime(provider, model string, oneHour bool) time.Duration

CacheLifetime is THE rule for how long a provider keeps a cache entry after a read.

oneHour is the tier, and the CALLER chooses which fact it stands for: the tier the request ASKED for (from the body or the row's cache_ttl), or the tier the provider BILLED (cache_write_1h > 0). They differ when a one-hour request is billed at five minutes. A caller that acts on the entry (the keeper, a "cold after" display) should pass the billed tier; a caller that has only the request should pass the requested one. oneHour is ignored for a provider with a fixed lifetime. The model is a parameter so that no caller can apply the GPT-5.6+ minimum to an older OpenAI model by forgetting the gate.

func CacheLifetimeSQL added in v0.6.5

func CacheLifetimeSQL(providerCol, oneHourCond string, unit time.Duration) string

CacheLifetimeSQL is CacheLifetime as a SQL CASE expression, in units of unit (time.Second or time.Millisecond). providerCol is a column or expression holding the provider name; oneHourCond is a SQL boolean for the one-hour tier. Both are inserted verbatim, so pass only code, never user input. SQL cannot parse a model name, so this gates on the PROVIDER only: use it only on rows a Go write path already gated on the model (kaSavedGate), or fetch the tier alone and finish in Go with CacheLifetime. The values come from the same constants as CacheLifetime, so the Go and SQL copies cannot disagree.

func CacheReadFracFor added in v0.6.5

func CacheReadFracFor(model string) float64

CacheReadFracFor is the cache-READ rate as a multiple of the fresh input rate, for a model whose price feed does not state one.

Source: the official pricing page, https://platform.claude.com/docs/en/about-claude/pricing ("Prompt caching" table and footnotes), read 2026-11-02. A cache read costs 0.1x base input. Exceptions: 0.025x on Claude Fable 5.1 and Claude Mythos 5.1; 0.05x on Claude Opus 5.5 and Claude Sonnet 5.5. "All other models use the standard 0.1x multiplier." Fable 5, Mythos 5, Opus 5, Sonnet 5 and Haiku 5.5 stay at 0.1x. Cache WRITE multiples do not change by model.

The match is on tier AND version. "claude-opus-5" is a prefix of "claude-opus-5-5", so a prefix test would give Opus 5 the Opus 5.5 rate. The version must be the whole "5-5" or "5.5", not the start of a longer number, so a date suffix such as "claude-opus-5-20260101" stays 0.1x. Vendor prefixes ("aws/", "us.anthropic.") and the "[1m]" suffix do not change the answer. Every other model, including every non-Anthropic one, gets AnthropicCacheReadFrac.

func CacheWriteFracFor added in v0.3.1

func CacheWriteFracFor(model string) float64

CacheWriteFracFor is the cache-CREATION rate as a multiple of the fresh input rate, for a model whose price feed does not state one.

It exists because a single fabricated multiple was applied to every model on earth. `1.25x input` applies to Anthropic and GPT-5.6 or later. Earlier OpenAI models and Gemini do not charge a per-token cache-write premium.

Why that mattered even though those providers never report cache_write: Event.Price uses CacheWrite for cost_usd, where a zero cache_write count makes the rate irrelevant, AND the legacy savings rule (now the read-time estimate of old rows, Event.ComponentSavedUSD) used it to price SAVED tokens, where the count is our own and the rate is applied regardless of what the request billed. So the fabricated premium reached the savings figure on traffic that could never have paid it.

Unknown families get 1.0 rather than 1.25: for a SAVINGS number the direction that does not invent value is the safe one. A feed that states a real rate never reaches this function.

func Exact added in v0.2.0

func Exact(r Resolver, ctx context.Context, model string) (tokens int, exact, ok bool)

Exact reports a window plus whether it is measured rather than guessed, for any Resolver. A resolver without the capability answers exact=false.

func Family added in v0.6.5

func Family(model string) string

Family names the Claude tier in a model id: FamilyOpus, FamilySonnet, FamilyHaiku or FamilyFable. It returns "" for any other id, including a gateway alias that hides the model.

One rule, because copies drifted: none of the earlier per-package copies knew "fable". The id goes through Normalize first, so case, spaces and a "[1m]" variant suffix never change the answer. Normalize does not strip a provider prefix from the full id. It does not need to: the match is a substring of the full id ("aws/", "vertex_ai/" and "us.anthropic." prefixes never hold a tier word), as every old copy did.

The tier order here is opus, sonnet, haiku, fable. The old billed-factor copy tested haiku first. No real id holds two tier words, so the result is the same.

Family says WHICH tier. Each caller still decides what a tier or "" means for it. A tier can have no measured value in a caller's table; that caller keeps its own default.

func FixedCacheLifetime added in v0.6.5

func FixedCacheLifetime(provider, model string) (time.Duration, bool)

FixedCacheLifetime reports a (provider, model) whose cache lifetime does not depend on a requested or billed tier. Only GPT-5.6+ on OpenAI qualifies: its documented minimum is 30 minutes, and a one-hour tier is never requested or billed there. An older OpenAI model has a variable, undocumented retention, so it is NOT fixed and reads like any other provider.

func GPT54OrLater added in v0.7.9

func GPT54OrLater(model string) bool

GPT54OrLater reports whether an OpenAI GPT model is version 5.4 or later. Routed ids such as azure/gpt-5.5 count.

func GPT56OrLater added in v0.4.0

func GPT56OrLater(model string) bool

GPT56OrLater reports whether an OpenAI GPT model uses the GPT-5.6+ cache rules. Routed model IDs (for example, azure/gpt-5.6-luna) are supported.

func HonoursCacheControl added in v0.6.5

func HonoursCacheControl(provider bschemas.ModelProvider) bool

HonoursCacheControl reports whether a provider accepts Anthropic-style `cache_control` breakpoints on the wire. It is the ONE list of such providers (#809). Four callers used to keep their own copy: the TTL tier, the prefix split, the keep-alive gate and cacheinject. One copy missed Bedrock Mantle, so cacheinject placed no breakpoint there while the tier said "5m".

Bedrock Mantle serves Claude through the native Anthropic Messages surface (`/anthropic/v1/messages`), so the same body, and the same `cache_control`, applies.

func IsClaude added in v0.6.5

func IsClaude(model string) bool

IsClaude reports whether the id names a Claude or Anthropic model by those words. It is narrower than Family != "": a bare tier word such as "opus" does not count.

func MinCacheableO200k added in v0.6.5

func MinCacheableO200k(model string) int

MinCacheableO200k is MinCacheablePrefix expressed in the units tokens.Count actually returns, so like is compared with like.

func MinCacheablePrefix added in v0.6.5

func MinCacheablePrefix(model string) int

MinCacheablePrefix returns the smallest system prefix worth marking for this model, in the PROVIDER's tokens. Callers holding an o200k count must go through MinCacheableO200k.

An UNNAMEABLE model gets the haiku figure, not the smaller default: the failure we are avoiding is paying for a cache entry that is never read, so when we cannot tell which family we are talking to, the conservative answer is to demand the larger prefix and place no mark below it.

func Normalize added in v0.5.3

func Normalize(model string) (full, tail string)

Normalize lowercases a model id, strips a provider prefix for the tail form, and strips a trailing bracketed variant suffix (see stripVariant), returning both the full normalized id and its last path segment. Exported for internal/modelinfo/litellm, which matches against both the same way this package's own LiteLLM resolver used to.

func NormalizeID added in v0.2.0

func NormalizeID(model string) string

normalize lowercases a model id, strips a provider prefix, and strips a trailing bracketed variant suffix, so gateway route names (aws/claude-sonnet-5, anthropic/…, bedrock/…, us.anthropic.…, aws/claude-opus-5[1m]) match the keys LiteLLM uses. Returns the full normalized id and its last path segment.

THE BRACKETED SUFFIX IS THE CONTEXT-LENGTH VARIANT, and not stripping it made every lookup for such an id miss the map entirely. The consequences ran in two directions, both bad:

  • The chain fell through to DefaultStatic, whose answer is never exact. Trigger.FracResolvable requires CtxWindowExact, and summarize ships min_request_frac: 0.9 — so on any id carrying a suffix the fraction gate could never fire, silently, which looks exactly like a gate that is working.
  • DefaultStatic's substring table answered 200,000 for `claude-opus-5[1m]` against a real 1,000,000. exact=false keeps the trigger from acting on that, but OutputFloor, IsHuge and extract_llm's fraction all read the non-exact Window(), where five times too low is only safe in one direction.

Found by a review, which then corrected itself twice about the reach: the gateway on the box it tested refuses these ids with a model-authorization error, and the client demonstrably works on that key with the un-suffixed name, so what the request body actually carries in `model` — the only field this reads — was never observed. So this is DEFENSIVE: the defect is real and the fix is right, with no demonstrated production impact. An operator can also work around it with a trailing `*` in a MODEL_PRICES entry.

Stripped from BOTH return values, and only when the suffix closes at the very end: `[` inside a key would be part of the name rather than a variant marker, and a half-open bracket is a malformed id this must not silently rewrite. NormalizeID is normalize's exported half: the full normalized id, for a caller outside this package that needs to match a model against a table of its own and must not re-implement the prefix and variant-suffix rules. dash's per-model client-ceiling table is the caller.

One implementation, because two would drift: this package already learned that the hard way when the bracketed `[1m]` suffix went unstripped and every lookup for such an id silently missed.

func OpenAI30MinuteCache added in v0.4.0

func OpenAI30MinuteCache(provider, model string) bool

OpenAI30MinuteCache is the shared provider/model gate for the GPT-5.6+ automatic-cache guarantee. Route-specific callers may impose further limits.

func OperatorCompactionPoint added in v0.7.2

func OperatorCompactionPoint(r Resolver, ctx context.Context, model string) (int, bool)

OperatorCompactionPoint asks a resolver for the operator's stated compaction point (billed input tokens). ok=false when the resolver cannot state one or states none. The capability is optional, as WindowExact is.

func PromptTokens added in v0.7.9

func PromptTokens(fresh, cacheRead, cacheWrite int64) int64

PromptTokens is the prompt size that picks a price tier: fresh input plus cache reads plus cache writes. It is the ONE place that says what counts as prompt size. Output tokens do not count.

Types

type Builtin added in v0.5.2

type Builtin struct {
	// contains filtered or unexported fields
}

Builtin answers EXACT windows for a short list of current Claude models, for the time the downloaded LiteLLM map is not there: no network, a request that arrives before the download ends, or a model the map does not list yet. Without it every min_request_frac trigger is off in those cases, because DefaultStatic is never exact (issue #515).

An entry matches ONE normalized model id (provider prefix and [1m] removed), and nothing else. There is no substring or prefix match. `claude-sonnet-5-future` is not `claude-sonnet-5`, so a model with no entry stays inexact and falls through to DefaultStatic. TestBuiltinPinnedToBundledMap pins every value to the bundled LiteLLM snapshot, so an entry that drifts from the public map fails CI.

Chain order: the downloaded map, then Builtin, then DefaultStatic. The map stays the authority.

func DefaultBuiltin added in v0.5.2

func DefaultBuiltin() Builtin

DefaultBuiltin returns the built-in exact list.

func (Builtin) Window added in v0.5.2

func (b Builtin) Window(_ context.Context, model string) (int, bool)

Window returns the window for an exactly listed model.

func (Builtin) WindowExact added in v0.5.2

func (b Builtin) WindowExact(ctx context.Context, model string) (int, bool, bool)

WindowExact reports exact=true for every hit. A miss says nothing about exactness.

func (Builtin) Windows added in v0.5.3

func (b Builtin) Windows() map[string]int

Windows returns the exact list's own ids and windows, for a test that needs to walk every entry (e.g. pinning each against the bundled LiteLLM snapshot) without reaching into the unexported map directly.

type Chain

type Chain []Resolver

Chain tries each resolver in order; the first ok wins.

func NewChain added in v0.5.2

func NewChain(live Resolver) Chain

NewChain is the default chain for the public map: live map, then Builtin, then DefaultStatic.

func (Chain) CompactionPoint added in v0.7.2

func (c Chain) CompactionPoint(ctx context.Context, model string) (int, bool)

CompactionPoint resolves an operator-stated compaction point (billed input tokens). The first link that states one wins. Links that cannot state one are skipped.

func (Chain) Price added in v0.1.1

func (c Chain) Price(ctx context.Context, model string) (Price, bool)

Price tries each element that can price a model; the first ok wins. Elements that only resolve windows are skipped, so a Chain{LiteLLM, Static} prices from LiteLLM and reports unknown when it has not loaded.

func (Chain) Unresolved added in v0.2.0

func (c Chain) Unresolved() (error, int)

Unresolved forwards the question to whichever element can answer it, so a caller holding a Chain — which is what the proxy is given — can still find out that the operator's document never loaded. A Chain whose live resolver is failing still ANSWERS every window lookup, from the fallback table behind it, which is exactly why this has to be askable through the Chain and not only on the element.

func (Chain) Window

func (c Chain) Window(ctx context.Context, model string) (int, bool)

func (Chain) WindowExact added in v0.2.0

func (c Chain) WindowExact(ctx context.Context, model string) (int, bool, bool)

WindowExact resolves as Window does and reports whether the link that ANSWERED considers its figure measured. First ok still wins — the exactness of a later link is irrelevant, because a later link was never consulted.

type ExactResolver added in v0.2.0

type ExactResolver interface {
	WindowExact(ctx context.Context, model string) (tokens int, exact, ok bool)
}

ExactResolver is the optional capability a Resolver implements to say whether the window it returned is a MEASURED figure for that model or a GUESS — and it exists because the two are not interchangeable for every caller.

DefaultStatic answers by substring with a `{"claude", 200000}` catch-all, so a 1M-window model it has no entry for comes back as 200,000 with ok=true. That is a fine floor for a caller that only wants "don't act on a tiny output" — a too-small window there merely raises a floor. It is NOT fine for a caller deciding "is this transcript 90% full", where a 5x-low window fires the decision five times too early. Such a caller must be able to tell the two apart, and ok=true cannot tell it.

A Resolver that does NOT implement this is treated as inexact by Chain, deliberately: a new source has to say it is authoritative, because the failure of forgetting is silent and the failure of declaring wrongly is not.

type Price added in v0.1.1

type Price struct {
	Input      float64 `json:"input"`       // fresh (uncached) input per token
	Output     float64 `json:"output"`      // completion per token
	CacheRead  float64 `json:"cache_read"`  // cache-hit input per token
	CacheWrite float64 `json:"cache_write"` // cache-creation input per token

	// The operator's multiples of Input for a tier the entry leaves blank. 0 means the operator
	// set none, so the model decides (see CacheReadFor). They are not part of the wire form.
	ReadFrac    float64 `json:"-"`
	WriteFrac   float64 `json:"-"`
	Write1hFrac float64 `json:"-"`
	// Currency is the unit of the rates, from the price file's currency key. Empty means USD (see
	// Unit). Not part of the wire form, so a price's JSON does not change.
	Currency string `json:"-"`

	// CacheReadFallback is set when Resolved filled the cache-read rate from a fallback rate: no
	// source stated it, the operator set no multiple, and the model is not a Claude model, so
	// CacheReadFracFor's Anthropic multiple is a guess (#1248). FallbackCost prices it. Not part
	// of the wire form.
	//
	// The read tier is the only one that can be a fallback. The 5-minute write multiple is a rule
	// per family that CacheWriteFracFor documents (1.25x where a premium is charged, else 1.0x, no
	// premium), and the operator Table applies the same rule. The 1-hour tier is billed only by
	// Claude models, which use their published multiples.
	CacheReadFallback bool `json:"-"`

	// Tiers hold the rates a request bills above a prompt size (see PriceTier and At). Empty means
	// one flat rate. A zero entry is unused. A fixed array, so Price stays comparable with ==.
	// Not part of the wire form, so a price's JSON does not change.
	Tiers [MaxTiers]PriceTier `json:"-"`
}

Price is a model's per-token rates, in the four tiers a prompt-caching provider bills. The rates are in Unit(): US dollars, unless the operator's price file names another unit. Zero rates mean "unknown" — a caller must treat a Price it did not get an ok=true for as "no pricing", never as free.

func (Price) At added in v0.7.9

func (p Price) At(promptTokens int64) Price

At returns the rates for a request whose prompt has promptTokens tokens. At or below a tier's line, that tier does not apply. Above it, the tier's rates apply to every token. With several tiers, the highest line below the prompt size wins. A price with no tiers returns itself. The result carries no tiers.

func (Price) CacheReadFor added in v0.6.5

func (p Price) CacheReadFor(model string) float64

CacheReadFor is the cache-READ rate per token for a model. This is the ONE place the rule lives. In order: a rate the entry states, then the operator's ReadFrac, then CacheReadFracFor(model).

func (Price) CacheWrite1h added in v0.6.5

func (p Price) CacheWrite1h() float64

CacheWrite1h is the per-token rate of a ONE-HOUR cache write. No gateway publishes it, so it is always derived. See CacheWrite1hFor.

func (Price) CacheWrite1hFor added in v0.6.5

func (p Price) CacheWrite1hFor(model string) float64

CacheWrite1hFor is the 1-hour cache-WRITE rate per token. No gateway states it, so it is always derived: the operator's Write1hFrac, else AnthropicCacheWrite1hFrac, times the fresh input rate. The operator's rate is never below the 5-minute rate, so every path that prices a 1-hour write gets the same number.

func (Price) CacheWrite1hPremium added in v0.7.4

func (p Price) CacheWrite1hPremium() float64

CacheWrite1hPremium is what a token written at the 1-hour tier costs on top of the 5-minute write rate: CacheWrite1h minus CacheWrite, never below zero. It is the one place the premium is taken, so every figure that prices a 1-hour write adds the same amount.

func (Price) CacheWrite5mFor added in v0.6.5

func (p Price) CacheWrite5mFor(model string) float64

CacheWrite5mFor is the 5-minute cache-WRITE rate per token for a model. Same order as CacheReadFor: stated rate, then the operator's WriteFrac, then CacheWriteFracFor(model).

func (Price) Cost added in v0.1.1

func (p Price) Cost(fresh, cacheRead, cacheWrite, output int64) float64

Cost prices one request's four token tiers in USD.

func (Price) CostWithCacheWrite1h added in v0.4.1

func (p Price) CostWithCacheWrite1h(fresh, cacheRead, cacheWrite, output, cacheWrite1h int64) float64

CostWithCacheWrite1h is Cost plus the one-hour cache-write premium.

Cost knows a single write rate — the 5-minute one, at roughly 1.25x base input — so tokens the provider billed at the 1-hour tier (2.0x) are short by the difference. Derived from the documented multiplier rather than from a second configured rate, because no gateway publishes one: 2.0x input, minus whatever the 5m write rate is, on exactly the tokens the response says were written at 1h.

Hoisted here so dash's Event.Price and the host-level keep-alive mechanism's own cost bookkeeping (proxy/keepalive.go's record1) price the SAME request shape identically instead of each inlining this formula — the two had drifted apart once already (see issue #382's review) when the keep-alive mechanism was decoupled from dash's event type. dash.tierUSD (dash/accountant_price.go) reads the same premium (CacheWrite1hPremium).

func (Price) FallbackCost added in v0.7.5

func (p Price) FallbackCost(cacheRead int64) float64

FallbackCost is the part of Cost that a fallback rate priced: the cache reads, when Resolved marked that rate. It is 0 for a price with no mark, and never below 0 (a feed can state a negative rate, which litellm keeps as it is).

func (Price) HasTiers added in v0.7.9

func (p Price) HasTiers() bool

HasTiers reports whether the price has at least one tier.

func (Price) Resolved added in v0.6.5

func (p Price) Resolved(model string) Price

Resolved returns the price with both cache tiers filled for the model and their multiples cleared. A price source calls it once the model is known. Callers then read the fields. Write1hFrac stays: no field states the 1-hour rate, so CacheWrite1h still needs it.

It also marks a cache-read rate it filled from a fallback rate (see CacheReadFallback). A second call sees the filled rate as stated, so it keeps the mark of the first call and never clears it.

func (Price) Unit added in v0.7.4

func (p Price) Unit() string

Unit is the currency of the price's rates. A Price that names none is in US dollars.

func (Price) WithTiers added in v0.7.9

func (p Price) WithTiers(model string) Price

WithTiers sets the built-in tier for the model, unless the price already has tiers: a tier a source states wins over the built-in table. Both the public feed and the operator price file call it, so one model gets one answer whatever the config.

func (Price) Zero added in v0.1.1

func (p Price) Zero() bool

Zero reports whether no rate at all is known (so a cost figure would be a lie).

type PriceTier added in v0.7.9

type PriceTier struct {
	AbovePromptTokens int64

	Input, Output, CacheRead, CacheWrite       float64
	InputMult, OutputMult, ReadMult, WriteMult float64
}

PriceTier is the rate set a model bills when a request's prompt is larger than AbovePromptTokens. Some providers bill the WHOLE request at the higher rates above the line, not only the tokens past it.

A rate is stated in one of two ways. An absolute rate (Input, Output, CacheRead, CacheWrite, per token) wins. When it is 0, the rate is the base rate times the multiple (InputMult, OutputMult, ReadMult, WriteMult). A multiple of 0 means 1. The write multiple applies to the 5-minute and the 1-hour write: the 1-hour rate is derived from Input, so it follows Input.

func BuiltinTier added in v0.7.9

func BuiltinTier(model string) (PriceTier, bool)

BuiltinTier returns the tier this package knows for a model id. Other Claude models are flat across their window and have none.

type Pricer added in v0.1.1

type Pricer interface {
	Price(ctx context.Context, model string) (Price, bool)
}

Pricer resolves a model's per-token rates. ok=false means "unknown"; callers must then report cost as unavailable rather than zero.

type Resolver

type Resolver interface {
	Window(ctx context.Context, model string) (tokens int, ok bool)
}

Resolver returns a model's context window in tokens. ok=false means "unknown".

type Static

type Static struct {
	// contains filtered or unexported fields
}

Static is a tiny last-resort table keyed by substring. Used only when a dynamic source is unavailable. Deliberately small — it is a floor, not a registry.

func DefaultStatic

func DefaultStatic() Static

DefaultStatic covers the common families with conservative windows.

THE 1M CLAUDE FAMILIES ARE LISTED EXPLICITLY, and they had to be. The table used to carry `{"claude-sonnet-5", 1000000}, {"claude-opus-4", 200000}, {"claude", 200000}` — so every Opus 4.6 and newer, Fable 5.1, Sonnet 4.6 and Opus 5 fell through to the 200,000 catch-all against a published 1,000,000. Five times low, with ok=true, so no caller ever saw "unknown"; they saw a confident wrong number. That is issue #233, and its live consumer was ExtractLLM.inputLimit, which reads this table directly when `model.model` is pinned in config: a 5x-low budget means large tool outputs are judged not to fit and are silently skipped, on exactly the long-context models the component exists for.

The windows here follow what LiteLLM publishes, which is also the resolver that answers ahead of this table whenever the map is reachable. This is the floor for when it is not.

IT IS STILL NEVER EXACT — see WindowExact. A caller deciding "is this transcript 90% full" must refuse a figure from this table however right it looks, because being right about today's model list is not the same as being authoritative about tomorrow's.

func (Static) Window

func (s Static) Window(_ context.Context, model string) (int, bool)

Window resolves by LONGEST matching substring, not by first match.

It used to be first-match-wins with a comment asking the reader to keep the table "most-specific first". That made correctness depend on nobody ever appending in the wrong place — and a table whose invariant is a comment is a table that gets appended to in the wrong place. Adding `{"claude-opus-5", 1000000}` after the `{"claude", 200000}` catch-all would have been a one-line change that silently did nothing.

Longest-match makes the order cosmetic: `claude-opus-4-8` beats `claude-opus-4` beats `claude` because it is longer, wherever each sits in the slice.

func (Static) WindowExact added in v0.2.0

func (s Static) WindowExact(ctx context.Context, model string) (int, bool, bool)

WindowExact: NEVER exact, and adding correct entries for today's models does not change that. Every answer here is a substring match against a deliberately tiny table ending in a `{"claude", 200000}` catch-all, so a model with no entry of its own still gets its family's floor rather than its own window. A floor is what this table is for; a fill percentage is not something it can answer, and the difference between "right about the models I listed" and "authoritative" is exactly what exact=false encodes.

type Table added in v0.1.1

type Table struct {
	// contains filtered or unexported fields
}

A Table is an OPERATOR-SUPPLIED price list, consulted before the public LiteLLM map. It exists because the public map prices the public API, and a gateway does not have to charge that: IBM's litellm-gateway bills claude-sonnet-5 at $1.52/MTok in where anthropic.com bills $3.00, so every dollar figure this dashboard produced for that gateway was ~2x too high. A price list is also the only way to price a model the public map has never heard of — a preview deployment, an internal route name, or a server-resolved TIER like Bob's `premium`, which is not a model id at all and left every Bob request's cost reading "unknown".

Rates in the file are per MILLION tokens, in the file's currency (US dollars unless the file's currency key names another unit, such as Bob's Bobcoins), because that is the unit every vendor's price page and every gateway's admin UI uses; storing per-token floats in a hand-edited file invites a factor-of-a-thousand typo that nothing would catch. They are converted once, here.

Nothing in a Table is a secret: these are list prices. It is a plain file, and a missing or malformed one is a startup error rather than a silent fallback — a price list that failed to load looks exactly like "this model is free".

func LoadTable added in v0.1.1

func LoadTable(path string) (*Table, error)

LoadTable reads a price list. An empty path returns a nil *Table, which prices nothing and is safe to put in a Chain.

func ParseTable added in v0.1.1

func ParseTable(b []byte) (*Table, error)

ParseTable builds a Table from the YAML document LoadTable reads.

func (*Table) CompactionPoint added in v0.7.2

func (t *Table) CompactionPoint(_ context.Context, model string) (int, bool)

CompactionPoint returns the operator's compaction point for a model, in billed input tokens. ok=false when the entry states none, so the bootstrap table of compactionpoint answers.

func (*Table) Len added in v0.1.1

func (t *Table) Len() int

Len is how many entries were loaded, for the startup log line.

func (*Table) Price added in v0.1.1

func (t *Table) Price(_ context.Context, model string) (Price, bool)

Price returns the operator's rate for a model. ok=false means "not in the file", and the next source in the Chain answers.

func (*Table) Window added in v0.1.1

func (t *Table) Window(_ context.Context, model string) (int, bool)

func (*Table) WindowExact added in v0.2.0

func (t *Table) WindowExact(ctx context.Context, model string) (int, bool, bool)

Window returns an operator-supplied context window, for models the public map does not list. Entries without one return ok=false so the public map still wins. WindowExact: an operator's own table is authoritative by construction — they wrote a window for this deployment's models, which is a stronger claim than the public map's.

Directories

Path Synopsis
Package litellm fetches and caches the LiteLLM community price/window map (model_prices_and_context_window.json) and prices the operator's own gateway rate card from it.
Package litellm fetches and caches the LiteLLM community price/window map (model_prices_and_context_window.json) and prices the operator's own gateway rate card from it.
Package ratefilltest holds what the per-caller price fixture tests share (issue #856): the model list and the check against testdata/ratefill_before.json.
Package ratefilltest holds what the per-caller price fixture tests share (issue #856): the model list and the check against testdata/ratefill_before.json.

Jump to

Keyboard shortcuts

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