feat: preserve Anthropic prompt cache controls

This commit is contained in:
sausheong committed 2026-07-20 08:21:59 +08:00
1 parent 0300af6717
commit c7846eeab9
5 files changed
+161 -31

No files matched your search

+11
View File
@@ -93,6 +93,11 @@ func stripCacheKey(tools []ToolDef, fields []string) string {
h.Write([]byte(t.Name))
h.Write([]byte("\x02"))
h.Write(t.Parameters)
if t.CacheControl != nil {
h.Write([]byte(t.CacheControl.Type))
h.Write([]byte("\x04"))
h.Write([]byte(t.CacheControl.TTL))
}
h.Write([]byte("\x03"))
}
return hex.EncodeToString(h.Sum(nil))
@@ -104,6 +109,12 @@ func cloneToolDefs(in []ToolDef) []ToolDef {
}
out := make([]ToolDef, len(in))
copy(out, in)
for i := range out {
if in[i].CacheControl != nil {
cache := *in[i].CacheControl
out[i].CacheControl = &cache
}
}
return out
}
+13
View File
@@ -118,3 +118,16 @@ func TestStripFieldsMalformedSchema(t *testing.T) {
assert.Equal(t, bad, out)
assert.Empty(t, diags)
}
func TestStripCacheKeyIncludesCacheControl(t *testing.T) {
base := ToolDef{Name: "lookup", Parameters: json.RawMessage(`{"type":"object"}`)}
fiveMinutes := base
fiveMinutes.CacheControl = &CacheControl{Type: "ephemeral", TTL: "5m"}
oneHour := base
oneHour.CacheControl = &CacheControl{Type: "ephemeral", TTL: "1h"}
assert.NotEqual(t, stripCacheKey([]ToolDef{fiveMinutes}, nil), stripCacheKey([]ToolDef{oneHour}, nil))
cloned := cloneToolDefs([]ToolDef{oneHour})
cloned[0].CacheControl.TTL = "5m"
assert.Equal(t, "1h", oneHour.CacheControl.TTL, "cached normalization results must not alias cache metadata")
}
+29 -13
View File
@@ -41,11 +41,14 @@ type ThinkingBlock struct {
type Message struct {
Role string `json:"role"` // "user", "assistant", "system"
Content string `json:"content,omitempty"`
Images []ImageContent `json:"-"` // image attachments (not serialized)
Images []ImageContent `json:"-"` // image attachments (not serialized)
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"` // for tool results
IsError bool `json:"is_error,omitempty"` // for tool results
ToolCallID string `json:"tool_call_id,omitempty"` // for tool results
IsError bool `json:"is_error,omitempty"` // for tool results
ThinkingBlocks []ThinkingBlock `json:"thinking_blocks,omitempty"` // echoed back for thinking-mode models
// CacheControl requests a cache breakpoint on the final cacheable block of
// this logical message. Nil means no explicit breakpoint.
CacheControl *CacheControl `json:"cache_control,omitempty"`
}
// ToolCall represents a tool invocation requested by the LLM.
@@ -57,9 +60,17 @@ type ToolCall struct {
// ToolDef defines a tool for the LLM.
type ToolDef struct {
Name string `json:"name"`
Description string `json:"description"`
Parameters json.RawMessage `json:"parameters"` // JSON Schema
Name string `json:"name"`
Description string `json:"description"`
Parameters json.RawMessage `json:"parameters"` // JSON Schema
CacheControl *CacheControl `json:"cache_control,omitempty"`
}
// CacheControl is provider-neutral prompt-cache metadata. Type is currently
// "ephemeral"; TTL is empty/"5m" or "1h".
type CacheControl struct {
Type string `json:"type"`
TTL string `json:"ttl,omitempty"`
}
// Diagnostic describes a single normalization or clamping event emitted
@@ -79,7 +90,8 @@ type SystemPromptPart struct {
Text string
// Cache requests that the prefix up to and including this part be cached.
// Anthropic-only; ignored elsewhere.
Cache bool
Cache bool
CacheControl *CacheControl
}
// ReasoningMode is the unified reasoning/thinking knob across providers.
@@ -130,7 +142,11 @@ type ChatRequest struct {
// CacheLastMessage requests that the final block of the final user
// message also be cache-marked. Anthropic-only; ignored elsewhere.
CacheLastMessage bool
Reasoning ReasoningMode // zero value = ReasoningOff; safe default
// CacheControl enables provider-level automatic prompt caching.
CacheControl *CacheControl
// SessionID is routing metadata only and is not sent to providers.
SessionID string
Reasoning ReasoningMode // zero value = ReasoningOff; safe default
}
// Usage tracks token usage.
@@ -143,12 +159,12 @@ type Usage struct {
// ChatEvent is a single streaming event from the LLM.
type ChatEvent struct {
Type EventType
Text string
ToolCall *ToolCall
Type EventType
Text string
ToolCall *ToolCall
ThinkingBlock *ThinkingBlock // populated on EventThinkingBlock
Usage *Usage
Error error
Usage *Usage
Error error
// StopReason carries the provider's terminal stop reason on EventDone
// ("end_turn", "tool_use", "max_tokens", "refusal", ...). Empty when
// the provider doesn't report one. StopReasonRefusal is the value the
+47 -16
View File
@@ -61,16 +61,18 @@ func (p *AnthropicProvider) buildMessageParams(req llm.ChatRequest) anthropic.Me
props = schema.Properties
required = schema.Required
}
tools = append(tools, anthropic.ToolUnionParam{
OfTool: &anthropic.ToolParam{
Name: t.Name,
Description: anthropic.String(t.Description),
InputSchema: anthropic.ToolInputSchemaParam{
Properties: props,
Required: required,
},
tool := anthropic.ToolParam{
Name: t.Name,
Description: anthropic.String(t.Description),
InputSchema: anthropic.ToolInputSchemaParam{
Properties: props,
Required: required,
},
})
}
if cacheRequested(t.CacheControl) {
tool.CacheControl = anthropicCacheControl(t.CacheControl)
}
tools = append(tools, anthropic.ToolUnionParam{OfTool: &tool})
}
maxTokens := int64(req.MaxTokens)
@@ -87,6 +89,9 @@ func (p *AnthropicProvider) buildMessageParams(req llm.ChatRequest) anthropic.Me
MaxTokens: maxTokens,
Messages: msgs,
}
if cacheRequested(req.CacheControl) {
params.CacheControl = anthropicCacheControl(req.CacheControl)
}
if len(tools) > 0 {
params.Tools = tools
}
@@ -526,7 +531,11 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
i-- // un-consume; outer loop will re-process
break
}
blocks = append(blocks, buildToolResultBlock(cur))
block := buildToolResultBlock(cur)
if cacheRequested(cur.CacheControl) {
setCacheControlOnBlock(&block, cur.CacheControl)
}
blocks = append(blocks, block)
}
msgs = append(msgs, anthropic.NewUserMessage(blocks...))
} else if len(m.Images) > 0 {
@@ -538,9 +547,16 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
if m.Content != "" {
blocks = append(blocks, anthropic.NewTextBlock(m.Content))
}
if cacheRequested(m.CacheControl) && len(blocks) > 0 {
setCacheControlOnBlock(&blocks[len(blocks)-1], m.CacheControl)
}
msgs = append(msgs, anthropic.NewUserMessage(blocks...))
} else {
msgs = append(msgs, anthropic.NewUserMessage(anthropic.NewTextBlock(m.Content)))
block := anthropic.NewTextBlock(m.Content)
if cacheRequested(m.CacheControl) {
setCacheControlOnBlock(&block, m.CacheControl)
}
msgs = append(msgs, anthropic.NewUserMessage(block))
}
case "assistant":
var blocks []anthropic.ContentBlockParamUnion
@@ -565,6 +581,9 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
blocks = append(blocks, anthropic.NewToolUseBlock(tc.ID, input, tc.Name))
}
if len(blocks) > 0 {
if cacheRequested(m.CacheControl) {
setCacheControlOnBlock(&blocks[len(blocks)-1], m.CacheControl)
}
msgs = append(msgs, anthropic.NewAssistantMessage(blocks...))
}
}
@@ -575,7 +594,7 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
if cacheLast && len(msgs) > 0 {
tail := &msgs[len(msgs)-1]
if len(tail.Content) > 0 {
setCacheControlOnBlock(&tail.Content[len(tail.Content)-1])
setCacheControlOnBlock(&tail.Content[len(tail.Content)-1], nil)
}
}
return msgs
@@ -587,8 +606,8 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
// so we mutate the variant struct directly. Variants other than text /
// tool_result / image / tool_use are out of scope; the runtime never
// produces them as the tail of a user message.
func setCacheControlOnBlock(block *anthropic.ContentBlockParamUnion) {
cc := anthropic.NewCacheControlEphemeralParam()
func setCacheControlOnBlock(block *anthropic.ContentBlockParamUnion, cache *llm.CacheControl) {
cc := anthropicCacheControl(cache)
switch {
case block.OfText != nil:
block.OfText.CacheControl = cc
@@ -650,8 +669,8 @@ func buildAnthropicSystem(req llm.ChatRequest) []anthropic.TextBlockParam {
continue
}
b := anthropic.TextBlockParam{Text: p.Text}
if p.Cache {
b.CacheControl = anthropic.NewCacheControlEphemeralParam()
if p.Cache || cacheRequested(p.CacheControl) {
b.CacheControl = anthropicCacheControl(p.CacheControl)
}
blocks = append(blocks, b)
}
@@ -665,3 +684,15 @@ func buildAnthropicSystem(req llm.ChatRequest) []anthropic.TextBlockParam {
}
return nil
}
func cacheRequested(cache *llm.CacheControl) bool {
return cache != nil && (cache.Type == "" || cache.Type == "ephemeral")
}
func anthropicCacheControl(cache *llm.CacheControl) anthropic.CacheControlEphemeralParam {
cc := anthropic.NewCacheControlEphemeralParam()
if cache != nil && cache.TTL != "" {
cc.TTL = anthropic.CacheControlEphemeralTTL(cache.TTL)
}
return cc
}
+61 -2
View File
@@ -10,9 +10,9 @@ import (
"testing"
anthropic "github.com/anthropics/anthropic-sdk-go"
"github.com/sausheong/harness/llm"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/sausheong/harness/llm"
)
// helper: extract tool_use IDs (in order) from an assistant MessageParam.
@@ -235,6 +235,65 @@ func TestAnthropicSystemPromptPartsEmitCacheControl(t *testing.T) {
require.Empty(t, string(got[1].CacheControl.Type), "second block must not be cache-marked")
}
func TestAnthropicCacheControlPreservesTTLAtEveryWireLocation(t *testing.T) {
cache1h := &llm.CacheControl{Type: "ephemeral", TTL: "1h"}
p := NewAnthropicProvider("test-key", "")
params := p.buildMessageParams(llm.ChatRequest{
Model: "claude-test",
MaxTokens: 10,
CacheControl: cache1h,
SystemPromptParts: []llm.SystemPromptPart{
{Text: "stable system", CacheControl: cache1h},
},
Tools: []llm.ToolDef{{
Name: "lookup", Parameters: json.RawMessage(`{"type":"object","properties":{}}`), CacheControl: cache1h,
}},
Messages: []llm.Message{{Role: "user", Content: "hello", CacheControl: cache1h}},
})
require.Equal(t, "ephemeral", string(params.CacheControl.Type))
require.Equal(t, "1h", string(params.CacheControl.TTL))
require.Len(t, params.System, 1)
require.Equal(t, "1h", string(params.System[0].CacheControl.TTL))
require.Len(t, params.Tools, 1)
require.NotNil(t, params.Tools[0].OfTool)
require.Equal(t, "1h", string(params.Tools[0].OfTool.CacheControl.TTL))
require.Len(t, params.Messages, 1)
messageCache := params.Messages[0].Content[0].GetCacheControl()
require.NotNil(t, messageCache)
require.Equal(t, "1h", string(messageCache.TTL))
}
func TestAnthropicCacheControlAppearsOnActualHTTPRequest(t *testing.T) {
bodyCh := make(chan map[string]any, 1)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
require.NoError(t, json.NewDecoder(r.Body).Decode(&body))
bodyCh <- body
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_1\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"claude-test\",\"usage\":{\"input_tokens\":1,\"output_tokens\":0}}}\n\nevent: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":1}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"))
}))
t.Cleanup(srv.Close)
cache := &llm.CacheControl{Type: "ephemeral", TTL: "1h"}
p := NewAnthropicProvider("test-key", srv.URL)
events, err := p.ChatStream(context.Background(), llm.ChatRequest{
Model: "claude-test", MaxTokens: 10, CacheControl: cache,
SystemPromptParts: []llm.SystemPromptPart{{Text: "system", CacheControl: cache}},
Tools: []llm.ToolDef{{Name: "lookup", Parameters: json.RawMessage(`{"type":"object","properties":{}}`), CacheControl: cache}},
Messages: []llm.Message{{Role: "user", Content: "hello", CacheControl: cache}},
})
require.NoError(t, err)
for range events {
}
body := <-bodyCh
require.Equal(t, "1h", body["cache_control"].(map[string]any)["ttl"])
require.Equal(t, "1h", body["system"].([]any)[0].(map[string]any)["cache_control"].(map[string]any)["ttl"])
require.Equal(t, "1h", body["tools"].([]any)[0].(map[string]any)["cache_control"].(map[string]any)["ttl"])
message := body["messages"].([]any)[0].(map[string]any)
require.Equal(t, "1h", message["content"].([]any)[0].(map[string]any)["cache_control"].(map[string]any)["ttl"])
}
func TestAnthropicSystemPromptStringFallback(t *testing.T) {
got := buildAnthropicSystem(llm.ChatRequest{SystemPrompt: "legacy"})
require.Len(t, got, 1)
@@ -544,7 +603,7 @@ func TestAdaptiveThinkingModels_EmitAdaptiveNotEnabled(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
models := []string{
"claude-fable-5",
"claude-fable-5-global", // LiteLLM / gateway model-group names
"claude-fable-5-global", // LiteLLM / gateway model-group names
"claude-mythos-5",
"claude-opus-4-7",
"claude-opus-4-8",