feat(pricing): price cached and cache-write input tokens

Cost now prices cache-read and cache-write prompt tokens at their own rates.
A model without a cache price keeps the input rate, so cost does not change.
The cache shares are clamped to the prompt, so odd usage cannot give a negative cost.
LiteLLM field names cache_read_input_token_cost and cache_creation_input_token_cost were confirmed in the fetched source.
The pricing-sync tool reads both fields. The table regeneration is a separate commit.
This commit is contained in:
2026-11-26 00:37:19 +00:00
parent 73ff7d92e0
commit 55ebe1fae1
6 changed files with 206 additions and 17 deletions
+1 -1
View File
@@ -16,7 +16,7 @@ var nonSecretConfigKeys = map[string]bool{
"openDuration": true, "passthroughPaths": true, "path": true, "pathBaseUrls": true,
"probeInterval": true, "providers": true, "requestTimeout": true,
"ttl": true, "type": true,
"defaultTier": true, "toolsMinTier": true, "classifier": true, "shadowClassifier": true, "intentTiers": true, "keywords": true, "selection": true, "tier": true, "header": true, "mode": true, "firstByteTimeout": true, "provider": true, "timeout": true,
"cachedInputPerM": true, "cacheWritePerM": true, "defaultTier": true, "toolsMinTier": true, "classifier": true, "shadowClassifier": true, "intentTiers": true, "keywords": true, "selection": true, "tier": true, "header": true, "mode": true, "firstByteTimeout": true, "provider": true, "timeout": true,
}
func collectStringKeys(t reflect.Type, seen map[reflect.Type]bool, out map[string]bool) {
+3
View File
@@ -22,4 +22,7 @@ type builtinModelMeta struct {
ContextTokens int
InputCostPerMTokMicroUSD int64
OutputCostPerMTokMicroUSD int64
// Cache prices; 0 means unknown, so billing falls back to the input price.
CachedInputCostPerMTokMicroUSD int64
CacheWriteCostPerMTokMicroUSD int64
}
+6 -2
View File
@@ -627,9 +627,13 @@ type AdminStatsConfig struct {
}
// ModelPricing overrides the built-in per-model price table.
// CachedInputPerM and CacheWritePerM price cache-read and cache-write
// prompt tokens; nil falls back to InputPerM.
type ModelPricing struct {
InputPerM float64 `json:"inputPerM"`
OutputPerM float64 `json:"outputPerM"`
CachedInputPerM *float64 `json:"cachedInputPerM,omitempty"`
CacheWritePerM *float64 `json:"cacheWritePerM,omitempty"`
InputPerM float64 `json:"inputPerM"`
OutputPerM float64 `json:"outputPerM"`
}
// ModelMetaConfig overrides one model's context window and per-token
+83 -5
View File
@@ -116,17 +116,74 @@ func costMicrosKnownFor(model string, u usage, overrides map[string]*ModelPricin
// [math.MinInt64, math.MaxInt64] instead of wrapping, so an absurd
// upstream-reported token count bills the maximum representable cost
// rather than a wrapped-around near-zero or negative one.
//
// Cache tokens are part of prompt: cached is clamped to [0, prompt] and
// cacheWrite to [0, prompt-cached] so odd or estimated usage never prices
// above the all-uncached cost or below zero. A nil cache price falls back
// to the input rate.
func computeCostMicros(price ModelPricing, u usage) int64 {
inputMicrosPerM := int64(math.Round(price.InputPerM * tokensPerMillion))
outputMicrosPerM := int64(math.Round(price.OutputPerM * tokensPerMillion))
cachedMicrosPerM := cacheRateMicrosPerM(price.CachedInputPerM, inputMicrosPerM)
writeMicrosPerM := cacheRateMicrosPerM(price.CacheWritePerM, inputMicrosPerM)
inputCost := saturatingMulInt64(u.prompt, inputMicrosPerM)
outputCost := saturatingMulInt64(u.completion, outputMicrosPerM)
total := saturatingAddInt64(inputCost, outputCost)
cached, write, uncached := splitPromptTokens(u)
total := saturatingMulInt64(uncached, inputMicrosPerM)
total = saturatingAddInt64(total, saturatingMulInt64(cached, cachedMicrosPerM))
total = saturatingAddInt64(total, saturatingMulInt64(write, writeMicrosPerM))
total = saturatingAddInt64(total, saturatingMulInt64(u.completion, outputMicrosPerM))
return roundedDivInt64(total, tokensPerMillion)
}
// promptCacheSavedMicros is the micro-USD a cache read saved against the
// plain input price, never negative.
func promptCacheSavedMicros(price ModelPricing, u usage) int64 {
if price.CachedInputPerM == nil {
return 0
}
inputMicrosPerM := int64(math.Round(price.InputPerM * tokensPerMillion))
cachedMicrosPerM := cacheRateMicrosPerM(price.CachedInputPerM, inputMicrosPerM)
diff := inputMicrosPerM - cachedMicrosPerM
if diff <= 0 {
return 0
}
cached, _, _ := splitPromptTokens(u)
return roundedDivInt64(saturatingMulInt64(cached, diff), tokensPerMillion)
}
func cacheRateMicrosPerM(perM *float64, fallbackMicrosPerM int64) int64 {
if perM == nil {
return fallbackMicrosPerM
}
return int64(math.Round(*perM * tokensPerMillion))
}
// splitPromptTokens clamps the cache shares of u.prompt (R2 ruling) and
// returns them with the remaining uncached share.
func splitPromptTokens(u usage) (int64, int64, int64) {
prompt := u.prompt
if prompt < 0 {
prompt = 0
}
cached := u.cached
if cached < 0 {
cached = 0
}
if cached > prompt {
cached = prompt
}
write := u.cacheWrite
if write < 0 {
write = 0
}
if write > prompt-cached {
write = prompt - cached
}
return cached, write, prompt - cached - write
}
// roundedDivInt64 divides total by denom, rounded to the nearest integer
// (half away from zero) rather than truncated toward zero — see
// computeCostMicros' own F9 discussion. denom is always tokensPerMillion
@@ -230,10 +287,19 @@ func lookupPricingSource(model string, overrides map[string]*ModelPricing) (pric
return p, priceSourceBuiltin, true
}
if m, ok := builtinModelMetaTable[model]; ok && (m.InputCostPerMTokMicroUSD > 0 || m.OutputCostPerMTokMicroUSD > 0) {
return ModelPricing{
p := ModelPricing{
InputPerM: microUSDPerMTokToUSD(m.InputCostPerMTokMicroUSD),
OutputPerM: microUSDPerMTokToUSD(m.OutputCostPerMTokMicroUSD),
}, priceSourceLitellm, true
}
if m.CachedInputCostPerMTokMicroUSD > 0 {
v := microUSDPerMTokToUSD(m.CachedInputCostPerMTokMicroUSD)
p.CachedInputPerM = &v
}
if m.CacheWriteCostPerMTokMicroUSD > 0 {
v := microUSDPerMTokToUSD(m.CacheWriteCostPerMTokMicroUSD)
p.CacheWritePerM = &v
}
return p, priceSourceLitellm, true
}
return ModelPricing{}, "", false
}
@@ -345,6 +411,18 @@ func validatePricing(raw map[string]*ModelPricing) (map[string]*ModelPricing, er
{"inputPerM", p.InputPerM},
{"outputPerM", p.OutputPerM},
}
if p.CachedInputPerM != nil {
fields = append(fields, struct {
name string
v float64
}{"cachedInputPerM", *p.CachedInputPerM})
}
if p.CacheWritePerM != nil {
fields = append(fields, struct {
name string
v float64
}{"cacheWritePerM", *p.CacheWritePerM})
}
for _, f := range fields {
if math.IsNaN(f.v) || math.IsInf(f.v, 0) {
return nil, fmt.Errorf("llmgateway: pricing: entry %q: %s must be a finite number, got %v", k, f.name, f.v)
+86
View File
@@ -0,0 +1,86 @@
package traefikllmgateway
import (
"testing"
"github.com/stretchr/testify/require"
)
func f64(v float64) *float64 { return &v }
func TestComputeCostMicrosNoCachedPriceUnchanged(t *testing.T) {
t.Parallel()
p := ModelPricing{InputPerM: 3, OutputPerM: 15}
require.EqualValues(t, 3_000_000, computeCostMicros(p, usage{prompt: 1_000_000, cached: 900_000}))
}
func TestComputeCostMicrosCachedRead(t *testing.T) {
t.Parallel()
p := ModelPricing{InputPerM: 3, OutputPerM: 15, CachedInputPerM: f64(0.3)}
require.EqualValues(t, 570_000, computeCostMicros(p, usage{prompt: 1_000_000, cached: 900_000}))
}
func TestComputeCostMicrosCacheWrite(t *testing.T) {
t.Parallel()
p := ModelPricing{InputPerM: 3, OutputPerM: 15, CachedInputPerM: f64(0.3), CacheWritePerM: f64(3.75)}
require.EqualValues(t, 915_000, computeCostMicros(p, usage{prompt: 1_000_000, cached: 800_000, cacheWrite: 100_000}))
}
func TestComputeCostMicrosCachedClamp(t *testing.T) {
t.Parallel()
p := ModelPricing{InputPerM: 3, OutputPerM: 15, CachedInputPerM: f64(0.3), CacheWritePerM: f64(3.75)}
uncached := computeCostMicros(ModelPricing{InputPerM: 3, OutputPerM: 15}, usage{prompt: 1_000_000})
for _, u := range []usage{
{prompt: 1_000_000, cached: 2_000_000},
{prompt: 1_000_000, cached: 800_000, cacheWrite: 800_000},
{prompt: 1_000_000, cached: -5, cacheWrite: -5},
} {
got := computeCostMicros(p, u)
require.GreaterOrEqual(t, got, int64(0))
require.LessOrEqual(t, got, uncached*2)
}
// cached clamped to prompt: all tokens priced at the cached rate.
require.EqualValues(t, 300_000, computeCostMicros(p, usage{prompt: 1_000_000, cached: 2_000_000}))
}
func TestPromptCacheSavedMicros(t *testing.T) {
t.Parallel()
p := ModelPricing{InputPerM: 3, OutputPerM: 15, CachedInputPerM: f64(0.3)}
require.EqualValues(t, 2_430_000, promptCacheSavedMicros(p, usage{prompt: 1_000_000, cached: 900_000}))
require.EqualValues(t, 0, promptCacheSavedMicros(ModelPricing{InputPerM: 3}, usage{prompt: 1_000_000, cached: 900_000}))
pricey := ModelPricing{InputPerM: 1, CachedInputPerM: f64(2)}
require.EqualValues(t, 0, promptCacheSavedMicros(pricey, usage{prompt: 10, cached: 5}))
}
func TestValidatePricingRejectsNegativeCached(t *testing.T) {
t.Parallel()
_, err := validatePricing(map[string]*ModelPricing{"m": {InputPerM: 1, CachedInputPerM: f64(-1)}})
require.Error(t, err)
_, err = validatePricing(map[string]*ModelPricing{"m": {InputPerM: 1, CacheWritePerM: f64(-1)}})
require.Error(t, err)
_, err = validatePricing(map[string]*ModelPricing{"m": {InputPerM: 1, CachedInputPerM: f64(0.1), CacheWritePerM: f64(1)}})
require.NoError(t, err)
}
func TestBuiltinCachedPriceFlowsToLookup(t *testing.T) {
// Mutates the package-global table, so no t.Parallel.
const id = "test-only-cache-model"
builtinModelMetaTable[id] = builtinModelMeta{
InputCostPerMTokMicroUSD: 3_000_000, OutputCostPerMTokMicroUSD: 15_000_000,
CachedInputCostPerMTokMicroUSD: 300_000, CacheWriteCostPerMTokMicroUSD: 3_750_000,
}
t.Cleanup(func() { delete(builtinModelMetaTable, id) })
p, src, ok := lookupPricingSource(id, nil)
require.True(t, ok)
require.Equal(t, priceSourceLitellm, src)
require.NotNil(t, p.CachedInputPerM)
require.InDelta(t, 0.3, *p.CachedInputPerM, 1e-9)
require.NotNil(t, p.CacheWritePerM)
require.InDelta(t, 3.75, *p.CacheWritePerM, 1e-9)
builtinModelMetaTable[id] = builtinModelMeta{InputCostPerMTokMicroUSD: 3_000_000}
p, _, _ = lookupPricingSource(id, nil)
require.Nil(t, p.CachedInputPerM)
require.Nil(t, p.CacheWritePerM)
}
+27 -9
View File
@@ -276,6 +276,8 @@ type litellmEntry struct {
DeprecationDate string `json:"deprecation_date"`
InputCostPerToken *float64 `json:"input_cost_per_token"`
OutputCostPerToken *float64 `json:"output_cost_per_token"`
CacheReadCost *float64 `json:"cache_read_input_token_cost"`
CacheCreationCost *float64 `json:"cache_creation_input_token_cost"`
MaxInputTokens *float64 `json:"max_input_tokens"`
MaxTokens *float64 `json:"max_tokens"`
LiteLLMProvider string `json:"litellm_provider"`
@@ -287,9 +289,11 @@ type litellmEntry struct {
// importing the plugin package, so this generator never depends on the
// (interpreted-only-constrained) plugin module at all.
type builtinEntry struct {
ContextTokens int
InputCostPerMTokMicroUSD int64
OutputCostPerMTokMicroUSD int64
ContextTokens int
InputCostPerMTokMicroUSD int64
OutputCostPerMTokMicroUSD int64
CachedInputCostPerMTokMicroUSD int64
CacheWriteCostPerMTokMicroUSD int64
}
// candidate is one surviving LiteLLM key considered for a given bare
@@ -414,15 +418,22 @@ func parseAndPrune(data []byte, opts pruneOptions) (map[string]builtinEntry, int
if isStale(bare, e.DeprecationDate, opts) {
continue
}
entry := builtinEntry{
ContextTokens: contextTokens(e),
InputCostPerMTokMicroUSD: microUSDPerMTok(*e.InputCostPerToken),
OutputCostPerMTokMicroUSD: microUSDPerMTok(*e.OutputCostPerToken),
}
if e.CacheReadCost != nil && *e.CacheReadCost > 0 {
entry.CachedInputCostPerMTokMicroUSD = microUSDPerMTok(*e.CacheReadCost)
}
if e.CacheCreationCost != nil && *e.CacheCreationCost > 0 {
entry.CacheWriteCostPerMTokMicroUSD = microUSDPerMTok(*e.CacheCreationCost)
}
byBare[bare] = append(byBare[bare], candidate{
fullKey: key,
provider: e.LiteLLMProvider,
bare: isBareKey,
entry: builtinEntry{
ContextTokens: contextTokens(e),
InputCostPerMTokMicroUSD: microUSDPerMTok(*e.InputCostPerToken),
OutputCostPerMTokMicroUSD: microUSDPerMTok(*e.OutputCostPerToken),
},
entry: entry,
})
}
@@ -578,8 +589,15 @@ func renderGoSource(table map[string]builtinEntry, meta sourceMeta) (string, err
b.WriteString("var builtinModelMetaTable = map[string]builtinModelMeta{\n")
for _, k := range keys {
e := table[k]
fmt.Fprintf(&b, "\t%q: {ContextTokens: %d, InputCostPerMTokMicroUSD: %d, OutputCostPerMTokMicroUSD: %d},\n",
fmt.Fprintf(&b, "\t%q: {ContextTokens: %d, InputCostPerMTokMicroUSD: %d, OutputCostPerMTokMicroUSD: %d",
k, e.ContextTokens, e.InputCostPerMTokMicroUSD, e.OutputCostPerMTokMicroUSD)
if e.CachedInputCostPerMTokMicroUSD > 0 {
fmt.Fprintf(&b, ", CachedInputCostPerMTokMicroUSD: %d", e.CachedInputCostPerMTokMicroUSD)
}
if e.CacheWriteCostPerMTokMicroUSD > 0 {
fmt.Fprintf(&b, ", CacheWriteCostPerMTokMicroUSD: %d", e.CacheWriteCostPerMTokMicroUSD)
}
b.WriteString("},\n")
}
b.WriteString("}\n")