3 Commits
9 changed files with 281 additions and 42 deletions

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")
}
+46 -16
View File
@@ -17,6 +17,9 @@ const (
EventToolCallDone
EventDone
EventError
// EventThinkingBlock is emitted when the model returns an extended-thinking
// block. The runtime must echo these back in subsequent turns verbatim.
EventThinkingBlock
)
// ImageContent holds image data for multimodal messages.
@@ -26,13 +29,26 @@ type ImageContent struct {
}
// Message represents a conversation message.
// ThinkingBlock holds an opaque thinking/reasoning block returned by models
// that support extended thinking (e.g. Anthropic with thinking enabled,
// DeepSeek-v4-pro). The Signature field is the provider-supplied integrity
// token that must be echoed back verbatim in subsequent turns.
type ThinkingBlock struct {
Thinking string `json:"thinking"`
Signature string `json:"signature,omitempty"`
}
type Message struct {
Role string `json:"role"` // "user", "assistant", "system"
Content string `json:"content,omitempty"`
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
Role string `json:"role"` // "user", "assistant", "system"
Content string `json:"content,omitempty"`
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
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.
@@ -44,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
@@ -66,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.
@@ -117,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.
@@ -130,11 +159,12 @@ type Usage struct {
// ChatEvent is a single streaming event from the LLM.
type ChatEvent struct {
Type EventType
Text string
ToolCall *ToolCall
Usage *Usage
Error error
Type EventType
Text string
ToolCall *ToolCall
ThinkingBlock *ThinkingBlock // populated on EventThinkingBlock
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
+90 -18
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
}
@@ -171,6 +176,8 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
var pendingTools []pendingTC
var currentBlockType string
var inputTokens, cacheCreationTokens, cacheReadTokens int64
var pendingThinking strings.Builder
var pendingThinkingSignature string
for stream.Next() {
event := stream.Current()
@@ -187,6 +194,10 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
switch cb.Type {
case "text":
currentBlockType = "text"
case "thinking":
currentBlockType = "thinking"
pendingThinking.Reset()
pendingThinkingSignature = ""
case "tool_use":
currentBlockType = "tool_use"
pending := pendingTC{
@@ -219,6 +230,10 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
Type: llm.EventTextDelta,
Text: delta.Text,
}
case "thinking_delta":
pendingThinking.WriteString(delta.Thinking)
case "signature_delta":
pendingThinkingSignature += delta.Signature
case "input_json_delta":
if len(pendingTools) > 0 {
pendingTools[len(pendingTools)-1].inputJSON.WriteString(delta.PartialJSON)
@@ -226,6 +241,17 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
}
case "content_block_stop":
if currentBlockType == "thinking" {
events <- llm.ChatEvent{
Type: llm.EventThinkingBlock,
ThinkingBlock: &llm.ThinkingBlock{
Thinking: pendingThinking.String(),
Signature: pendingThinkingSignature,
},
}
pendingThinking.Reset()
pendingThinkingSignature = ""
}
if currentBlockType == "tool_use" && len(pendingTools) > 0 {
// Index in place rather than copying the element: the
// pendingTC holds a strings.Builder, which must not be
@@ -314,8 +340,8 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
// mid-flight; the partial output of the failed stream is discarded so
// the prompt cache prefix on the next turn stays byte-identical.
//
// Note: thinking blocks (when reasoning is enabled) are NOT surfaced —
// matches the streaming path which also doesn't emit thinking deltas.
// Thinking blocks are surfaced as EventThinkingBlock events so the runtime
// can store and echo them back in subsequent turns.
// Tool-use input is converted to JSON via the SDK's RawJSON field.
func (p *AnthropicProvider) ChatNonStreaming(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
params := p.buildMessageParams(req)
@@ -329,6 +355,16 @@ func (p *AnthropicProvider) ChatNonStreaming(ctx context.Context, req llm.ChatRe
defer close(events)
for _, block := range msg.Content {
switch block.Type {
case "thinking":
if block.Thinking != "" || block.Signature != "" {
events <- llm.ChatEvent{
Type: llm.EventThinkingBlock,
ThinkingBlock: &llm.ThinkingBlock{
Thinking: block.Thinking,
Signature: block.Signature,
},
}
}
case "text":
if block.Text != "" {
events <- llm.ChatEvent{Type: llm.EventTextDelta, Text: block.Text}
@@ -495,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 {
@@ -507,12 +547,29 @@ 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
// Thinking blocks must come first, before text and tool_use.
for _, tb := range m.ThinkingBlocks {
blocks = append(blocks, anthropic.ContentBlockParamUnion{
OfThinking: &anthropic.ThinkingBlockParam{
Type: "thinking",
Thinking: tb.Thinking,
Signature: tb.Signature,
},
})
}
if m.Content != "" {
blocks = append(blocks, anthropic.NewTextBlock(m.Content))
}
@@ -524,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...))
}
}
@@ -534,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
@@ -546,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
@@ -609,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)
}
@@ -624,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",
+9
View File
@@ -212,6 +212,15 @@ func assembleMessages(history []session.SessionEntry) []llm.Message {
Role: entry.Role,
Content: md.Text,
}
// Restore thinking blocks for assistant messages (must be echoed back).
if entry.Role == "assistant" {
for _, tb := range md.ThinkingBlocks {
msg.ThinkingBlocks = append(msg.ThinkingBlocks, llm.ThinkingBlock{
Thinking: tb.Thinking,
Signature: tb.Signature,
})
}
}
// Convert session images to LLM image content
if entry.Role == "user" {
for _, img := range md.Images {
+16 -2
View File
@@ -531,6 +531,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
var textContent strings.Builder
var toolCalls []llm.ToolCall
var thinkingBlocks []session.ThinkingBlockData
gotFirstToken := false
streamingOn := r.streamingToolsEnabled()
@@ -562,6 +563,14 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}
r.emit(AgentEvent{Type: EventToolCallStart, ToolCall: event.ToolCall})
case llm.EventThinkingBlock:
if event.ThinkingBlock != nil {
thinkingBlocks = append(thinkingBlocks, session.ThinkingBlockData{
Thinking: event.ThinkingBlock.Thinking,
Signature: event.ThinkingBlock.Signature,
})
}
case llm.EventToolCallDone:
if event.ToolCall == nil {
continue
@@ -696,8 +705,13 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
"text_chars", textContent.Len(),
"tool_calls", len(toolCalls))
if textContent.Len() > 0 {
r.Session.Append(session.AssistantMessageEntry(textContent.String()))
if textContent.Len() > 0 || len(thinkingBlocks) > 0 {
if len(thinkingBlocks) > 0 {
r.Session.Append(session.AssistantMessageEntryWithThinking(textContent.String(), thinkingBlocks))
} else {
r.Session.Append(session.AssistantMessageEntry(textContent.String()))
}
thinkingBlocks = nil
if r.KG != nil {
r.kgMu.Lock()
thread = append(thread, Message{
+14 -2
View File
@@ -112,6 +112,7 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag
var textContent strings.Builder
var toolCalls []llm.ToolCall
var thinkingBlocks []session.ThinkingBlockData
var lastUsage *llm.Usage
retriedRefusal := false
streamLoop:
@@ -125,6 +126,13 @@ streamLoop:
emit(AgentEvent{Type: EventTextDelta, Text: event.Text})
case llm.EventToolCallStart:
emit(AgentEvent{Type: EventToolCallStart, ToolCall: event.ToolCall})
case llm.EventThinkingBlock:
if event.ThinkingBlock != nil {
thinkingBlocks = append(thinkingBlocks, session.ThinkingBlockData{
Thinking: event.ThinkingBlock.Thinking,
Signature: event.ThinkingBlock.Signature,
})
}
case llm.EventToolCallDone:
if event.ToolCall != nil {
toolCalls = append(toolCalls, *event.ToolCall)
@@ -170,8 +178,12 @@ streamLoop:
break streamLoop
}
if textContent.Len() > 0 {
r.Session.Append(session.AssistantMessageEntry(textContent.String()))
if textContent.Len() > 0 || len(thinkingBlocks) > 0 {
if len(thinkingBlocks) > 0 {
r.Session.Append(session.AssistantMessageEntryWithThinking(textContent.String(), thinkingBlocks))
} else {
r.Session.Append(session.AssistantMessageEntry(textContent.String()))
}
}
if len(toolCalls) == 0 {
+21 -2
View File
@@ -36,10 +36,18 @@ type ImageData struct {
Data string `json:"data"` // base64-encoded
}
// ThinkingBlockData stores a thinking block from a model response.
// It must be echoed back verbatim in subsequent turns.
type ThinkingBlockData struct {
Thinking string `json:"thinking"`
Signature string `json:"signature,omitempty"`
}
// MessageData holds text message content.
type MessageData struct {
Text string `json:"text"`
Images []ImageData `json:"images,omitempty"`
Text string `json:"text"`
Images []ImageData `json:"images,omitempty"`
ThinkingBlocks []ThinkingBlockData `json:"thinking_blocks,omitempty"`
}
// ToolCallData holds a tool call's details.
@@ -338,6 +346,17 @@ func AssistantMessageEntry(text string) SessionEntry {
}
}
// AssistantMessageEntryWithThinking creates an assistant message entry that
// includes thinking blocks which must be echoed back in subsequent turns.
func AssistantMessageEntryWithThinking(text string, blocks []ThinkingBlockData) SessionEntry {
data, _ := json.Marshal(MessageData{Text: text, ThinkingBlocks: blocks})
return SessionEntry{
Type: EntryTypeMessage,
Role: "assistant",
Data: data,
}
}
// ToolCallEntry creates a tool call entry.
//
// input is sanitised to "{}" when empty or not valid JSON. The