Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions intercept_anthropic_messages_base.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package aibridge

import (
"fmt"
"net/http"
"net/http/httputil"
"strings"

"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
"github.com/coder/aibridge/mcp"
"github.com/google/uuid"

Expand Down Expand Up @@ -44,6 +48,16 @@ func (i *AnthropicMessagesInterceptionBase) injectTools() {
return
}

// Any existing tool definitions.
for _, tool := range i.req.Tools {
if tool.OfTool == nil {
continue
}

// Explicitly unset all cache control settings, we'll set one at the end.
tool.OfTool.CacheControl = anthropic.CacheControlEphemeralParam{}
}

// Inject tools.
for _, tool := range i.mcpProxy.ListTools() {
i.req.Tools = append(i.req.Tools, anthropic.ToolUnionParam{
Expand All @@ -55,10 +69,18 @@ func (i *AnthropicMessagesInterceptionBase) injectTools() {
Name: tool.ID,
Description: anthropic.String(tool.Description),
Type: anthropic.ToolTypeCustom,
// Explicitly unset all cache control settings, we'll set one at the end.
CacheControl: anthropic.CacheControlEphemeralParam{},
},
})
}

// See https://docs.claude.com/en/docs/build-with-claude/prompt-caching.
// "The cache_control parameter on the last tool definition caches all tool definitions."
if count := len(i.req.Tools); count > 0 {
i.req.Tools[count-1].OfTool.CacheControl = anthropic.NewCacheControlEphemeralParam()
}

// Note: Parallel tool calls are disabled to avoid tool_use/tool_result block mismatches.
i.req.ToolChoice = anthropic.ToolChoiceUnionParam{
OfAny: &anthropic.ToolChoiceAnyParam{
Expand Down
14 changes: 14 additions & 0 deletions intercept_anthropic_messages_streaming.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,20 @@ func (i *AnthropicMessagesStreamingInterception) ProcessRequest(w http.ResponseW
return fmt.Errorf("developer error: req is nil")
}

// Explicitly unset any cache control markers on "assistant" messages; these should never be set
// since it's more beneficial for us to cache tool definitions, and Anthropic only allows for 4
// cache markers...
// https://docs.claude.com/en/docs/build-with-claude/prompt-caching#when-to-use-multiple-breakpoints
for _, msg := range i.req.Messages {
if msg.Role == anthropic.MessageParamRoleAssistant {
for _, c := range msg.Content {
if c.OfText != nil {
c.OfText.CacheControl = anthropic.CacheControlEphemeralParam{}
}
}
}
}

// Allow us to interrupt watch via cancel.
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
Expand Down