mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 00:05:30 +00:00
fix(usage): reconcile prompt totals across cache-only updates
This commit is contained in:
1 parent
bcb0512132
commit
9e4c03d2fe
9 files changed
+538
-67
No files matched your search
@@ -0,0 +1,42 @@
|
||||
//go:build unit
|
||||
|
||||
package apicompat
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAnthropicUsageCacheReadPresenceRoundtrip(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
payload string
|
||||
present bool
|
||||
value int
|
||||
}{
|
||||
{"missing", `{}`, false, 0},
|
||||
{"null", `{"cache_read_input_tokens":null,"cached_tokens":null,"prompt_tokens_details":{"cached_tokens":null}}`, false, 0},
|
||||
{"zero", `{"cache_read_input_tokens":0,"cached_tokens":0,"prompt_tokens_details":{"cached_tokens":0}}`, true, 0},
|
||||
{"positive", `{"cache_read_input_tokens":20,"cached_tokens":20,"prompt_tokens_details":{"cached_tokens":20}}`, 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 {
|
||||
require.Equal(t, test.present, usage.CacheReadInputTokensPresent)
|
||||
require.Equal(t, test.present, usage.CachedTokensPresent)
|
||||
require.Equal(t, test.value, usage.CacheReadInputTokens)
|
||||
require.Equal(t, test.value, usage.CachedTokens)
|
||||
if usage.PromptTokensDetails != nil {
|
||||
require.Equal(t, test.present, usage.PromptTokensDetails.CachedTokensPresent)
|
||||
require.Equal(t, test.value, usage.PromptTokensDetails.CachedTokens)
|
||||
}
|
||||
encoded, err := json.Marshal(usage)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, json.Unmarshal(encoded, &usage))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -163,7 +163,33 @@ func AnthropicStopReasonString(p *string) string {
|
||||
// AnthropicPromptTokensDetails holds OpenAI-compatible prompt token details
|
||||
// occasionally included by Anthropic-compatible providers.
|
||||
type AnthropicPromptTokensDetails struct {
|
||||
CachedTokens int `json:"cached_tokens,omitempty"`
|
||||
CachedTokens int `json:"cached_tokens,omitempty"`
|
||||
CachedTokensPresent bool `json:"-"`
|
||||
}
|
||||
|
||||
func (details *AnthropicPromptTokensDetails) UnmarshalJSON(data []byte) error {
|
||||
var decoded struct {
|
||||
CachedTokens *int `json:"cached_tokens"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &decoded); err != nil {
|
||||
return err
|
||||
}
|
||||
*details = AnthropicPromptTokensDetails{}
|
||||
if decoded.CachedTokens != nil {
|
||||
details.CachedTokens = *decoded.CachedTokens
|
||||
details.CachedTokensPresent = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (details AnthropicPromptTokensDetails) MarshalJSON() ([]byte, error) {
|
||||
var cachedTokens *int
|
||||
if details.CachedTokensPresent || details.CachedTokens != 0 {
|
||||
cachedTokens = &details.CachedTokens
|
||||
}
|
||||
return json.Marshal(struct {
|
||||
CachedTokens *int `json:"cached_tokens,omitempty"`
|
||||
}{CachedTokens: cachedTokens})
|
||||
}
|
||||
|
||||
// AnthropicCacheCreation holds Anthropic's cache creation TTL breakdown.
|
||||
@@ -192,6 +218,8 @@ type AnthropicUsage struct {
|
||||
|
||||
// Presence distinguishes explicit zero from missing/null; TTL details remain raw.
|
||||
CacheCreationInputTokensPresent bool `json:"-"`
|
||||
CacheReadInputTokensPresent bool `json:"-"`
|
||||
CachedTokensPresent bool `json:"-"`
|
||||
}
|
||||
|
||||
func (usage *AnthropicUsage) UnmarshalJSON(data []byte) error {
|
||||
@@ -199,6 +227,8 @@ func (usage *AnthropicUsage) UnmarshalJSON(data []byte) error {
|
||||
var decoded struct {
|
||||
usageAlias
|
||||
CacheCreationInputTokens *int `json:"cache_creation_input_tokens"`
|
||||
CacheReadInputTokens *int `json:"cache_read_input_tokens"`
|
||||
CachedTokens *int `json:"cached_tokens"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &decoded); err != nil {
|
||||
return err
|
||||
@@ -208,6 +238,14 @@ func (usage *AnthropicUsage) UnmarshalJSON(data []byte) error {
|
||||
usage.CacheCreationInputTokens = *decoded.CacheCreationInputTokens
|
||||
usage.CacheCreationInputTokensPresent = true
|
||||
}
|
||||
if decoded.CacheReadInputTokens != nil {
|
||||
usage.CacheReadInputTokens = *decoded.CacheReadInputTokens
|
||||
usage.CacheReadInputTokensPresent = true
|
||||
}
|
||||
if decoded.CachedTokens != nil {
|
||||
usage.CachedTokens = *decoded.CachedTokens
|
||||
usage.CachedTokensPresent = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -222,10 +260,19 @@ func (usage AnthropicUsage) MarshalJSON() ([]byte, error) {
|
||||
if usage.HasCacheCreationInputTokens() {
|
||||
aggregate = &usage.CacheCreationInputTokens
|
||||
}
|
||||
var cacheReadTokens, cachedTokens *int
|
||||
if usage.CacheReadInputTokensPresent || usage.CacheReadInputTokens != 0 {
|
||||
cacheReadTokens = &usage.CacheReadInputTokens
|
||||
}
|
||||
if usage.CachedTokensPresent || usage.CachedTokens != 0 {
|
||||
cachedTokens = &usage.CachedTokens
|
||||
}
|
||||
return json.Marshal(struct {
|
||||
usageAlias
|
||||
CacheCreationInputTokens *int `json:"cache_creation_input_tokens,omitempty"`
|
||||
}{usageAlias: usageAlias(usage), CacheCreationInputTokens: aggregate})
|
||||
CacheReadInputTokens *int `json:"cache_read_input_tokens,omitempty"`
|
||||
CachedTokens *int `json:"cached_tokens,omitempty"`
|
||||
}{usageAlias: usageAlias(usage), CacheCreationInputTokens: aggregate, CacheReadInputTokens: cacheReadTokens, CachedTokens: cachedTokens})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"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 TestAnthropicPromptTotalSnapshots(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
start string
|
||||
deltas []string
|
||||
inputs []int
|
||||
}{
|
||||
{"prompt total", `"prompt_tokens":100`, []string{`{"cache_creation":{"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_5m_input_tokens":0}}`, `{"cache_read_input_tokens":10}`, `{"prompt_tokens":120}`, `{"output_tokens":2}`}, []int{50, 50, 70, 60, 80, 80}},
|
||||
{"independent input", `"input_tokens":80`, []string{`{"cache_creation":{"ephemeral_1h_input_tokens":30}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, []int{80, 80}},
|
||||
{"miss overrides total", `"prompt_tokens":100`, []string{`{"prompt_tokens":100,"prompt_cache_miss_tokens":40}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, []int{40, 40}},
|
||||
{"late read aliases", `"prompt_tokens":100`, []string{`{"cached_tokens":10}`, `{"cached_tokens":15}`, `{"prompt_tokens_details":{"cached_tokens":20}}`, `{"prompt_cache_hit_tokens":25}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, []int{70, 65, 60, 55, 25}},
|
||||
{"aggregate clears", `"prompt_tokens":100`, []string{`{"cache_creation_input_tokens":50}`, `{"cache_creation_input_tokens":0}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, []int{50, 100, 100}},
|
||||
{"cache exceeds prompt", `"prompt_tokens":100`, []string{`{"cache_creation":{"ephemeral_1h_input_tokens":100}}`, `{"cache_creation":{"ephemeral_1h_input_tokens":30}}`}, []int{0, 50}},
|
||||
} {
|
||||
for _, parser := range []string{"typed", "raw", "generic"} {
|
||||
t.Run(test.name+"/"+parser, func(t *testing.T) {
|
||||
usage := &ClaudeUsage{}
|
||||
merge := func(snapshot string, start bool) {
|
||||
if parser == "typed" {
|
||||
var source apicompat.AnthropicUsage
|
||||
require.NoError(t, json.Unmarshal([]byte(snapshot), &source))
|
||||
mergeAnthropicUsage(usage, source)
|
||||
return
|
||||
}
|
||||
data := `{"type":"message_delta","usage":` + snapshot + `}`
|
||||
if start {
|
||||
data = `{"type":"message_start","message":{"usage":` + snapshot + `}}`
|
||||
}
|
||||
if parser == "raw" {
|
||||
parseSSEUsagePassthrough(data, usage)
|
||||
} else {
|
||||
(&GatewayService{}).parseSSEUsage(data, usage)
|
||||
}
|
||||
}
|
||||
merge(`{`+test.start+`,"cache_creation":{"ephemeral_5m_input_tokens":20}}`, true)
|
||||
require.Equal(t, 80, usage.InputTokens)
|
||||
for index, delta := range test.deltas {
|
||||
merge(delta, false)
|
||||
require.Equal(t, test.inputs[index], usage.InputTokens, "delta %d", index)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnthropicPromptTotalCacheReadPresence(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
delta string
|
||||
read int
|
||||
}{
|
||||
{"canonical zero", `{"cache_read_input_tokens":0}`, 0},
|
||||
{"cached zero", `{"cached_tokens":0}`, 0},
|
||||
{"details zero", `{"prompt_tokens_details":{"cached_tokens":0}}`, 0},
|
||||
{"hit zero", `{"prompt_cache_hit_tokens":0}`, 0},
|
||||
{"missing", `{"output_tokens":2}`, 20},
|
||||
{"null", `{"cache_read_input_tokens":null,"cached_tokens":null,"prompt_tokens_details":{"cached_tokens":null},"prompt_cache_hit_tokens":null}`, 20},
|
||||
{"canonical precedence", `{"cache_read_input_tokens":12,"cached_tokens":13,"prompt_tokens_details":{"cached_tokens":14},"prompt_cache_hit_tokens":15}`, 12},
|
||||
{"zero falls back", `{"cache_read_input_tokens":0,"cached_tokens":13,"prompt_tokens_details":{"cached_tokens":14},"prompt_cache_hit_tokens":15}`, 13},
|
||||
{"alias zero falls back", `{"cached_tokens":0,"prompt_tokens_details":{"cached_tokens":14},"prompt_cache_hit_tokens":15}`, 14},
|
||||
{"details zero falls back", `{"prompt_tokens_details":{"cached_tokens":0},"prompt_cache_hit_tokens":15}`, 15},
|
||||
} {
|
||||
for _, parser := range []string{"typed", "raw", "generic"} {
|
||||
t.Run(test.name+"/"+parser, func(t *testing.T) {
|
||||
usage := &ClaudeUsage{}
|
||||
merge := func(snapshot string, start bool) {
|
||||
if parser == "typed" {
|
||||
var source apicompat.AnthropicUsage
|
||||
require.NoError(t, json.Unmarshal([]byte(snapshot), &source))
|
||||
mergeAnthropicUsage(usage, source)
|
||||
return
|
||||
}
|
||||
data := `{"type":"message_delta","usage":` + snapshot + `}`
|
||||
if start {
|
||||
data = `{"type":"message_start","message":{"usage":` + snapshot + `}}`
|
||||
}
|
||||
if parser == "raw" {
|
||||
parseSSEUsagePassthrough(data, usage)
|
||||
} else {
|
||||
(&GatewayService{}).parseSSEUsage(data, usage)
|
||||
}
|
||||
}
|
||||
merge(`{"prompt_tokens":100,"cache_read_input_tokens":20,"cache_creation_input_tokens":10}`, true)
|
||||
require.Equal(t, 70, usage.InputTokens)
|
||||
merge(test.delta, false)
|
||||
require.Equal(t, test.read, usage.CacheReadInputTokens)
|
||||
require.Equal(t, 90-test.read, usage.InputTokens)
|
||||
merge(`{"output_tokens":3}`, false)
|
||||
require.Equal(t, test.read, usage.CacheReadInputTokens)
|
||||
require.Equal(t, 90-test.read, usage.InputTokens)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnthropicPromptTotalCacheReadZeroForwardBoundary(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, field := range []string{"cache_read_input_tokens", "cached_tokens"} {
|
||||
for _, route := range []string{"typed", "raw", "generic"} {
|
||||
for _, terminal := range []string{"stop", "eof"} {
|
||||
t.Run(field+"/"+route+"/"+terminal, func(t *testing.T) {
|
||||
payload := "event: message_start\ndata: " + `{"type":"message_start","message":{"id":"msg_zero","type":"message","role":"assistant","model":"claude-sonnet-4","content":[],"usage":{"input_tokens":100,"prompt_tokens":100,"cache_read_input_tokens":20,"cache_creation_input_tokens":10}}}` + "\n\n"
|
||||
payload += "event: message_delta\ndata: " + `{"type":"message_delta","usage":{"` + field + `":0}}` + "\n\n"
|
||||
payload += "event: message_delta\ndata: " + `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}` + "\n\n"
|
||||
if terminal == "stop" {
|
||||
payload += "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"
|
||||
}
|
||||
response := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(payload))}
|
||||
recorder := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(recorder)
|
||||
ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
|
||||
service := &GatewayService{cfg: &config.Config{}, rateLimitService: &RateLimitService{}}
|
||||
var usage *ClaudeUsage
|
||||
var err error
|
||||
if route == "typed" {
|
||||
var result *ForwardResult
|
||||
result, err = service.handleResponsesStreamingResponse(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{})
|
||||
require.NotNil(t, result)
|
||||
usage = &result.Usage
|
||||
} else {
|
||||
var result *streamingResult
|
||||
if route == "raw" {
|
||||
result, err = service.handleStreamingResponseAnthropicAPIKeyPassthrough(context.Background(), response, ctx, &Account{ID: 701}, time.Now(), "claude-sonnet-4")
|
||||
} else {
|
||||
result, err = service.handleStreamingResponse(context.Background(), response, ctx, &Account{ID: 701}, time.Now(), "claude-sonnet-4", "claude-sonnet-4", false)
|
||||
}
|
||||
require.NotNil(t, result)
|
||||
usage = result.usage
|
||||
}
|
||||
if terminal == "eof" && route != "typed" {
|
||||
require.ErrorContains(t, err, "missing terminal event")
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
require.NotNil(t, usage)
|
||||
require.Equal(t, 90, usage.InputTokens)
|
||||
require.Zero(t, usage.CacheReadInputTokens)
|
||||
require.Equal(t, 10, usage.CacheCreationInputTokens)
|
||||
require.Equal(t, 2, usage.OutputTokens)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnthropicCacheReadZeroPreservesIndependentInput(t *testing.T) {
|
||||
for _, field := range []string{"cache_read_input_tokens", "cached_tokens"} {
|
||||
for _, parser := range []string{"typed", "generic", "raw"} {
|
||||
t.Run(field+"/"+parser, func(t *testing.T) {
|
||||
usage := &ClaudeUsage{}
|
||||
for index, snapshot := range []string{
|
||||
`{"input_tokens":80,"cache_read_input_tokens":20,"cache_creation_input_tokens":10}`,
|
||||
`{"` + field + `":0}`,
|
||||
} {
|
||||
if parser == "typed" {
|
||||
var source apicompat.AnthropicUsage
|
||||
require.NoError(t, json.Unmarshal([]byte(snapshot), &source))
|
||||
mergeAnthropicUsage(usage, source)
|
||||
} else if parser == "raw" {
|
||||
if index == 0 {
|
||||
parseSSEUsagePassthrough(`{"type":"message_start","message":{"usage":`+snapshot+`}}`, usage)
|
||||
} else {
|
||||
parseSSEUsagePassthrough(`{"type":"message_delta","usage":`+snapshot+`}`, usage)
|
||||
}
|
||||
} else if index == 0 {
|
||||
(&GatewayService{}).parseSSEUsage(`{"type":"message_start","message":{"usage":`+snapshot+`}}`, usage)
|
||||
} else {
|
||||
(&GatewayService{}).parseSSEUsage(`{"type":"message_delta","usage":`+snapshot+`}`, usage)
|
||||
}
|
||||
require.Equal(t, 80, usage.InputTokens)
|
||||
}
|
||||
require.Zero(t, usage.CacheReadInputTokens)
|
||||
require.Equal(t, 10, usage.CacheCreationInputTokens)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnthropicPromptTotalForwardBoundary(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, source := range []string{"prompt total", "independent input"} {
|
||||
for _, route := range []string{"messages", "passthrough", "native messages", "responses", "buffered responses", "chat", "buffered chat", "native responses", "buffered native responses", "native chat", "buffered native chat"} {
|
||||
for _, terminal := range []string{"stop", "eof"} {
|
||||
t.Run(source+"/"+route+"/"+terminal, func(t *testing.T) {
|
||||
inputField, wantInput := `"input_tokens":80`, 80
|
||||
if source == "prompt total" {
|
||||
inputField, wantInput = `"input_tokens":100,"prompt_tokens":100`, 50
|
||||
}
|
||||
payload := "event: message_start\ndata: " + `{"type":"message_start","message":{"id":"msg_total","type":"message","role":"assistant","model":"claude-sonnet-4","content":[],"usage":{` + inputField + `,"cache_creation":{"ephemeral_5m_input_tokens":20}}}}` + "\n\n"
|
||||
for range 2 {
|
||||
payload += "event: message_delta\ndata: " + `{"type":"message_delta","usage":{"cache_creation":{"ephemeral_1h_input_tokens":30}}}` + "\n\n"
|
||||
}
|
||||
payload += "event: message_delta\ndata: " + `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}` + "\n\n"
|
||||
if terminal == "stop" {
|
||||
payload += "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"
|
||||
}
|
||||
response := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(payload))}
|
||||
recorder := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(recorder)
|
||||
ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
|
||||
service := &GatewayService{cfg: &config.Config{}, rateLimitService: &RateLimitService{}}
|
||||
native := &OpenAIGatewayService{cfg: &config.Config{}}
|
||||
var result *ForwardResult
|
||||
var nativeResult *OpenAIForwardResult
|
||||
var err error
|
||||
switch route {
|
||||
case "messages", "passthrough":
|
||||
var streamed *streamingResult
|
||||
if route == "messages" {
|
||||
streamed, err = service.handleStreamingResponse(context.Background(), response, ctx, &Account{ID: 701}, time.Now(), "claude-sonnet-4", "claude-sonnet-4", false)
|
||||
} else {
|
||||
streamed, err = service.handleStreamingResponseAnthropicAPIKeyPassthrough(context.Background(), response, ctx, &Account{ID: 701}, time.Now(), "claude-sonnet-4")
|
||||
}
|
||||
require.NotNil(t, streamed)
|
||||
result = &ForwardResult{Usage: *streamed.usage}
|
||||
case "native messages":
|
||||
nativeResult, err = native.handleNativeAnthropicStreamingResponse(context.Background(), response, ctx, &Account{ID: 701}, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now())
|
||||
case "responses":
|
||||
result, err = service.handleResponsesStreamingResponse(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{})
|
||||
case "buffered responses":
|
||||
result, err = service.handleResponsesBufferedStreamingResponse(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{})
|
||||
case "chat":
|
||||
result, err = service.handleCCStreamingFromAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now())
|
||||
case "buffered chat":
|
||||
result, err = service.handleCCBufferedFromAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", nil, time.Now())
|
||||
case "native responses":
|
||||
nativeResult, err = native.handleResponsesStreamingFromNativeAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{})
|
||||
case "buffered native responses":
|
||||
nativeResult, err = native.handleResponsesBufferedFromNativeAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now(), apicompat.ResponsesClientToolMapping{})
|
||||
case "native chat":
|
||||
nativeResult, err = native.handleCCStreamingFromNativeAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now())
|
||||
case "buffered native chat":
|
||||
nativeResult, err = native.handleCCBufferedFromNativeAnthropic(response, ctx, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now())
|
||||
}
|
||||
if terminal == "eof" && (route == "messages" || route == "passthrough" || route == "native messages") {
|
||||
require.ErrorContains(t, err, "missing terminal event")
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
if nativeResult != nil {
|
||||
require.Equal(t, wantInput+50, nativeResult.Usage.InputTokens)
|
||||
billingResult := *nativeResult
|
||||
billingResult.Model, billingResult.BillingModel, billingResult.UpstreamModel = "k3", "kimi-k3", "k3"
|
||||
assertNativeCacheRecordUsage(t, &billingResult, nativeAnthropicTestAccount(), wantInput, 0.16)
|
||||
result = &ForwardResult{Usage: ClaudeUsage{InputTokens: nativeResult.Usage.InputTokens - nativeResult.Usage.CacheCreationInputTokens, OutputTokens: nativeResult.Usage.OutputTokens, CacheCreationInputTokens: nativeResult.Usage.CacheCreationInputTokens, CacheCreation5mTokens: nativeResult.Usage.CacheCreation5mTokens, CacheCreation1hTokens: nativeResult.Usage.CacheCreation1hTokens}}
|
||||
}
|
||||
require.NotNil(t, result)
|
||||
require.Equal(t, wantInput, result.Usage.InputTokens)
|
||||
require.Equal(t, 2, result.Usage.OutputTokens)
|
||||
require.Equal(t, 50, result.Usage.CacheCreationInputTokens)
|
||||
require.Equal(t, 20, result.Usage.CacheCreation5mTokens)
|
||||
require.Equal(t, 30, result.Usage.CacheCreation1hTokens)
|
||||
result.Model = "claude-sonnet-4"
|
||||
assertAnthropicCacheCreationResultCosts(t, result, 0.16)
|
||||
if strings.Contains(route, "messages") || route == "passthrough" {
|
||||
return
|
||||
}
|
||||
var clientUsage gjson.Result
|
||||
if strings.HasPrefix(route, "buffered") {
|
||||
clientUsage = gjson.GetBytes(recorder.Body.Bytes(), "usage")
|
||||
} else {
|
||||
count := 0
|
||||
for _, line := range strings.Split(recorder.Body.String(), "\n") {
|
||||
if !strings.HasPrefix(line, "data: ") {
|
||||
continue
|
||||
}
|
||||
data := strings.TrimPrefix(line, "data: ")
|
||||
if gjson.Get(data, "type").String() == "response.completed" {
|
||||
clientUsage = gjson.Get(data, "response.usage")
|
||||
count++
|
||||
} else if gjson.Get(data, "usage").Exists() {
|
||||
clientUsage = gjson.Get(data, "usage")
|
||||
count++
|
||||
}
|
||||
}
|
||||
require.Equal(t, 1, count)
|
||||
}
|
||||
require.True(t, clientUsage.Exists())
|
||||
inputPath, creationPath := "input_tokens", "cache_creation_input_tokens"
|
||||
if strings.HasSuffix(route, "chat") {
|
||||
inputPath, creationPath = "prompt_tokens", "prompt_tokens_details.cache_creation_tokens"
|
||||
}
|
||||
require.EqualValues(t, wantInput+50, clientUsage.Get(inputPath).Int())
|
||||
require.EqualValues(t, 50, clientUsage.Get(creationPath).Int())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnthropicPromptTotalBufferedMessages(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, source := range []string{"prompt total", "independent input"} {
|
||||
for _, route := range []string{"messages", "passthrough", "native messages"} {
|
||||
t.Run(source+"/"+route, func(t *testing.T) {
|
||||
inputField, wantInput := `"input_tokens":80`, 80
|
||||
if source == "prompt total" {
|
||||
inputField, wantInput = `"input_tokens":100,"prompt_tokens":100`, 50
|
||||
}
|
||||
body := `{"id":"msg_total","type":"message","model":"claude-sonnet-4","role":"assistant","content":[],"usage":{` + inputField + `,"output_tokens":2,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":30}}}`
|
||||
response := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(body))}
|
||||
recorder := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(recorder)
|
||||
ctx.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
|
||||
service := &GatewayService{cfg: &config.Config{}, rateLimitService: &RateLimitService{}}
|
||||
account := &Account{ID: 701}
|
||||
var usage *ClaudeUsage
|
||||
var err error
|
||||
switch route {
|
||||
case "messages":
|
||||
usage, err = service.handleNonStreamingResponse(context.Background(), response, ctx, account, "claude-sonnet-4", "claude-sonnet-4")
|
||||
case "passthrough":
|
||||
usage, err = service.handleNonStreamingResponseAnthropicAPIKeyPassthrough(context.Background(), response, ctx, account)
|
||||
case "native messages":
|
||||
var result *OpenAIForwardResult
|
||||
result, err = (&OpenAIGatewayService{cfg: &config.Config{}}).handleNativeAnthropicBufferedResponse(context.Background(), response, ctx, account, "claude-sonnet-4", "claude-sonnet-4", "claude-sonnet-4", nil, time.Now())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, wantInput+50, result.Usage.InputTokens)
|
||||
result.Model, result.BillingModel, result.UpstreamModel = "k3", "kimi-k3", "k3"
|
||||
assertNativeCacheRecordUsage(t, result, nativeAnthropicTestAccount(), wantInput, 0.16)
|
||||
usage = parseClaudeUsageFromResponseBody([]byte(body))
|
||||
}
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, wantInput, usage.InputTokens)
|
||||
assertAnthropicCacheCreationResultCosts(t, &ForwardResult{Model: "claude-sonnet-4", Usage: *usage}, 0.16)
|
||||
require.JSONEq(t, body, recorder.Body.String())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -635,7 +635,6 @@ func parseSSEUsagePassthrough(data string, usage *ClaudeUsage) {
|
||||
msgUsage := parsed.Get("message.usage")
|
||||
if msgUsage.Exists() {
|
||||
usage.InputTokens = int(msgUsage.Get("input_tokens").Int())
|
||||
usage.CacheReadInputTokens = int(msgUsage.Get("cache_read_input_tokens").Int())
|
||||
|
||||
mergeRawAnthropicCacheCreationUsage(msgUsage, usage)
|
||||
}
|
||||
@@ -648,10 +647,6 @@ func parseSSEUsagePassthrough(data string, usage *ClaudeUsage) {
|
||||
if v := deltaUsage.Get("output_tokens").Int(); v > 0 {
|
||||
usage.OutputTokens = int(v)
|
||||
}
|
||||
if v := deltaUsage.Get("cache_read_input_tokens").Int(); v > 0 {
|
||||
usage.CacheReadInputTokens = int(v)
|
||||
}
|
||||
|
||||
mergeRawAnthropicCacheCreationUsage(deltaUsage, usage)
|
||||
}
|
||||
default:
|
||||
@@ -662,15 +657,6 @@ func parseSSEUsagePassthrough(data string, usage *ClaudeUsage) {
|
||||
mergeRawAnthropicCacheCreationUsage(usageNode, usage)
|
||||
}
|
||||
|
||||
if usage.CacheReadInputTokens == 0 {
|
||||
if cached := parsed.Get("message.usage.cached_tokens").Int(); cached > 0 {
|
||||
usage.CacheReadInputTokens = int(cached)
|
||||
}
|
||||
if cached := parsed.Get("usage.cached_tokens").Int(); usage.CacheReadInputTokens == 0 && cached > 0 {
|
||||
usage.CacheReadInputTokens = int(cached)
|
||||
}
|
||||
}
|
||||
|
||||
// Kimi's Anthropic-compatible stream uses input_tokens with two meanings:
|
||||
// message_start reports total prompt input, while message_delta reports only
|
||||
// uncached input. prompt_tokens remains the total in both events. Normalize
|
||||
@@ -680,6 +666,17 @@ func parseSSEUsagePassthrough(data string, usage *ClaudeUsage) {
|
||||
if parsed.Get("type").String() == "message_start" {
|
||||
usageNode = parsed.Get("message.usage")
|
||||
}
|
||||
if !usageNode.Exists() || usageNode.Type == gjson.Null {
|
||||
usageNode = parsed.Get("message.usage")
|
||||
}
|
||||
for _, path := range []string{"cache_read_input_tokens", "cached_tokens", "prompt_tokens_details.cached_tokens", "prompt_cache_hit_tokens"} {
|
||||
if value := usageNode.Get(path); value.Exists() && value.Type != gjson.Null {
|
||||
usage.CacheReadInputTokens = max(int(value.Int()), 0)
|
||||
if usage.CacheReadInputTokens > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
normalizeAnthropicCompatiblePromptUsage(usageNode, usage)
|
||||
}
|
||||
|
||||
@@ -694,38 +691,28 @@ func normalizeAnthropicCompatiblePromptUsage(usageNode gjson.Result, usage *Clau
|
||||
promptCacheHitTokens := usageNode.Get("prompt_cache_hit_tokens")
|
||||
promptCacheMissTokens := usageNode.Get("prompt_cache_miss_tokens")
|
||||
if (!promptTokens.Exists() || promptTokens.Int() <= 0) &&
|
||||
!promptCacheHitTokens.Exists() && !promptCacheMissTokens.Exists() {
|
||||
!promptCacheHitTokens.Exists() && !promptCacheMissTokens.Exists() && !usage.promptTotalPresent {
|
||||
return false
|
||||
}
|
||||
|
||||
cacheReadTokens := usage.CacheReadInputTokens
|
||||
if v := usageNode.Get("cache_read_input_tokens"); v.Exists() {
|
||||
cacheReadTokens = int(v.Int())
|
||||
}
|
||||
if cacheReadTokens == 0 {
|
||||
if v := usageNode.Get("cached_tokens"); v.Exists() {
|
||||
cacheReadTokens = int(v.Int())
|
||||
for _, path := range []string{"cache_read_input_tokens", "cached_tokens", "prompt_tokens_details.cached_tokens", "prompt_cache_hit_tokens"} {
|
||||
if value := usageNode.Get(path); value.Exists() && value.Type != gjson.Null {
|
||||
cacheReadTokens = max(int(value.Int()), 0)
|
||||
if cacheReadTokens > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if cacheReadTokens == 0 {
|
||||
if v := usageNode.Get("prompt_tokens_details.cached_tokens"); v.Exists() {
|
||||
cacheReadTokens = int(v.Int())
|
||||
}
|
||||
}
|
||||
if cacheReadTokens == 0 && promptCacheHitTokens.Exists() {
|
||||
cacheReadTokens = max(int(promptCacheHitTokens.Int()), 0)
|
||||
}
|
||||
|
||||
mergeRawAnthropicCacheCreationUsage(usageNode, usage)
|
||||
cacheCreationTokens := usage.CacheCreationInputTokens
|
||||
|
||||
if promptCacheMissTokens.Exists() {
|
||||
usage.InputTokens = max(int(promptCacheMissTokens.Int()), 0)
|
||||
} else {
|
||||
usage.InputTokens = max(int(promptTokens.Int())-cacheReadTokens-cacheCreationTokens, 0)
|
||||
}
|
||||
usage.CacheReadInputTokens = cacheReadTokens
|
||||
usage.CacheCreationInputTokens = cacheCreationTokens
|
||||
var cacheMissTokens *int
|
||||
if promptCacheMissTokens.Exists() && promptCacheMissTokens.Type != gjson.Null {
|
||||
value := int(promptCacheMissTokens.Int())
|
||||
cacheMissTokens = &value
|
||||
}
|
||||
normalizeAnthropicPromptTotal(usage, int(promptTokens.Int()), cacheMissTokens)
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -285,12 +285,14 @@ func assertAnthropicCacheCreationOverrideCosts(t *testing.T, result *ForwardResu
|
||||
require.Equal(t, result.Usage.CacheCreation5mTokens, usageRepo.lastLog.CacheCreation5mTokens)
|
||||
require.Equal(t, result.Usage.CacheCreation1hTokens, usageRepo.lastLog.CacheCreation1hTokens)
|
||||
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)
|
||||
wantTotalCost := float64(result.Usage.InputTokens)*0.001 + float64(result.Usage.OutputTokens)*0.002 + wantCacheCost
|
||||
require.Equal(t, result.Usage.InputTokens, usageRepo.lastLog.InputTokens)
|
||||
require.InDelta(t, wantTotalCost, usageRepo.lastLog.TotalCost, 1e-12)
|
||||
require.InDelta(t, wantTotalCost*0.5, usageRepo.lastLog.ActualCost, 1e-12)
|
||||
require.Equal(t, 1, billingRepo.calls)
|
||||
require.InDelta(t, (0.014+wantCacheCost)*0.5, billingRepo.lastCmd.BalanceCost, 1e-12)
|
||||
require.InDelta(t, wantTotalCost*0.5, billingRepo.lastCmd.BalanceCost, 1e-12)
|
||||
require.NotNil(t, usageRepo.lastLog.AccountStatsCost)
|
||||
require.InDelta(t, (0.014+wantCacheCost)*statsMultiplier, *usageRepo.lastLog.AccountStatsCost, 1e-12)
|
||||
require.InDelta(t, wantTotalCost*statsMultiplier, *usageRepo.lastLog.AccountStatsCost, 1e-12)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -294,31 +294,27 @@ func mergeAnthropicUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) {
|
||||
return
|
||||
}
|
||||
|
||||
cacheReadTokens := src.CacheReadInputTokens
|
||||
if cacheReadTokens == 0 && src.CachedTokens > 0 {
|
||||
cacheReadTokens = src.CachedTokens
|
||||
cacheReadTokens := max(src.CacheReadInputTokens, 0)
|
||||
hasCacheReadTokens := src.CacheReadInputTokensPresent || src.CacheReadInputTokens != 0
|
||||
if cacheReadTokens == 0 && (src.CachedTokensPresent || src.CachedTokens != 0) {
|
||||
cacheReadTokens = max(src.CachedTokens, 0)
|
||||
hasCacheReadTokens = true
|
||||
}
|
||||
if cacheReadTokens == 0 && src.PromptTokensDetails != nil && src.PromptTokensDetails.CachedTokens > 0 {
|
||||
cacheReadTokens = src.PromptTokensDetails.CachedTokens
|
||||
if cacheReadTokens == 0 && src.PromptTokensDetails != nil && (src.PromptTokensDetails.CachedTokensPresent || src.PromptTokensDetails.CachedTokens != 0) {
|
||||
cacheReadTokens = max(src.PromptTokensDetails.CachedTokens, 0)
|
||||
hasCacheReadTokens = true
|
||||
}
|
||||
if cacheReadTokens == 0 && src.PromptCacheHitTokens != nil {
|
||||
cacheReadTokens = max(*src.PromptCacheHitTokens, 0)
|
||||
hasCacheReadTokens = true
|
||||
}
|
||||
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
|
||||
// overloaded input_tokens field. This covers Kimi's changing stream
|
||||
// semantics as well as GLM/DeepSeek cache aliases.
|
||||
if src.PromptTokens > 0 || src.PromptCacheHitTokens != nil || src.PromptCacheMissTokens != nil {
|
||||
if src.PromptCacheMissTokens != nil {
|
||||
dst.InputTokens = max(*src.PromptCacheMissTokens, 0)
|
||||
} else {
|
||||
dst.InputTokens = max(src.PromptTokens-cacheReadTokens-cacheCreationTokens, 0)
|
||||
}
|
||||
dst.CacheReadInputTokens = cacheReadTokens
|
||||
} else {
|
||||
if src.PromptTokens <= 0 && src.PromptCacheHitTokens == nil && src.PromptCacheMissTokens == nil && !dst.promptTotalPresent {
|
||||
// Without an authoritative prompt total or miss bucket, input_tokens is
|
||||
// provider-specific: it may already be the uncached bucket, or it may be
|
||||
// a total from an earlier event. Do not infer a subtraction merely because
|
||||
@@ -327,15 +323,31 @@ func mergeAnthropicUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) {
|
||||
if src.InputTokens > 0 {
|
||||
dst.InputTokens = src.InputTokens
|
||||
}
|
||||
if cacheReadTokens > 0 {
|
||||
dst.CacheReadInputTokens = cacheReadTokens
|
||||
}
|
||||
}
|
||||
if hasCacheReadTokens {
|
||||
dst.CacheReadInputTokens = cacheReadTokens
|
||||
}
|
||||
normalizeAnthropicPromptTotal(dst, src.PromptTokens, src.PromptCacheMissTokens)
|
||||
if src.OutputTokens > 0 {
|
||||
dst.OutputTokens = src.OutputTokens
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeAnthropicPromptTotal(usage *ClaudeUsage, promptTokens int, promptCacheMissTokens *int) {
|
||||
if promptCacheMissTokens != nil {
|
||||
usage.promptTotalPresent = false
|
||||
usage.InputTokens = max(*promptCacheMissTokens, 0)
|
||||
return
|
||||
}
|
||||
if promptTokens > 0 {
|
||||
usage.promptTotalTokens = promptTokens
|
||||
usage.promptTotalPresent = true
|
||||
}
|
||||
if usage.promptTotalPresent {
|
||||
usage.InputTokens = max(usage.promptTotalTokens-usage.CacheReadInputTokens-usage.CacheCreationInputTokens, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func mergeAnthropicCacheCreationUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) {
|
||||
if src.HasCacheCreationInputTokens() {
|
||||
dst.CacheCreationInputTokens = max(src.CacheCreationInputTokens, 0)
|
||||
|
||||
@@ -606,6 +606,8 @@ type ClaudeUsage struct {
|
||||
ImageOutputTokens int `json:"image_output_tokens,omitempty"`
|
||||
|
||||
cacheCreationInputTokensPresent bool
|
||||
promptTotalTokens int
|
||||
promptTotalPresent bool
|
||||
}
|
||||
|
||||
// ForwardResult 转发结果
|
||||
|
||||
@@ -1178,6 +1178,8 @@ func (s *GatewayService) parseSSEUsage(data string, usage *ClaudeUsage) {
|
||||
}
|
||||
|
||||
type sseUsagePatch struct {
|
||||
promptTokens int
|
||||
promptCacheMissTokens *int
|
||||
inputTokens int
|
||||
hasInputTokens bool
|
||||
outputTokens int
|
||||
@@ -1206,7 +1208,7 @@ func (s *GatewayService) extractSSEUsagePatch(event map[string]any) *sseUsagePat
|
||||
return nil
|
||||
}
|
||||
|
||||
patch := &sseUsagePatch{}
|
||||
patch := extractAnthropicPromptPatch(usageObj)
|
||||
patch.hasInputTokens = true
|
||||
if v, ok := parseSSEUsageInt(usageObj["input_tokens"]); ok {
|
||||
patch.inputTokens = v
|
||||
@@ -1215,10 +1217,11 @@ func (s *GatewayService) extractSSEUsagePatch(event map[string]any) *sseUsagePat
|
||||
patch.cacheCreationInputTokens = v
|
||||
patch.hasCacheCreationInput = true
|
||||
}
|
||||
patch.hasCacheReadInput = true
|
||||
if v, ok := parseSSEUsageInt(usageObj["cache_read_input_tokens"]); ok {
|
||||
patch.cacheReadInputTokens = v
|
||||
patch.cacheReadInputTokens = max(v, 0)
|
||||
patch.hasCacheReadInput = true
|
||||
}
|
||||
applyAnthropicCacheReadAliases(patch, usageObj)
|
||||
if cc, ok := usageObj["cache_creation"].(map[string]any); ok {
|
||||
if v, exists := parseSSEUsageInt(cc["ephemeral_5m_input_tokens"]); exists {
|
||||
patch.cacheCreation5mTokens = v
|
||||
@@ -1237,7 +1240,7 @@ func (s *GatewayService) extractSSEUsagePatch(event map[string]any) *sseUsagePat
|
||||
return nil
|
||||
}
|
||||
|
||||
patch := &sseUsagePatch{}
|
||||
patch := extractAnthropicPromptPatch(usageObj)
|
||||
if v, ok := parseSSEUsageInt(usageObj["input_tokens"]); ok && v > 0 {
|
||||
patch.inputTokens = v
|
||||
patch.hasInputTokens = true
|
||||
@@ -1250,10 +1253,11 @@ func (s *GatewayService) extractSSEUsagePatch(event map[string]any) *sseUsagePat
|
||||
patch.cacheCreationInputTokens = v
|
||||
patch.hasCacheCreationInput = true
|
||||
}
|
||||
if v, ok := parseSSEUsageInt(usageObj["cache_read_input_tokens"]); ok && v > 0 {
|
||||
patch.cacheReadInputTokens = v
|
||||
if v, ok := parseSSEUsageInt(usageObj["cache_read_input_tokens"]); ok {
|
||||
patch.cacheReadInputTokens = max(v, 0)
|
||||
patch.hasCacheReadInput = true
|
||||
}
|
||||
applyAnthropicCacheReadAliases(patch, usageObj)
|
||||
if cc, ok := usageObj["cache_creation"].(map[string]any); ok {
|
||||
if v, exists := parseSSEUsageInt(cc["ephemeral_5m_input_tokens"]); exists {
|
||||
patch.cacheCreation5mTokens = v
|
||||
@@ -1270,6 +1274,28 @@ func (s *GatewayService) extractSSEUsagePatch(event map[string]any) *sseUsagePat
|
||||
return nil
|
||||
}
|
||||
|
||||
func extractAnthropicPromptPatch(usageObj map[string]any) *sseUsagePatch {
|
||||
patch := &sseUsagePatch{}
|
||||
patch.promptTokens, _ = parseSSEUsageInt(usageObj["prompt_tokens"])
|
||||
if value, ok := parseSSEUsageInt(usageObj["prompt_cache_miss_tokens"]); ok {
|
||||
patch.promptCacheMissTokens = &value
|
||||
}
|
||||
return patch
|
||||
}
|
||||
|
||||
func applyAnthropicCacheReadAliases(patch *sseUsagePatch, usageObj map[string]any) {
|
||||
details, _ := usageObj["prompt_tokens_details"].(map[string]any)
|
||||
for _, alias := range []any{usageObj["cached_tokens"], details["cached_tokens"], usageObj["prompt_cache_hit_tokens"]} {
|
||||
if patch.cacheReadInputTokens != 0 {
|
||||
break
|
||||
}
|
||||
if value, ok := parseSSEUsageInt(alias); ok {
|
||||
patch.cacheReadInputTokens = max(value, 0)
|
||||
patch.hasCacheReadInput = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func mergeSSEUsagePatch(usage *ClaudeUsage, patch *sseUsagePatch) {
|
||||
if usage == nil || patch == nil {
|
||||
return
|
||||
@@ -1297,6 +1323,7 @@ func mergeSSEUsagePatch(usage *ClaudeUsage, patch *sseUsagePatch) {
|
||||
if !usage.cacheCreationInputTokensPresent && (patch.hasCacheCreation5m || patch.hasCacheCreation1h) {
|
||||
usage.CacheCreationInputTokens = max(usage.CacheCreation5mTokens, 0) + max(usage.CacheCreation1hTokens, 0)
|
||||
}
|
||||
normalizeAnthropicPromptTotal(usage, patch.promptTokens, patch.promptCacheMissTokens)
|
||||
}
|
||||
|
||||
func parseSSEUsageInt(value any) (int, bool) {
|
||||
@@ -1414,6 +1441,7 @@ func (s *GatewayService) handleNonStreamingResponse(ctx context.Context, resp *h
|
||||
}
|
||||
|
||||
mergeRawAnthropicCacheCreationUsage(gjson.GetBytes(body, "usage"), &response.Usage)
|
||||
normalizeAnthropicCompatiblePromptUsage(gjson.GetBytes(body, "usage"), &response.Usage)
|
||||
|
||||
// 兼容 Kimi cached_tokens → cache_read_input_tokens
|
||||
if response.Usage.CacheReadInputTokens == 0 {
|
||||
|
||||
@@ -216,7 +216,7 @@ func assertNativeCacheRecordUsageWithSettings(t *testing.T, result *OpenAIForwar
|
||||
require.Equal(t, result.Usage.CacheCreation5mTokens, usageRepo.lastLog.CacheCreation5mTokens)
|
||||
require.Equal(t, result.Usage.CacheCreation1hTokens, usageRepo.lastLog.CacheCreation1hTokens)
|
||||
require.InDelta(t, cacheCost, usageRepo.lastLog.CacheCreationCost, 1e-12)
|
||||
totalCost := float64(uncachedInput)*0.001 + 0.0047 + cacheCost
|
||||
totalCost := float64(uncachedInput)*0.001 + float64(result.Usage.OutputTokens)*0.002 + float64(result.Usage.CacheReadInputTokens)*0.0001 + cacheCost
|
||||
require.InDelta(t, totalCost, usageRepo.lastLog.TotalCost, 1e-12)
|
||||
require.InDelta(t, totalCost*0.5, usageRepo.lastLog.ActualCost, 1e-12)
|
||||
require.InDelta(t, totalCost*0.5, billingRepo.lastCmd.BalanceCost, 1e-12)
|
||||
|
||||
Reference in new issue
Block a user