mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 08:06:50 +00:00
Merge pull request #8825 from r266-tech/codex/deepseek-explicit-pricing-overrides
fix(pricing): honor explicit DeepSeek token price overrides
This commit is contained in:
4 files changed
+181
-28
No files matched your search
@@ -98,15 +98,16 @@ type BillingCache interface {
|
||||
type ModelPricing struct {
|
||||
// UltrafastMultiplier is model-owned and independent of operator Fast pricing.
|
||||
UltrafastMultiplier float64
|
||||
InputPricePerToken float64 // 每token输入价格 (USD)
|
||||
InputPricePerTokenPriority float64 // priority service tier 下每token输入价格 (USD)
|
||||
ImageInputPricePerToken float64 // 图片输入 token 价格 (USD),用于多模态 embedding 等图文不同价场景;为 0 时回退到 InputPricePerToken
|
||||
ImageCacheReadPricePerToken float64 // 图片缓存输入价格;无独立价格时沿用缓存读取价
|
||||
OutputPricePerToken float64 // 每token输出价格 (USD)
|
||||
OutputPricePerTokenPriority float64 // priority service tier 下每token输出价格 (USD)
|
||||
CacheCreationPricePerToken float64 // 缓存创建每token价格 (USD)
|
||||
CacheCreationPricePerTokenPriority float64 // priority service tier 下缓存创建每token价格 (USD)
|
||||
CacheCreationPriceExplicit bool // 是否由渠道/区间定价显式设定(为 true 时即使 == 0 也不回退)
|
||||
InputPricePerToken float64 // 每token输入价格 (USD)
|
||||
InputPricePerTokenPriority float64 // priority service tier 下每token输入价格 (USD)
|
||||
ImageInputPricePerToken float64 // 图片输入 token 价格 (USD),用于多模态 embedding 等图文不同价场景;为 0 时回退到 InputPricePerToken
|
||||
ImageCacheReadPricePerToken float64 // 图片缓存输入价格;无独立价格时沿用缓存读取价
|
||||
OutputPricePerToken float64 // 每token输出价格 (USD)
|
||||
OutputPricePerTokenPriority float64 // priority service tier 下每token输出价格 (USD)
|
||||
CacheCreationPricePerToken float64 // 缓存创建每token价格 (USD)
|
||||
CacheCreationPricePerTokenPriority float64 // priority service tier 下缓存创建每token价格 (USD)
|
||||
CacheCreationPriceExplicit bool // 是否由渠道/区间定价显式设定(为 true 时即使 == 0 也不回退)
|
||||
priceOverrides tokenPriceOverrides
|
||||
CacheReadPricePerToken float64 // 缓存读取每token价格 (USD)
|
||||
CacheReadPricePerTokenPriority float64 // priority service tier 下缓存读取每token价格 (USD)
|
||||
FastMultiplier *float64 // 渠道显式 Fast/priority 倍率;nil 时沿用模型目录行为
|
||||
@@ -1454,6 +1455,7 @@ func (s *BillingService) getModelPricingAt(model string, pricingAt time.Time) (*
|
||||
price1h := litellmPricing.CacheCreationInputTokenCostAbove1hr
|
||||
enableBreakdown := price1h > 0 && price1h > price5m
|
||||
return s.applyModelSpecificPricingPolicyEx(model, &ModelPricing{
|
||||
priceOverrides: litellmPricing.priceOverrides,
|
||||
InputPricePerToken: litellmPricing.InputCostPerToken,
|
||||
InputPricePerTokenPriority: litellmPricing.InputCostPerTokenPriority,
|
||||
OutputPricePerToken: litellmPricing.OutputCostPerToken,
|
||||
@@ -1676,13 +1678,19 @@ func (s *BillingService) calculateTokenCost(resolved *ResolvedPricing, input Cos
|
||||
// DeepSeek 模型默认价卡按官方峰谷口径调整:高峰时段(01:00–04:00 与
|
||||
// 06:00–10:00 UTC,仅工作日;北京时间周末全天低谷)按 2× 低谷价计费。
|
||||
// 仅作用于默认价卡(Source=LiteLLM,无分组/渠道自定义定价)——分组/渠道
|
||||
// 自定义定价保持运营者语义,不叠加。先克隆再乘,避免污染共享 fallbackPrices 指针。
|
||||
// 自定义定价及 override_file 显式覆盖的字段不叠加。先克隆再乘,避免污染共享价卡。
|
||||
if resolved.Source == PricingSourceLiteLLM && isDeepSeekModel(input.Model) {
|
||||
if mult := deepseekPeakMultiplierAt(pricingAt); mult > 1 {
|
||||
cloned := *pricing
|
||||
cloned.InputPricePerToken *= mult
|
||||
cloned.OutputPricePerToken *= mult
|
||||
cloned.CacheReadPricePerToken *= mult
|
||||
if !cloned.priceOverrides.input {
|
||||
cloned.InputPricePerToken *= mult
|
||||
}
|
||||
if !cloned.priceOverrides.output {
|
||||
cloned.OutputPricePerToken *= mult
|
||||
}
|
||||
if !cloned.priceOverrides.cacheRead {
|
||||
cloned.CacheReadPricePerToken *= mult
|
||||
}
|
||||
pricing = &cloned
|
||||
}
|
||||
}
|
||||
@@ -1986,7 +1994,7 @@ func (s *BillingService) applyModelSpecificPricingPolicyEx(model string, pricing
|
||||
if pricing == nil {
|
||||
return nil
|
||||
}
|
||||
// DeepSeek 模型:无论 JSON/远端价格表给什么价,一律强制官方低谷价
|
||||
// DeepSeek 模型:目录/回退数据使用官方低谷价;override_file 显式覆盖的字段保留。
|
||||
// (Flash 三档为 2026-09-10 官方降价后口径)。这是覆盖远端旧价的关键——远端
|
||||
// 仓库不可改,生产会先拉到旧价,必须在此兜底修正;克隆后再覆盖,避免污染
|
||||
// 共享 fallbackPrices 指针。
|
||||
@@ -1997,16 +2005,18 @@ func (s *BillingService) applyModelSpecificPricingPolicyEx(model string, pricing
|
||||
// 对默认价卡另行叠加(分组/渠道自定义定价不叠加)。
|
||||
if forceDeepSeekRates && isDeepSeekModel(model) {
|
||||
cloned := *pricing
|
||||
inputPrice, outputPrice, cacheReadPrice := deepseekFlashOffPeakInputPrice, deepseekFlashOffPeakOutputPrice, deepseekFlashOffPeakCacheRead
|
||||
if isDeepSeekProModel(model) {
|
||||
cloned.InputPricePerToken = deepseekProOffPeakInputPrice
|
||||
cloned.OutputPricePerToken = deepseekProOffPeakOutputPrice
|
||||
cloned.CacheReadPricePerToken = deepseekProOffPeakCacheRead
|
||||
} else {
|
||||
// deepseek-flash(= V4.1-Flash)、deepseek-v4-flash /
|
||||
// deepseek-v4-flash-vision-exp 与其余 deepseek-* 共用 flash 价。
|
||||
cloned.InputPricePerToken = deepseekFlashOffPeakInputPrice
|
||||
cloned.OutputPricePerToken = deepseekFlashOffPeakOutputPrice
|
||||
cloned.CacheReadPricePerToken = deepseekFlashOffPeakCacheRead
|
||||
inputPrice, outputPrice, cacheReadPrice = deepseekProOffPeakInputPrice, deepseekProOffPeakOutputPrice, deepseekProOffPeakCacheRead
|
||||
}
|
||||
if !cloned.priceOverrides.input {
|
||||
cloned.InputPricePerToken = inputPrice
|
||||
}
|
||||
if !cloned.priceOverrides.output {
|
||||
cloned.OutputPricePerToken = outputPrice
|
||||
}
|
||||
if !cloned.priceOverrides.cacheRead {
|
||||
cloned.CacheReadPricePerToken = cacheReadPrice
|
||||
}
|
||||
return &cloned
|
||||
}
|
||||
|
||||
@@ -442,3 +442,115 @@ func TestCalculateCostUnified_DeepseekProRetainsRatesAfterSeptember14(t *testing
|
||||
require.InDelta(t, proTotal, versioned.TotalCost, 1e-10,
|
||||
"versioned pro names must retain Pro rates on September 14")
|
||||
}
|
||||
|
||||
// Explicit override-file token prices are final operator rates, including zero.
|
||||
// Fields absent from that patch still use the official default and peak policy.
|
||||
func TestDeepseekOverrideFileTokenPrices(t *testing.T) {
|
||||
type prices struct{ input, output, cacheRead float64 }
|
||||
official := prices{1.5e-7, 6e-7, 3e-9}
|
||||
officialPeak := prices{3e-7, 1.2e-6, 6e-9}
|
||||
custom := prices{2e-6, 3e-6, 4e-7}
|
||||
fullPatch := `{"input_cost_per_token":0.000002,"output_cost_per_token":0.000003,"cache_read_input_token_cost":0.0000004}`
|
||||
cases := []struct {
|
||||
name, model, layer, patch string
|
||||
offPeak, peak prices
|
||||
}{
|
||||
{"flash full", "deepseek-flash", "catalog", fullPatch, custom, custom},
|
||||
{"pro full", "deepseek-v4-pro", "catalog", fullPatch, custom, custom},
|
||||
{"versioned pro full", "deepseek-v4-pro-0813", "catalog", fullPatch, custom, custom},
|
||||
{"fallback full", "deepseek-flash", "fallback", fullPatch, custom, custom},
|
||||
{"custom model override only", "deepseek-custom", "override", fullPatch, custom, custom},
|
||||
{"override only", "deepseek-flash", "override", fullPatch, custom, custom},
|
||||
{"input only", "deepseek-flash", "catalog", `{"input_cost_per_token":0.000002}`, prices{2e-6, 6e-7, 3e-9}, prices{2e-6, 1.2e-6, 6e-9}},
|
||||
{"zero input", "deepseek-flash", "catalog", `{"input_cost_per_token":0}`, prices{0, 6e-7, 3e-9}, prices{0, 1.2e-6, 6e-9}},
|
||||
{"zero output", "deepseek-flash", "catalog", `{"output_cost_per_token":0}`, prices{1.5e-7, 0, 3e-9}, prices{3e-7, 0, 6e-9}},
|
||||
{"zero cache read", "deepseek-flash", "catalog", `{"cache_read_input_token_cost":0}`, prices{1.5e-7, 6e-7, 0}, prices{3e-7, 1.2e-6, 0}},
|
||||
{"metadata only", "deepseek-flash", "catalog", `{"supports_prompt_caching":true}`, official, officialPeak},
|
||||
{"null input", "deepseek-flash", "catalog", `{"input_cost_per_token":null}`, official, officialPeak},
|
||||
{"negative input", "deepseek-flash", "catalog", `{"input_cost_per_token":-0.000002}`, official, officialPeak},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := &config.Config{}
|
||||
cfg.Pricing.DataDir = dir
|
||||
cfg.Pricing.OverrideFile = filepath.Join(dir, "overrides.json")
|
||||
require.NoError(t, os.WriteFile(cfg.Pricing.OverrideFile, []byte(`{"`+tc.model+`":`+tc.patch+`}`), 0644))
|
||||
// Deliberately stale catalog rates must still be corrected for every
|
||||
// field that the operator did not explicitly override.
|
||||
catalog := []byte(`{"` + tc.model + `":{"input_cost_per_token":0.00001,"output_cost_per_token":0.00002,"cache_read_input_token_cost":0.000001}}`)
|
||||
if tc.layer == "fallback" {
|
||||
cfg.Pricing.FallbackFile = filepath.Join(dir, "fallback.json")
|
||||
require.NoError(t, os.WriteFile(cfg.Pricing.FallbackFile, catalog, 0644))
|
||||
}
|
||||
if tc.layer != "catalog" {
|
||||
catalog = []byte(`{"other-model":{"input_cost_per_token":0.000001}}`)
|
||||
}
|
||||
svc := &PricingService{cfg: cfg}
|
||||
require.NoError(t, os.WriteFile(svc.getPricingFilePath(), catalog, 0644))
|
||||
require.NoError(t, svc.loadPricingData(svc.getPricingFilePath()))
|
||||
billing := NewBillingService(cfg, svc)
|
||||
resolver := NewModelPricingResolver(nil, billing)
|
||||
tokens := UsageTokens{InputTokens: 1000, OutputTokens: 500, CacheReadTokens: 2000}
|
||||
for _, slot := range []struct {
|
||||
name string
|
||||
at time.Time
|
||||
want prices
|
||||
}{
|
||||
{"off peak", time.Date(2026, 8, 24, 12, 0, 0, 0, time.UTC), tc.offPeak},
|
||||
{"peak", time.Date(2026, 8, 24, 2, 0, 0, 0, time.UTC), tc.peak},
|
||||
} {
|
||||
t.Run(slot.name, func(t *testing.T) {
|
||||
cost, err := billing.CalculateCostUnified(CostInput{
|
||||
Ctx: context.Background(), Model: tc.model, Tokens: tokens, RateMultiplier: 1.25,
|
||||
Resolver: resolver, PricingAt: slot.at,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, 1000*slot.want.input, cost.InputCost, 1e-12)
|
||||
require.InDelta(t, 500*slot.want.output, cost.OutputCost, 1e-12)
|
||||
require.InDelta(t, 2000*slot.want.cacheRead, cost.CacheReadCost, 1e-12)
|
||||
want := 1000*slot.want.input + 500*slot.want.output + 2000*slot.want.cacheRead
|
||||
require.InDelta(t, want, cost.TotalCost, 1e-12)
|
||||
require.InDelta(t, want*1.25, cost.ActualCost, 1e-12)
|
||||
stats := tryModelFilePricing(billing, tc.model, tokens, "", slot.at, false)
|
||||
require.NotNil(t, stats)
|
||||
require.InDelta(t, want, *stats, 1e-12, "account statistics use the same override rates")
|
||||
})
|
||||
}
|
||||
// Catalog lookup and legacy estimates also retain the override.
|
||||
pricing, err := billing.GetModelPricing(tc.model)
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, tc.offPeak.input, pricing.InputPricePerToken, 1e-15)
|
||||
require.InDelta(t, tc.offPeak.output, pricing.OutputPricePerToken, 1e-15)
|
||||
require.InDelta(t, tc.offPeak.cacheRead, pricing.CacheReadPricePerToken, 1e-15)
|
||||
estimate, err := billing.CalculateCost(tc.model, tokens, 1)
|
||||
require.NoError(t, err)
|
||||
want := 1000*tc.offPeak.input + 500*tc.offPeak.output + 2000*tc.offPeak.cacheRead
|
||||
require.InDelta(t, want, estimate.TotalCost, 1e-12)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeepseekOverrideFileReloadRestoresOfficialPolicy(t *testing.T) {
|
||||
svc := newHotReloadPricingService(t, `{"deepseek-flash":{"input_cost_per_token":0.00001,"output_cost_per_token":0.00002}}`,
|
||||
`{"deepseek-flash":{"input_cost_per_token":0.000002,"output_cost_per_token":0.000003,"cache_read_input_token_cost":0}}`)
|
||||
billing := NewBillingService(svc.cfg, svc)
|
||||
resolver := NewModelPricingResolver(nil, billing)
|
||||
check := func(wantInput, wantOutput, wantCacheRead float64) {
|
||||
t.Helper()
|
||||
cost, err := billing.CalculateCostUnified(CostInput{Ctx: context.Background(), Model: "deepseek-flash",
|
||||
Tokens: UsageTokens{InputTokens: 1000, OutputTokens: 500, CacheReadTokens: 2000}, RateMultiplier: 1,
|
||||
Resolver: resolver, PricingAt: time.Date(2026, 8, 24, 2, 0, 0, 0, time.UTC)})
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, wantInput, cost.InputCost, 1e-12)
|
||||
require.InDelta(t, wantOutput, cost.OutputCost, 1e-12)
|
||||
require.InDelta(t, wantCacheRead, cost.CacheReadCost, 1e-12)
|
||||
}
|
||||
check(0.002, 0.0015, 0)
|
||||
require.NoError(t, os.WriteFile(svc.cfg.Pricing.OverrideFile, []byte(`{"deepseek-flash":{"output_cost_per_token":0}}`), 0644))
|
||||
svc.reloadIfCustomFilesChanged()
|
||||
check(0.0003, 0, 0.000012)
|
||||
require.NoError(t, os.Remove(svc.cfg.Pricing.OverrideFile))
|
||||
svc.reloadIfCustomFilesChanged()
|
||||
check(0.0003, 0.0006, 0.000012)
|
||||
}
|
||||
@@ -232,10 +232,17 @@ var (
|
||||
}
|
||||
)
|
||||
|
||||
// tokenPriceOverrides tracks explicit nonnegative rates from pricing.override_file.
|
||||
// Keep this provenance with the parsed card so billing never rereads the file.
|
||||
type tokenPriceOverrides struct {
|
||||
input, output, cacheRead bool
|
||||
}
|
||||
|
||||
// LiteLLMModelPricing LiteLLM价格数据结构
|
||||
// 只保留我们需要的字段,使用指针来处理可能缺失的值
|
||||
type LiteLLMModelPricing struct {
|
||||
CacheCreationInputTokenCostExplicit bool `json:"-"`
|
||||
CacheCreationInputTokenCostExplicit bool `json:"-"`
|
||||
priceOverrides tokenPriceOverrides
|
||||
InputCostPerToken float64 `json:"input_cost_per_token"`
|
||||
InputCostPerTokenPriority float64 `json:"input_cost_per_token_priority"`
|
||||
OutputCostPerToken float64 `json:"output_cost_per_token"`
|
||||
@@ -695,7 +702,7 @@ func (s *PricingService) parsePricingData(body []byte) (map[string]*LiteLLMModel
|
||||
if err := json.Unmarshal(body, &rawData); err != nil {
|
||||
return nil, fmt.Errorf("parse raw JSON: %w", err)
|
||||
}
|
||||
rawData = s.applyPricingOverrides(rawData)
|
||||
rawData, priceOverrides := s.applyPricingOverrides(rawData)
|
||||
|
||||
result := make(map[string]*LiteLLMModelPricing)
|
||||
skipped := 0
|
||||
@@ -720,6 +727,7 @@ func (s *PricingService) parsePricingData(body []byte) (map[string]*LiteLLMModel
|
||||
}
|
||||
|
||||
pricing := &LiteLLMModelPricing{
|
||||
priceOverrides: priceOverrides[modelName],
|
||||
LiteLLMProvider: entry.LiteLLMProvider,
|
||||
Mode: entry.Mode,
|
||||
SupportsPromptCaching: entry.SupportsPromptCaching,
|
||||
@@ -960,11 +968,12 @@ func warnOrphanCacheTierFields(entries []string) {
|
||||
// 文件的解析都经过 parsePricingData,因此 override 是最高优先级的数据源。这里只修补
|
||||
// 已存在的条目:目录/回退里都没有的模型由 mergeOverrideOnlyModels 在两层数据合并后
|
||||
// 统一并入——若在此处抢先建条目,纯 override 条目会挡住回退文件中同名完整条目的合并。
|
||||
func (s *PricingService) applyPricingOverrides(rawData map[string]json.RawMessage) map[string]json.RawMessage {
|
||||
func (s *PricingService) applyPricingOverrides(rawData map[string]json.RawMessage) (map[string]json.RawMessage, map[string]tokenPriceOverrides) {
|
||||
overrides := s.loadPricingOverrideEntries()
|
||||
if len(overrides) == 0 {
|
||||
return rawData
|
||||
return rawData, nil
|
||||
}
|
||||
priceOverrides := make(map[string]tokenPriceOverrides, len(overrides))
|
||||
for name, patch := range overrides {
|
||||
base, ok := rawData[name]
|
||||
if !ok {
|
||||
@@ -976,8 +985,25 @@ func (s *PricingService) applyPricingOverrides(rawData map[string]json.RawMessag
|
||||
continue
|
||||
}
|
||||
rawData[name] = merged
|
||||
priceOverrides[name] = tokenPriceOverridesFromPatch(patch)
|
||||
}
|
||||
return rawData, priceOverrides
|
||||
}
|
||||
|
||||
func tokenPriceOverridesFromPatch(patch json.RawMessage) tokenPriceOverrides {
|
||||
var fields map[string]json.RawMessage
|
||||
if json.Unmarshal(patch, &fields) != nil {
|
||||
return tokenPriceOverrides{}
|
||||
}
|
||||
explicitRate := func(field string) bool {
|
||||
var rate *float64
|
||||
return json.Unmarshal(fields[field], &rate) == nil && rate != nil && *rate >= 0
|
||||
}
|
||||
return tokenPriceOverrides{
|
||||
input: explicitRate("input_cost_per_token"),
|
||||
output: explicitRate("output_cost_per_token"),
|
||||
cacheRead: explicitRate("cache_read_input_token_cost"),
|
||||
}
|
||||
return rawData
|
||||
}
|
||||
|
||||
// loadPricingOverrideEntries 读取 override 文件的原始条目。未配置返回 nil;
|
||||
|
||||
@@ -1155,6 +1155,11 @@ pricing:
|
||||
# Gemini 显式缓存存储单价(每 token 每小时,USD)优先取这里的 cache_storage_cost_per_token_per_hour 字段,
|
||||
# 未配置时使用内置官方价(先按已发布型号,再按 Pro / Flash 系列兜底);两者都没有的模型拒绝创建缓存。
|
||||
# 目录中不存在的模型条目还须同时提供 input_cost_per_token / output_cost_per_token。
|
||||
# Explicit nonnegative DeepSeek input/output/cache-read token prices here,
|
||||
# including zero, are final rates and do not receive the official peak multiplier.
|
||||
# Omitted or null fields still use the official defaults and peak/off-peak rules.
|
||||
# DeepSeek 的输入/输出/缓存读单价若在此显式设为非负值(含 0),按该价计费,
|
||||
# 不叠加官方高峰倍率;省略或 null 的字段仍按官方默认价与峰谷规则计费。
|
||||
# override_file: "./data/model_pricing_overrides.json"
|
||||
# Update interval in hours
|
||||
# 更新间隔(小时)
|
||||
|
||||
Reference in new issue
Block a user