Support deferred tool loading in claude code (#19578)

This commit is contained in:
J Berg authored and GitHub committed 2026-11-12 13:24:56 -08:00
1 parent 4a7b194120
commit 361b3e17fd
6 files changed
+350 -29

No files matched your search

+104 -19
View File
@@ -180,6 +180,8 @@ type Tool struct {
Description string `json:"description,omitempty"`
InputSchema json.RawMessage `json:"input_schema,omitempty"`
DeferLoading bool `json:"defer_loading,omitempty"`
// Web search specific fields
MaxUses int `json:"max_uses,omitempty"`
}
@@ -349,8 +351,9 @@ func FromMessagesRequest(r MessagesRequest, thinking ...*model.Thinking) (*api.C
}
}
conv := newMessageConverter(r.Tools)
for i, msg := range r.Messages {
converted, err := convertMessage(msg)
converted, err := conv.convertMessage(msg)
if err != nil {
logutil.Trace("anthropic: message conversion failed", "index", i, "role", msg.Role, "err", err)
return nil, err
@@ -379,15 +382,15 @@ func FromMessagesRequest(r MessagesRequest, thinking ...*model.Thinking) (*api.C
}
var tools api.Tools
hasBuiltinWebSearch := false
for _, t := range r.Tools {
if strings.HasPrefix(t.Type, "web_search") {
hasBuiltinWebSearch = true
break
}
}
hasBuiltinWebSearch := hasToolType(r.Tools, "web_search")
honorDefer := !hasToolType(r.Tools, "tool_search_tool")
for _, t := range r.Tools {
if t.DeferLoading && honorDefer && !conv.loaded[t.Name] {
logutil.Trace("anthropic: deferred tool kept out of tool list", "tool", t.Name)
continue
}
// Anthropic built-in web_search maps to Ollama function name "web_search".
// If a user-defined tool also uses that name in the same request, drop the
// user-defined one to avoid ambiguous tool-call routing.
@@ -442,8 +445,32 @@ func FromMessagesRequest(r MessagesRequest, thinking ...*model.Thinking) (*api.C
return convertedRequest, nil
}
type messageConverter struct {
tools map[string]Tool
loaded map[string]bool
}
func newMessageConverter(tools []Tool) *messageConverter {
byName := make(map[string]Tool, len(tools))
for _, t := range tools {
if _, ok := byName[t.Name]; !ok {
byName[t.Name] = t
}
}
return &messageConverter{tools: byName, loaded: map[string]bool{}}
}
func hasToolType(tools []Tool, prefix string) bool {
for _, t := range tools {
if strings.HasPrefix(t.Type, prefix) {
return true
}
}
return false
}
// convertMessage converts an Anthropic MessageParam to Ollama api.Message(s)
func convertMessage(msg MessageParam) ([]api.Message, error) {
func (c *messageConverter) convertMessage(msg MessageParam) ([]api.Message, error) {
var messages []api.Message
role := strings.ToLower(msg.Role)
@@ -493,6 +520,7 @@ func convertMessage(msg MessageParam) ([]api.Message, error) {
logutil.Trace("anthropic: tool_use block missing name", "role", role)
return nil, errors.New("tool_use block missing required 'name' field")
}
c.loaded[block.Name] = true
toolCalls = append(toolCalls, api.ToolCall{
ID: block.ID,
Function: api.ToolCallFunction{
@@ -503,18 +531,31 @@ func convertMessage(msg MessageParam) ([]api.Message, error) {
case "tool_result":
toolResultBlocks++
resultContent, resultImages, err := convertToolResultContent(block.Content)
resultContent, resultImages, refs, err := convertToolResultContent(block.Content)
if err != nil {
logutil.Trace("anthropic: invalid tool_result content", "role", role, "error", err)
return nil, err
}
toolResults = append(toolResults, api.Message{
result := api.Message{
Role: "tool",
Content: resultContent,
Images: resultImages,
ToolCallID: block.ToolUseID,
})
}
if len(refs) > 0 {
defs, err := c.renderToolReferences(refs)
if err != nil {
logutil.Trace("anthropic: invalid tool_reference", "role", role, "error", err)
return nil, err
}
if resultContent == "" {
result.Content = defs
} else if defs != "" {
result.Content = resultContent + "\n\n" + defs
}
}
toolResults = append(toolResults, result)
case "thinking":
thinkingBlocks++
@@ -1040,15 +1081,16 @@ func resolveImageSource(source *ImageSource) (api.ImageData, error) {
return decoded, nil
}
func convertToolResultContent(content any) (string, []api.ImageData, error) {
func convertToolResultContent(content any) (string, []api.ImageData, []string, error) {
switch c := content.(type) {
case nil:
return "", nil, nil
return "", nil, nil, nil
case string:
return c, nil, nil
return c, nil, nil, nil
case []any:
var text strings.Builder
var images []api.ImageData
var refs []string
for _, cb := range c {
cbMap, ok := cb.(map[string]any)
@@ -1064,7 +1106,7 @@ func convertToolResultContent(content any) (string, []api.ImageData, error) {
case "image":
rawSource, ok := cbMap["source"].(map[string]any)
if !ok {
return "", nil, errors.New("invalid tool_result image source")
return "", nil, nil, errors.New("invalid tool_result image source")
}
var source ImageSource
@@ -1080,18 +1122,61 @@ func convertToolResultContent(content any) (string, []api.ImageData, error) {
img, err := resolveImageSource(&source)
if err != nil {
return "", nil, err
return "", nil, nil, err
}
images = append(images, img)
case "tool_reference":
if name, ok := cbMap["tool_name"].(string); ok && name != "" {
refs = append(refs, name)
}
}
}
return text.String(), images, nil
return text.String(), images, refs, nil
default:
return "", nil, nil
return "", nil, nil, nil
}
}
type toolSearchDefinition struct {
Type string `json:"type"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Parameters json.RawMessage `json:"parameters,omitempty"`
}
func (c *messageConverter) renderToolReferences(names []string) (string, error) {
defs := make([]toolSearchDefinition, 0, len(names))
for _, name := range names {
t, ok := c.tools[name]
if !ok {
logutil.Trace("anthropic: tool_reference names an undeclared tool", "tool", name)
continue
}
c.loaded[name] = true
def := toolSearchDefinition{Type: "function", Name: name, Description: t.Description}
if len(t.InputSchema) > 0 {
var b bytes.Buffer
if err := json.Compact(&b, t.InputSchema); err != nil {
return "", fmt.Errorf("invalid input_schema for tool %q: %w", name, err)
}
def.Parameters = b.Bytes()
}
defs = append(defs, def)
}
if len(defs) == 0 {
return "", nil
}
var out bytes.Buffer
enc := json.NewEncoder(&out)
enc.SetEscapeHTML(false)
if err := enc.Encode(defs); err != nil {
return "", err
}
return strings.TrimSuffix(out.String(), "\n"), nil
}
// ptr returns a pointer to the given string value
func ptr(s string) *string {
return &s
+4 -4
View File
@@ -1934,7 +1934,7 @@ func TestConvertMessage_ServerToolUse(t *testing.T) {
},
}
messages, err := convertMessage(msg)
messages, err := newMessageConverter(nil).convertMessage(msg)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -1975,7 +1975,7 @@ func TestConvertMessage_WebSearchToolResult(t *testing.T) {
},
}
messages, err := convertMessage(msg)
messages, err := newMessageConverter(nil).convertMessage(msg)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -2010,7 +2010,7 @@ func TestConvertMessage_WebSearchToolResultEmptyStillCreatesToolMessage(t *testi
},
}
messages, err := convertMessage(msg)
messages, err := newMessageConverter(nil).convertMessage(msg)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -2044,7 +2044,7 @@ func TestConvertMessage_WebSearchToolResultErrorStillCreatesToolMessage(t *testi
},
}
messages, err := convertMessage(msg)
messages, err := newMessageConverter(nil).convertMessage(msg)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
+173
View File
@@ -0,0 +1,173 @@
package anthropic
import (
"encoding/json"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/ollama/ollama/api"
)
const (
ccBashTool = `{"name":"Bash","description":"Run a shell command","input_schema":{"type":"object","properties":{"command":{"type":"string"}},"required":["command"]}}`
ccToolSearchTool = `{"name":"ToolSearch","description":"Load deferred tools","input_schema":{"type":"object","properties":{"query":{"type":"string"}},"required":["query"]}}`
ccPlaceholderTool = `{"name":"DeferredToolPlaceholder","description":"Reserved placeholder that keeps deferred tool loading active; never call this tool.","input_schema":{"type":"object","properties":{}},"defer_loading":true}`
ccMonitorTool = `{"name":"Monitor","description":"Watch a process; prints <lines> & exits","input_schema":{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"timeout_ms":{"type":"number"}},"required":["timeout_ms"]},"defer_loading":true}`
ccMonitorDefinition = `[{"type":"function","name":"Monitor","description":"Watch a process; prints <lines> & exits","parameters":{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"timeout_ms":{"type":"number"}},"required":["timeout_ms"]}}]`
)
func ccRequest(t *testing.T, tools, messages string) MessagesRequest {
t.Helper()
var req MessagesRequest
body := `{"model":"glm-5.3:cloud","max_tokens":1024,"stream":true,"tools":[` + tools + `],"messages":[` + messages + `]}`
if err := json.Unmarshal([]byte(body), &req); err != nil {
t.Fatalf("unmarshal request: %v", err)
}
return req
}
func ccPreLoad(t *testing.T) MessagesRequest {
return ccRequest(t, ccBashTool+","+ccToolSearchTool+","+ccPlaceholderTool,
`{"role":"user","content":"watch the build"}`)
}
func ccPostLoad(t *testing.T) MessagesRequest {
return ccRequest(t, ccBashTool+","+ccMonitorTool+","+ccToolSearchTool+","+ccPlaceholderTool,
`{"role":"user","content":"watch the build"},
{"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"ToolSearch","input":{"query":"select:Monitor"}}]},
{"role":"user","content":[
{"type":"tool_result","tool_use_id":"call_1","content":[{"type":"tool_reference","tool_name":"Monitor"}]},
{"type":"text","text":"Tool loaded."}]}`)
}
func toolNames(tools api.Tools) []string {
names := make([]string, 0, len(tools))
for _, tool := range tools {
names = append(names, tool.Function.Name)
}
return names
}
func toolMessage(t *testing.T, messages []api.Message) api.Message {
t.Helper()
for _, m := range messages {
if m.Role == "tool" {
return m
}
}
t.Fatalf("no tool message in %+v", messages)
return api.Message{}
}
func TestFromMessagesRequest_DeferredPlaceholderNotDeclared(t *testing.T) {
result, err := FromMessagesRequest(ccPreLoad(t))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if diff := cmp.Diff([]string{"Bash", "ToolSearch"}, toolNames(result.Tools)); diff != "" {
t.Errorf("declared tools mismatch (-want +got):\n%s", diff)
}
}
func TestFromMessagesRequest_ToolReferenceExpandsDefinition(t *testing.T) {
result, err := FromMessagesRequest(ccPostLoad(t))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(result.Messages) != 4 {
t.Fatalf("expected 4 messages, got %d: %+v", len(result.Messages), result.Messages)
}
tool := result.Messages[2]
if tool.Role != "tool" || tool.ToolCallID != "call_1" {
t.Fatalf("expected the ToolSearch result as message 2, got %+v", tool)
}
if tool.Content != ccMonitorDefinition {
t.Errorf("tool result content mismatch\nwant %s\ngot %s", ccMonitorDefinition, tool.Content)
}
if got := result.Messages[3]; got.Role != "user" || got.Content != "Tool loaded." {
t.Errorf("expected the sibling text as a user message, got %+v", got)
}
}
func TestFromMessagesRequest_ReferencedDeferredToolDeclaredByDefault(t *testing.T) {
result, err := FromMessagesRequest(ccPostLoad(t))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if diff := cmp.Diff([]string{"Bash", "Monitor", "ToolSearch"}, toolNames(result.Tools)); diff != "" {
t.Errorf("declared tools mismatch (-want +got):\n%s", diff)
}
}
func TestFromMessagesRequest_ToolReferenceUnknownTool(t *testing.T) {
req := ccRequest(t, ccToolSearchTool,
`{"role":"user","content":[{"type":"tool_result","tool_use_id":"call_1","content":[{"type":"tool_reference","tool_name":"Nope"}]}]}`)
result, err := FromMessagesRequest(req)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got := toolMessage(t, result.Messages).Content; got != "" {
t.Errorf("unexpected content: %s", got)
}
if diff := cmp.Diff([]string{"ToolSearch"}, toolNames(result.Tools)); diff != "" {
t.Errorf("declared tools mismatch (-want +got):\n%s", diff)
}
}
func TestFromMessagesRequest_DeferredToolCalledInHistoryStaysDeclared(t *testing.T) {
req := ccRequest(t, ccBashTool+","+ccMonitorTool+","+ccToolSearchTool+","+ccPlaceholderTool,
`{"role":"user","content":"watch the build"},
{"role":"assistant","content":[{"type":"tool_use","id":"call_2","name":"Monitor","input":{"timeout_ms":1000}}]},
{"role":"user","content":[{"type":"tool_result","tool_use_id":"call_2","content":"done"}]}`)
result, err := FromMessagesRequest(req)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if diff := cmp.Diff([]string{"Bash", "Monitor", "ToolSearch"}, toolNames(result.Tools)); diff != "" {
t.Errorf("declared tools mismatch (-want +got):\n%s", diff)
}
}
func TestFromMessagesRequest_ToolReferenceMixedWithText(t *testing.T) {
req := ccRequest(t, ccToolSearchTool+","+ccMonitorTool,
`{"role":"user","content":[{"type":"tool_result","tool_use_id":"call_1","content":[
{"type":"text","text":"Found 1 tool."},{"type":"tool_reference","tool_name":"Monitor"}]}]}`)
result, err := FromMessagesRequest(req)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
tool := toolMessage(t, result.Messages)
if want := "Found 1 tool.\n\n" + ccMonitorDefinition; tool.Content != want {
t.Errorf("content mismatch\nwant %q\ngot %q", want, tool.Content)
}
if diff := cmp.Diff([]string{"ToolSearch", "Monitor"}, toolNames(result.Tools)); diff != "" {
t.Errorf("declared tools mismatch (-want +got):\n%s", diff)
}
}
func TestFromMessagesRequest_ServerToolSearchKeepsDeferredTools(t *testing.T) {
req := ccRequest(t, `{"type":"tool_search_tool_regex_20251119","name":"tool_search_tool_regex"},`+ccMonitorTool,
`{"role":"user","content":"hi"}`)
result, err := FromMessagesRequest(req)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if diff := cmp.Diff([]string{"tool_search_tool_regex", "Monitor"}, toolNames(result.Tools)); diff != "" {
t.Errorf("declared tools mismatch (-want +got):\n%s", diff)
}
}
func TestFromMessagesRequest_InvalidDeferredToolSchema(t *testing.T) {
req := ccPostLoad(t)
for i := range req.Tools {
if req.Tools[i].Name == "Monitor" {
req.Tools[i].InputSchema = json.RawMessage(`{"type":`)
}
}
if _, err := FromMessagesRequest(req); err == nil {
t.Fatal("expected an error for an invalid input_schema on a referenced tool")
}
}
+6 -5
View File
@@ -211,11 +211,12 @@ func traceTools(tools []Tool) []map[string]any {
// TraceTool returns a compact trace representation of an Anthropic Tool.
func TraceTool(t Tool) map[string]any {
return map[string]any{
"type": t.Type,
"name": t.Name,
"description": TraceTruncateString(t.Description),
"input_schema": TraceJSON(t.InputSchema),
"max_uses": t.MaxUses,
"type": t.Type,
"name": t.Name,
"description": TraceTruncateString(t.Description),
"input_schema": TraceJSON(t.InputSchema),
"defer_loading": t.DeferLoading,
"max_uses": t.MaxUses,
}
}
+2 -1
View File
@@ -293,7 +293,7 @@ See the [Claude Code guide](/integrations/claude-code) for Ollama Launch and [di
- [x] Image `content` (base64)
- [x] Array of content blocks
- [x] `tool_use` blocks
- [x] `tool_result` blocks
- [x] `tool_result` blocks (including `tool_reference` blocks from client-side tool search)
- [x] `thinking` blocks
- [x] `system` (string or array)
- [x] `stream`
@@ -302,6 +302,7 @@ See the [Claude Code guide](/integrations/claude-code) for Ollama Launch and [di
- [x] `top_k`
- [x] `stop_sequences`
- [x] `tools`
- [x] `defer_loading` (a deferred tool is offered to the model only after a `tool_reference` loads it)
- [x] `thinking`
- [x] `output_config`
- [x] `effort` (model-defined names)
+61
View File
@@ -3090,3 +3090,64 @@ func containsString(values []string, target string) bool {
}
return false
}
func TestAnthropicMessagesMiddleware_DeferredToolLoad(t *testing.T) {
body := `{
"model": "test-model",
"max_tokens": 1024,
"tools": [
{"name": "Bash", "input_schema": {"type": "object", "properties": {"command": {"type": "string"}}}},
{"name": "Monitor", "description": "Watch a process", "input_schema": {"type": "object", "properties": {"timeout_ms": {"type": "number"}}}, "defer_loading": true},
{"name": "ToolSearch", "input_schema": {"type": "object", "properties": {"query": {"type": "string"}}}},
{"name": "DeferredToolPlaceholder", "description": "never call this tool", "input_schema": {"type": "object", "properties": {}}, "defer_loading": true}
],
"messages": [
{"role": "user", "content": "watch the build"},
{"role": "assistant", "content": [{"type": "tool_use", "id": "call_1", "name": "ToolSearch", "input": {"query": "select:Monitor"}}]},
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "call_1", "content": [{"type": "tool_reference", "tool_name": "Monitor"}]},
{"type": "text", "text": "Tool loaded."}
]}
]
}`
var captured *api.ChatRequest
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(AnthropicMessagesMiddleware(), captureAnthropicRequest(&captured))
router.Handle(http.MethodPost, "/v1/messages", func(c *gin.Context) { c.Status(http.StatusOK) })
req, _ := http.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
resp := httptest.NewRecorder()
router.ServeHTTP(resp, req)
if resp.Code != http.StatusOK {
t.Fatalf("unexpected status %d: %s", resp.Code, resp.Body.String())
}
if captured == nil {
t.Fatal("request was not captured")
}
var names []string
for _, tool := range captured.Tools {
names = append(names, tool.Function.Name)
}
if diff := cmp.Diff([]string{"Bash", "Monitor", "ToolSearch"}, names); diff != "" {
t.Errorf("declared tools mismatch (-want +got):\n%s", diff)
}
want := `[{"type":"function","name":"Monitor","description":"Watch a process","parameters":{"type":"object","properties":{"timeout_ms":{"type":"number"}}}}]`
var found bool
for _, m := range captured.Messages {
if m.Role == "tool" && m.ToolCallID == "call_1" {
found = true
if m.Content != want {
t.Errorf("tool result content mismatch\nwant %s\ngot %s", want, m.Content)
}
}
}
if !found {
t.Fatalf("no ToolSearch result in %+v", captured.Messages)
}
}