modelinfo

package
v0.6.4 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: Apache-2.0 Imports: 7 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 (
	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 (
	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 Anthropic family's published cache-READ multiple of the fresh
	// input rate. Exported for internal/modelinfo/litellm's fallback when a price feed states no
	// cache-read rate of its own.
	AnthropicCacheReadFrac = 0.1
)

anthropicCacheWriteFrac / anthropicCacheReadFrac are the Anthropic family's published multiples, named rather than repeated as bare literals in three files.

Variables

This section is empty.

Functions

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 baselineDeltaUSD uses 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 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 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.

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) 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
}

Price is a model's per-token USD rates, in the four tiers a prompt-caching provider bills. 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) 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.

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 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 USD per MILLION tokens, 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) 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.

Jump to

Keyboard shortcuts

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