mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 08:06:50 +00:00
feat(gateway): write Claude Code compaction requests at 5m cache TTL
With the 1h cache TTL injection on, every breakpoint of a compaction request was rewritten to 1h, although the conversation is replaced by the summary afterwards and nothing reads the tokens added since the last main-thread breakpoint again. A compaction request is recognised by the fixed preamble of the compact prompt in the last user message. Every breakpoint becomes 5m, including one the client already wrote as 1h. A 5m breakpoint still reads the prefix the main thread cached at 1h, and an all-5m request keeps the tools, system, messages TTL order Anthropic requires. The admin settings hint for the switch names the exception.
This commit is contained in:
1 parent
530c5e3a4f
commit
e2631bbb38
4 files changed
+136
-2
No files matched your search
@@ -1192,10 +1192,57 @@ func normalizeCacheControlTTLOrder(body []byte) []byte {
|
||||
|
||||
// injectAnthropicCacheControlTTL1h 将已有 ephemeral cache_control 块的 ttl 强制写为 1h。
|
||||
// 仅修改已经存在的 cache_control,不新增缓存断点。
|
||||
//
|
||||
// Claude Code compaction requests are written at 5m instead: the conversation is
|
||||
// replaced by the summary afterwards, so nothing reads the extra tokens again,
|
||||
// and a 5m breakpoint still reads the prefix the main thread wrote at 1h.
|
||||
func injectAnthropicCacheControlTTL1h(body []byte) []byte {
|
||||
if isClaudeCodeCompactionRequest(body) {
|
||||
return forceEphemeralCacheControlTTL(body, cacheTTLTarget5m)
|
||||
}
|
||||
return forceEphemeralCacheControlTTL(body, cacheTTLTarget1h)
|
||||
}
|
||||
|
||||
// claudeCodeCompactPreamble opens the compact prompt of Claude Code 2.1.282 in
|
||||
// its full, partial-from and partial-up-to variants, and no other prompt it sends.
|
||||
const claudeCodeCompactPreamble = "CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.\n\n"
|
||||
|
||||
// isClaudeCodeCompactionRequest reports whether the last user message is a compact
|
||||
// prompt. When auto-compaction fires during a tool loop the prompt arrives as a text
|
||||
// block merged into the user message that carries the tool_result.
|
||||
func isClaudeCodeCompactionRequest(body []byte) bool {
|
||||
return claudeLastUserTextHasPrefix(body, claudeCodeCompactPreamble)
|
||||
}
|
||||
|
||||
// claudeLastUserTextHasPrefix reports whether a text block (or the string content) of
|
||||
// the last user message starts with any of prefixes.
|
||||
func claudeLastUserTextHasPrefix(body []byte, prefixes ...string) bool {
|
||||
hasPrefix := func(s string) bool {
|
||||
for _, p := range prefixes {
|
||||
if strings.HasPrefix(s, p) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
var last gjson.Result
|
||||
gjson.GetBytes(body, "messages").ForEach(func(_, msg gjson.Result) bool {
|
||||
if msg.Get("role").String() == "user" {
|
||||
last = msg.Get("content")
|
||||
}
|
||||
return true
|
||||
})
|
||||
if last.Type == gjson.String {
|
||||
return hasPrefix(last.Str)
|
||||
}
|
||||
found := false
|
||||
last.ForEach(func(_, block gjson.Result) bool {
|
||||
found = block.Get("type").String() == "text" && hasPrefix(block.Get("text").String())
|
||||
return !found
|
||||
})
|
||||
return found
|
||||
}
|
||||
|
||||
func forceEphemeralCacheControlTTL(body []byte, ttl string) []byte {
|
||||
if len(body) == 0 || ttl == "" {
|
||||
return body
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// Only the preamble is the real marker; the rest of the prompt is placeholder text.
|
||||
const testCompactPrompt = claudeCodeCompactPreamble + "placeholder compact instructions"
|
||||
|
||||
// compactionTestBody builds a request with three breakpoints (two system blocks and
|
||||
// the assistant message before the last user message) and a trailing role:system
|
||||
// message. lastUser is the JSON content of the last user message; a non-empty
|
||||
// cacheTTL is written into every breakpoint.
|
||||
func compactionTestBody(t *testing.T, lastUser string, cacheTTL string) []byte {
|
||||
t.Helper()
|
||||
cc := `{"type":"ephemeral"}`
|
||||
if cacheTTL != "" {
|
||||
cc = fmt.Sprintf(`{"type":"ephemeral","ttl":%q}`, cacheTTL)
|
||||
}
|
||||
body := fmt.Sprintf(`{"model":"claude-test","messages":[`+
|
||||
`{"role":"user","content":[{"type":"text","text":"first question"}]},`+
|
||||
`{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"Bash","input":{"command":"ls"},"cache_control":%[1]s}]},`+
|
||||
`{"role":"user","content":%[2]s},`+
|
||||
`{"role":"system","content":"placeholder trailing system message"}],`+
|
||||
`"system":[{"type":"text","text":"billing block"},`+
|
||||
`{"type":"text","text":"system block one","cache_control":%[1]s},`+
|
||||
`{"type":"text","text":"system block two","cache_control":%[1]s}],`+
|
||||
`"tools":[{"name":"Bash","input_schema":{}}],"max_tokens":1024,"stream":true}`, cc, lastUser)
|
||||
require.True(t, json.Valid([]byte(body)))
|
||||
return []byte(body)
|
||||
}
|
||||
|
||||
func compactionTestJSONString(t *testing.T, s string) string {
|
||||
t.Helper()
|
||||
b, err := json.Marshal(s)
|
||||
require.NoError(t, err)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func requireCompactionTestTTLs(t *testing.T, body []byte, want string) {
|
||||
t.Helper()
|
||||
for _, path := range []string{"system.1.cache_control", "system.2.cache_control", "messages.1.content.0.cache_control"} {
|
||||
require.Equal(t, want, gjson.GetBytes(body, path+".ttl").String(), path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectAnthropicCacheControlTTL1h_CompactionUses5m(t *testing.T) {
|
||||
prompt := compactionTestJSONString(t, testCompactPrompt)
|
||||
cases := map[string]string{
|
||||
"merged_with_tool_result": `[{"type":"tool_result","tool_use_id":"toolu_1","content":"ok"},{"type":"text","text":` + prompt + `}]`,
|
||||
"own_message": prompt,
|
||||
}
|
||||
for name, lastUser := range cases {
|
||||
for _, clientTTL := range []string{"", "1h"} {
|
||||
t.Run(name+"/client_ttl="+clientTTL, func(t *testing.T) {
|
||||
out := injectAnthropicCacheControlTTL1h(compactionTestBody(t, lastUser, clientTTL))
|
||||
require.NotContains(t, string(out), `"1h"`)
|
||||
requireCompactionTestTTLs(t, out, "5m")
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectAnthropicCacheControlTTL1h_NonCompactionStill1h(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"tool_result_and_reminder": `[{"type":"tool_result","tool_use_id":"toolu_1","content":"ok"},{"type":"text","text":"keep going"}]`,
|
||||
"preamble_not_at_start": compactionTestJSONString(t, "note: "+testCompactPrompt),
|
||||
}
|
||||
for name, lastUser := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
out := injectAnthropicCacheControlTTL1h(compactionTestBody(t, lastUser, ""))
|
||||
requireCompactionTestTTLs(t, out, "1h")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsClaudeCodeCompactionRequest_OnlyLastUserMessageCounts(t *testing.T) {
|
||||
earlier := `{"messages":[{"role":"user","content":` + compactionTestJSONString(t, testCompactPrompt) + `},{"role":"assistant","content":"summary"},{"role":"user","content":"next question"}]}`
|
||||
require.False(t, isClaudeCodeCompactionRequest([]byte(earlier)))
|
||||
require.False(t, isClaudeCodeCompactionRequest([]byte(`{"messages":[]}`)))
|
||||
require.False(t, isClaudeCodeCompactionRequest([]byte(`{}`)))
|
||||
}
|
||||
@@ -576,7 +576,7 @@ export default {
|
||||
cacheTTL5m: '5 minutes',
|
||||
cacheTTL1h: '1 hour',
|
||||
anthropicCacheTTL1hInjection: 'Anthropic Cache TTL Injection',
|
||||
anthropicCacheTTL1hInjectionHint: 'When enabled, existing ephemeral cache_control blocks in Anthropic OAuth/Setup Token request bodies are forced to 1h; response usage is billed back as 5m by default, with account-level TTL billing override taking priority.',
|
||||
anthropicCacheTTL1hInjectionHint: 'When enabled, existing ephemeral cache_control blocks in Anthropic OAuth/Setup Token request bodies are forced to 1h, except Claude Code compaction requests, which use 5m; response usage is billed back as 5m by default, with account-level TTL billing override taking priority.',
|
||||
rewriteMessageCacheControl: 'Rewrite Message Cache Breakpoints',
|
||||
rewriteMessageCacheControlHint: 'Default off: preserve client cache_control on message content blocks. When enabled, client breakpoints are stripped and proxy breakpoints are injected for clients that do not manage caching themselves.',
|
||||
clientDatelineNormalization: 'Client Dateline Normalization',
|
||||
|
||||
@@ -569,7 +569,7 @@ export default {
|
||||
cacheTTL5m: '5 分钟',
|
||||
cacheTTL1h: '1 小时',
|
||||
anthropicCacheTTL1hInjection: 'Anthropic 缓存 TTL 注入',
|
||||
anthropicCacheTTL1hInjectionHint: '开启后,对 Anthropic OAuth/Setup Token 请求体中已有的 ephemeral 缓存块强制写入 1h;响应 usage 默认按 5m 回写计费,账号级 TTL 计费设置优先。',
|
||||
anthropicCacheTTL1hInjectionHint: '开启后,对 Anthropic OAuth/Setup Token 请求体中已有的 ephemeral 缓存块强制写入 1h,Claude Code 压缩请求除外,写入 5m;响应 usage 默认按 5m 回写计费,账号级 TTL 计费设置优先。',
|
||||
rewriteMessageCacheControl: '改写消息缓存断点',
|
||||
rewriteMessageCacheControlHint: '默认关闭,保留客户端在 messages 内容块中的 cache_control。开启后会清除客户端断点并注入代理断点,适合不自行管理缓存策略的客户端。',
|
||||
clientDatelineNormalization: '客户端 dateline 归一化',
|
||||
|
||||
Reference in new issue
Block a user