mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 00:05:30 +00:00
fix(usage): preserve authoritative cache creation totals
This commit is contained in:
1 parent
c91c594cc8
commit
efc58486d8
20 files changed
+936
-165
No files matched your search
@@ -0,0 +1,179 @@
|
||||
package apicompat
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAnthropicCacheCreationAggregatePresence(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
snapshot string
|
||||
want int
|
||||
present bool
|
||||
}{
|
||||
{"contradictory aggregate", `{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 100, true},
|
||||
{"explicit zero", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 0, true},
|
||||
{"missing aggregate", `{"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 200, false},
|
||||
{"null aggregate", `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 200, false},
|
||||
{"null TTL", `{"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":200}}`, 200, false},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var usage AnthropicUsage
|
||||
require.NoError(t, json.Unmarshal([]byte(test.snapshot), &usage))
|
||||
require.Equal(t, test.present, usage.HasCacheCreationInputTokens())
|
||||
response := AnthropicToResponsesResponse(&AnthropicResponse{Usage: usage})
|
||||
require.Equal(t, test.want, response.Usage.CacheCreationInputTokens)
|
||||
require.Equal(t, test.want, response.Usage.InputTokens)
|
||||
state := NewAnthropicEventToResponsesState()
|
||||
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{
|
||||
Type: "message_start", Message: &AnthropicResponse{ID: "msg_cache", Usage: usage},
|
||||
}, state)
|
||||
for range 2 {
|
||||
var delta AnthropicUsage
|
||||
require.NoError(t, json.Unmarshal([]byte(`{"cache_creation":{"ephemeral_1h_input_tokens":200}}`), &delta))
|
||||
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_delta", Usage: &delta}, state)
|
||||
require.Equal(t, test.want, state.CacheCreationInputTokens)
|
||||
}
|
||||
events := AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_stop"}, state)
|
||||
require.NotEmpty(t, events)
|
||||
completed := events[len(events)-1].Response
|
||||
require.NotNil(t, completed)
|
||||
require.Equal(t, test.want, completed.Usage.CacheCreationInputTokens)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnthropicUsageJSONRoundtrip(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
payload string
|
||||
present bool
|
||||
value int
|
||||
}{
|
||||
{"absent", `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`, false, 0},
|
||||
{"null", `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, false, 0},
|
||||
{"zero", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, true, 0},
|
||||
{"positive", `{"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, true, 20},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var usage AnthropicUsage
|
||||
require.NoError(t, json.Unmarshal([]byte(test.payload), &usage))
|
||||
for range 2 {
|
||||
encoded, err := json.Marshal(usage)
|
||||
require.NoError(t, err)
|
||||
var fields map[string]json.RawMessage
|
||||
require.NoError(t, json.Unmarshal(encoded, &fields))
|
||||
_, present := fields["cache_creation_input_tokens"]
|
||||
require.Equal(t, test.present, present)
|
||||
var roundtrip AnthropicUsage
|
||||
require.NoError(t, json.Unmarshal(encoded, &roundtrip))
|
||||
require.Equal(t, test.present, roundtrip.HasCacheCreationInputTokens())
|
||||
require.Equal(t, test.value, roundtrip.CacheCreationInputTokens)
|
||||
require.Equal(t, usage.CacheCreation, roundtrip.CacheCreation)
|
||||
usage = roundtrip
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnthropicUsageSyntheticJSONRoundtrip(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
usage AnthropicUsage
|
||||
present bool
|
||||
}{
|
||||
{"missing", AnthropicUsage{}, false},
|
||||
{"inferred nonzero", AnthropicUsage{CacheCreationInputTokens: 25}, true},
|
||||
{"explicit zero", AnthropicUsage{CacheCreationInputTokensPresent: true}, true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
test.usage.InputTokens = 10
|
||||
test.usage.OutputTokens = 7
|
||||
test.usage.CacheReadInputTokens = 3
|
||||
encoded, err := json.Marshal(test.usage)
|
||||
require.NoError(t, err)
|
||||
var roundtrip AnthropicUsage
|
||||
require.NoError(t, json.Unmarshal(encoded, &roundtrip))
|
||||
require.Equal(t, test.present, roundtrip.HasCacheCreationInputTokens())
|
||||
require.Equal(t, test.usage.CacheCreationInputTokens, roundtrip.CacheCreationInputTokens)
|
||||
require.Equal(t, 10, roundtrip.InputTokens)
|
||||
require.Equal(t, 7, roundtrip.OutputTokens)
|
||||
require.Equal(t, 3, roundtrip.CacheReadInputTokens)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnthropicUsageAdapterZeroContracts(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
usage AnthropicUsage
|
||||
present bool
|
||||
}{
|
||||
{"missing Responses usage", anthropicUsageFromResponsesUsage(nil), false},
|
||||
{"explicit Responses totals", anthropicUsageFromResponsesUsage(&ResponsesUsage{}), true},
|
||||
{"missing Chat usage", chatUsageToAnthropicUsage(nil), false},
|
||||
{"explicit Chat totals", chatUsageToAnthropicUsage(&ChatUsage{}), true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
encoded, err := json.Marshal(test.usage)
|
||||
require.NoError(t, err)
|
||||
var decoded AnthropicUsage
|
||||
require.NoError(t, json.Unmarshal(encoded, &decoded))
|
||||
require.Equal(t, test.present, decoded.HasCacheCreationInputTokens())
|
||||
require.Zero(t, decoded.CacheCreationInputTokens)
|
||||
})
|
||||
}
|
||||
responsesState := NewResponsesEventToAnthropicState()
|
||||
startEvents := resToAnthHandleCreated(&ResponsesStreamEvent{}, responsesState)
|
||||
chatState := NewChatCompletionsToAnthropicStreamState("claude-sonnet-4")
|
||||
startEvents = append(startEvents, ensureCCAnthropicMessageStart(chatState)...)
|
||||
for _, event := range startEvents {
|
||||
encoded, err := json.Marshal(event)
|
||||
require.NoError(t, err)
|
||||
var decoded AnthropicStreamEvent
|
||||
require.NoError(t, json.Unmarshal(encoded, &decoded))
|
||||
require.NotNil(t, decoded.Message)
|
||||
require.False(t, decoded.Message.Usage.HasCacheCreationInputTokens())
|
||||
}
|
||||
terminalEvents := FinalizeResponsesAnthropicStream(responsesState)
|
||||
terminalEvents = append(terminalEvents, FinalizeChatCompletionsAnthropicStream(chatState)...)
|
||||
usageEvents := 0
|
||||
for _, event := range terminalEvents {
|
||||
if event.Usage == nil {
|
||||
continue
|
||||
}
|
||||
encoded, err := json.Marshal(event)
|
||||
require.NoError(t, err)
|
||||
var decoded AnthropicStreamEvent
|
||||
require.NoError(t, json.Unmarshal(encoded, &decoded))
|
||||
require.NotNil(t, decoded.Usage)
|
||||
require.True(t, decoded.Usage.HasCacheCreationInputTokens())
|
||||
require.Zero(t, decoded.Usage.CacheCreationInputTokens)
|
||||
usageEvents++
|
||||
}
|
||||
require.Equal(t, 2, usageEvents)
|
||||
}
|
||||
|
||||
func TestAnthropicCacheCreationPartialSnapshots(t *testing.T) {
|
||||
state := NewAnthropicEventToResponsesState()
|
||||
for index, snapshot := range []string{
|
||||
`{"cache_creation":{"ephemeral_5m_input_tokens":20}}`,
|
||||
`{"cache_creation":{"ephemeral_1h_input_tokens":30}}`,
|
||||
`{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}}`,
|
||||
`{"cache_creation":{"ephemeral_1h_input_tokens":30}}`,
|
||||
`{"cache_creation_input_tokens":40}`,
|
||||
`{"output_tokens":1}`,
|
||||
`{"cache_creation_input_tokens":0}`,
|
||||
`{"cache_creation":{"ephemeral_1h_input_tokens":200}}`,
|
||||
`{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":null}}`,
|
||||
`{"cache_creation_input_tokens":100}`,
|
||||
} {
|
||||
var usage AnthropicUsage
|
||||
require.NoError(t, json.Unmarshal([]byte(snapshot), &usage))
|
||||
state.mergeCacheCreationUsage(usage)
|
||||
require.Equal(t, []int{20, 50, 50, 50, 40, 40, 0, 0, 0, 100}[index], state.CacheCreationInputTokens)
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,9 @@ func encodeAnthropicThinking(block AnthropicContentBlock) string {
|
||||
}
|
||||
|
||||
func anthropicCacheCreationInputTokens(usage AnthropicUsage) int {
|
||||
if usage.HasCacheCreationInputTokens() {
|
||||
return max(usage.CacheCreationInputTokens, 0)
|
||||
}
|
||||
if usage.CacheCreation != nil && (usage.CacheCreation.Ephemeral5mInputTokens != nil || usage.CacheCreation.Ephemeral1hInputTokens != nil) {
|
||||
cacheCreationTokens := 0
|
||||
if usage.CacheCreation.Ephemeral5mInputTokens != nil {
|
||||
@@ -235,6 +238,8 @@ type AnthropicEventToResponsesState struct {
|
||||
CacheCreationInputTokens int
|
||||
CacheCreation AnthropicCacheCreation
|
||||
|
||||
cacheCreationInputTokensPresent bool
|
||||
|
||||
StopReason string
|
||||
}
|
||||
|
||||
@@ -246,6 +251,10 @@ func NewAnthropicEventToResponsesState() *AnthropicEventToResponsesState {
|
||||
}
|
||||
|
||||
func (state *AnthropicEventToResponsesState) mergeCacheCreationUsage(usage AnthropicUsage) {
|
||||
if usage.HasCacheCreationInputTokens() {
|
||||
state.CacheCreationInputTokens = max(usage.CacheCreationInputTokens, 0)
|
||||
state.cacheCreationInputTokensPresent = true
|
||||
}
|
||||
if usage.CacheCreation != nil {
|
||||
if usage.CacheCreation.Ephemeral5mInputTokens != nil {
|
||||
tokens := max(*usage.CacheCreation.Ephemeral5mInputTokens, 0)
|
||||
@@ -256,10 +265,8 @@ func (state *AnthropicEventToResponsesState) mergeCacheCreationUsage(usage Anthr
|
||||
state.CacheCreation.Ephemeral1hInputTokens = &tokens
|
||||
}
|
||||
}
|
||||
if state.CacheCreation.Ephemeral5mInputTokens != nil || state.CacheCreation.Ephemeral1hInputTokens != nil {
|
||||
if !state.cacheCreationInputTokensPresent && (state.CacheCreation.Ephemeral5mInputTokens != nil || state.CacheCreation.Ephemeral1hInputTokens != nil) {
|
||||
state.CacheCreationInputTokens = anthropicCacheCreationInputTokens(AnthropicUsage{CacheCreation: &state.CacheCreation})
|
||||
} else if usage.CacheCreationInputTokens > 0 {
|
||||
state.CacheCreationInputTokens = usage.CacheCreationInputTokens
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -540,10 +540,11 @@ func chatUsageToAnthropicUsage(usage *ChatUsage) AnthropicUsage {
|
||||
}
|
||||
|
||||
return AnthropicUsage{
|
||||
InputTokens: inputTokens,
|
||||
OutputTokens: usage.CompletionTokens,
|
||||
CacheReadInputTokens: cachedTokens,
|
||||
CacheCreationInputTokens: cacheCreationTokens,
|
||||
InputTokens: inputTokens,
|
||||
OutputTokens: usage.CompletionTokens,
|
||||
CacheReadInputTokens: cachedTokens,
|
||||
CacheCreationInputTokens: cacheCreationTokens,
|
||||
CacheCreationInputTokensPresent: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -714,10 +715,11 @@ func FinalizeChatCompletionsAnthropicStream(state *ChatCompletionsToAnthropicStr
|
||||
StopReason: stopReason,
|
||||
},
|
||||
Usage: &AnthropicUsage{
|
||||
InputTokens: state.InputTokens,
|
||||
OutputTokens: state.OutputTokens,
|
||||
CacheReadInputTokens: state.CacheReadInputTokens,
|
||||
CacheCreationInputTokens: state.CacheCreationInputTokens,
|
||||
InputTokens: state.InputTokens,
|
||||
OutputTokens: state.OutputTokens,
|
||||
CacheReadInputTokens: state.CacheReadInputTokens,
|
||||
CacheCreationInputTokens: state.CacheCreationInputTokens,
|
||||
CacheCreationInputTokensPresent: true,
|
||||
},
|
||||
},
|
||||
AnthropicStreamEvent{Type: "message_stop"},
|
||||
|
||||
@@ -138,13 +138,13 @@ func TestAnthropicEventToResponsesEvents_MergesCacheCreationBreakdown(t *testing
|
||||
{"explicit_5m_zero", `{"cache_creation":{"ephemeral_5m_input_tokens":0}}`, 0, 3, 3},
|
||||
{"omitted_details", `{}`, 2, 3, 5},
|
||||
{"empty_details", `{"cache_creation":{}}`, 2, 3, 5},
|
||||
{"legacy_aggregate_after_details", `{"cache_creation_input_tokens":99}`, 2, 3, 5},
|
||||
{"explicit_both_zero", `{"cache_creation_input_tokens":99,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}}`, 0, 0, 0},
|
||||
{"legacy_aggregate_after_details", `{"cache_creation_input_tokens":99}`, 2, 3, 99},
|
||||
{"explicit_both_zero", `{"cache_creation_input_tokens":99,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}}`, 0, 0, 99},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var startUsage, deltaUsage AnthropicUsage
|
||||
require.NoError(t, json.Unmarshal([]byte(`{"input_tokens":10,"cache_read_input_tokens":4,"cache_creation_input_tokens":99,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":3}}`), &startUsage))
|
||||
require.NoError(t, json.Unmarshal([]byte(`{"input_tokens":10,"cache_read_input_tokens":4,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":3}}`), &startUsage))
|
||||
require.NoError(t, json.Unmarshal([]byte(test.delta), &deltaUsage))
|
||||
state := NewAnthropicEventToResponsesState()
|
||||
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{
|
||||
@@ -159,7 +159,7 @@ func TestAnthropicEventToResponsesEvents_MergesCacheCreationBreakdown(t *testing
|
||||
assert.Equal(t, test.want1h, *state.CacheCreation.Ephemeral1hInputTokens)
|
||||
assert.Equal(t, test.wantTotal, state.CacheCreationInputTokens)
|
||||
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{
|
||||
Type: "message_delta", Usage: &AnthropicUsage{OutputTokens: 7, CacheCreationInputTokens: 99},
|
||||
Type: "message_delta", Usage: &AnthropicUsage{OutputTokens: 7},
|
||||
}, state)
|
||||
|
||||
events := AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_stop"}, state)
|
||||
|
||||
@@ -111,10 +111,11 @@ func anthropicUsageFromResponsesUsage(usage *ResponsesUsage) AnthropicUsage {
|
||||
}
|
||||
|
||||
return AnthropicUsage{
|
||||
InputTokens: inputTokens,
|
||||
OutputTokens: usage.OutputTokens,
|
||||
CacheReadInputTokens: cachedTokens,
|
||||
CacheCreationInputTokens: usage.CacheCreationInputTokens,
|
||||
InputTokens: inputTokens,
|
||||
OutputTokens: usage.OutputTokens,
|
||||
CacheReadInputTokens: cachedTokens,
|
||||
CacheCreationInputTokens: usage.CacheCreationInputTokens,
|
||||
CacheCreationInputTokensPresent: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -285,10 +286,11 @@ func FinalizeResponsesAnthropicStream(state *ResponsesEventToAnthropicState) []A
|
||||
StopReason: stopReason,
|
||||
},
|
||||
Usage: &AnthropicUsage{
|
||||
InputTokens: state.InputTokens,
|
||||
OutputTokens: state.OutputTokens,
|
||||
CacheReadInputTokens: state.CacheReadInputTokens,
|
||||
CacheCreationInputTokens: state.CacheCreationInputTokens,
|
||||
InputTokens: state.InputTokens,
|
||||
OutputTokens: state.OutputTokens,
|
||||
CacheReadInputTokens: state.CacheReadInputTokens,
|
||||
CacheCreationInputTokens: state.CacheCreationInputTokens,
|
||||
CacheCreationInputTokensPresent: true,
|
||||
},
|
||||
},
|
||||
AnthropicStreamEvent{Type: "message_stop"},
|
||||
@@ -768,10 +770,11 @@ func resToAnthHandleCompleted(evt *ResponsesStreamEvent, state *ResponsesEventTo
|
||||
StopReason: stopReason,
|
||||
},
|
||||
Usage: &AnthropicUsage{
|
||||
InputTokens: state.InputTokens,
|
||||
OutputTokens: state.OutputTokens,
|
||||
CacheReadInputTokens: state.CacheReadInputTokens,
|
||||
CacheCreationInputTokens: state.CacheCreationInputTokens,
|
||||
InputTokens: state.InputTokens,
|
||||
OutputTokens: state.OutputTokens,
|
||||
CacheReadInputTokens: state.CacheReadInputTokens,
|
||||
CacheCreationInputTokens: state.CacheCreationInputTokens,
|
||||
CacheCreationInputTokensPresent: true,
|
||||
},
|
||||
},
|
||||
AnthropicStreamEvent{Type: "message_stop"},
|
||||
|
||||
@@ -189,6 +189,43 @@ type AnthropicUsage struct {
|
||||
PromptTokensDetails *AnthropicPromptTokensDetails `json:"prompt_tokens_details,omitempty"`
|
||||
PromptCacheHitTokens *int `json:"prompt_cache_hit_tokens,omitempty"`
|
||||
PromptCacheMissTokens *int `json:"prompt_cache_miss_tokens,omitempty"`
|
||||
|
||||
// Presence distinguishes explicit zero from missing/null; TTL details remain raw.
|
||||
CacheCreationInputTokensPresent bool `json:"-"`
|
||||
}
|
||||
|
||||
func (usage *AnthropicUsage) UnmarshalJSON(data []byte) error {
|
||||
type usageAlias AnthropicUsage
|
||||
var decoded struct {
|
||||
usageAlias
|
||||
CacheCreationInputTokens *int `json:"cache_creation_input_tokens"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &decoded); err != nil {
|
||||
return err
|
||||
}
|
||||
*usage = AnthropicUsage(decoded.usageAlias)
|
||||
if decoded.CacheCreationInputTokens != nil {
|
||||
usage.CacheCreationInputTokens = *decoded.CacheCreationInputTokens
|
||||
usage.CacheCreationInputTokensPresent = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (usage AnthropicUsage) HasCacheCreationInputTokens() bool {
|
||||
return usage.CacheCreationInputTokensPresent || usage.CacheCreationInputTokens != 0
|
||||
}
|
||||
|
||||
// MarshalJSON preserves aggregate presence and raw TTL details without deriving totals.
|
||||
func (usage AnthropicUsage) MarshalJSON() ([]byte, error) {
|
||||
type usageAlias AnthropicUsage
|
||||
var aggregate *int
|
||||
if usage.HasCacheCreationInputTokens() {
|
||||
aggregate = &usage.CacheCreationInputTokens
|
||||
}
|
||||
return json.Marshal(struct {
|
||||
usageAlias
|
||||
CacheCreationInputTokens *int `json:"cache_creation_input_tokens,omitempty"`
|
||||
}{usageAlias: usageAlias(usage), CacheCreationInputTokens: aggregate})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -27,6 +27,9 @@ func TestAnthropicChatStreamAuthoritativeUsage(t *testing.T) {
|
||||
prompt, billableInput, totalInput, output, cached, created int
|
||||
}{
|
||||
{"cache", `,"usage":{"input_tokens":308,"cache_read_input_tokens":241,"cache_creation_input_tokens":17}`, `,"usage":{"output_tokens":49}`, "", true, 566, 308, 566, 49, 241, 17},
|
||||
{"contradictory_cache_creation", `,"usage":{"input_tokens":10,"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `,"usage":{"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `,"usage":{"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, true, 110, 10, 110, 7, 0, 100},
|
||||
{"zero_cache_creation", `,"usage":{"input_tokens":10,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `,"usage":{"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, "", true, 10, 10, 10, 7, 0, 0},
|
||||
{"partial_cache_creation", `,"usage":{"input_tokens":10,"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `,"usage":{"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, `,"usage":{"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, true, 60, 10, 60, 7, 0, 50},
|
||||
{"deepseek_partial_cache", "", `,"usage":{"input_tokens":1200,"output_tokens":30,"prompt_cache_hit_tokens":800,"prompt_cache_miss_tokens":400}`, "", true, 1200, 400, 1200, 30, 800, 0},
|
||||
{"openai_partial_cache", "", `,"usage":{"prompt_tokens":1200,"output_tokens":30,"prompt_tokens_details":{"cached_tokens":800}}`, "", true, 1200, 400, 1200, 30, 800, 0},
|
||||
{"repeated_authoritative_cache_bucket", `,"usage":{"input_tokens":1200,"prompt_tokens":1200}`, `,"usage":{"output_tokens":30,"prompt_tokens":1200,"cache_read_input_tokens":800}`, `,"usage":{"output_tokens":30,"prompt_tokens":1200,"cache_read_input_tokens":800}`, true, 1200, 400, 1200, 30, 800, 0},
|
||||
|
||||
@@ -1781,14 +1781,14 @@ func TestExtractSSEUsage(t *testing.T) {
|
||||
{
|
||||
name: "top-level usage with all fields",
|
||||
line: `data: {"usage":{"input_tokens":10,"output_tokens":20,"cache_read_input_tokens":5,"cache_creation_input_tokens":3}}`,
|
||||
expected: ClaudeUsage{InputTokens: 10, OutputTokens: 20, CacheReadInputTokens: 5, CacheCreationInputTokens: 3},
|
||||
expected: ClaudeUsage{InputTokens: 10, OutputTokens: 20, CacheReadInputTokens: 5, CacheCreationInputTokens: 3, cacheCreationInputTokensPresent: true},
|
||||
},
|
||||
{
|
||||
// Anthropic message_start 把 usage 嵌套在 message.usage 下,
|
||||
// 必须从这里提取输入侧字段(含 cache_read/cache_creation_input_tokens)。
|
||||
name: "message_start nested usage with input/cache tokens",
|
||||
line: `data: {"type":"message_start","message":{"id":"msg_01","usage":{"input_tokens":35576,"cache_creation_input_tokens":0,"cache_read_input_tokens":12000,"output_tokens":1}}}`,
|
||||
expected: ClaudeUsage{InputTokens: 35576, OutputTokens: 1, CacheReadInputTokens: 12000},
|
||||
expected: ClaudeUsage{InputTokens: 35576, OutputTokens: 1, CacheReadInputTokens: 12000, cacheCreationInputTokensPresent: true},
|
||||
},
|
||||
{
|
||||
// message_start.message.usage.cache_creation 内的 5m/1h 明细也要解析。
|
||||
|
||||
@@ -151,12 +151,7 @@ func (s *AntigravityGatewayService) ForwardUpstream(ctx context.Context, c *gin.
|
||||
FirstTokenMs: firstTokenMs,
|
||||
ClientDisconnect: clientDisconnect,
|
||||
UpstreamHeaders: resp.Header,
|
||||
Usage: ClaudeUsage{
|
||||
InputTokens: usage.InputTokens,
|
||||
OutputTokens: usage.OutputTokens,
|
||||
CacheReadInputTokens: usage.CacheReadInputTokens,
|
||||
CacheCreationInputTokens: usage.CacheCreationInputTokens,
|
||||
},
|
||||
Usage: *usage,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -335,8 +330,9 @@ func (s *AntigravityGatewayService) extractSSEUsage(line string, usage *ClaudeUs
|
||||
if v, ok := u["cache_read_input_tokens"].(float64); ok && int(v) > 0 {
|
||||
usage.CacheReadInputTokens = int(v)
|
||||
}
|
||||
if v, ok := u["cache_creation_input_tokens"].(float64); ok && int(v) > 0 {
|
||||
if v, ok := u["cache_creation_input_tokens"].(float64); ok && int(v) >= 0 {
|
||||
usage.CacheCreationInputTokens = int(v)
|
||||
usage.cacheCreationInputTokensPresent = true
|
||||
}
|
||||
// 解析嵌套的 cache_creation 对象中的 5m/1h 明细
|
||||
if cc, ok := u["cache_creation"].(map[string]any); ok {
|
||||
@@ -368,6 +364,7 @@ func (s *AntigravityGatewayService) extractClaudeUsage(body []byte) *ClaudeUsage
|
||||
}
|
||||
if v, ok := u["cache_creation_input_tokens"].(float64); ok {
|
||||
usage.CacheCreationInputTokens = int(v)
|
||||
usage.cacheCreationInputTokensPresent = true
|
||||
}
|
||||
// 解析嵌套的 cache_creation 对象中的 5m/1h 明细
|
||||
if cc, ok := u["cache_creation"].(map[string]any); ok {
|
||||
|
||||
@@ -1287,7 +1287,7 @@ func TestExtractAnthropicSSEDataLine(t *testing.T) {
|
||||
|
||||
func TestGatewayService_ParseSSEUsagePassthrough_MessageStartFallbacks(t *testing.T) {
|
||||
usage := &ClaudeUsage{}
|
||||
data := `{"type":"message_start","message":{"usage":{"input_tokens":12,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"cached_tokens":9,"cache_creation":{"ephemeral_5m_input_tokens":3,"ephemeral_1h_input_tokens":4}}}}`
|
||||
data := `{"type":"message_start","message":{"usage":{"input_tokens":12,"cache_read_input_tokens":0,"cached_tokens":9,"cache_creation":{"ephemeral_5m_input_tokens":3,"ephemeral_1h_input_tokens":4}}}}`
|
||||
|
||||
parseSSEUsagePassthrough(data, usage)
|
||||
|
||||
@@ -1341,6 +1341,72 @@ func TestGatewayService_ParseSSEUsagePassthrough_FallbackFromUsageNode(t *testin
|
||||
require.Equal(t, 3, usage.CacheCreationInputTokens)
|
||||
}
|
||||
|
||||
func TestGatewayService_ParseSSEUsagePassthrough_OtherEventCacheCreation(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
start string
|
||||
snapshots []string
|
||||
wantAggregate int
|
||||
}{
|
||||
{
|
||||
name: "omitted aggregate merges partial TTL snapshots",
|
||||
snapshots: []string{`{"cache_creation":{"ephemeral_5m_input_tokens":2}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":1}}`},
|
||||
wantAggregate: 3,
|
||||
},
|
||||
{
|
||||
name: "null aggregate falls back to TTL",
|
||||
snapshots: []string{`{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":1}}`},
|
||||
wantAggregate: 3,
|
||||
},
|
||||
{
|
||||
name: "explicit zero retains raw TTL",
|
||||
snapshots: []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":1}}`},
|
||||
},
|
||||
{
|
||||
name: "previous explicit aggregate survives null",
|
||||
start: `{"cache_creation_input_tokens":9}`,
|
||||
snapshots: []string{`{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":1}}`},
|
||||
wantAggregate: 9,
|
||||
},
|
||||
{
|
||||
name: "previous explicit zero survives omitted aggregate",
|
||||
start: `{"cache_creation_input_tokens":0}`,
|
||||
snapshots: []string{`{"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":1}}`},
|
||||
},
|
||||
{
|
||||
name: "explicit zero replaces previous aggregate",
|
||||
start: `{"cache_creation_input_tokens":9}`,
|
||||
snapshots: []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":1}}`},
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
for _, location := range []string{"usage", "message.usage", "null usage with message.usage"} {
|
||||
t.Run(test.name+"/"+location, func(t *testing.T) {
|
||||
usage := &ClaudeUsage{}
|
||||
if test.start != "" {
|
||||
parseSSEUsagePassthrough(`{"type":"message_start","message":{"usage":`+test.start+`}}`, usage)
|
||||
}
|
||||
for _, snapshot := range test.snapshots {
|
||||
data := `{"type":"content_block_delta","usage":` + snapshot + `}`
|
||||
switch location {
|
||||
case "message.usage":
|
||||
data = `{"type":"content_block_delta","message":{"usage":` + snapshot + `}}`
|
||||
case "null usage with message.usage":
|
||||
data = `{"type":"content_block_delta","usage":null,"message":{"usage":` + snapshot + `}}`
|
||||
}
|
||||
parseSSEUsagePassthrough(data, usage)
|
||||
previous := *usage
|
||||
parseSSEUsagePassthrough(data, usage)
|
||||
require.Equal(t, previous, *usage, "repeated cumulative snapshots must be idempotent")
|
||||
}
|
||||
require.Equal(t, test.wantAggregate, usage.CacheCreationInputTokens)
|
||||
require.Equal(t, 2, usage.CacheCreation5mTokens)
|
||||
require.Equal(t, 1, usage.CacheCreation1hTokens)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseClaudeUsageFromResponseBody(t *testing.T) {
|
||||
t.Run("empty or missing usage", func(t *testing.T) {
|
||||
got := parseClaudeUsageFromResponseBody(nil)
|
||||
@@ -1353,7 +1419,7 @@ func TestParseClaudeUsageFromResponseBody(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("parse all usage fields and fallback", func(t *testing.T) {
|
||||
body := []byte(`{"usage":{"input_tokens":21,"output_tokens":34,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"cached_tokens":13,"cache_creation":{"ephemeral_5m_input_tokens":5,"ephemeral_1h_input_tokens":8}}}`)
|
||||
body := []byte(`{"usage":{"input_tokens":21,"output_tokens":34,"cache_read_input_tokens":0,"cached_tokens":13,"cache_creation":{"ephemeral_5m_input_tokens":5,"ephemeral_1h_input_tokens":8}}}`)
|
||||
got := parseClaudeUsageFromResponseBody(body)
|
||||
require.Equal(t, 21, got.InputTokens)
|
||||
require.Equal(t, 34, got.OutputTokens)
|
||||
|
||||
@@ -635,16 +635,9 @@ func parseSSEUsagePassthrough(data string, usage *ClaudeUsage) {
|
||||
msgUsage := parsed.Get("message.usage")
|
||||
if msgUsage.Exists() {
|
||||
usage.InputTokens = int(msgUsage.Get("input_tokens").Int())
|
||||
usage.CacheCreationInputTokens = int(msgUsage.Get("cache_creation_input_tokens").Int())
|
||||
usage.CacheReadInputTokens = int(msgUsage.Get("cache_read_input_tokens").Int())
|
||||
|
||||
// 保持与通用解析一致:message_start 允许覆盖 5m/1h 明细(包括 0)。
|
||||
cc5m := msgUsage.Get("cache_creation.ephemeral_5m_input_tokens")
|
||||
cc1h := msgUsage.Get("cache_creation.ephemeral_1h_input_tokens")
|
||||
if cc5m.Exists() || cc1h.Exists() {
|
||||
usage.CacheCreation5mTokens = int(cc5m.Int())
|
||||
usage.CacheCreation1hTokens = int(cc1h.Int())
|
||||
}
|
||||
mergeRawAnthropicCacheCreationUsage(msgUsage, usage)
|
||||
}
|
||||
case "message_delta":
|
||||
deltaUsage := parsed.Get("usage")
|
||||
@@ -655,22 +648,18 @@ func parseSSEUsagePassthrough(data string, usage *ClaudeUsage) {
|
||||
if v := deltaUsage.Get("output_tokens").Int(); v > 0 {
|
||||
usage.OutputTokens = int(v)
|
||||
}
|
||||
if v := deltaUsage.Get("cache_creation_input_tokens").Int(); v > 0 {
|
||||
usage.CacheCreationInputTokens = int(v)
|
||||
}
|
||||
if v := deltaUsage.Get("cache_read_input_tokens").Int(); v > 0 {
|
||||
usage.CacheReadInputTokens = int(v)
|
||||
}
|
||||
|
||||
cc5m := deltaUsage.Get("cache_creation.ephemeral_5m_input_tokens")
|
||||
cc1h := deltaUsage.Get("cache_creation.ephemeral_1h_input_tokens")
|
||||
if cc5m.Exists() {
|
||||
usage.CacheCreation5mTokens = int(cc5m.Int())
|
||||
}
|
||||
if cc1h.Exists() {
|
||||
usage.CacheCreation1hTokens = int(cc1h.Int())
|
||||
}
|
||||
mergeRawAnthropicCacheCreationUsage(deltaUsage, usage)
|
||||
}
|
||||
default:
|
||||
usageNode := parsed.Get("usage")
|
||||
if !usageNode.Exists() || usageNode.Type == gjson.Null {
|
||||
usageNode = parsed.Get("message.usage")
|
||||
}
|
||||
mergeRawAnthropicCacheCreationUsage(usageNode, usage)
|
||||
}
|
||||
|
||||
if usage.CacheReadInputTokens == 0 {
|
||||
@@ -681,18 +670,6 @@ func parseSSEUsagePassthrough(data string, usage *ClaudeUsage) {
|
||||
usage.CacheReadInputTokens = int(cached)
|
||||
}
|
||||
}
|
||||
if usage.CacheCreationInputTokens == 0 {
|
||||
cc5m := parsed.Get("message.usage.cache_creation.ephemeral_5m_input_tokens").Int()
|
||||
cc1h := parsed.Get("message.usage.cache_creation.ephemeral_1h_input_tokens").Int()
|
||||
if cc5m == 0 && cc1h == 0 {
|
||||
cc5m = parsed.Get("usage.cache_creation.ephemeral_5m_input_tokens").Int()
|
||||
cc1h = parsed.Get("usage.cache_creation.ephemeral_1h_input_tokens").Int()
|
||||
}
|
||||
total := cc5m + cc1h
|
||||
if total > 0 {
|
||||
usage.CacheCreationInputTokens = int(total)
|
||||
}
|
||||
}
|
||||
|
||||
// Kimi's Anthropic-compatible stream uses input_tokens with two meanings:
|
||||
// message_start reports total prompt input, while message_delta reports only
|
||||
@@ -739,17 +716,8 @@ func normalizeAnthropicCompatiblePromptUsage(usageNode gjson.Result, usage *Clau
|
||||
cacheReadTokens = max(int(promptCacheHitTokens.Int()), 0)
|
||||
}
|
||||
|
||||
mergeRawAnthropicCacheCreationUsage(usageNode, usage)
|
||||
cacheCreationTokens := usage.CacheCreationInputTokens
|
||||
if v := usageNode.Get("cache_creation_input_tokens"); v.Exists() {
|
||||
cacheCreationTokens = int(v.Int())
|
||||
}
|
||||
if cacheCreationTokens == 0 {
|
||||
cc5m := usageNode.Get("cache_creation.ephemeral_5m_input_tokens").Int()
|
||||
cc1h := usageNode.Get("cache_creation.ephemeral_1h_input_tokens").Int()
|
||||
if cc5m > 0 || cc1h > 0 {
|
||||
cacheCreationTokens = int(cc5m + cc1h)
|
||||
}
|
||||
}
|
||||
|
||||
if promptCacheMissTokens.Exists() {
|
||||
usage.InputTokens = max(int(promptCacheMissTokens.Int()), 0)
|
||||
@@ -775,18 +743,9 @@ func parseClaudeUsageFromResponseBody(body []byte) *ClaudeUsage {
|
||||
|
||||
usage.InputTokens = int(usageNode.Get("input_tokens").Int())
|
||||
usage.OutputTokens = int(usageNode.Get("output_tokens").Int())
|
||||
usage.CacheCreationInputTokens = int(usageNode.Get("cache_creation_input_tokens").Int())
|
||||
usage.CacheReadInputTokens = int(usageNode.Get("cache_read_input_tokens").Int())
|
||||
|
||||
cc5m := usageNode.Get("cache_creation.ephemeral_5m_input_tokens").Int()
|
||||
cc1h := usageNode.Get("cache_creation.ephemeral_1h_input_tokens").Int()
|
||||
if cc5m > 0 || cc1h > 0 {
|
||||
usage.CacheCreation5mTokens = int(cc5m)
|
||||
usage.CacheCreation1hTokens = int(cc1h)
|
||||
}
|
||||
if usage.CacheCreationInputTokens == 0 && (cc5m > 0 || cc1h > 0) {
|
||||
usage.CacheCreationInputTokens = int(cc5m + cc1h)
|
||||
}
|
||||
mergeRawAnthropicCacheCreationUsage(usageNode, usage)
|
||||
if usage.CacheReadInputTokens == 0 {
|
||||
if cached := usageNode.Get("cached_tokens").Int(); cached > 0 {
|
||||
usage.CacheReadInputTokens = int(cached)
|
||||
|
||||
@@ -0,0 +1,497 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/apicompat"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func TestAnthropicCacheCreationSnapshots(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
snapshots []string
|
||||
wantTotals []int
|
||||
want5m int
|
||||
want1h int
|
||||
billed5m int
|
||||
billed1h int
|
||||
}{
|
||||
{
|
||||
name: "aggregate 100 with 1h 200",
|
||||
snapshots: []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`},
|
||||
wantTotals: []int{100, 100}, want1h: 200, billed1h: 100,
|
||||
},
|
||||
{
|
||||
name: "contradictory explicit aggregate",
|
||||
snapshots: []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":300}}`},
|
||||
wantTotals: []int{100, 100}, want5m: 50, want1h: 300, billed5m: 14, billed1h: 86,
|
||||
},
|
||||
{
|
||||
name: "partial TTL snapshots derive missing aggregate",
|
||||
snapshots: []string{`{"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":0}}`},
|
||||
wantTotals: []int{20, 50, 30}, want1h: 30, billed1h: 30,
|
||||
},
|
||||
{
|
||||
name: "aggregate only delta replaces derived total",
|
||||
snapshots: []string{`{"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`, `{"cache_creation_input_tokens":40}`, `{"output_tokens":7}`, `{"cache_creation":{"ephemeral_1h_input_tokens":200}}`},
|
||||
wantTotals: []int{50, 40, 40, 40}, want5m: 20, want1h: 200, billed5m: 4, billed1h: 36,
|
||||
},
|
||||
{
|
||||
name: "explicit zero survives TTL updates",
|
||||
snapshots: []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":50}}`},
|
||||
wantTotals: []int{0, 0}, want5m: 50, want1h: 200,
|
||||
},
|
||||
{
|
||||
name: "explicit zero delta clears aggregate",
|
||||
snapshots: []string{`{"cache_creation_input_tokens":100}`, `{"cache_creation_input_tokens":0}`, `{"cache_creation":{"ephemeral_1h_input_tokens":200}}`},
|
||||
wantTotals: []int{100, 0, 0}, want1h: 200,
|
||||
},
|
||||
{
|
||||
name: "repeated cumulative snapshots do not double count",
|
||||
snapshots: []string{`{"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`},
|
||||
wantTotals: []int{50, 50, 50}, want5m: 20, want1h: 30, billed5m: 20, billed1h: 30,
|
||||
},
|
||||
{
|
||||
name: "null aggregate derives merged partial TTL",
|
||||
snapshots: []string{`{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}}`},
|
||||
wantTotals: []int{20, 50, 50}, want5m: 20, want1h: 30, billed5m: 20, billed1h: 30,
|
||||
},
|
||||
{
|
||||
name: "null aggregate does not clear explicit aggregate",
|
||||
snapshots: []string{`{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":null}}`},
|
||||
wantTotals: []int{100, 100}, want1h: 200, billed1h: 100,
|
||||
},
|
||||
{
|
||||
name: "null does not clear explicit zero",
|
||||
snapshots: []string{`{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":null}}`},
|
||||
wantTotals: []int{0, 0}, want5m: 20, want1h: 200,
|
||||
},
|
||||
{
|
||||
name: "zero to positive retains partial TTL history",
|
||||
snapshots: []string{`{"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":50}}`, `{"cache_creation_input_tokens":35}`},
|
||||
wantTotals: []int{20, 0, 0, 35}, want5m: 20, want1h: 50, billed5m: 10, billed1h: 25,
|
||||
},
|
||||
{
|
||||
name: "all null is absent before partial TTL",
|
||||
snapshots: []string{`{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`},
|
||||
wantTotals: []int{0, 20, 50}, want5m: 20, want1h: 30, billed5m: 20, billed1h: 30,
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
for _, parser := range []string{"shared merge", "raw passthrough", "generic SSE"} {
|
||||
t.Run(test.name+"/"+parser, func(t *testing.T) {
|
||||
usage := &ClaudeUsage{}
|
||||
for index, snapshot := range test.snapshots {
|
||||
if parser == "shared merge" {
|
||||
var source apicompat.AnthropicUsage
|
||||
require.NoError(t, json.Unmarshal([]byte(snapshot), &source))
|
||||
mergeAnthropicUsage(usage, source)
|
||||
} else if parser == "generic SSE" {
|
||||
if index == 0 {
|
||||
(&GatewayService{}).parseSSEUsage(`{"type":"message_start","message":{"usage":`+snapshot+`}}`, usage)
|
||||
} else {
|
||||
(&GatewayService{}).parseSSEUsage(`{"type":"message_delta","usage":`+snapshot+`}`, usage)
|
||||
}
|
||||
} else if index == 0 {
|
||||
parseSSEUsagePassthrough(`{"type":"message_start","message":{"usage":`+snapshot+`}}`, usage)
|
||||
} else {
|
||||
parseSSEUsagePassthrough(`{"type":"message_delta","usage":`+snapshot+`}`, usage)
|
||||
}
|
||||
require.Equal(t, test.wantTotals[index], usage.CacheCreationInputTokens)
|
||||
}
|
||||
require.Equal(t, test.want5m, usage.CacheCreation5mTokens)
|
||||
require.Equal(t, test.want1h, usage.CacheCreation1hTokens)
|
||||
cache5m, cache1h := normalizeCacheCreationBreakdown(usage.billingUsageTokens())
|
||||
require.Equal(t, test.billed5m, cache5m)
|
||||
require.Equal(t, test.billed1h, cache1h)
|
||||
assertAnthropicCacheCreationRecordCosts(t, *usage, float64(test.billed5m)*0.002+float64(test.billed1h)*0.004)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertAnthropicCacheCreationRecordCosts(t *testing.T, usage ClaudeUsage, wantCacheCost float64) {
|
||||
t.Helper()
|
||||
usage.InputTokens = 10
|
||||
usage.OutputTokens = 2
|
||||
assertAnthropicCacheCreationResultCosts(t, &ForwardResult{RequestID: "cache_creation", Model: "claude-sonnet-4", Usage: usage, Duration: time.Second}, wantCacheCost)
|
||||
}
|
||||
|
||||
func assertAnthropicCacheCreationResultCosts(t *testing.T, result *ForwardResult, wantCacheCost float64) {
|
||||
t.Helper()
|
||||
for _, customStats := range []bool{false, true} {
|
||||
usageRepo := &openAIRecordUsageLogRepoStub{inserted: true}
|
||||
svc := newGatewayRecordUsageServiceForTest(usageRepo, &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{})
|
||||
svc.billingService = newTestBillingServiceWithPrices(map[string]*ModelPricing{
|
||||
"claude-sonnet-4": {
|
||||
InputPricePerToken: 0.001, OutputPricePerToken: 0.002,
|
||||
CacheCreationPricePerToken: 0.002, SupportsCacheBreakdown: true,
|
||||
CacheCreation5mPrice: 0.002, CacheCreation1hPrice: 0.004,
|
||||
},
|
||||
})
|
||||
channel := &Channel{ID: 1, Status: StatusActive}
|
||||
statsMultiplier := 1.0
|
||||
if customStats {
|
||||
statsMultiplier = 10
|
||||
channel.AccountStatsPricingRules = []AccountStatsPricingRule{{
|
||||
AccountIDs: []int64{701},
|
||||
Pricing: []ChannelModelPricing{{
|
||||
Platform: PlatformAnthropic, Models: []string{"claude-sonnet-4"}, BillingMode: BillingModeToken,
|
||||
InputPrice: float64Ptr(0.01), OutputPrice: float64Ptr(0.02),
|
||||
CacheWritePrice: float64Ptr(0.02), CacheWrite1hPrice: float64Ptr(0.04),
|
||||
}},
|
||||
}}
|
||||
}
|
||||
svc.channelService = newTestChannelServiceForStats(t, channel, 10, PlatformAnthropic)
|
||||
svc.resolver = NewModelPricingResolver(svc.channelService, svc.billingService)
|
||||
groupID := int64(10)
|
||||
require.NoError(t, svc.RecordUsage(context.Background(), &RecordUsageInput{
|
||||
Result: result,
|
||||
APIKey: &APIKey{ID: 501, GroupID: &groupID, Group: &Group{ID: groupID, Platform: PlatformAnthropic, RateMultiplier: 0.5}},
|
||||
User: &User{ID: 601}, Account: &Account{ID: 701, Platform: PlatformAnthropic},
|
||||
}))
|
||||
require.NotNil(t, usageRepo.lastLog)
|
||||
require.InDelta(t, wantCacheCost, usageRepo.lastLog.CacheCreationCost, 1e-12)
|
||||
require.InDelta(t, 0.014+wantCacheCost, usageRepo.lastLog.TotalCost, 1e-12)
|
||||
require.InDelta(t, (0.014+wantCacheCost)*0.5, usageRepo.lastLog.ActualCost, 1e-12)
|
||||
require.NotNil(t, usageRepo.lastLog.AccountStatsCost)
|
||||
require.InDelta(t, (0.014+wantCacheCost)*statsMultiplier, *usageRepo.lastLog.AccountStatsCost, 1e-12)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleNonStreamingResponse_CacheCreationRecordUsageBoundary(t *testing.T) {
|
||||
assertAnthropicCacheCreationForwardBoundary(t, false)
|
||||
}
|
||||
|
||||
func TestAntigravityForwardUpstream_CacheCreationRecordUsageBoundary(t *testing.T) {
|
||||
assertAnthropicCacheCreationForwardBoundary(t, true)
|
||||
}
|
||||
|
||||
func assertAnthropicCacheCreationForwardBoundary(t *testing.T, antigravity bool) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
cache string
|
||||
aggregate int
|
||||
present bool
|
||||
cache5m int
|
||||
cache1h int
|
||||
cacheCost float64
|
||||
}{
|
||||
{"explicit aggregate zero", `"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}`, 0, true, 50, 200, 0},
|
||||
{"missing aggregate", `"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}`, 250, false, 50, 200, 0.9},
|
||||
{"null aggregate", `"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}`, 250, false, 50, 200, 0.9},
|
||||
{"positive aggregate caps TTL", `"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}`, 100, true, 50, 200, 0.36},
|
||||
{"explicit zero TTL falls back to aggregate", `"cache_creation_input_tokens":200,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}`, 200, true, 0, 0, 0.4},
|
||||
{"missing TTL falls back to aggregate", `"cache_creation_input_tokens":200`, 200, true, 0, 0, 0.4},
|
||||
{"null TTL falls back to aggregate", `"cache_creation_input_tokens":200,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}`, 200, true, 0, 0, 0.4},
|
||||
{"explicit zero TTL without aggregate", `"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}`, 0, false, 0, 0, 0},
|
||||
} {
|
||||
for _, stream := range []bool{false, true} {
|
||||
if !antigravity && stream {
|
||||
continue
|
||||
}
|
||||
mode := "nonstream"
|
||||
if stream {
|
||||
mode = "stream"
|
||||
}
|
||||
t.Run(test.name+"/"+mode, func(t *testing.T) {
|
||||
usageJSON := `{"input_tokens":10,"output_tokens":2,"cache_read_input_tokens":0,` + test.cache + `}`
|
||||
body := `{"id":"msg_cache","type":"message","model":"claude-sonnet-4","usage":` + usageJSON + `}`
|
||||
contentType := "application/json"
|
||||
if stream {
|
||||
contentType = "text/event-stream"
|
||||
body = "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"usage\":" + usageJSON + "}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(recorder)
|
||||
ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
|
||||
response := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{contentType}}, Body: io.NopCloser(strings.NewReader(body))}
|
||||
var result *ForwardResult
|
||||
if antigravity {
|
||||
service := &AntigravityGatewayService{httpUpstream: &httpUpstreamStub{resp: response}, settingService: &SettingService{}}
|
||||
requestBody := `{"model":"claude-sonnet-4","messages":[],"stream":` + strconv.FormatBool(stream) + `}`
|
||||
var err error
|
||||
result, err = service.ForwardUpstream(context.Background(), ctx, &Account{ID: 701, Credentials: map[string]any{"base_url": "https://upstream.example", "api_key": "test-key"}}, []byte(requestBody))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, stream, result.Stream)
|
||||
} else {
|
||||
service := &GatewayService{cfg: &config.Config{}, rateLimitService: &RateLimitService{}}
|
||||
usage, err := service.handleNonStreamingResponse(context.Background(), response, ctx, &Account{ID: 701}, "claude-sonnet-4", "claude-sonnet-4")
|
||||
require.NoError(t, err)
|
||||
result = &ForwardResult{Model: "claude-sonnet-4", Usage: *usage}
|
||||
}
|
||||
require.Equal(t, http.StatusOK, recorder.Code)
|
||||
require.Equal(t, body, recorder.Body.String())
|
||||
wantAggregate := test.aggregate
|
||||
if antigravity && !test.present {
|
||||
wantAggregate = 0
|
||||
}
|
||||
require.Equal(t, wantAggregate, result.Usage.CacheCreationInputTokens)
|
||||
require.Equal(t, test.present, result.Usage.cacheCreationInputTokensPresent)
|
||||
require.Equal(t, test.cache5m, result.Usage.CacheCreation5mTokens)
|
||||
require.Equal(t, test.cache1h, result.Usage.CacheCreation1hTokens)
|
||||
assertAnthropicCacheCreationResultCosts(t, result, test.cacheCost)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnthropicCacheCreationMarshaledSSEBoundary(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
aggregate int
|
||||
present bool
|
||||
wantAggregate int
|
||||
wantCacheCost float64
|
||||
}{
|
||||
{"missing", 0, false, 50, 0.16},
|
||||
{"explicit zero", 0, true, 0, 0},
|
||||
{"synthetic nonzero", 40, false, 40, 0.128},
|
||||
} {
|
||||
for _, terminal := range []string{"message_stop", "eof"} {
|
||||
t.Run(test.name+"/"+terminal, func(t *testing.T) {
|
||||
cache5m, cache1h := 20, 30
|
||||
events := []apicompat.AnthropicStreamEvent{
|
||||
{Type: "message_start", Message: &apicompat.AnthropicResponse{ID: "msg_cache", Type: "message", Role: "assistant", Model: "claude-sonnet-4", Usage: apicompat.AnthropicUsage{
|
||||
InputTokens: 10, CacheCreationInputTokens: test.aggregate, CacheCreationInputTokensPresent: test.present,
|
||||
CacheCreation: &apicompat.AnthropicCacheCreation{Ephemeral5mInputTokens: &cache5m},
|
||||
}}},
|
||||
{Type: "message_delta", Usage: &apicompat.AnthropicUsage{OutputTokens: 2, CacheCreation: &apicompat.AnthropicCacheCreation{Ephemeral1hInputTokens: &cache1h}}},
|
||||
{Type: "message_delta", Delta: &apicompat.AnthropicDelta{StopReason: "end_turn"}, Usage: &apicompat.AnthropicUsage{OutputTokens: 2}},
|
||||
}
|
||||
if terminal == "message_stop" {
|
||||
events = append(events, apicompat.AnthropicStreamEvent{Type: "message_stop"})
|
||||
}
|
||||
var stream strings.Builder
|
||||
for _, event := range events {
|
||||
encoded, err := apicompat.ResponsesAnthropicEventToSSE(event)
|
||||
require.NoError(t, err)
|
||||
stream.WriteString(encoded)
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(recorder)
|
||||
response := &http.Response{Body: io.NopCloser(strings.NewReader(stream.String()))}
|
||||
result, err := (&GatewayService{}).handleResponsesStreamingResponse(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, test.wantAggregate, result.Usage.CacheCreationInputTokens)
|
||||
var completed apicompat.ResponsesStreamEvent
|
||||
for _, line := range strings.Split(recorder.Body.String(), "\n") {
|
||||
if strings.HasPrefix(line, "data: ") {
|
||||
var event apicompat.ResponsesStreamEvent
|
||||
require.NoError(t, json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &event))
|
||||
if event.Type == "response.completed" {
|
||||
completed = event
|
||||
}
|
||||
}
|
||||
}
|
||||
require.NotNil(t, completed.Response)
|
||||
require.NotNil(t, completed.Response.Usage)
|
||||
require.Equal(t, 10+test.wantAggregate, completed.Response.Usage.InputTokens)
|
||||
require.Equal(t, test.wantAggregate, completed.Response.Usage.CacheCreationInputTokens)
|
||||
assertAnthropicCacheCreationRecordCosts(t, result.Usage, test.wantCacheCost)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRawAnthropicCacheCreationExplicitZero(t *testing.T) {
|
||||
for _, prompt := range []string{"", `,"prompt_tokens":500`} {
|
||||
usage := parseClaudeUsageFromResponseBody([]byte(`{"usage":{"input_tokens":10,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}` + prompt + `}}`))
|
||||
require.Zero(t, usage.CacheCreationInputTokens)
|
||||
require.Equal(t, 200, usage.CacheCreation1hTokens)
|
||||
assertAnthropicCacheCreationRecordCosts(t, *usage, 0)
|
||||
if prompt != "" {
|
||||
require.Equal(t, 500, usage.InputTokens)
|
||||
}
|
||||
}
|
||||
usage := &ClaudeUsage{CacheCreationInputTokens: 100}
|
||||
(&AntigravityGatewayService{}).extractSSEUsage(`data: {"type":"message_delta","usage":{"cache_creation_input_tokens":0}}`, usage)
|
||||
require.Zero(t, usage.CacheCreationInputTokens)
|
||||
}
|
||||
|
||||
func TestAnthropicCacheCreationNullBodyParity(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
payload string
|
||||
want int
|
||||
present bool
|
||||
wantCost float64
|
||||
}{
|
||||
{"missing aggregate", `{"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 200, false, 0.8},
|
||||
{"null aggregate", `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 200, false, 0.8},
|
||||
{"zero aggregate", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 0, true, 0},
|
||||
{"null TTL with positive aggregate", `{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}}`, 100, true, 0.2},
|
||||
{"all null", `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}}`, 0, false, 0},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var source apicompat.AnthropicUsage
|
||||
require.NoError(t, json.Unmarshal([]byte(test.payload), &source))
|
||||
typed := &ClaudeUsage{}
|
||||
mergeAnthropicUsage(typed, source)
|
||||
raw := parseClaudeUsageFromResponseBody([]byte(`{"usage":` + test.payload + `}`))
|
||||
generic := &ClaudeUsage{}
|
||||
(&GatewayService{}).parseSSEUsage(`{"type":"message_start","message":{"usage":`+test.payload+`}}`, generic)
|
||||
require.Equal(t, typed, raw)
|
||||
require.Equal(t, typed, generic)
|
||||
require.Equal(t, test.want, raw.CacheCreationInputTokens)
|
||||
require.Equal(t, test.present, raw.cacheCreationInputTokensPresent)
|
||||
assertAnthropicCacheCreationRecordCosts(t, *raw, test.wantCost)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAntigravityCacheCreationUsage(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
payload string
|
||||
aggregate int
|
||||
present bool
|
||||
wantCost float64
|
||||
}{
|
||||
{"explicit zero with TTL", `{"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`, 0, true, 0},
|
||||
{"missing aggregate keeps TTL fallback", `{"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`, 0, false, 0.9},
|
||||
{"null aggregate keeps TTL fallback", `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":50,"ephemeral_1h_input_tokens":200}}`, 0, false, 0.9},
|
||||
{"positive aggregate", `{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, 100, true, 0.4},
|
||||
{"all null", `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}}`, 0, false, 0},
|
||||
} {
|
||||
for _, parser := range []string{"body", "stream"} {
|
||||
t.Run(test.name+"/"+parser, func(t *testing.T) {
|
||||
service := &AntigravityGatewayService{}
|
||||
usage := &ClaudeUsage{}
|
||||
if parser == "body" {
|
||||
usage = service.extractClaudeUsage([]byte(`{"usage":` + test.payload + `}`))
|
||||
} else {
|
||||
service.extractSSEUsage(`data: {"type":"message_start","message":{"usage":`+test.payload+`}}`, usage)
|
||||
}
|
||||
require.Equal(t, test.aggregate, usage.CacheCreationInputTokens)
|
||||
require.Equal(t, test.present, usage.cacheCreationInputTokensPresent)
|
||||
require.Equal(t, int(gjson.Get(test.payload, "cache_creation.ephemeral_5m_input_tokens").Int()), usage.CacheCreation5mTokens)
|
||||
require.Equal(t, int(gjson.Get(test.payload, "cache_creation.ephemeral_1h_input_tokens").Int()), usage.CacheCreation1hTokens)
|
||||
assertAnthropicCacheCreationRecordCosts(t, *usage, test.wantCost)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAntigravityCacheCreationLateDeltas(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
aggregate string
|
||||
wantTotal int
|
||||
present bool
|
||||
wantCost float64
|
||||
}{
|
||||
{"explicit zero survives", `"cache_creation_input_tokens":0,`, 0, true, 0},
|
||||
{"missing aggregate keeps TTL fallback", "", 0, false, 1.3},
|
||||
{"null aggregate keeps TTL fallback", `"cache_creation_input_tokens":null,`, 0, false, 1.3},
|
||||
{"positive aggregate survives", `"cache_creation_input_tokens":100,`, 100, true, 0.372},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
service := &AntigravityGatewayService{}
|
||||
usage := &ClaudeUsage{}
|
||||
service.extractSSEUsage(`data: {"type":"message_start","message":{"usage":{`+test.aggregate+`"cache_creation":{"ephemeral_1h_input_tokens":200}}}}`, usage)
|
||||
for _, delta := range []string{
|
||||
`{"cache_creation":{"ephemeral_5m_input_tokens":50}}`,
|
||||
`{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":300}}`,
|
||||
`{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":null}}`,
|
||||
} {
|
||||
service.extractSSEUsage(`data: {"type":"message_delta","usage":`+delta+`}`, usage)
|
||||
require.Equal(t, test.wantTotal, usage.CacheCreationInputTokens)
|
||||
require.Equal(t, test.present, usage.cacheCreationInputTokensPresent)
|
||||
}
|
||||
require.Equal(t, 50, usage.CacheCreation5mTokens)
|
||||
require.Equal(t, 300, usage.CacheCreation1hTokens)
|
||||
assertAnthropicCacheCreationRecordCosts(t, *usage, test.wantCost)
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("explicit zero delta clears aggregate with retained TTL", func(t *testing.T) {
|
||||
service := &AntigravityGatewayService{}
|
||||
usage := &ClaudeUsage{}
|
||||
service.extractSSEUsage(`data: {"type":"message_start","message":{"usage":{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}}}`, usage)
|
||||
service.extractSSEUsage(`data: {"type":"message_delta","usage":{"cache_creation_input_tokens":0}}`, usage)
|
||||
service.extractSSEUsage(`data: {"type":"message_delta","usage":{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":50}}}`, usage)
|
||||
require.Zero(t, usage.CacheCreationInputTokens)
|
||||
require.True(t, usage.cacheCreationInputTokensPresent)
|
||||
require.Equal(t, 50, usage.CacheCreation5mTokens)
|
||||
require.Equal(t, 200, usage.CacheCreation1hTokens)
|
||||
assertAnthropicCacheCreationRecordCosts(t, *usage, 0)
|
||||
})
|
||||
}
|
||||
|
||||
func TestAnthropicCacheOnlyBufferedSSEUsage(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
start string
|
||||
delta string
|
||||
wantAggregate int
|
||||
}{
|
||||
{"explicit zero transition", `{"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}}`, `{"cache_creation_input_tokens":0}`, 0},
|
||||
{"derived zero transition", `{"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":0}}`, 0},
|
||||
{"merged partial TTL", `{"cache_creation":{"ephemeral_5m_input_tokens":20}}`, `{"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":30}}`, 50},
|
||||
} {
|
||||
for _, adapter := range []string{"responses", "chat", "native responses", "native chat"} {
|
||||
t.Run(test.name+"/"+adapter, func(t *testing.T) {
|
||||
stream := "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_cache\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-sonnet-4\",\"content\":[],\"usage\":" + test.start + "}}\n\n" +
|
||||
"event: message_delta\ndata: {\"type\":\"message_delta\",\"usage\":" + test.delta + "}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"
|
||||
recorder := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(recorder)
|
||||
response := &http.Response{Body: io.NopCloser(strings.NewReader(stream))}
|
||||
var aggregate int
|
||||
var err error
|
||||
switch adapter {
|
||||
case "responses":
|
||||
var result *ForwardResult
|
||||
result, err = (&GatewayService{}).handleResponsesBufferedStreamingResponse(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{})
|
||||
require.NoError(t, err)
|
||||
aggregate = result.Usage.CacheCreationInputTokens
|
||||
case "chat":
|
||||
var result *ForwardResult
|
||||
result, err = (&GatewayService{}).handleCCBufferedFromAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now())
|
||||
require.NoError(t, err)
|
||||
aggregate = result.Usage.CacheCreationInputTokens
|
||||
case "native responses":
|
||||
var result *OpenAIForwardResult
|
||||
result, err = (&OpenAIGatewayService{}).handleResponsesBufferedFromNativeAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{})
|
||||
require.NoError(t, err)
|
||||
aggregate = result.Usage.CacheCreationInputTokens
|
||||
case "native chat":
|
||||
var result *OpenAIForwardResult
|
||||
result, err = (&OpenAIGatewayService{}).handleCCBufferedFromNativeAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now())
|
||||
require.NoError(t, err)
|
||||
aggregate = result.Usage.CacheCreationInputTokens
|
||||
}
|
||||
require.Equal(t, test.wantAggregate, aggregate)
|
||||
require.Equal(t, http.StatusOK, recorder.Code)
|
||||
require.True(t, json.Valid(recorder.Body.Bytes()))
|
||||
inputPath := "usage.input_tokens"
|
||||
cachePath := "usage.cache_creation_input_tokens"
|
||||
if strings.HasSuffix(adapter, "chat") {
|
||||
inputPath = "usage.prompt_tokens"
|
||||
cachePath = "usage.prompt_tokens_details.cache_creation_tokens"
|
||||
}
|
||||
require.True(t, gjson.GetBytes(recorder.Body.Bytes(), inputPath).Exists())
|
||||
require.Equal(t, int64(test.wantAggregate), gjson.GetBytes(recorder.Body.Bytes(), inputPath).Int())
|
||||
require.Equal(t, int64(test.wantAggregate), gjson.GetBytes(recorder.Body.Bytes(), cachePath).Int())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -316,14 +316,7 @@ func (s *GatewayService) handleCCBufferedFromAnthropic(
|
||||
}
|
||||
|
||||
// Update usage from accumulated delta
|
||||
if usage.InputTokens > 0 || usage.OutputTokens > 0 {
|
||||
finalResp.Usage = apicompat.AnthropicUsage{
|
||||
InputTokens: usage.InputTokens,
|
||||
OutputTokens: usage.OutputTokens,
|
||||
CacheCreationInputTokens: usage.CacheCreationInputTokens,
|
||||
CacheReadInputTokens: usage.CacheReadInputTokens,
|
||||
}
|
||||
}
|
||||
normalizeAnthropicEventUsageForResponses(&apicompat.AnthropicStreamEvent{Message: finalResp}, usage)
|
||||
|
||||
// Chain: Anthropic → Responses → Chat Completions
|
||||
responsesResp := apicompat.AnthropicToResponsesResponse(finalResp)
|
||||
|
||||
@@ -304,21 +304,8 @@ func mergeAnthropicUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) {
|
||||
if cacheReadTokens == 0 && src.PromptCacheHitTokens != nil {
|
||||
cacheReadTokens = max(*src.PromptCacheHitTokens, 0)
|
||||
}
|
||||
if src.CacheCreation != nil {
|
||||
if src.CacheCreation.Ephemeral5mInputTokens != nil {
|
||||
dst.CacheCreation5mTokens = max(*src.CacheCreation.Ephemeral5mInputTokens, 0)
|
||||
}
|
||||
if src.CacheCreation.Ephemeral1hInputTokens != nil {
|
||||
dst.CacheCreation1hTokens = max(*src.CacheCreation.Ephemeral1hInputTokens, 0)
|
||||
}
|
||||
if src.CacheCreation.Ephemeral5mInputTokens != nil || src.CacheCreation.Ephemeral1hInputTokens != nil {
|
||||
dst.CacheCreationInputTokens = dst.CacheCreation5mTokens + dst.CacheCreation1hTokens
|
||||
}
|
||||
}
|
||||
cacheCreationTokens := src.CacheCreationInputTokens
|
||||
if src.CacheCreation != nil && (src.CacheCreation.Ephemeral5mInputTokens != nil || src.CacheCreation.Ephemeral1hInputTokens != nil) {
|
||||
cacheCreationTokens = dst.CacheCreationInputTokens
|
||||
}
|
||||
mergeAnthropicCacheCreationUsage(dst, src)
|
||||
cacheCreationTokens := dst.CacheCreationInputTokens
|
||||
|
||||
// Some Anthropic-compatible providers retain OpenAI-style prompt/cache
|
||||
// fields. Prefer those authoritative totals or hit/miss buckets over the
|
||||
@@ -331,7 +318,6 @@ func mergeAnthropicUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) {
|
||||
dst.InputTokens = max(src.PromptTokens-cacheReadTokens-cacheCreationTokens, 0)
|
||||
}
|
||||
dst.CacheReadInputTokens = cacheReadTokens
|
||||
dst.CacheCreationInputTokens = cacheCreationTokens
|
||||
} else {
|
||||
// Without an authoritative prompt total or miss bucket, input_tokens is
|
||||
// provider-specific: it may already be the uncached bucket, or it may be
|
||||
@@ -344,15 +330,48 @@ func mergeAnthropicUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) {
|
||||
if cacheReadTokens > 0 {
|
||||
dst.CacheReadInputTokens = cacheReadTokens
|
||||
}
|
||||
if cacheCreationTokens > 0 {
|
||||
dst.CacheCreationInputTokens = cacheCreationTokens
|
||||
}
|
||||
}
|
||||
if src.OutputTokens > 0 {
|
||||
dst.OutputTokens = src.OutputTokens
|
||||
}
|
||||
}
|
||||
|
||||
func mergeAnthropicCacheCreationUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) {
|
||||
if src.HasCacheCreationInputTokens() {
|
||||
dst.CacheCreationInputTokens = max(src.CacheCreationInputTokens, 0)
|
||||
dst.cacheCreationInputTokensPresent = true
|
||||
}
|
||||
if src.CacheCreation != nil {
|
||||
if src.CacheCreation.Ephemeral5mInputTokens != nil {
|
||||
dst.CacheCreation5mTokens = max(*src.CacheCreation.Ephemeral5mInputTokens, 0)
|
||||
}
|
||||
if src.CacheCreation.Ephemeral1hInputTokens != nil {
|
||||
dst.CacheCreation1hTokens = max(*src.CacheCreation.Ephemeral1hInputTokens, 0)
|
||||
}
|
||||
if !dst.cacheCreationInputTokensPresent && (src.CacheCreation.Ephemeral5mInputTokens != nil || src.CacheCreation.Ephemeral1hInputTokens != nil) {
|
||||
dst.CacheCreationInputTokens = dst.CacheCreation5mTokens + dst.CacheCreation1hTokens
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func mergeRawAnthropicCacheCreationUsage(node gjson.Result, dst *ClaudeUsage) {
|
||||
aggregate := node.Get("cache_creation_input_tokens")
|
||||
usage := apicompat.AnthropicUsage{
|
||||
CacheCreationInputTokens: int(aggregate.Int()),
|
||||
CacheCreationInputTokensPresent: aggregate.Exists() && aggregate.Type != gjson.Null,
|
||||
CacheCreation: &apicompat.AnthropicCacheCreation{},
|
||||
}
|
||||
if tokens := node.Get("cache_creation.ephemeral_5m_input_tokens"); tokens.Exists() && tokens.Type != gjson.Null {
|
||||
value := int(tokens.Int())
|
||||
usage.CacheCreation.Ephemeral5mInputTokens = &value
|
||||
}
|
||||
if tokens := node.Get("cache_creation.ephemeral_1h_input_tokens"); tokens.Exists() && tokens.Type != gjson.Null {
|
||||
value := int(tokens.Int())
|
||||
usage.CacheCreation.Ephemeral1hInputTokens = &value
|
||||
}
|
||||
mergeAnthropicCacheCreationUsage(dst, usage)
|
||||
}
|
||||
|
||||
func syncAnthropicResponsesUsage(state *apicompat.AnthropicEventToResponsesState, usage ClaudeUsage) {
|
||||
state.InputTokens = usage.InputTokens
|
||||
state.OutputTokens = usage.OutputTokens
|
||||
@@ -369,6 +388,7 @@ func normalizeAnthropicEventUsageForResponses(event *apicompat.AnthropicStreamEv
|
||||
dst.OutputTokens = usage.OutputTokens
|
||||
dst.CacheReadInputTokens = usage.CacheReadInputTokens
|
||||
dst.CacheCreationInputTokens = usage.CacheCreationInputTokens
|
||||
dst.CacheCreationInputTokensPresent = true
|
||||
}
|
||||
normalize(event.Usage)
|
||||
if event.Message != nil {
|
||||
@@ -491,14 +511,7 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse(
|
||||
}
|
||||
|
||||
// Update usage from accumulated delta
|
||||
if usage.InputTokens > 0 || usage.OutputTokens > 0 {
|
||||
finalResp.Usage = apicompat.AnthropicUsage{
|
||||
InputTokens: usage.InputTokens,
|
||||
OutputTokens: usage.OutputTokens,
|
||||
CacheCreationInputTokens: usage.CacheCreationInputTokens,
|
||||
CacheReadInputTokens: usage.CacheReadInputTokens,
|
||||
}
|
||||
}
|
||||
normalizeAnthropicEventUsageForResponses(&apicompat.AnthropicStreamEvent{Message: finalResp}, usage)
|
||||
|
||||
// Convert to Responses format
|
||||
if isClaude55SignedThinkingModel(mappedModel) {
|
||||
|
||||
@@ -369,6 +369,30 @@ func TestHandleResponsesStreamingResponse_NormalizesTerminalUsage(t *testing.T)
|
||||
wantOutput: 30,
|
||||
wantCacheCreation: 800,
|
||||
},
|
||||
{
|
||||
name: "explicit aggregate caps contradictory TTL breakdown",
|
||||
startUsage: `"input_tokens":10,"cache_creation_input_tokens":100,"cache_creation":{"ephemeral_1h_input_tokens":200}`,
|
||||
deltaUsage: `"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":200}`,
|
||||
wantInput: 10, wantOutput: 7, wantCacheCreation: 100,
|
||||
},
|
||||
{
|
||||
name: "explicit zero survives contradictory TTL breakdown",
|
||||
startUsage: `"input_tokens":10,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}`,
|
||||
deltaUsage: `"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":200}`,
|
||||
wantInput: 10, wantOutput: 7,
|
||||
},
|
||||
{
|
||||
name: "null aggregate and TTL preserve partial snapshots",
|
||||
startUsage: `"input_tokens":10,"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":null}`,
|
||||
deltaUsage: `"output_tokens":7,"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_5m_input_tokens":null,"ephemeral_1h_input_tokens":30}`,
|
||||
wantInput: 10, wantOutput: 7, wantCacheCreation: 50,
|
||||
},
|
||||
{
|
||||
name: "null does not clear explicit aggregate zero",
|
||||
startUsage: `"input_tokens":10,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":200}`,
|
||||
deltaUsage: `"output_tokens":7,"cache_creation_input_tokens":null,"cache_creation":{"ephemeral_1h_input_tokens":null}`,
|
||||
wantInput: 10, wantOutput: 7,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
|
||||
@@ -604,6 +604,8 @@ type ClaudeUsage struct {
|
||||
CacheCreation5mTokens int // 5分钟缓存创建token(来自嵌套 cache_creation 对象)
|
||||
CacheCreation1hTokens int // 1小时缓存创建token(来自嵌套 cache_creation 对象)
|
||||
ImageOutputTokens int `json:"image_output_tokens,omitempty"`
|
||||
|
||||
cacheCreationInputTokensPresent bool
|
||||
}
|
||||
|
||||
// ForwardResult 转发结果
|
||||
|
||||
@@ -1211,9 +1211,9 @@ func (s *GatewayService) extractSSEUsagePatch(event map[string]any) *sseUsagePat
|
||||
if v, ok := parseSSEUsageInt(usageObj["input_tokens"]); ok {
|
||||
patch.inputTokens = v
|
||||
}
|
||||
patch.hasCacheCreationInput = true
|
||||
if v, ok := parseSSEUsageInt(usageObj["cache_creation_input_tokens"]); ok {
|
||||
patch.cacheCreationInputTokens = v
|
||||
patch.hasCacheCreationInput = true
|
||||
}
|
||||
patch.hasCacheReadInput = true
|
||||
if v, ok := parseSSEUsageInt(usageObj["cache_read_input_tokens"]); ok {
|
||||
@@ -1246,7 +1246,7 @@ func (s *GatewayService) extractSSEUsagePatch(event map[string]any) *sseUsagePat
|
||||
patch.outputTokens = v
|
||||
patch.hasOutputTokens = true
|
||||
}
|
||||
if v, ok := parseSSEUsageInt(usageObj["cache_creation_input_tokens"]); ok && v > 0 {
|
||||
if v, ok := parseSSEUsageInt(usageObj["cache_creation_input_tokens"]); ok && v >= 0 {
|
||||
patch.cacheCreationInputTokens = v
|
||||
patch.hasCacheCreationInput = true
|
||||
}
|
||||
@@ -1280,6 +1280,7 @@ func mergeSSEUsagePatch(usage *ClaudeUsage, patch *sseUsagePatch) {
|
||||
}
|
||||
if patch.hasCacheCreationInput {
|
||||
usage.CacheCreationInputTokens = patch.cacheCreationInputTokens
|
||||
usage.cacheCreationInputTokensPresent = true
|
||||
}
|
||||
if patch.hasCacheReadInput {
|
||||
usage.CacheReadInputTokens = patch.cacheReadInputTokens
|
||||
@@ -1293,6 +1294,9 @@ func mergeSSEUsagePatch(usage *ClaudeUsage, patch *sseUsagePatch) {
|
||||
if patch.hasCacheCreation1h {
|
||||
usage.CacheCreation1hTokens = patch.cacheCreation1hTokens
|
||||
}
|
||||
if !usage.cacheCreationInputTokensPresent && (patch.hasCacheCreation5m || patch.hasCacheCreation1h) {
|
||||
usage.CacheCreationInputTokens = max(usage.CacheCreation5mTokens, 0) + max(usage.CacheCreation1hTokens, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func parseSSEUsageInt(value any) (int, bool) {
|
||||
@@ -1419,13 +1423,7 @@ func (s *GatewayService) handleNonStreamingResponse(ctx context.Context, resp *h
|
||||
return nil, fmt.Errorf("parse response: %w", err)
|
||||
}
|
||||
|
||||
// 解析嵌套的 cache_creation 对象中的 5m/1h 明细
|
||||
cc5m := gjson.GetBytes(body, "usage.cache_creation.ephemeral_5m_input_tokens")
|
||||
cc1h := gjson.GetBytes(body, "usage.cache_creation.ephemeral_1h_input_tokens")
|
||||
if cc5m.Exists() || cc1h.Exists() {
|
||||
response.Usage.CacheCreation5mTokens = int(cc5m.Int())
|
||||
response.Usage.CacheCreation1hTokens = int(cc1h.Int())
|
||||
}
|
||||
mergeRawAnthropicCacheCreationUsage(gjson.GetBytes(body, "usage"), &response.Usage)
|
||||
|
||||
// 兼容 Kimi cached_tokens → cache_read_input_tokens
|
||||
if response.Usage.CacheReadInputTokens == 0 {
|
||||
|
||||
@@ -848,13 +848,7 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage
|
||||
account.ID, *apiKey.GroupID, result.UpstreamModel, result.Model,
|
||||
// Anthropic's input_tokens excludes cache_read and cache_creation (billed separately);
|
||||
// OpenAI gateway uses actualInputTokens which also excludes cache_read for the same reason.
|
||||
UsageTokens{
|
||||
InputTokens: result.Usage.InputTokens,
|
||||
OutputTokens: result.Usage.OutputTokens,
|
||||
CacheCreationTokens: result.Usage.CacheCreationInputTokens,
|
||||
CacheReadTokens: result.Usage.CacheReadInputTokens,
|
||||
ImageOutputTokens: result.Usage.ImageOutputTokens,
|
||||
},
|
||||
result.Usage.billingUsageTokens(),
|
||||
cost.TotalCost-cacheStorageCost, pricingAt,
|
||||
accountStatsLongContextPricingEnabled(nil),
|
||||
)
|
||||
@@ -1215,6 +1209,25 @@ func (s *GatewayService) calculateImageCost(
|
||||
return s.billingService.CalculateImageCost(billingModel, sizeTier, result.ImageCount, groupConfig, multiplier)
|
||||
}
|
||||
|
||||
// billingUsageTokens projects explicit aggregate zero to effective zero TTL usage
|
||||
// for billing and account stats, retaining raw TTL details on ClaudeUsage.
|
||||
func (usage ClaudeUsage) billingUsageTokens() UsageTokens {
|
||||
tokens := UsageTokens{
|
||||
InputTokens: usage.InputTokens,
|
||||
OutputTokens: usage.OutputTokens,
|
||||
CacheCreationTokens: usage.CacheCreationInputTokens,
|
||||
CacheReadTokens: usage.CacheReadInputTokens,
|
||||
CacheCreation5mTokens: usage.CacheCreation5mTokens,
|
||||
CacheCreation1hTokens: usage.CacheCreation1hTokens,
|
||||
ImageOutputTokens: usage.ImageOutputTokens,
|
||||
}
|
||||
if usage.cacheCreationInputTokensPresent && usage.CacheCreationInputTokens == 0 {
|
||||
tokens.CacheCreation5mTokens = 0
|
||||
tokens.CacheCreation1hTokens = 0
|
||||
}
|
||||
return tokens
|
||||
}
|
||||
|
||||
// calculateTokenCost 计算 Token 计费:路径选择(分组/渠道定价 → 内置定价)
|
||||
// 统一交给 BillingService.CalculateTokenCostForRequest,与模型广场的阶梯表查询同源。
|
||||
func (s *GatewayService) calculateTokenCost(
|
||||
@@ -1225,15 +1238,7 @@ func (s *GatewayService) calculateTokenCost(
|
||||
multiplier float64,
|
||||
pricingAt time.Time,
|
||||
) *CostBreakdown {
|
||||
tokens := UsageTokens{
|
||||
InputTokens: result.Usage.InputTokens,
|
||||
OutputTokens: result.Usage.OutputTokens,
|
||||
CacheCreationTokens: result.Usage.CacheCreationInputTokens,
|
||||
CacheReadTokens: result.Usage.CacheReadInputTokens,
|
||||
CacheCreation5mTokens: result.Usage.CacheCreation5mTokens,
|
||||
CacheCreation1hTokens: result.Usage.CacheCreation1hTokens,
|
||||
ImageOutputTokens: result.Usage.ImageOutputTokens,
|
||||
}
|
||||
tokens := result.Usage.billingUsageTokens()
|
||||
|
||||
var resolved *ResolvedPricing
|
||||
if s.resolver != nil && apiKey.Group != nil {
|
||||
|
||||
@@ -259,14 +259,7 @@ func (s *OpenAIGatewayService) handleCCBufferedFromNativeAnthropic(
|
||||
return nil, fmt.Errorf("upstream stream ended without response")
|
||||
}
|
||||
|
||||
if usage.InputTokens > 0 || usage.OutputTokens > 0 {
|
||||
finalResp.Usage = apicompat.AnthropicUsage{
|
||||
InputTokens: usage.InputTokens,
|
||||
OutputTokens: usage.OutputTokens,
|
||||
CacheCreationInputTokens: usage.CacheCreationInputTokens,
|
||||
CacheReadInputTokens: usage.CacheReadInputTokens,
|
||||
}
|
||||
}
|
||||
normalizeAnthropicEventUsageForResponses(&apicompat.AnthropicStreamEvent{Message: finalResp}, usage)
|
||||
|
||||
responsesResp := apicompat.AnthropicToResponsesResponse(finalResp)
|
||||
ccResp := apicompat.ResponsesToChatCompletions(responsesResp, originalModel)
|
||||
|
||||
@@ -262,14 +262,7 @@ func (s *OpenAIGatewayService) handleResponsesBufferedFromNativeAnthropic(
|
||||
return nil, fmt.Errorf("upstream stream ended without response")
|
||||
}
|
||||
|
||||
if usage.InputTokens > 0 || usage.OutputTokens > 0 {
|
||||
finalResp.Usage = apicompat.AnthropicUsage{
|
||||
InputTokens: usage.InputTokens,
|
||||
OutputTokens: usage.OutputTokens,
|
||||
CacheCreationInputTokens: usage.CacheCreationInputTokens,
|
||||
CacheReadInputTokens: usage.CacheReadInputTokens,
|
||||
}
|
||||
}
|
||||
normalizeAnthropicEventUsageForResponses(&apicompat.AnthropicStreamEvent{Message: finalResp}, usage)
|
||||
|
||||
if isClaude55SignedThinkingModel(upstreamModel) {
|
||||
finalResp.Model = upstreamModel
|
||||
|
||||
Reference in new issue
Block a user