refactor(pricing): share one prompt token split

This commit is contained in:
2026-11-26 01:55:17 +00:00
parent ee758d5d09
commit cf1ae262d6
3 changed files with 19 additions and 25 deletions
+1 -1
View File
@@ -2080,7 +2080,7 @@ func (l *limiter) accountWith(scopes []limitScope, u usage, costMicros int64, x
var pcRead, pcWrite, pcSave int64
if !x.responseCacheHit {
pcRead, pcWrite, _ = promptCacheSplit(u)
pcRead, pcWrite, _ = splitPromptTokens(u)
pcSave = x.promptCacheSaved
if pcSave < 0 || pcSave > maxCostMicrosPerRequest {
pcSave = 0
+1 -24
View File
@@ -51,35 +51,12 @@ func (s *promptCacheStats) snapshot() map[promptCacheKey]int64 {
return out
}
// promptCacheSplit clamps like computeCostMicros: cached in [0,prompt], write in [0,prompt-cached].
func promptCacheSplit(u usage) (int64, int64, int64) {
cached := u.cached
if cached < 0 {
cached = 0
}
if cached > u.prompt {
cached = u.prompt
}
write := u.cacheWrite
if write < 0 {
write = 0
}
if write > u.prompt-cached {
write = u.prompt - cached
}
rest := u.prompt - cached - write
if rest < 0 {
rest = 0
}
return cached, write, rest
}
// recordPromptCache counts one real upstream response; never call it for a response-cache hit.
func (g *Gateway) recordPromptCache(provider, model string, u usage) {
if !metricsEnabled(g.cfg) {
return
}
cached, write, rest := promptCacheSplit(u)
cached, write, rest := splitPromptTokens(u)
g.promptCacheStats.add(promptCacheKey{provider, model, promptCacheKindRead}, cached)
g.promptCacheStats.add(promptCacheKey{provider, model, promptCacheKindWrite}, write)
g.promptCacheStats.add(promptCacheKey{provider, model, promptCacheKindUncached}, rest)
+17
View File
@@ -192,3 +192,20 @@ func TestAdminUsageModelsDetailBudgetUnchanged(t *testing.T) {
require.NotNil(t, got.Models[0].PromptCacheReadTokens)
assert.EqualValues(t, 7, *got.Models[0].PromptCacheReadTokens)
}
func TestSplitPromptTokensNegativePrompt(t *testing.T) {
t.Parallel()
u := usage{prompt: -5, cached: 3, cacheWrite: 2}
cached, write, rest := splitPromptTokens(u)
assert.Zero(t, cached)
assert.Zero(t, write)
assert.Zero(t, rest)
cfg := newAdminTestConfig()
cfg.Metrics = &MetricsConfig{Enabled: true}
_, gw := newAdminGatewayHandle(t, cfg)
gw.recordPromptCache("p", "m", u)
for k, v := range gw.promptCacheStats.snapshot() {
assert.Zero(t, v, "%v", k)
}
}