pricing

package
v0.20.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 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 pricing is the domain layer for the Pricing entity — a named rate sheet owned by a Host and applied to one or more Models. One Pricing row holds every rate that bills against a (model, host) pair: input, output, cache_read, cache_creation, reasoning, audio_*, and any context-tier variants.

Pricing is owner=host so that "Anthropic's price list" and "Bedrock's price list" are two distinct entities even when they cover overlapping Models. TargetModelIDs lets one rate sheet cover a whole tier (claude-4 family etc.) without duplicating rows.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Meter

type Meter string

Meter is the dimension a Rate prices. Closed set; new meters require a schema bump (intentional — billing surface area should grow deliberately).

const (
	MeterTokensInput               Meter = "tokens.input"
	MeterTokensOutput              Meter = "tokens.output"
	MeterTokensCacheRead           Meter = "tokens.cache_read"
	MeterTokensCacheCreation       Meter = "tokens.cache_creation"
	MeterTokensCacheCreation1h     Meter = "tokens.cache_creation_1h"
	MeterTokensReasoning           Meter = "tokens.reasoning"
	MeterTokensAudioInput          Meter = "tokens.audio_input"
	MeterTokensAudioOutput         Meter = "tokens.audio_output"
	MeterTokensAcceptedPrediction  Meter = "tokens.accepted_prediction"
	MeterTokensRejectedPrediction  Meter = "tokens.rejected_prediction"
	MeterTokensServerToolUseInput  Meter = "tokens.server_tool_use_input"
	MeterTokensServerToolUseOutput Meter = "tokens.server_tool_use_output"
)

func MeterForUsageKey

func MeterForUsageKey(k string) (Meter, bool)

MeterForUsageKey maps a usage.Tokens key (as emitted by Adapter.ExtractTokens) to its corresponding pricing Meter. Returns the meter and true if known, or "" and false for unpriced keys.

type Pricing

type Pricing struct {
	Meta meta.Metadata `json:"metadata" yaml:"metadata"`
	Spec Spec          `json:"spec"     yaml:"spec"`
}

Pricing is a rate sheet. Owner.Kind must be OwnerHost; Owner.ID is the Host id.

func (*Pricing) Cost

func (p *Pricing) Cost(tokens usage.Tokens) float64

Cost computes the total cost (in Spec.Currency units, typically USD) for the given Tokens map. Tier selection uses the prompt length (usage.Tokens.PromptTokens) — the axis providers price context-length tiers by. Keys not mapped by MeterForUsageKey are silently skipped (unpriced dimension). Returns 0 when Pricing is disabled or carries no rates. Each token is charged once, as in CostNanos. Prices at the base rates.

func (*Pricing) CostForServiceTier added in v0.10.6

func (p *Pricing) CostForServiceTier(tokens usage.Tokens, serviceTier string) float64

CostForServiceTier is Cost for a response served in serviceTier, with rates picked as in RateForServiceTier.

func (*Pricing) CostNanos added in v0.3.0

func (p *Pricing) CostNanos(tokens usage.Tokens) (total int64, breakdown map[string]int64, ok bool)

CostNanos computes the total cost in integer nano-USD (1 USD = 1e9 nanos) plus a per-meter breakdown keyed by Meter string. Integer money because the result is stamped onto immutable usage events — float drift across sums/aggregates is not acceptable for a billing-adjacent record, and per-request magnitudes fit int64 with room to spare (~9.2e9 USD).

Tier semantics match Cost (and sdk/catalog.Binding.Cost): the tier axis is the prompt length (usage.Tokens.PromptTokens, cached tokens included); the rate with the largest AboveTokens ≤ prompt length applies, and the WHOLE meter count bills at that tier (no marginal splitting) — the conventional context-length-tier model across providers.

ok is false when nothing was priced: nil/disabled pricing, no tokens, or no token key matched a rate. Callers must treat !ok as "unpriced", never as a zero cost — a fabricated $0 is the silent-drop bug class. A genuine zero (priced meters with zero counts) returns ok=true with total 0.

Each token is charged once. Some keys count tokens that are also inside input or output (usage.Tokens lists them); when the sheet has a rate for such a part, the part is charged there and left out of the whole's charge. So a breakdown entry is rate × usage.Tokens.Billable for its key, which for input and output can be less than rate × the stored count. The tier still comes from the stored counts.

CostNanos prices at the base rates; CostNanosForServiceTier prices a response the upstream reports as served in a service tier.

func (*Pricing) CostNanosForServiceTier added in v0.10.6

func (p *Pricing) CostNanosForServiceTier(tokens usage.Tokens, serviceTier string) (total int64, breakdown map[string]int64, ok bool)

CostNanosForServiceTier is CostNanos with rates picked as in RateForServiceTier.

func (*Pricing) IsEnabled

func (p *Pricing) IsEnabled() bool

IsEnabled returns true when Enabled is unset or explicitly true.

func (*Pricing) RateFor

func (p *Pricing) RateFor(meter Meter, tokens int) (*Rate, bool)

RateFor returns the base rate that should bill against the given meter and request-side token count. Walks the base Rates for the meter and picks the row with the largest AboveTokens that is still ≤ tokens. Returns (nil, false) if no base rate exists for the meter.

func (*Pricing) RateForServiceTier added in v0.10.6

func (p *Pricing) RateForServiceTier(meter Meter, tokens int, serviceTier string) (*Rate, bool)

RateForServiceTier is RateFor for a response served in serviceTier: a rate carrying that service tier wins whenever one qualifies at tokens, otherwise the base rate applies — a tier only lists the meters it prices differently.

func (*Pricing) Validate

func (p *Pricing) Validate() error

Validate runs intra-row rules via the shared meta.Validator and enforces the Pricing-specific invariants:

  • Owner.Kind == OwnerHost and Owner.ID is set (the Host id).
  • No two Rates share the same (Meter, AboveTokens, ServiceTier) — would be ambiguous at billing time.

Cross-entity checks (TargetModelIDs resolve, no two enabled Pricings claim the same (model, host) pair) live in the catalog composition layer.

type Rate

type Rate struct {
	Meter       Meter   `` /* 650-byte string literal not displayed */
	Unit        Unit    `` /* 208-byte string literal not displayed */
	Amount      float64 `` /* 170-byte string literal not displayed */
	AboveTokens int     `` /* 217-byte string literal not displayed */
	ServiceTier string  `` /* 164-byte string literal not displayed */
}

Rate is one priced meter. AboveTokens=0 is the base tier; AboveTokens>0 is the rate charged once the request's prompt length (usage.Tokens.PromptTokens) reaches that threshold. The billing-time picker walks rates for the meter and applies the largest qualifying threshold. Amount 0 is valid: a free meter (e.g. an embedding model's output tokens) is an explicit zero rate, not a missing one. ServiceTier empty is the base rate; set, the rate applies only to responses the upstream reports as served in that tier, under the upstream's own tier name.

type Spec

type Spec struct {
	Currency       string   `` /* 136-byte string literal not displayed */
	TargetModelIDs []string `` /* 155-byte string literal not displayed */
	Rates          []Rate   `` /* 151-byte string literal not displayed */
	Enabled        *bool    `` /* 147-byte string literal not displayed */
}

Spec carries the rate list, the target model set, currency, and an enable flag.

type Store

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

Store is the Pricing data-access type. Holds a DB rather than Queries so Upsert can run a multi-table transaction.

func NewStore

func NewStore(db storage.DB) *Store

NewStore constructs a Store bound to a pool or an open transaction.

func (*Store) Delete

func (s *Store) Delete(ctx context.Context, id string) error

Delete removes a Pricing by id. Junction rows cascade via FK.

func (*Store) Get

func (s *Store) Get(ctx context.Context, id string) (*Pricing, error)

Get returns the Pricing with the given id, hydrating TargetModelIDs. Returns (nil, nil) if not found.

func (*Store) List

func (s *Store) List(ctx context.Context) ([]*Pricing, error)

List returns every Pricing row with Spec.TargetModelIDs hydrated from the pricing_models junction in declaration order.

func (*Store) Upsert

func (s *Store) Upsert(ctx context.Context, p *Pricing) error

Upsert writes p across pricings + pricing_models in a single tx. Caller stamps Meta.ID and Owner.ID (host id).

type Unit

type Unit string

Unit is how Amount is interpreted. per_million is the common case for token rates (Amount=2.50 means $2.50 per 1M tokens). per_unit is for future meters like per-image or per-call.

const (
	UnitPerMillion Unit = "per_million"
	UnitPerUnit    Unit = "per_unit"
)

Jump to

Keyboard shortcuts

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