fix(apicompat): keep tool_use input a JSON object in buffered responses

A tool call whose arguments were not a JSON object (truncated by max_output_tokens, empty, or the free-form input of a custom_tool_call) made json.Marshal fail, so /v1/messages answered 200 with an empty body.
ResponsesToAnthropic now keeps an object as it is, uses {} for a function_call with anything else, and wraps a custom_tool_call input as {"input": ...}, the shape extractCustomToolCallInput reads back.
Both converters now render custom_tool_call items, which were dropped when the terminal output carried them.
The streaming converter is unchanged: it forwards the argument deltas as the upstream sent them.
This commit is contained in:
Anankke committed 2026-11-14 12:56:42 -08:00
1 parent b8f0e91b6b
commit 250deb70e5
5 files changed
+142 -5

No files matched your search

@@ -52,7 +52,14 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo
Type: "tool_use",
ID: fromResponsesCallID(item.CallID),
Name: item.Name,
Input: sanitizeAnthropicToolUseInput(item.Name, item.Arguments),
Input: anthropicToolUseInput(item.Type, item.Name, item.Arguments),
})
case "custom_tool_call":
blocks = append(blocks, AnthropicContentBlock{
Type: "tool_use",
ID: fromResponsesCallID(item.CallID),
Name: item.Name,
Input: anthropicToolUseInput(item.Type, item.Name, item.Input),
})
case "web_search_call":
toolUseID := "srvtoolu_" + item.ID
@@ -139,6 +146,25 @@ func containsAnthropicToolUseBlock(blocks []AnthropicContentBlock) bool {
return false
}
// anthropicToolUseInput returns the input of a non-streaming tool_use block,
// which must be a JSON object. An object is kept as it is. A function_call whose
// arguments are not an object (truncated by max_output_tokens, or empty) gets {};
// a custom_tool_call's free-form input is wrapped in the same {"input": ...}
// shape that downgrades a custom tool to a function tool, so that
// extractCustomToolCallInput gives the text back.
func anthropicToolUseInput(itemType, name, raw string) json.RawMessage {
if trimmed := strings.TrimSpace(raw); strings.HasPrefix(trimmed, "{") && json.Valid([]byte(trimmed)) {
return sanitizeAnthropicToolUseInput(name, raw)
}
if itemType == "custom_tool_call" {
wrapped, err := json.Marshal(map[string]string{"input": raw})
if err == nil {
return wrapped
}
}
return json.RawMessage("{}")
}
func sanitizeAnthropicToolUseInput(name string, raw string) json.RawMessage {
if name != "Read" || raw == "" {
return json.RawMessage(raw)
@@ -0,0 +1,68 @@
package apicompat
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
)
func TestAnthropicToolUseInput(t *testing.T) {
tests := []struct {
name string
itemType string
raw string
want string
}{
{"object kept", "function_call", "{\"a\":1}", "{\"a\":1}"},
{"object with padding kept", "function_call", " {\"a\": 1}\n", " {\"a\": 1}\n"},
{"truncated function arguments", "function_call", "{\"a\":1", "{}"},
{"empty function arguments", "function_call", "", "{}"},
{"non-object function arguments", "function_call", "[1]", "{}"},
{"custom input wrapped", "custom_tool_call", "dir /b", "{\"input\":\"dir /b\"}"},
{"empty custom input wrapped", "custom_tool_call", "", "{\"input\":\"\"}"},
{"custom input that is an object kept", "custom_tool_call", "{\"a\":1}", "{\"a\":1}"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := anthropicToolUseInput(tc.itemType, "exec", tc.raw)
require.Equal(t, tc.want, string(got))
require.True(t, json.Valid(got))
})
}
}
// The wrapper must round-trip through the helper that undoes the custom tool
// downgrade, including text that is itself valid JSON or has outer whitespace.
func TestAnthropicToolUseInputCustomRoundTrip(t *testing.T) {
for _, text := range []string{"dir", " padded text\n", "", "\"quoted\"", "[1,2]", "line1\nline2"} {
wrapped := anthropicToolUseInput("custom_tool_call", "exec", text)
require.Equal(t, text, extractCustomToolCallInput(string(wrapped)), text)
}
}
func TestResponsesToAnthropicInvalidToolInputStillMarshals(t *testing.T) {
resp := &ResponsesResponse{ID: "resp_1", Status: "incomplete", IncompleteDetails: &ResponsesIncompleteDetails{Reason: "max_output_tokens"}, Output: []ResponsesOutput{
{Type: "reasoning", Summary: []ResponsesSummary{{Type: "summary_text", Text: "plan"}}},
{Type: "function_call", CallID: "call_1", Name: "get", Arguments: "{\"a\":1"},
{Type: "custom_tool_call", CallID: "call_2", Name: "exec", Input: "dir"},
}}
out := ResponsesToAnthropic(resp, "m")
body, err := json.Marshal(out)
require.NoError(t, err)
require.Len(t, out.Content, 3)
require.Equal(t, "thinking", out.Content[0].Type)
require.Equal(t, "{}", string(out.Content[1].Input))
require.Equal(t, "{\"input\":\"dir\"}", string(out.Content[2].Input))
require.Equal(t, "max_tokens", *out.StopReason, string(body))
}
func TestResponsesToChatCompletionsRendersCustomToolCall(t *testing.T) {
resp := &ResponsesResponse{ID: "resp_1", Status: "completed", Output: []ResponsesOutput{
{Type: "custom_tool_call", CallID: "call_1", Name: "exec", Input: "dir"},
}}
out := ResponsesToChatCompletions(resp, "m")
require.Len(t, out.Choices[0].Message.ToolCalls, 1)
require.Equal(t, "dir", out.Choices[0].Message.ToolCalls[0].Function.Arguments)
require.Equal(t, "tool_calls", out.Choices[0].FinishReason)
}
@@ -56,6 +56,15 @@ func ResponsesToChatCompletions(resp *ResponsesResponse, model string) *ChatComp
Arguments: item.Arguments,
},
})
case "custom_tool_call":
toolCalls = append(toolCalls, ChatToolCall{
ID: item.CallID,
Type: "function",
Function: ChatFunctionCall{
Name: item.Name,
Arguments: item.Input,
},
})
case "reasoning":
reasoningText += responsesReasoningText(item)
case "web_search_call":
@@ -280,9 +280,8 @@ func (s *openAICompatOutputSlot) buildMessage() (apicompat.ResponsesOutput, bool
return item, s.done != nil || s.text.Len() > 0 || s.refusal.Len() > 0
}
// buildToolCall returns a function_call item. A custom_tool_call is returned in
// that form as well, with its input as the arguments, because that is the shape
// the Chat Completions and Messages converters render as a tool call.
// buildToolCall returns the function_call or custom_tool_call item of the slot,
// with the arguments or input a done item left empty taken from the deltas.
func (s *openAICompatOutputSlot) buildToolCall() (apicompat.ResponsesOutput, bool) {
if s.done == nil && s.added == nil {
return apicompat.ResponsesOutput{}, false
@@ -317,6 +316,10 @@ func (s *openAICompatOutputSlot) buildToolCall() (apicompat.ResponsesOutput, boo
if arguments == "" {
arguments = s.args.String()
}
item.Type, item.Input, item.Arguments = "function_call", "", arguments
if item.Type == "custom_tool_call" {
item.Input = arguments
} else {
item.Arguments = arguments
}
return item, true
}
@@ -405,3 +405,34 @@ func TestForwardAsAnthropic_CancelledTerminalKeepsHostedOutputItems(t *testing.T
bufferedItemsSSE(bufferedHostedItemsCreated, bufferedHostedItemsWebSearchDone, cancelled))
require.Equal(t, "server_tool_use", gjson.Get(out, "content.0.type").String(), out)
}
// A tool call whose arguments are not a JSON object must not empty the response:
// a truncated function call gets {}, a custom tool call its input wrapped.
func TestForwardAsAnthropic_BufferedNonObjectToolInput(t *testing.T) {
toolBody := `{"model":"gpt-5.5","max_tokens":64,"stream":false,"tools":[{"name":"get","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"hi"}]}`
truncated := bufferedItemsSSE(
bufferedHostedItemsCreated,
`{"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"plan"}]}}`,
`{"type":"response.output_item.added","output_index":1,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get","arguments":""}}`,
`{"type":"response.function_call_arguments.delta","output_index":1,"delta":"{\"a\":1"}`,
`{"type":"response.incomplete","response":{"id":"resp_1","status":"incomplete","incomplete_details":{"reason":"max_output_tokens"},"output":[]}}`,
)
out := forwardBufferedHostedItems(t, "/v1/messages", toolBody, truncated)
require.Equal(t, "thinking", gjson.Get(out, "content.0.type").String(), out)
require.Equal(t, "plan", gjson.Get(out, "content.0.thinking").String(), out)
require.Equal(t, "tool_use", gjson.Get(out, "content.1.type").String(), out)
require.Equal(t, "{}", gjson.Get(out, "content.1.input").Raw, out)
require.Equal(t, "max_tokens", gjson.Get(out, "stop_reason").String(), out)
custom := bufferedItemsSSE(
bufferedHostedItemsCreated,
`{"type":"response.output_item.added","output_index":0,"item":{"type":"custom_tool_call","id":"ctc_1","call_id":"call_1","name":"get","input":""}}`,
`{"type":"response.custom_tool_call_input.delta","output_index":0,"delta":"dir"}`,
`{"type":"response.output_item.done","output_index":0,"item":{"type":"custom_tool_call","id":"ctc_1","call_id":"call_1","name":"get","input":"dir"}}`,
bufferedHostedItemsCompleted,
)
out = forwardBufferedHostedItems(t, "/v1/messages", toolBody, custom)
require.Equal(t, "tool_use", gjson.Get(out, "content.0.type").String(), out)
require.Equal(t, `{"input":"dir"}`, gjson.Get(out, "content.0.input").Raw, out)
require.Equal(t, "tool_use", gjson.Get(out, "stop_reason").String(), out)
}