cost

package
v0.182.2 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: Apache-2.0 Imports: 10 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 cost turns token usage into dollars using the versioned pricing table, and computes the cache-savings math ported from Caprock-python (_savings.py).

Index

Constants

View Source
const (
	CacheTTL5m = 5 * time.Minute
	CacheTTL1h = time.Hour
)

Prompt cache lifetimes: a cached prefix not read again within its TTL is gone. Claude Code writes the 5-minute cache unless the session writes the 1-hour one (cache_creation.ephemeral_1h_input_tokens above zero).

Variables

This section is empty.

Functions

func PromptTokens added in v0.180.0

func PromptTokens(d event.TokenDelta) int64

PromptTokens is the size of the prompt a request sent, as Anthropic, OpenAI and Google count it for prompt-length pricing: all of its input, cache reads and cache writes included.

Types

type Correction added in v0.64.0

type Correction struct {
	// Model is a prefix of the stored model id (SQL LIKE "model%"); each turn
	// it selects is then repriced by the matching rule, so a turn whose id no
	// row matches is left as it was.
	Model string `json:"model"`
	// From is the first UTC day, "YYYY-MM-DD", whose turns are affected.
	// Empty means every turn of that model.
	From string `json:"from,omitempty"`
	// Reason is for the person reading the table.
	Reason string `json:"reason,omitempty"`
}

Correction marks turns an earlier table priced wrongly. A price change never restates history (see Model.Until); a mistake in the table is different — the figure it produced was one nobody was charged, and keeping it keeps an invented number (rule 6). Two cases made this necessary: Opus 5.5 had no row and fell through to Opus 5's by prefix, at 1.25x its input price and 2.5x its cache read; and Sonnet 5's announced rise to $3/$15 on 2026-08-31 was cancelled, so every Sonnet 5 turn from that day had been priced at a rate that never applied.

The daemon reprices the matching turns once per table version, at the row in force at each turn's own timestamp, and moves the session and daily totals by the difference (rollup.ApplyCorrections).

type Model

type Model struct {
	ID            string  `json:"id"`
	Display       string  `json:"display"`
	Input         float64 `json:"input"`
	CacheWrite5m  float64 `json:"cache_write_5m"`
	CacheWrite1h  float64 `json:"cache_write_1h"`
	CacheRead     float64 `json:"cache_read"`
	Output        float64 `json:"output"`
	ContextWindow int64   `json:"context_window"`

	// Until is the last date this row's prices applied, "YYYY-MM-DD"
	// inclusive, in UTC. Empty means "still current" — almost every row.
	//
	// A vendor's introductory price is a real price for the turns that ran
	// while it was live, and a different real price afterwards; overwriting
	// the figure on the day it changes would silently restate every earlier
	// turn at a price nobody was charged, which is rule 6's "no invented
	// numbers" applied to our own history. So a superseded price stays in the
	// table with the date it stopped applying, and Lookup picks the row that
	// was in force when the turn happened. (Sonnet 5 was the first case; its
	// announced rise was then cancelled, which is a Correction, not a change.)
	//
	// Rows for one model id are ordered oldest-first in the JSON; the current
	// row is the one with no Until.
	Until string `json:"until,omitempty"`

	// Tiers are the prices for a larger prompt, lowest threshold first. A
	// vendor that prices by prompt length bills the whole request at the
	// higher rate once the prompt passes the threshold: Claude Haiku 5.5 over
	// 100,000 tokens costs five times its base rate, GPT-6 over 272K twice the
	// input and 1.5x the output. The row's own columns are the base tier;
	// ForPrompt picks the one a request falls in. Empty for most rows.
	Tiers []Tier `json:"tiers,omitempty"`
}

Model is one row of the pricing table. Prices are USD per million tokens.

func (Model) ForPrompt added in v0.180.0

func (m Model) ForPrompt(prompt int64) Model

ForPrompt is this row with its prices replaced by those of the highest tier whose threshold the prompt exceeds, or the row unchanged when none does. A prompt exactly at a threshold is in the lower tier: the vendors say "over" and "more than".

type Savings

type Savings struct {
	BilledWith    float64 `json:"billed_with"`
	BilledWithout float64 `json:"billed_without"`
	Saved         float64 `json:"saved"`
	// HitRate = cache_read / (in + cache_read + cache_write); 0 when no input.
	HitRate float64 `json:"hit_rate"`
	// CutPct = saved / billed_without × 100; 0 when nothing was billed.
	CutPct float64 `json:"cut_pct"`
}

Savings is the cache-savings math from Caprock-python, in input-token equivalents.

billed_with    = in + 1.25·cache_write + 0.10·cache_read
billed_without = in + cache_write + cache_read     (all fresh input)
saved          = billed_without − billed_with

func ComputeSavings

func ComputeSavings(in, cacheRead, cacheWrite int64) Savings

ComputeSavings applies the formula to raw token counts.

type Table

type Table struct {
	Version   string   `json:"version"`
	Source    string   `json:"source"`
	FetchedAt string   `json:"fetched_at"`
	Currency  string   `json:"currency"`
	Unit      string   `json:"unit"`
	Notes     []string `json:"notes"`
	Models    []Model  `json:"models"`
	// Corrections name the turns this version prices differently because an
	// earlier version was wrong, not because a price changed. See Correction.
	Corrections []Correction `json:"corrections,omitempty"`
	// UserOverride is true when the table came from <data_dir>/pricing.json.
	UserOverride bool `json:"user_override,omitempty"`
}

Table is the parsed pricing table.

func Embedded

func Embedded() (*Table, error)

Embedded returns the table compiled into the binary.

func Load

func Load(overridePath string) (*Table, error)

Load returns the user override at overridePath if it exists and parses, else the embedded table. A broken override is an error (never silently ignored — a wrong price file must not masquerade as the default).

func Parse

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

Parse decodes a pricing table and validates it.

func (*Table) CompactionCost added in v0.168.0

func (t *Table) CompactionCost(model string, at time.Time, pre, summaryTokens int64, warm bool) (float64, bool)

CompactionCost is the estimated cost of the call that summarised pre tokens of context into summaryTokens of output, at model's prices at `at`: the context read from the cache when it was warm, sent as uncached input when it was not, and the summary as output. The call's prompt is the pre tokens, so a model priced by prompt length is charged at the tier they fall in. ok is false when the model is not in the table.

func (*Table) CompactionSaving added in v0.168.0

func (t *Table) CompactionSaving(model string, at time.Time, prompt, dropped int64) (float64, bool)

CompactionSaving is what one call after a compaction did not pay for the dropped tokens it would otherwise have read from the cache, at the call's own model and time. prompt is the call's own prompt (PromptTokens); without the compaction it would have been prompt+dropped, so the dropped tokens are priced at the tier that larger prompt falls in. The rest of the call moving into a higher tier is not counted: the estimate stays on the dropped tokens. ok is false when the model is not in the table.

func (*Table) Lookup

func (t *Table) Lookup(model string) (Model, bool)

Lookup finds the pricing row for a model id observed in a transcript (e.g. "claude-opus-5", "claude-sonnet-4-5-20250929", "us.anthropic.claude-sonnet-4-5-20250929-v1:0"). at today's prices; see LookupAt. ok is false when nothing matches — the caller must then leave cost nil, never zero.

func (*Table) LookupAt added in v0.35.0

func (t *Table) LookupAt(model string, at time.Time) (Model, bool)

LookupAt is Lookup for a turn that happened at a particular instant, which is what pricing a historical turn requires.

Prices change, and a change is not retroactive: turns that ran under an introductory price were charged that price forever, and turns after it were not. A table with one row per model can only express "the price now", so restating history is the unavoidable side effect of every price change — August's spend would silently grow on the morning Sonnet 5's introductory rate expired.

So a model may have several rows, oldest first, each carrying the date its price stopped applying (`until`, inclusive, UTC). This returns the first row whose window contains `at`. A zero `at` means the current time, which is what Lookup does and what anything without a timestamp gets. It means the clock, not "the row with no until": a change announced for a future date is entered in advance as a row with that `until` followed by the new one, and today must still read today's price (Gemini 4 Carbon's rise on 2026-12-01 was the first such change).

A row matches an id when the id is the row's id, or the row's id followed by a suffix that names the same model (matchesID). The longest matching id wins; the date only chooses between rows that already matched.

func (*Table) Price

func (t *Table) Price(model string, d event.TokenDelta) (float64, bool)

Price returns the USD cost of a token delta for a model, at today's prices. ok is false when the model is unknown to the table.

func (*Table) PriceAt added in v0.35.0

func (t *Table) PriceAt(model string, d event.TokenDelta, at time.Time) (float64, bool)

PriceAt is Price for a turn that ran at a particular instant, so a turn from before a price change is costed at the price it actually ran under. See LookupAt. A zero `at` prices at today's rates.

type Tier added in v0.180.0

type Tier struct {
	AbovePromptTokens int64   `json:"above_prompt_tokens"`
	Input             float64 `json:"input"`
	CacheWrite5m      float64 `json:"cache_write_5m"`
	CacheWrite1h      float64 `json:"cache_write_1h"`
	CacheRead         float64 `json:"cache_read"`
	Output            float64 `json:"output"`
}

Tier is a row's prices for prompts larger than AbovePromptTokens. The prompt is the request's whole input as the vendor counts it: fresh input, cache reads and cache writes (PromptTokens). Every column is given; a tier never inherits a price from the base row.

Jump to

Keyboard shortcuts

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