mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 00:05:30 +00:00
fix(apicompat): preserve Anthropic cache creation TTL details
This commit is contained in:
1 parent
b0a02a3304
commit
7f6673ead5
7 files changed
+193
-20
No files matched your search
@@ -29,6 +29,20 @@ func encodeAnthropicThinking(block AnthropicContentBlock) string {
|
||||
return anthropicThinkingEnvelopePrefix + base64.RawStdEncoding.EncodeToString(payload)
|
||||
}
|
||||
|
||||
func anthropicCacheCreationInputTokens(usage AnthropicUsage) int {
|
||||
if usage.CacheCreation != nil && (usage.CacheCreation.Ephemeral5mInputTokens != nil || usage.CacheCreation.Ephemeral1hInputTokens != nil) {
|
||||
cacheCreationTokens := 0
|
||||
if usage.CacheCreation.Ephemeral5mInputTokens != nil {
|
||||
cacheCreationTokens += max(*usage.CacheCreation.Ephemeral5mInputTokens, 0)
|
||||
}
|
||||
if usage.CacheCreation.Ephemeral1hInputTokens != nil {
|
||||
cacheCreationTokens += max(*usage.CacheCreation.Ephemeral1hInputTokens, 0)
|
||||
}
|
||||
return cacheCreationTokens
|
||||
}
|
||||
return usage.CacheCreationInputTokens
|
||||
}
|
||||
|
||||
// AnthropicToResponsesResponse converts an Anthropic Messages response into a
|
||||
// Responses API response. This is the reverse of ResponsesToAnthropic and
|
||||
// enables Anthropic upstream responses to be returned in OpenAI Responses format.
|
||||
@@ -130,14 +144,15 @@ func AnthropicToResponsesResponse(resp *AnthropicResponse) *ResponsesResponse {
|
||||
// Anthropic's input_tokens excludes cache_read/cache_creation, while OpenAI
|
||||
// Responses' input_tokens is the total including cached tokens. Add them back
|
||||
// when converting so downstream consumers see OpenAI semantics.
|
||||
cacheCreationTokens := anthropicCacheCreationInputTokens(resp.Usage)
|
||||
totalInputTokens := resp.Usage.InputTokens +
|
||||
resp.Usage.CacheReadInputTokens +
|
||||
resp.Usage.CacheCreationInputTokens
|
||||
cacheCreationTokens
|
||||
out.Usage = &ResponsesUsage{
|
||||
InputTokens: totalInputTokens,
|
||||
OutputTokens: resp.Usage.OutputTokens,
|
||||
TotalTokens: totalInputTokens + resp.Usage.OutputTokens,
|
||||
CacheCreationInputTokens: resp.Usage.CacheCreationInputTokens,
|
||||
CacheCreationInputTokens: cacheCreationTokens,
|
||||
}
|
||||
if resp.Usage.CacheReadInputTokens > 0 {
|
||||
out.Usage.InputTokensDetails = &ResponsesInputTokensDetails{
|
||||
@@ -218,6 +233,7 @@ type AnthropicEventToResponsesState struct {
|
||||
OutputTokens int
|
||||
CacheReadInputTokens int
|
||||
CacheCreationInputTokens int
|
||||
CacheCreation AnthropicCacheCreation
|
||||
|
||||
StopReason string
|
||||
}
|
||||
@@ -229,6 +245,24 @@ func NewAnthropicEventToResponsesState() *AnthropicEventToResponsesState {
|
||||
}
|
||||
}
|
||||
|
||||
func (state *AnthropicEventToResponsesState) mergeCacheCreationUsage(usage AnthropicUsage) {
|
||||
if usage.CacheCreation != nil {
|
||||
if usage.CacheCreation.Ephemeral5mInputTokens != nil {
|
||||
tokens := max(*usage.CacheCreation.Ephemeral5mInputTokens, 0)
|
||||
state.CacheCreation.Ephemeral5mInputTokens = &tokens
|
||||
}
|
||||
if usage.CacheCreation.Ephemeral1hInputTokens != nil {
|
||||
tokens := max(*usage.CacheCreation.Ephemeral1hInputTokens, 0)
|
||||
state.CacheCreation.Ephemeral1hInputTokens = &tokens
|
||||
}
|
||||
}
|
||||
if state.CacheCreation.Ephemeral5mInputTokens != nil || state.CacheCreation.Ephemeral1hInputTokens != nil {
|
||||
state.CacheCreationInputTokens = anthropicCacheCreationInputTokens(AnthropicUsage{CacheCreation: &state.CacheCreation})
|
||||
} else if usage.CacheCreationInputTokens > 0 {
|
||||
state.CacheCreationInputTokens = usage.CacheCreationInputTokens
|
||||
}
|
||||
}
|
||||
|
||||
// AnthropicEventToResponsesEvents converts a single Anthropic SSE event into
|
||||
// zero or more Responses SSE events, updating state as it goes.
|
||||
func AnthropicEventToResponsesEvents(
|
||||
@@ -295,9 +329,7 @@ func anthToResHandleMessageStart(evt *AnthropicStreamEvent, state *AnthropicEven
|
||||
if evt.Message.Usage.CacheReadInputTokens > 0 {
|
||||
state.CacheReadInputTokens = evt.Message.Usage.CacheReadInputTokens
|
||||
}
|
||||
if evt.Message.Usage.CacheCreationInputTokens > 0 {
|
||||
state.CacheCreationInputTokens = evt.Message.Usage.CacheCreationInputTokens
|
||||
}
|
||||
state.mergeCacheCreationUsage(evt.Message.Usage)
|
||||
}
|
||||
|
||||
if state.CreatedSent {
|
||||
@@ -558,9 +590,7 @@ func anthToResHandleMessageDelta(evt *AnthropicStreamEvent, state *AnthropicEven
|
||||
if evt.Usage.CacheReadInputTokens > 0 {
|
||||
state.CacheReadInputTokens = evt.Usage.CacheReadInputTokens
|
||||
}
|
||||
if evt.Usage.CacheCreationInputTokens > 0 {
|
||||
state.CacheCreationInputTokens = evt.Usage.CacheCreationInputTokens
|
||||
}
|
||||
state.mergeCacheCreationUsage(*evt.Usage)
|
||||
}
|
||||
if evt.Delta != nil && evt.Delta.StopReason != "" {
|
||||
state.StopReason = evt.Delta.StopReason
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package apicompat
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -97,3 +98,101 @@ func TestAnthropicToResponsesResponse_CacheCreation(t *testing.T) {
|
||||
assert.Equal(t, 20, out.Usage.InputTokens, "total = input(10) + cache_read(4) + cache_creation(6)")
|
||||
assert.Equal(t, 6, out.Usage.CacheCreationInputTokens, "cache creation must round-trip")
|
||||
}
|
||||
|
||||
func TestAnthropicUsageDecodesCacheCreationBreakdown(t *testing.T) {
|
||||
var usage AnthropicUsage
|
||||
require.NoError(t, json.Unmarshal([]byte(`{"input_tokens":10,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":7}}`), &usage))
|
||||
require.NotNil(t, usage.CacheCreation)
|
||||
require.NotNil(t, usage.CacheCreation.Ephemeral5mInputTokens)
|
||||
require.NotNil(t, usage.CacheCreation.Ephemeral1hInputTokens)
|
||||
assert.Equal(t, 0, *usage.CacheCreation.Ephemeral5mInputTokens)
|
||||
assert.Equal(t, 7, *usage.CacheCreation.Ephemeral1hInputTokens)
|
||||
}
|
||||
|
||||
func TestAnthropicToResponsesResponse_UsesCacheCreationBreakdown(t *testing.T) {
|
||||
fiveMinutes := 2
|
||||
oneHour := 3
|
||||
resp := AnthropicResponse{Usage: AnthropicUsage{
|
||||
InputTokens: 10,
|
||||
CacheCreation: &AnthropicCacheCreation{
|
||||
Ephemeral5mInputTokens: &fiveMinutes,
|
||||
Ephemeral1hInputTokens: &oneHour,
|
||||
},
|
||||
}}
|
||||
|
||||
out := AnthropicToResponsesResponse(&resp)
|
||||
require.NotNil(t, out.Usage)
|
||||
assert.Equal(t, 15, out.Usage.InputTokens)
|
||||
assert.Equal(t, 5, out.Usage.CacheCreationInputTokens)
|
||||
}
|
||||
|
||||
func TestAnthropicEventToResponsesEvents_MergesCacheCreationBreakdown(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
delta string
|
||||
want5m int
|
||||
want1h int
|
||||
wantTotal int
|
||||
}{
|
||||
{"explicit_1h_zero", `{"cache_creation":{"ephemeral_1h_input_tokens":0}}`, 2, 0, 2},
|
||||
{"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},
|
||||
}
|
||||
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(test.delta), &deltaUsage))
|
||||
state := NewAnthropicEventToResponsesState()
|
||||
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{
|
||||
Type: "message_start",
|
||||
Message: &AnthropicResponse{ID: "msg_test", Usage: startUsage},
|
||||
}, state)
|
||||
assert.Equal(t, 5, state.CacheCreationInputTokens)
|
||||
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_delta", Usage: &deltaUsage}, state)
|
||||
require.NotNil(t, state.CacheCreation.Ephemeral5mInputTokens)
|
||||
require.NotNil(t, state.CacheCreation.Ephemeral1hInputTokens)
|
||||
assert.Equal(t, test.want5m, *state.CacheCreation.Ephemeral5mInputTokens)
|
||||
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},
|
||||
}, state)
|
||||
|
||||
events := AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_stop"}, state)
|
||||
require.Len(t, events, 1)
|
||||
require.Equal(t, "response.completed", events[0].Type)
|
||||
require.NotNil(t, events[0].Response)
|
||||
usage := events[0].Response.Usage
|
||||
require.NotNil(t, usage)
|
||||
assert.Equal(t, test.wantTotal, usage.CacheCreationInputTokens)
|
||||
assert.Equal(t, 14+test.wantTotal, usage.InputTokens)
|
||||
assert.Equal(t, 7, usage.OutputTokens)
|
||||
assert.Equal(t, 21+test.wantTotal, usage.TotalTokens)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnthropicEventToResponsesEvents_CacheCreationLegacyFallback(t *testing.T) {
|
||||
state := NewAnthropicEventToResponsesState()
|
||||
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{
|
||||
Type: "message_start",
|
||||
Message: &AnthropicResponse{Usage: AnthropicUsage{InputTokens: 10, CacheCreationInputTokens: 5}},
|
||||
}, state)
|
||||
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{
|
||||
Type: "message_delta", Usage: &AnthropicUsage{CacheCreationInputTokens: 6, CacheCreation: &AnthropicCacheCreation{}},
|
||||
}, state)
|
||||
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_delta", Usage: &AnthropicUsage{OutputTokens: 7}}, state)
|
||||
assert.Nil(t, state.CacheCreation.Ephemeral5mInputTokens)
|
||||
assert.Nil(t, state.CacheCreation.Ephemeral1hInputTokens)
|
||||
|
||||
events := AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "message_stop"}, state)
|
||||
require.Len(t, events, 1)
|
||||
require.NotNil(t, events[0].Response)
|
||||
require.NotNil(t, events[0].Response.Usage)
|
||||
assert.Equal(t, 6, events[0].Response.Usage.CacheCreationInputTokens)
|
||||
assert.Equal(t, 16, events[0].Response.Usage.InputTokens)
|
||||
}
|
||||
@@ -166,12 +166,21 @@ type AnthropicPromptTokensDetails struct {
|
||||
CachedTokens int `json:"cached_tokens,omitempty"`
|
||||
}
|
||||
|
||||
// AnthropicCacheCreation holds Anthropic's cache creation TTL breakdown.
|
||||
// Pointers preserve the distinction between an omitted field and an explicit
|
||||
// zero in streaming usage events.
|
||||
type AnthropicCacheCreation struct {
|
||||
Ephemeral5mInputTokens *int `json:"ephemeral_5m_input_tokens,omitempty"`
|
||||
Ephemeral1hInputTokens *int `json:"ephemeral_1h_input_tokens,omitempty"`
|
||||
}
|
||||
|
||||
// AnthropicUsage holds token counts in Anthropic format.
|
||||
type AnthropicUsage struct {
|
||||
InputTokens int `json:"input_tokens"`
|
||||
OutputTokens int `json:"output_tokens"`
|
||||
CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
|
||||
CacheReadInputTokens int `json:"cache_read_input_tokens"`
|
||||
InputTokens int `json:"input_tokens"`
|
||||
OutputTokens int `json:"output_tokens"`
|
||||
CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
|
||||
CacheReadInputTokens int `json:"cache_read_input_tokens"`
|
||||
CacheCreation *AnthropicCacheCreation `json:"cache_creation,omitempty"`
|
||||
// Anthropic-compatible providers can also expose their native OpenAI-style
|
||||
// total/cache fields. Preserve them so callers can normalize provider totals
|
||||
// into Anthropic's mutually-exclusive billing buckets.
|
||||
|
||||
@@ -114,7 +114,7 @@ func TestHandleCCBufferedFromAnthropic_PreservesMessageStartCacheUsageAndReasoni
|
||||
Header: http.Header{"x-request-id": []string{"rid_cc_buffered"}},
|
||||
Body: io.NopCloser(strings.NewReader(strings.Join([]string{
|
||||
`event: message_start`,
|
||||
`data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4.5","stop_reason":"","usage":{"input_tokens":12,"cache_read_input_tokens":9,"cache_creation_input_tokens":3}}}`,
|
||||
`data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4.5","stop_reason":"","usage":{"input_tokens":12,"cache_read_input_tokens":9,"cache_creation_input_tokens":5,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":3}}}}`,
|
||||
``,
|
||||
`event: content_block_start`,
|
||||
`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":"hello"}}`,
|
||||
@@ -132,7 +132,9 @@ func TestHandleCCBufferedFromAnthropic_PreservesMessageStartCacheUsageAndReasoni
|
||||
require.Equal(t, 12, result.Usage.InputTokens)
|
||||
require.Equal(t, 7, result.Usage.OutputTokens)
|
||||
require.Equal(t, 9, result.Usage.CacheReadInputTokens)
|
||||
require.Equal(t, 3, result.Usage.CacheCreationInputTokens)
|
||||
require.Equal(t, 5, result.Usage.CacheCreationInputTokens)
|
||||
require.Equal(t, 2, result.Usage.CacheCreation5mTokens)
|
||||
require.Equal(t, 3, result.Usage.CacheCreation1hTokens)
|
||||
require.NotNil(t, result.ReasoningEffort)
|
||||
require.Equal(t, "high", *result.ReasoningEffort)
|
||||
}
|
||||
|
||||
@@ -296,6 +296,21 @@ 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
|
||||
}
|
||||
|
||||
// Some Anthropic-compatible providers retain OpenAI-style prompt/cache
|
||||
// fields. Prefer those authoritative totals or hit/miss buckets over the
|
||||
@@ -305,10 +320,10 @@ func mergeAnthropicUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) {
|
||||
if src.PromptCacheMissTokens != nil {
|
||||
dst.InputTokens = max(*src.PromptCacheMissTokens, 0)
|
||||
} else {
|
||||
dst.InputTokens = max(src.PromptTokens-cacheReadTokens-src.CacheCreationInputTokens, 0)
|
||||
dst.InputTokens = max(src.PromptTokens-cacheReadTokens-cacheCreationTokens, 0)
|
||||
}
|
||||
dst.CacheReadInputTokens = cacheReadTokens
|
||||
dst.CacheCreationInputTokens = src.CacheCreationInputTokens
|
||||
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
|
||||
@@ -321,8 +336,8 @@ func mergeAnthropicUsage(dst *ClaudeUsage, src apicompat.AnthropicUsage) {
|
||||
if cacheReadTokens > 0 {
|
||||
dst.CacheReadInputTokens = cacheReadTokens
|
||||
}
|
||||
if src.CacheCreationInputTokens > 0 {
|
||||
dst.CacheCreationInputTokens = src.CacheCreationInputTokens
|
||||
if cacheCreationTokens > 0 {
|
||||
dst.CacheCreationInputTokens = cacheCreationTokens
|
||||
}
|
||||
}
|
||||
if src.OutputTokens > 0 {
|
||||
|
||||
@@ -252,7 +252,7 @@ func TestHandleResponsesBufferedStreamingResponse_PreservesMessageStartCacheUsag
|
||||
Header: http.Header{"x-request-id": []string{"rid_buffered"}},
|
||||
Body: io.NopCloser(strings.NewReader(strings.Join([]string{
|
||||
`event: message_start`,
|
||||
`data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4.5","stop_reason":"","usage":{"input_tokens":12,"cache_read_input_tokens":9,"cache_creation_input_tokens":3}}}`,
|
||||
`data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4.5","stop_reason":"","usage":{"input_tokens":12,"cache_read_input_tokens":9,"cache_creation_input_tokens":5,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":3}}}}`,
|
||||
``,
|
||||
`event: content_block_start`,
|
||||
`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":"hello"}}`,
|
||||
@@ -270,7 +270,9 @@ func TestHandleResponsesBufferedStreamingResponse_PreservesMessageStartCacheUsag
|
||||
require.Equal(t, 12, result.Usage.InputTokens)
|
||||
require.Equal(t, 7, result.Usage.OutputTokens)
|
||||
require.Equal(t, 9, result.Usage.CacheReadInputTokens)
|
||||
require.Equal(t, 3, result.Usage.CacheCreationInputTokens)
|
||||
require.Equal(t, 5, result.Usage.CacheCreationInputTokens)
|
||||
require.Equal(t, 2, result.Usage.CacheCreation5mTokens)
|
||||
require.Equal(t, 3, result.Usage.CacheCreation1hTokens)
|
||||
require.Contains(t, rec.Body.String(), `"cached_tokens":9`)
|
||||
}
|
||||
|
||||
|
||||
@@ -246,3 +246,19 @@ func TestCNProviderAnthropicUsageBillsUncachedInput(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergeAnthropicUsagePreservesCacheCreationBreakdownPresence(t *testing.T) {
|
||||
var first apicompat.AnthropicUsage
|
||||
require.NoError(t, json.Unmarshal([]byte(`{"input_tokens":10,"cache_creation":{"ephemeral_5m_input_tokens":2,"ephemeral_1h_input_tokens":3}}`), &first))
|
||||
var later apicompat.AnthropicUsage
|
||||
require.NoError(t, json.Unmarshal([]byte(`{"output_tokens":7,"cache_creation":{"ephemeral_1h_input_tokens":0}}`), &later))
|
||||
|
||||
usage := &ClaudeUsage{}
|
||||
mergeAnthropicUsage(usage, first)
|
||||
mergeAnthropicUsage(usage, later)
|
||||
|
||||
require.Equal(t, 2, usage.CacheCreation5mTokens)
|
||||
require.Equal(t, 0, usage.CacheCreation1hTokens)
|
||||
require.Equal(t, 2, usage.CacheCreationInputTokens)
|
||||
require.Equal(t, 7, usage.OutputTokens)
|
||||
}
|
||||
Reference in new issue
Block a user