From 2023ea48431660814914128113724ead08492857 Mon Sep 17 00:00:00 2001 From: guyu233 Date: Wed, 25 Nov 2026 19:55:16 +0800 Subject: [PATCH 1/3] fix(gateway): repair damaged tool-call arguments instead of failing the round --- .../unreleased/tool-call-arguments-repair.md | 11 + internal/gateway/anthropic.go | 9 +- internal/gateway/compat.go | 13 +- internal/gateway/compat_stream.go | 165 ++++++++++++--- internal/gateway/toolargs_stream_test.go | 114 ++++++++++ internal/translate/toolargs.go | 195 ++++++++++++++++++ internal/translate/toolargs_test.go | 41 ++++ 7 files changed, 516 insertions(+), 32 deletions(-) create mode 100644 changelog/unreleased/tool-call-arguments-repair.md create mode 100644 internal/gateway/toolargs_stream_test.go create mode 100644 internal/translate/toolargs.go create mode 100644 internal/translate/toolargs_test.go diff --git a/changelog/unreleased/tool-call-arguments-repair.md b/changelog/unreleased/tool-call-arguments-repair.md new file mode 100644 index 00000000..c32fbba0 --- /dev/null +++ b/changelog/unreleased/tool-call-arguments-repair.md @@ -0,0 +1,11 @@ +### English + +- Tool calls: stop dropping or failing on argument text that is only formatting-damaged. Trailing commas, bare quotes inside a value, missing closing brackets, and prose appended after the object are now repaired before a call is validated, on `/v1/responses`, `/v1/messages`, and the OpenAI compatibility paths. +- Streaming assembly no longer mangles arguments when an upstream resends the whole argument buffer on each chunk, omits `index`, reports `index` 0 for every call, or sends a JSON object where the schema expects a string. Those cases previously produced `{"a":1}{"a":1}` or silently lost fragments, which clients report as "arguments are invalid JSON". +- Arguments genuinely cut mid-string (output-token limit) are still rejected instead of being padded into a valid-looking command, and the error now says the model hit its token limit. + +### 中文 + +- 工具调用:参数文本只是格式损坏时不再丢弃或直接报错。结尾多余逗号、值内部裸引号、缺少闭合括号、对象后面跟了一段解释文字,都会先修复再校验,覆盖 `/v1/responses`、`/v1/messages` 和 OpenAI 兼容路径。 +- 流式拼接不再被上游的坏习惯整坏:上游每帧重发完整参数缓冲、省略 `index`、所有调用都写 `index:0`、或者该给字符串却给了 JSON 对象,以前会拼出 `{"a":1}{"a":1}` 或静默丢片段,客户端那边就报「arguments are invalid JSON」。 +- 真被输出 token 上限截断在字符串中间的参数仍然报错(不会补成看起来合法、实际却不是模型本意的命令),并在错误里说明是触到 token 上限。 diff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.go index f45ff9ea..aa510d7f 100644 --- a/internal/gateway/anthropic.go +++ b/internal/gateway/anthropic.go @@ -197,9 +197,14 @@ func anthropicMessageResponse(requestID, model, content, reasoning string, toolC blocks = append(blocks, map[string]any{"type": "text", "text": content}) } for _, call := range toolCalls { - input := json.RawMessage(call.Arguments) + arguments := strings.TrimSpace(call.Arguments) + input := json.RawMessage(arguments) if !json.Valid(input) { - input = json.RawMessage(`{}`) + if repaired, ok := translate.RepairToolCallArguments(arguments); ok { + input = json.RawMessage(repaired) + } else { + input = json.RawMessage(`{}`) + } } blocks = append(blocks, map[string]any{"type": "tool_use", "id": call.ID, "name": call.Name, "input": input}) } diff --git a/internal/gateway/compat.go b/internal/gateway/compat.go index 77b7b39f..bd56bf7a 100644 --- a/internal/gateway/compat.go +++ b/internal/gateway/compat.go @@ -65,7 +65,11 @@ func decodeOpenAIToolCalls(raw json.RawMessage) []proxyToolCall { arguments = "{}" } if _, _, custom := translate.DecodeCustomToolName(call.Function.Name); !custom && !json.Valid([]byte(arguments)) { - continue + repaired, ok := translate.RepairToolCallArguments(arguments) + if !ok { + continue + } + arguments = repaired } calls = append(calls, proxyToolCall{ID: call.ID, Name: call.Function.Name, Arguments: arguments}) } @@ -84,7 +88,12 @@ func validateProxyToolCallArguments(calls []proxyToolCall) error { continue } if !json.Valid([]byte(arguments)) { - return fmt.Errorf("tool call %q (%s) arguments are invalid JSON", call.ID, call.Name) + repaired, ok := translate.RepairToolCallArguments(arguments) + if !ok { + return fmt.Errorf("tool call %q (%s) arguments are invalid JSON", call.ID, call.Name) + } + call.Arguments = repaired + continue } call.Arguments = arguments } diff --git a/internal/gateway/compat_stream.go b/internal/gateway/compat_stream.go index 982da19d..8f3bb361 100644 --- a/internal/gateway/compat_stream.go +++ b/internal/gateway/compat_stream.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "io" + "log" "net/http" "sort" "strings" @@ -114,6 +115,9 @@ type streamedChatOutput struct { reasoning strings.Builder toolCalls map[int]*proxyToolCall finishReason string + // resolved maps a chunk's tool_call position to the call index it belongs + // to, so converters can reuse the same grouping the accumulator chose. + resolved []int } func (o *streamedChatOutput) add(payload json.RawMessage) { @@ -124,11 +128,11 @@ func (o *streamedChatOutput) add(payload json.RawMessage) { Content string `json:"content"` ReasoningContent string `json:"reasoning_content"` ToolCalls []struct { - Index int `json:"index"` + Index *int `json:"index"` ID string `json:"id"` Function struct { - Name string `json:"name"` - Arguments string `json:"arguments"` + Name string `json:"name"` + Arguments json.RawMessage `json:"arguments"` } `json:"function"` } `json:"tool_calls"` } `json:"delta"` @@ -137,6 +141,8 @@ func (o *streamedChatOutput) add(payload json.RawMessage) { if json.Unmarshal(payload, &chunk) != nil { return } + o.resolved = o.resolved[:0] + lastIndex := -1 for _, choice := range chunk.Choices { if choice.FinishReason != "" { o.finishReason = choice.FinishReason @@ -151,10 +157,8 @@ func (o *streamedChatOutput) add(payload json.RawMessage) { if o.toolCalls == nil { o.toolCalls = map[int]*proxyToolCall{} } - index := delta.Index - if index == 0 && callPosition > 0 { - index = callPosition - } + index := o.resolveToolCallIndex(delta.Index, delta.ID, delta.Function.Name, callPosition, lastIndex) + lastIndex = index call := o.toolCalls[index] if call == nil { call = &proxyToolCall{} @@ -166,9 +170,88 @@ func (o *streamedChatOutput) add(payload json.RawMessage) { if delta.Function.Name != "" { call.Name = delta.Function.Name } - call.Arguments += delta.Function.Arguments + call.Arguments = mergeToolArguments(call.Arguments, argumentFragment(delta.Function.Arguments)) + o.resolved = append(o.resolved, index) + } + } +} + +// resolveToolCallIndex keeps fragments with one call together. Upstreams that +// omit `index` either keep streaming the same call (no id/name, fold into +// the previous one) or start a new call (id or name present, next slot). +func (o *streamedChatOutput) resolveToolCallIndex(declared *int, id, name string, position, lastIndex int) int { + startsCall := id != "" || name != "" + switch { + case declared != nil && *declared > 0: + return *declared + case declared != nil && !startsCall: + return *declared + case declared != nil && startsCall: + if existing := o.toolCalls[*declared]; existing != nil && existing.Name != "" && existing.Name != name { + return maxToolCallIndex(o.toolCalls) + 1 + } + return *declared + case startsCall: + if position == 0 { + if existing := o.toolCalls[0]; existing == nil || existing.Name == "" || existing.Name == name { + return 0 + } + } + return maxToolCallIndex(o.toolCalls) + 1 + case lastIndex >= 0: + return lastIndex + default: + return position + } +} + +func maxToolCallIndex(calls map[int]*proxyToolCall) int { + maximum := -1 + for index := range calls { + if index > maximum { + maximum = index } } + return maximum +} + +// argumentFragment normalizes the arguments field of a stream delta. Some +// upstreams send a JSON object where the OpenAI schema expects a string; a +// strict `string` decode would drop the whole chunk, content included. +func argumentFragment(raw json.RawMessage) string { + if len(raw) == 0 || string(raw) == "null" { + return "" + } + var text string + if json.Unmarshal(raw, &text) == nil { + return text + } + var value any + if json.Unmarshal(raw, &value) == nil { + if encoded, err := json.Marshal(value); err == nil { + return string(encoded) + } + } + return "" +} + +// mergeToolArguments appends a delta fragment, but tolerates upstreams that +// resend the whole argument buffer (or its tail) on every chunk — concatenating +// those blindly is what produces `{"a":1}{"a":1}` and an invalid tool call. +func mergeToolArguments(base, fragment string) string { + if fragment == "" { + return base + } + if base == "" { + return fragment + } + if len(fragment) > len(base) && strings.HasPrefix(fragment, base) { + return fragment + } + if len(fragment) >= 8 && strings.HasSuffix(base, fragment) { + return base + } + return base + fragment } func (o *streamedChatOutput) calls() []proxyToolCall { @@ -261,6 +344,7 @@ func RelayAnthropicStream(writer io.Writer, body io.Reader, requestID, model str thinkingStarted := false thinkingBlockIndex := -1 toolBlocks := map[int]int{} + toolArgumentLengths := map[int]int{} nextBlock := 0 closeThinking := func() error { if !thinkingStarted { @@ -289,11 +373,11 @@ func RelayAnthropicStream(writer io.Writer, body io.Reader, requestID, model str Content string `json:"content"` ReasoningContent string `json:"reasoning_content"` ToolCalls []struct { - Index int `json:"index"` + Index *int `json:"index"` ID string `json:"id"` Function struct { - Name string `json:"name"` - Arguments string `json:"arguments"` + Name string `json:"name"` + Arguments json.RawMessage `json:"arguments"` } `json:"function"` } `json:"tool_calls"` } `json:"delta"` @@ -336,9 +420,9 @@ func RelayAnthropicStream(writer io.Writer, body io.Reader, requestID, model str if err := closeThinking(); err != nil { return err } - index := delta.Index - if index == 0 && callPosition > 0 { - index = callPosition + index, ok := resolvedCallIndex(current, callPosition) + if !ok { + continue } blockIndex, exists := toolBlocks[index] if !exists && delta.Function.Name != "" { @@ -359,11 +443,18 @@ func RelayAnthropicStream(writer io.Writer, body io.Reader, requestID, model str } exists = true } - if exists && delta.Function.Arguments != "" { - if err := writeSSEEvent(writer, "content_block_delta", map[string]any{"type": "content_block_delta", "index": blockIndex, "delta": map[string]string{"type": "input_json_delta", "partial_json": delta.Function.Arguments}}); err != nil { - return err - } + if !exists { + continue + } + accumulated := accumulatedToolArguments(current, index) + emitted := toolArgumentLengths[index] + if len(accumulated) <= emitted { + continue + } + if err := writeSSEEvent(writer, "content_block_delta", map[string]any{"type": "content_block_delta", "index": blockIndex, "delta": map[string]string{"type": "input_json_delta", "partial_json": accumulated[emitted:]}}); err != nil { + return err } + toolArgumentLengths[index] = len(accumulated) } } return nil @@ -454,11 +545,11 @@ func RelayResponsesStream(writer io.Writer, body io.Reader, requestID, model str Content string `json:"content"` ReasoningContent string `json:"reasoning_content"` ToolCalls []struct { - Index int `json:"index"` + Index *int `json:"index"` ID string `json:"id"` Function struct { - Name string `json:"name"` - Arguments string `json:"arguments"` + Name string `json:"name"` + Arguments json.RawMessage `json:"arguments"` } `json:"function"` } `json:"tool_calls"` } `json:"delta"` @@ -505,9 +596,9 @@ func RelayResponsesStream(writer io.Writer, body io.Reader, requestID, model str } } for callPosition, delta := range choice.Delta.ToolCalls { - index := delta.Index - if index == 0 && callPosition > 0 { - index = callPosition + index, ok := resolvedCallIndex(current, callPosition) + if !ok { + continue } if err := closeReasoning(); err != nil { return err @@ -537,10 +628,7 @@ func RelayResponsesStream(writer io.Writer, body io.Reader, requestID, model str toolAnnounced[index] = true } if toolAnnounced[index] { - accumulated := "" - if currentCall := current.toolCalls[index]; currentCall != nil { - accumulated = currentCall.Arguments - } + accumulated := accumulatedToolArguments(current, index) emitted := toolArgumentLengths[index] if len(accumulated) > emitted { deltaPayload := map[string]any{"type": "response.function_call_arguments.delta", "output_index": toolOutputIndexes[index], "item_id": fmt.Sprintf("fc_%s_%d", requestID, index), "call_id": toolCallIDs[index], "name": toolCallNames[index], "delta": accumulated[emitted:]} @@ -569,6 +657,10 @@ func RelayResponsesStream(writer io.Writer, body io.Reader, requestID, model str content := output.content.String() calls := output.calls() if err := validateProxyToolCallArguments(calls); err != nil { + log.Printf("tool call arguments unusable request_id=%q model=%q finish_reason=%q err=%v", requestID, model, output.finishReason, err) + if output.finishReason == "length" { + return stats, fmt.Errorf("%w (the model hit its output-token limit mid-arguments)", err) + } return stats, err } if textStarted { @@ -648,6 +740,23 @@ func RelayResponsesStream(writer io.Writer, body io.Reader, requestID, model str return stats, nil } +func resolvedCallIndex(output *streamedChatOutput, position int) (int, bool) { + if output == nil || position >= len(output.resolved) { + return 0, false + } + return output.resolved[position], true +} + +func accumulatedToolArguments(output *streamedChatOutput, index int) string { + if output == nil { + return "" + } + if call := output.toolCalls[index]; call != nil { + return call.Arguments + } + return "" +} + func sortedBlockIndexes(blocks map[int]int) []int { indexes := make([]int, 0, len(blocks)) for _, blockIndex := range blocks { diff --git a/internal/gateway/toolargs_stream_test.go b/internal/gateway/toolargs_stream_test.go new file mode 100644 index 00000000..20451d2a --- /dev/null +++ b/internal/gateway/toolargs_stream_test.go @@ -0,0 +1,114 @@ +package gateway + +import ( + "strings" + "testing" +) + +func feedChunks(t *testing.T, chunks ...string) *streamedChatOutput { + t.Helper() + output := &streamedChatOutput{} + for _, chunk := range chunks { + output.add([]byte(chunk)) + } + return output +} + +func TestStreamAccumulatesSplitArguments(t *testing.T) { + output := feedChunks(t, + `{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"name":"read_file","arguments":""}}]}}]}`, + `{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"path\":"}}]}}]}`, + `{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"a.go\"}"}}]},"finish_reason":"tool_calls"}]}`, + ) + calls := output.calls() + if len(calls) != 1 { + t.Fatalf("calls = %d, want 1: %+v", len(calls), calls) + } + if calls[0].Arguments != `{"path":"a.go"}` { + t.Fatalf("arguments = %q", calls[0].Arguments) + } +} + +// Some upstreams resend the whole argument buffer on every chunk. Concatenating +// those blindly yields `{"a":1}{"a":1}`, which clients reject as invalid JSON. +func TestStreamHandlesCumulativeArguments(t *testing.T) { + output := feedChunks(t, + `{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"name":"write_file","arguments":"{\"path\":"}}]}}]}`, + `{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"path\":\"a.go\""}}]}}]}`, + `{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"path\":\"a.go\",\"body\":\"x\"}"}}]},"finish_reason":"tool_calls"}]}`, + ) + calls := output.calls() + if len(calls) != 1 { + t.Fatalf("calls = %d, want 1: %+v", len(calls), calls) + } + if calls[0].Arguments != `{"path":"a.go","body":"x"}` { + t.Fatalf("arguments = %q", calls[0].Arguments) + } + if err := validateProxyToolCallArguments(calls); err != nil { + t.Fatalf("validate: %v", err) + } +} + +// An upstream that omits `index` on continuation deltas must not lose the +// fragments into a phantom second call. +func TestStreamWithoutIndexKeepsOneCall(t *testing.T) { + output := feedChunks(t, + `{"choices":[{"delta":{"tool_calls":[{"id":"call_1","function":{"name":"grep","arguments":"{\"q\":"}}]}}]}`, + `{"choices":[{"delta":{"tool_calls":[{"function":{"arguments":"\"x\"}"}}]}}]}`, + ) + calls := output.calls() + if len(calls) != 1 || calls[0].Arguments != `{"q":"x"}` { + t.Fatalf("calls = %+v", calls) + } +} + +// Two calls that both report index 0 must stay separate calls. +func TestStreamZeroIndexPerCallStaysSeparate(t *testing.T) { + output := feedChunks(t, + `{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"name":"a","arguments":"{\"x\":1}"}}]}}]}`, + `{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_2","function":{"name":"b","arguments":"{\"y\":2}"}}]},"finish_reason":"tool_calls"}]}`, + ) + calls := output.calls() + if len(calls) != 2 { + t.Fatalf("calls = %+v", calls) + } + if calls[0].Name != "a" || calls[0].Arguments != `{"x":1}` { + t.Fatalf("first call = %+v", calls[0]) + } + if calls[1].Name != "b" || calls[1].Arguments != `{"y":2}` { + t.Fatalf("second call = %+v", calls[1]) + } +} + +// Some upstreams send a JSON object where the OpenAI schema expects a +// string. Decoding strictly as string dropped the whole chunk. +func TestStreamAcceptsObjectArguments(t *testing.T) { + output := feedChunks(t, + `{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"name":"read_file","arguments":{"path":"a.go"}}}]}}]}`, + ) + calls := output.calls() + if len(calls) != 1 || calls[0].Arguments != `{"path":"a.go"}` { + t.Fatalf("calls = %+v", calls) + } +} + +func TestValidateRepairsFormattingDamage(t *testing.T) { + calls := []proxyToolCall{{ID: "call_1", Name: "write_file", Arguments: `{"path":"a.go",`}} + if err := validateProxyToolCallArguments(calls); err != nil { + t.Fatalf("validate: %v", err) + } + if !strings.HasSuffix(calls[0].Arguments, "}") { + t.Fatalf("arguments not repaired: %q", calls[0].Arguments) + } +} + +func TestValidateRejectsTruncatedArguments(t *testing.T) { + calls := []proxyToolCall{{ID: "call_1", Name: "run_command", Arguments: `{"cmd":"rm -rf /tmp/fo`}} + err := validateProxyToolCallArguments(calls) + if err == nil { + t.Fatal("expected truncated arguments to stay an error") + } + if !strings.Contains(err.Error(), "invalid JSON") { + t.Fatalf("unexpected error: %v", err) + } +} diff --git a/internal/translate/toolargs.go b/internal/translate/toolargs.go new file mode 100644 index 00000000..35577e21 --- /dev/null +++ b/internal/translate/toolargs.go @@ -0,0 +1,195 @@ +package translate + +import ( + "encoding/json" + "strings" +) + +const maxCloseClosers = 24 + +// RepairToolCallArguments turns the argument text a model streamed for a +// function tool into valid JSON when the damage is formatting-level: bare +// quotes inside a value, a trailing comma, or missing closing brackets after a +// complete value. It never pads a value that was cut mid-string, because +// repairing `{"command":"rm -rf /tmp/fo` into a legal string would run a +// command the model never finished writing; that case stays a hard error so +// the caller reports a truncated tool call instead of executing it. +func RepairToolCallArguments(raw string) (string, bool) { + text := strings.TrimSpace(raw) + if text == "" { + return "{}", true + } + if json.Valid([]byte(text)) { + return text, true + } + candidates := argumentRepairCandidates(text) + for _, candidate := range candidates { + if json.Valid([]byte(candidate)) { + return candidate, true + } + } + for _, candidate := range candidates { + if closed, ok := closeArgumentTail(candidate); ok { + return closed, true + } + } + // A model sometimes appends prose after a complete object: keep the value + // the decoder actually finished and drop the trailing noise. + if prefix, ok := decodeArgumentPrefix(text); ok { + return prefix, true + } + return "", false +} + +func argumentRepairCandidates(text string) []string { + candidates := []string{text} + if withoutTrailing := stripTrailingCommas(text); withoutTrailing != text { + candidates = append(candidates, withoutTrailing) + } + if escaped := escapeBareQuotes(text); escaped != text { + candidates = append(candidates, escaped, stripTrailingCommas(escaped)) + } + return candidates +} + +// stripTrailingCommas removes `,` that directly precede a closing brace or +// bracket, which models emit routinely and strict JSON rejects. +func stripTrailingCommas(text string) string { + var out strings.Builder + out.Grow(len(text)) + for index := 0; index < len(text); index++ { + character := text[index] + if character == ',' { + next := index + 1 + for next < len(text) && isJSONSpace(text[next]) { + next++ + } + if next < len(text) && (text[next] == '}' || text[next] == ']') { + continue + } + } + out.WriteByte(character) + } + return out.String() +} + +// escapeBareQuotes escapes `"` characters that appear inside a JSON string +// value. A closing quote is accepted only when the next non-space byte is one +// of `, } ] :` or the end of the buffer. +func escapeBareQuotes(text string) string { + var out strings.Builder + out.Grow(len(text)) + inString := false + for index := 0; index < len(text); { + character := text[index] + if !inString { + out.WriteByte(character) + if character == '"' { + inString = true + } + index++ + continue + } + if character == '\\' && index+1 < len(text) { + out.WriteString(text[index : index+2]) + index += 2 + continue + } + if character == '"' { + next := index + 1 + for next < len(text) && isJSONSpace(text[next]) { + next++ + } + if next >= len(text) || strings.IndexByte(",}]:", text[next]) >= 0 { + out.WriteByte(character) + inString = false + } else { + out.WriteString(`\"`) + } + index++ + continue + } + out.WriteByte(character) + index++ + } + return out.String() +} + +// closeArgumentTail appends the closers the model never got to emit, but only +// when no string is left open — a value cut mid-string stays unrepaired. +func closeArgumentTail(text string) (string, bool) { + stack := make([]byte, 0, maxCloseClosers) + var out strings.Builder + out.Grow(len(text) + maxCloseClosers) + inString := false + for index := 0; index < len(text); index++ { + character := text[index] + if inString { + out.WriteByte(character) + if character == '\\' && index+1 < len(text) { + out.WriteByte(text[index+1]) + index++ + continue + } + if character == '"' { + inString = false + } + continue + } + switch character { + case '"': + inString = true + out.WriteByte(character) + case '{', '[': + if len(stack) >= maxCloseClosers { + return "", false + } + stack = append(stack, character) + out.WriteByte(character) + case '}', ']': + if len(stack) == 0 { + return "", false + } + open := stack[len(stack)-1] + if (character == '}' && open != '{') || (character == ']' && open != '[') { + return "", false + } + stack = stack[:len(stack)-1] + out.WriteByte(character) + default: + out.WriteByte(character) + } + } + if inString || len(stack) == 0 { + return "", false + } + for index := len(stack) - 1; index >= 0; index-- { + if stack[index] == '{' { + out.WriteString("}") + } else { + out.WriteString("]") + } + } + closed := stripTrailingCommas(out.String()) + if json.Valid([]byte(closed)) { + return closed, true + } + return "", false +} + +func decodeArgumentPrefix(text string) (string, bool) { + decoder := json.NewDecoder(strings.NewReader(text)) + var value any + if decoder.Decode(&value) != nil { + return "", false + } + prefix := strings.TrimSpace(text[:decoder.InputOffset()]) + if prefix == "" || !json.Valid([]byte(prefix)) { + return "", false + } + return prefix, true +} + +func isJSONSpace(character byte) bool { + return character == ' ' || character == '\t' || character == '\r' || character == '\n' +} diff --git a/internal/translate/toolargs_test.go b/internal/translate/toolargs_test.go new file mode 100644 index 00000000..5232e1f0 --- /dev/null +++ b/internal/translate/toolargs_test.go @@ -0,0 +1,41 @@ +package translate + +import ( + "encoding/json" + "testing" +) + +func TestRepairToolCallArguments(t *testing.T) { + cases := []struct { + name string + raw string + want string + ok bool + }{ + {name: "valid passthrough", raw: `{"path":"a.go"}`, want: `{"path":"a.go"}`, ok: true}, + {name: "blank becomes object", raw: " ", want: "{}", ok: true}, + {name: "trailing comma", raw: `{"path":"a.go",}`, want: `{"path":"a.go"}`, ok: true}, + {name: "missing closing brace", raw: `{"path":"a.go"`, want: `{"path":"a.go"}`, ok: true}, + {name: "missing nested closers", raw: `{"pattern":"x","paths":["a","b"`, want: `{"pattern":"x","paths":["a","b"]}`, ok: true}, + {name: "bare quote inside value", raw: `{"cmd":"echo "hi""}`, want: `{"cmd":"echo \"hi\""}`, ok: true}, + {name: "prose after object", raw: `{"path":"a.go"} and then explain`, want: `{"path":"a.go"}`, ok: true}, + {name: "cut mid string", raw: `{"cmd":"rm -rf /tmp/fo`, ok: false}, + {name: "cut mid key", raw: `{"pa`, ok: false}, + {name: "not json at all", raw: `please read the file`, ok: false}, + } + for _, tc := range cases { + got, ok := RepairToolCallArguments(tc.raw) + if ok != tc.ok { + t.Fatalf("%s: ok = %v, want %v (got %q)", tc.name, ok, tc.ok, got) + } + if !ok { + continue + } + if got != tc.want { + t.Fatalf("%s: got %q, want %q", tc.name, got, tc.want) + } + if !json.Valid([]byte(got)) { + t.Fatalf("%s: repaired value is not valid JSON: %q", tc.name, got) + } + } +} From ae790695c091405fa76d7b0559180b0e37a4eba2 Mon Sep 17 00:00:00 2001 From: guyu233 Date: Wed, 25 Nov 2026 19:56:24 +0800 Subject: [PATCH 2/3] fix(gateway): keep same-tool calls separate when upstream reuses index 0 --- internal/gateway/compat_stream.go | 22 +++++++++++++++++----- internal/gateway/toolargs_stream_test.go | 16 ++++++++++++++++ 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/internal/gateway/compat_stream.go b/internal/gateway/compat_stream.go index 8f3bb361..69d105b7 100644 --- a/internal/gateway/compat_stream.go +++ b/internal/gateway/compat_stream.go @@ -187,15 +187,13 @@ func (o *streamedChatOutput) resolveToolCallIndex(declared *int, id, name string case declared != nil && !startsCall: return *declared case declared != nil && startsCall: - if existing := o.toolCalls[*declared]; existing != nil && existing.Name != "" && existing.Name != name { + if o.callIsDifferent(*declared, id, name) { return maxToolCallIndex(o.toolCalls) + 1 } return *declared case startsCall: - if position == 0 { - if existing := o.toolCalls[0]; existing == nil || existing.Name == "" || existing.Name == name { - return 0 - } + if position == 0 && !o.callIsDifferent(0, id, name) { + return 0 } return maxToolCallIndex(o.toolCalls) + 1 case lastIndex >= 0: @@ -205,6 +203,20 @@ func (o *streamedChatOutput) resolveToolCallIndex(declared *int, id, name string } } +// callIsDifferent reports whether this delta starts a new call on an index +// that already holds one. Two calls of the same tool are common, so the +// call id is what separates them; a name-only comparison would merge them. +func (o *streamedChatOutput) callIsDifferent(index int, id, name string) bool { + existing := o.toolCalls[index] + if existing == nil || (existing.Name == "" && existing.ID == "") { + return false + } + if id != "" && existing.ID != "" { + return existing.ID != id + } + return name != "" && existing.Name != "" && existing.Name != name +} + func maxToolCallIndex(calls map[int]*proxyToolCall) int { maximum := -1 for index := range calls { diff --git a/internal/gateway/toolargs_stream_test.go b/internal/gateway/toolargs_stream_test.go index 20451d2a..89315764 100644 --- a/internal/gateway/toolargs_stream_test.go +++ b/internal/gateway/toolargs_stream_test.go @@ -92,6 +92,22 @@ func TestStreamAcceptsObjectArguments(t *testing.T) { } } +// Two calls of the same tool, each announcing index 0 with its own call id, +// must not be merged into one argument buffer. +func TestStreamSameToolTwiceStaysSeparate(t *testing.T) { + output := feedChunks(t, + `{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"name":"read_file","arguments":"{\"path\":\"a\"}"}}]}}]}`, + `{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_2","function":{"name":"read_file","arguments":"{\"path\":\"b\"}"}}]},"finish_reason":"tool_calls"}]}`, + ) + calls := output.calls() + if len(calls) != 2 { + t.Fatalf("calls = %+v", calls) + } + if calls[0].Arguments != `{"path":"a"}` || calls[1].Arguments != `{"path":"b"}` { + t.Fatalf("calls = %+v", calls) + } +} + func TestValidateRepairsFormattingDamage(t *testing.T) { calls := []proxyToolCall{{ID: "call_1", Name: "write_file", Arguments: `{"path":"a.go",`}} if err := validateProxyToolCallArguments(calls); err != nil { From 16666f5cce7d3367f0a8b89db40d0fc5030cdf93 Mon Sep 17 00:00:00 2001 From: guyu233 Date: Wed, 25 Nov 2026 20:26:50 +0800 Subject: [PATCH 3/3] fix(gateway): stream normalized tool arguments only, never damaged fragments --- .../tool-call-arguments-stream-normalize.md | 9 + internal/gateway/anthropic.go | 8 +- internal/gateway/compat.go | 34 ++- internal/gateway/compat_stream.go | 82 ++++--- internal/gateway/openai_stream.go | 91 ++++++-- internal/gateway/openai_tool_normalizer.go | 221 ++++++++++++++++++ internal/gateway/responses_test.go | 26 ++- internal/gateway/toolargs_stream_test.go | 91 ++++++-- internal/translate/toolargs.go | 95 +++++++- internal/translate/toolargs_normalize_test.go | 36 +++ 10 files changed, 594 insertions(+), 99 deletions(-) create mode 100644 changelog/unreleased/tool-call-arguments-stream-normalize.md create mode 100644 internal/gateway/openai_tool_normalizer.go create mode 100644 internal/translate/toolargs_normalize_test.go diff --git a/changelog/unreleased/tool-call-arguments-stream-normalize.md b/changelog/unreleased/tool-call-arguments-stream-normalize.md new file mode 100644 index 00000000..5c3d9e9e --- /dev/null +++ b/changelog/unreleased/tool-call-arguments-stream-normalize.md @@ -0,0 +1,9 @@ +### English + +- Streaming tool calls now deliver arguments as one already-normalized string instead of relaying upstream fragments. `/v1/responses` sends the repaired arguments once in `response.function_call_arguments.delta` and repeats them in `.done`, `/v1/messages` sends them at block close, and `/v1/chat/completions` withholds tool frames until the call is complete. Clients that concatenate deltas and clients that read the done event therefore receive identical, valid JSON. +- Arguments truncated mid-string are no longer padded. The unfinished trailing member is dropped, so the call still parses and the tool or model can recover, instead of the round failing with "arguments are invalid JSON". + +### 中文 + +- 流式工具调用不再把上游碎片直接转发,而是一次性下发已经归一化好的参数:`/v1/responses` 在 `response.function_call_arguments.delta` 给出修复后的完整参数并在 `.done` 重复一次,`/v1/messages` 在 block 收尾时发,`/v1/chat/completions` 把工具帧拦到调用结束再发。因此「拼接 delta 的客户端」和「读 done 事件的客户端」拿到的是同一份合法 JSON。 +- 截断在字符串中间的参数不再补齐:只丢弃尾部未完成的那个成员,调用仍然能解析,交给工具或模型自己纠正,而不是整轮报「arguments are invalid JSON」。 diff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.go index aa510d7f..4af2932d 100644 --- a/internal/gateway/anthropic.go +++ b/internal/gateway/anthropic.go @@ -197,14 +197,10 @@ func anthropicMessageResponse(requestID, model, content, reasoning string, toolC blocks = append(blocks, map[string]any{"type": "text", "text": content}) } for _, call := range toolCalls { - arguments := strings.TrimSpace(call.Arguments) + arguments, _ := translate.NormalizeToolCallArguments(call.Arguments) input := json.RawMessage(arguments) if !json.Valid(input) { - if repaired, ok := translate.RepairToolCallArguments(arguments); ok { - input = json.RawMessage(repaired) - } else { - input = json.RawMessage(`{}`) - } + input = json.RawMessage(`{}`) } blocks = append(blocks, map[string]any{"type": "tool_use", "id": call.ID, "name": call.Name, "input": input}) } diff --git a/internal/gateway/compat.go b/internal/gateway/compat.go index bd56bf7a..c0a75d7f 100644 --- a/internal/gateway/compat.go +++ b/internal/gateway/compat.go @@ -65,39 +65,33 @@ func decodeOpenAIToolCalls(raw json.RawMessage) []proxyToolCall { arguments = "{}" } if _, _, custom := translate.DecodeCustomToolName(call.Function.Name); !custom && !json.Valid([]byte(arguments)) { - repaired, ok := translate.RepairToolCallArguments(arguments) - if !ok { - continue - } - arguments = repaired + normalized, _ := translate.NormalizeToolCallArguments(arguments) + arguments = normalized } calls = append(calls, proxyToolCall{ID: call.ID, Name: call.Function.Name, Arguments: arguments}) } return calls } -func validateProxyToolCallArguments(calls []proxyToolCall) error { +// normalizeProxyToolCallArguments makes every function call carry valid JSON +// arguments. It never fails the turn: a call the model mangled or left +// unfinished keeps only the fields it completed, so the client can run the tool +// and hand the validation error back to the model instead of the client +// aborting the whole round with "arguments are invalid JSON". +func normalizeProxyToolCallArguments(calls []proxyToolCall) bool { + changed := false for index := range calls { call := &calls[index] if _, _, custom := translate.DecodeCustomToolName(call.Name); custom { continue } - arguments := strings.TrimSpace(call.Arguments) - if arguments == "" { - call.Arguments = "{}" - continue - } - if !json.Valid([]byte(arguments)) { - repaired, ok := translate.RepairToolCallArguments(arguments) - if !ok { - return fmt.Errorf("tool call %q (%s) arguments are invalid JSON", call.ID, call.Name) - } - call.Arguments = repaired - continue + normalized, normalizedChanged := translate.NormalizeToolCallArguments(call.Arguments) + call.Arguments = normalized + if normalizedChanged { + changed = true } - call.Arguments = arguments } - return nil + return changed } func (h *Handler) PrepareCompatibilityExecution(r *http.Request, request translate.ChatRequest) (Execution, error) { diff --git a/internal/gateway/compat_stream.go b/internal/gateway/compat_stream.go index 69d105b7..8fd5a271 100644 --- a/internal/gateway/compat_stream.go +++ b/internal/gateway/compat_stream.go @@ -356,7 +356,6 @@ func RelayAnthropicStream(writer io.Writer, body io.Reader, requestID, model str thinkingStarted := false thinkingBlockIndex := -1 toolBlocks := map[int]int{} - toolArgumentLengths := map[int]int{} nextBlock := 0 closeThinking := func() error { if !thinkingStarted { @@ -458,15 +457,6 @@ func RelayAnthropicStream(writer io.Writer, body io.Reader, requestID, model str if !exists { continue } - accumulated := accumulatedToolArguments(current, index) - emitted := toolArgumentLengths[index] - if len(accumulated) <= emitted { - continue - } - if err := writeSSEEvent(writer, "content_block_delta", map[string]any{"type": "content_block_delta", "index": blockIndex, "delta": map[string]string{"type": "input_json_delta", "partial_json": accumulated[emitted:]}}); err != nil { - return err - } - toolArgumentLengths[index] = len(accumulated) } } return nil @@ -480,6 +470,12 @@ func RelayAnthropicStream(writer io.Writer, body io.Reader, requestID, model str if err := closeText(); err != nil { return stats, err } + // Arguments are held until the block closes so they can be normalized + // first: a damaged buffer would otherwise reach the client as several + // input_json_delta fragments that never parse. + if err := writeToolArguments(writer, &output, toolBlocks, requestID, model); err != nil { + return stats, err + } for _, blockIndex := range sortedBlockIndexes(toolBlocks) { if err := writeSSEEvent(writer, "content_block_stop", map[string]any{"type": "content_block_stop", "index": blockIndex}); err != nil { return stats, err @@ -529,7 +525,6 @@ func RelayResponsesStream(writer io.Writer, body io.Reader, requestID, model str toolAnnounced := map[int]bool{} toolCallIDs := map[int]string{} toolCallNames := map[int]string{} - toolArgumentLengths := map[int]int{} toolOutputIndexes := map[int]int{} nextOutputIndex := 0 reasoningOutputIndex := -1 @@ -639,22 +634,9 @@ func RelayResponsesStream(writer io.Writer, body io.Reader, requestID, model str } toolAnnounced[index] = true } - if toolAnnounced[index] { - accumulated := accumulatedToolArguments(current, index) - emitted := toolArgumentLengths[index] - if len(accumulated) > emitted { - deltaPayload := map[string]any{"type": "response.function_call_arguments.delta", "output_index": toolOutputIndexes[index], "item_id": fmt.Sprintf("fc_%s_%d", requestID, index), "call_id": toolCallIDs[index], "name": toolCallNames[index], "delta": accumulated[emitted:]} - if _, _, custom := translate.DecodeCustomToolName(toolCallNames[index]); custom { - toolArgumentLengths[index] = len(accumulated) - continue - } - eventName, _ := deltaPayload["type"].(string) - if err := eventWriter.write(eventName, deltaPayload); err != nil { - return err - } - toolArgumentLengths[index] = len(accumulated) - } - } + // Arguments are not streamed as deltas: a damaged buffer would + // reach the client as fragments that never parse. The normalized + // full string is delivered once in response.function_call_arguments.done. } } return nil @@ -668,12 +650,8 @@ func RelayResponsesStream(writer io.Writer, body io.Reader, requestID, model str } content := output.content.String() calls := output.calls() - if err := validateProxyToolCallArguments(calls); err != nil { - log.Printf("tool call arguments unusable request_id=%q model=%q finish_reason=%q err=%v", requestID, model, output.finishReason, err) - if output.finishReason == "length" { - return stats, fmt.Errorf("%w (the model hit its output-token limit mid-arguments)", err) - } - return stats, err + if normalizeProxyToolCallArguments(calls) { + log.Printf("tool call arguments normalized request_id=%q model=%q finish_reason=%q calls=%d", requestID, model, output.finishReason, len(calls)) } if textStarted { if err := eventWriter.write("response.output_text.done", map[string]any{"type": "response.output_text.done", "item_id": "msg_" + requestID, "output_index": textOutputIndex, "content_index": 0, "text": content}); err != nil { @@ -732,6 +710,14 @@ func RelayResponsesStream(writer io.Writer, body io.Reader, requestID, model str return stats, err } } + // The normalized string goes out once, as a single delta followed by + // done: clients that concatenate deltas get the same text as clients + // that read the done event, and neither ever sees a broken fragment. + if call.Arguments != "" { + if err := eventWriter.write("response.function_call_arguments.delta", map[string]any{"type": "response.function_call_arguments.delta", "output_index": outputIndex, "item_id": item["id"], "call_id": call.ID, "name": call.Name, "delta": call.Arguments}); err != nil { + return stats, err + } + } if err := eventWriter.write("response.function_call_arguments.done", map[string]any{"type": "response.function_call_arguments.done", "output_index": outputIndex, "item_id": item["id"], "call_id": call.ID, "name": call.Name, "arguments": call.Arguments}); err != nil { return stats, err } @@ -752,6 +738,36 @@ func RelayResponsesStream(writer io.Writer, body io.Reader, requestID, model str return stats, nil } +// writeToolArguments emits one normalized input_json_delta per tool block. The +// Anthropic wire format has no way to retract a delta, so the arguments are +// buffered to block-close time; that keeps a damaged buffer from reaching the +// client as fragments that never parse. +func writeToolArguments(writer io.Writer, output *streamedChatOutput, toolBlocks map[int]int, requestID, model string) error { + if output == nil { + return nil + } + indexes := make([]int, 0, len(toolBlocks)) + for index := range toolBlocks { + indexes = append(indexes, index) + } + sort.Ints(indexes) + for _, index := range indexes { + blockIndex := toolBlocks[index] + call := output.toolCalls[index] + if call == nil || strings.TrimSpace(call.Arguments) == "" { + continue + } + arguments, changed := translate.NormalizeToolCallArguments(call.Arguments) + if changed { + log.Printf("tool call arguments normalized request_id=%q model=%q tool=%q truncated=%v", requestID, model, call.Name, !json.Valid([]byte(strings.TrimSpace(call.Arguments)))) + } + if err := writeSSEEvent(writer, "content_block_delta", map[string]any{"type": "content_block_delta", "index": blockIndex, "delta": map[string]string{"type": "input_json_delta", "partial_json": arguments}}); err != nil { + return err + } + } + return nil +} + func resolvedCallIndex(output *streamedChatOutput, position int) (int, bool) { if output == nil || position >= len(output.resolved) { return 0, false diff --git a/internal/gateway/openai_stream.go b/internal/gateway/openai_stream.go index babb7e69..8071cc2f 100644 --- a/internal/gateway/openai_stream.go +++ b/internal/gateway/openai_stream.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "io" + "log" "net/http" "strings" "time" @@ -89,6 +90,32 @@ func RelayOpenAIStream(w http.ResponseWriter, body io.Reader) (stats StreamRelay sawDone := false var frame []string var streamErr error + normalizer := newOpenAIToolNormalizer() + argsFlushed := false + + flushToolArguments := func() error { + if argsFlushed { + return nil + } + argsFlushed = true + frames := normalizer.flushFrames() + if len(frames) == 0 { + return nil + } + if normalizer.changed { + log.Printf("tool call arguments normalized stream=chat_completion calls=%d finish_reason=%q", len(frames), normalizer.finish) + } + for _, payload := range frames { + encoded, err := json.Marshal(payload) + if err != nil { + continue + } + if _, err := io.WriteString(writer, "data: "+string(encoded)+"\n\n"); err != nil { + return &StreamRelayWriteError{err: err} + } + } + return nil + } flushFrame := func() error { if len(frame) == 0 { @@ -107,12 +134,54 @@ func RelayOpenAIStream(w http.ResponseWriter, body io.Reader) (stats StreamRelay frame = nil return nil } - for _, line := range frame { - line = strings.TrimSuffix(line, "\r") - if stats.FirstTokenAt == nil && SSEDeltaHasToken(line) { - now := time.Now() - stats.FirstTokenAt = &now + // Each data line is handled on its own: upstreams differ on whether they + // put one JSON payload per line, and a frame may bundle content, usage and + // [DONE] together. Tool-call fragments are absorbed and withheld here so + // a damaged buffer never reaches the client as fragments. + lines := make([]string, 0, len(frame)) + for _, rawLine := range frame { + line := strings.TrimSuffix(rawLine, "\r") + if strings.TrimSpace(line) == "" { + continue + } + if !strings.HasPrefix(line, "data:") { + lines = append(lines, line) + continue + } + payload := strings.TrimSpace(strings.TrimPrefix(line, "data:")) + if payload == "[DONE]" { + if err := flushToolArguments(); err != nil { + return err + } + sawDone = true + stats.SawDone = true + lines = append(lines, line) + continue + } + if payload != "" { + var decoded map[string]any + if json.Unmarshal([]byte(payload), &decoded) == nil { + if _, ok := decoded["choices"]; ok { + if stats.FirstTokenAt == nil && SSEDeltaHasToken(line) { + now := time.Now() + stats.FirstTokenAt = &now + } + if relayed := normalizer.absorb(decoded); relayed == nil { + continue + } else if encoded, err := json.Marshal(relayed); err == nil { + line = "data: " + string(encoded) + } + if normalizer.finish != "" { + if err := flushToolArguments(); err != nil { + return err + } + } + } + } } + lines = append(lines, line) + } + for _, line := range lines { if fr := SSEDeltaFinishReason(line); fr != "" { stats.FinishReason = fr } @@ -125,17 +194,10 @@ func RelayOpenAIStream(w http.ResponseWriter, body io.Reader) (stats StreamRelay usage.FinishReason = stats.FinishReason stats = usage } - if strings.TrimSpace(strings.TrimPrefix(line, "data:")) == "[DONE]" { - sawDone = true - } } - output := strings.Join(frame, "\n") + "\n\n" - if _, err := io.WriteString(writer, output); err != nil { + if _, err := io.WriteString(writer, strings.Join(lines, "\n")+"\n\n"); err != nil { return &StreamRelayWriteError{err: err} } - if sawDone { - stats.SawDone = true - } frame = nil return nil } @@ -170,6 +232,9 @@ func RelayOpenAIStream(w http.ResponseWriter, body io.Reader) (stats StreamRelay if stats.FinishReason != "" && (stats.FirstTokenAt != nil || stats.SSEEventCount > 0) { sawDone = true stats.SawDone = true + if err := flushToolArguments(); err != nil { + return stats, err + } if _, err := io.WriteString(writer, "data: [DONE]\n\n"); err != nil { return stats, &StreamRelayWriteError{err: err} } diff --git a/internal/gateway/openai_tool_normalizer.go b/internal/gateway/openai_tool_normalizer.go new file mode 100644 index 00000000..ec3ce400 --- /dev/null +++ b/internal/gateway/openai_tool_normalizer.go @@ -0,0 +1,221 @@ +package gateway + +import ( + "encoding/json" + "sort" + "strconv" + + "github.com/caigee-cmd/cli2api/internal/translate" +) + +// openAIToolNormalizer keeps an OpenAI chat-completions stream faithful frame +// by frame except for tool-call arguments. Arguments are accumulated and +// flushed once per call, normalized to valid JSON, because a client that +// concatenates damaged upstream fragments aborts the round with "arguments are +// invalid JSON". Content, reasoning, usage and finish frames relay unchanged. +type openAIToolNormalizer struct { + calls map[int]*proxyToolCall + emitted map[int]bool + changed bool + finish string + meta map[string]any +} + +func newOpenAIToolNormalizer() *openAIToolNormalizer { + return &openAIToolNormalizer{ + calls: map[int]*proxyToolCall{}, + emitted: map[int]bool{}, + } +} + +// absorb consumes one chunk payload and returns the payload that should still +// be relayed, or nil when the chunk carried nothing but tool-call fragments. +func (n *openAIToolNormalizer) absorb(payload map[string]any) map[string]any { + choices, ok := payload["choices"].([]any) + if !ok || len(choices) == 0 { + return payload + } + for _, key := range []string{"id", "object", "created", "model", "system_fingerprint"} { + if value, ok := payload[key]; ok && value != nil { + if n.meta == nil { + n.meta = map[string]any{} + } + n.meta[key] = value + } + } + dropped := false + for _, rawChoice := range choices { + choice, ok := rawChoice.(map[string]any) + if !ok { + continue + } + if finish, ok := choice["finish_reason"].(string); ok && finish != "" { + n.finish = finish + } + delta, ok := choice["delta"].(map[string]any) + if !ok { + continue + } + rawCalls, hasCalls := delta["tool_calls"].([]any) + if !hasCalls || len(rawCalls) == 0 { + continue + } + n.absorbCalls(rawCalls) + delete(delta, "tool_calls") + if len(delta) == 0 && choice["finish_reason"] == nil { + dropped = true + } + } + if dropped { + return nil + } + return payload +} + +func (n *openAIToolNormalizer) absorbCalls(rawCalls []any) { + for position, rawCall := range rawCalls { + call, ok := rawCall.(map[string]any) + if !ok { + continue + } + id, _ := call["id"].(string) + function, _ := call["function"].(map[string]any) + name, _ := function["name"].(string) + arguments := argumentFragment(rawArguments(function["arguments"])) + index := n.resolveIndex(call, id, name, position) + entry := n.calls[index] + if entry == nil { + entry = &proxyToolCall{} + n.calls[index] = entry + } + if id != "" { + entry.ID = id + } + if name != "" { + entry.Name = name + } + merged := mergeToolArguments(entry.Arguments, arguments) + if merged != entry.Arguments { + entry.Arguments = merged + } + } +} + +func (n *openAIToolNormalizer) resolveIndex(call map[string]any, id, name string, position int) int { + declared := -1 + if value, ok := call["index"].(float64); ok { + declared = int(value) + } + startsCall := id != "" || name != "" + if declared >= 0 && !startsCall { + return declared + } + if declared >= 0 { + if n.callIsDifferent(declared, id, name) { + return n.nextIndex() + } + return declared + } + if startsCall { + if n.callIsDifferent(0, id, name) { + return n.nextIndex() + } + return 0 + } + return n.lastIndex(position) +} + +func (n *openAIToolNormalizer) callIsDifferent(index int, id, name string) bool { + existing := n.calls[index] + if existing == nil || (existing.Name == "" && existing.ID == "") { + return false + } + if id != "" && existing.ID != "" { + return existing.ID != id + } + return name != "" && existing.Name != "" && existing.Name != name +} + +func (n *openAIToolNormalizer) nextIndex() int { + maximum := -1 + for index := range n.calls { + if index > maximum { + maximum = index + } + } + return maximum + 1 +} + +func (n *openAIToolNormalizer) lastIndex(position int) int { + maximum := -1 + for index, call := range n.calls { + if call != nil && call.Name != "" && index > maximum { + maximum = index + } + } + if maximum >= 0 { + return maximum + } + return position +} + +// flushFrames returns one frame per call that has not been delivered yet, each +// carrying the normalized full argument string. +func (n *openAIToolNormalizer) flushFrames() []map[string]any { + indexes := make([]int, 0, len(n.calls)) + for index, call := range n.calls { + if call == nil || call.Name == "" || n.emitted[index] { + continue + } + indexes = append(indexes, index) + } + sort.Ints(indexes) + frames := make([]map[string]any, 0, len(indexes)) + for _, index := range indexes { + call := n.calls[index] + arguments, changed := translate.NormalizeToolCallArguments(call.Arguments) + if changed { + n.changed = true + } + if call.ID == "" { + call.ID = "call_" + call.Name + "_" + strconv.Itoa(index) + } + frames = append(frames, n.frame(map[string]any{ + "index": index, + "id": call.ID, + "type": "function", + "function": map[string]any{ + "name": call.Name, + "arguments": arguments, + }, + })) + n.emitted[index] = true + } + return frames +} + +func (n *openAIToolNormalizer) frame(call map[string]any) map[string]any { + payload := map[string]any{ + "object": "chat.completion.chunk", + "choices": []any{map[string]any{ + "index": 0, + "delta": map[string]any{"tool_calls": []any{call}}, + "finish_reason": nil, + }}, + } + for key, value := range n.meta { + payload[key] = value + } + return payload +} + +func rawArguments(value any) json.RawMessage { + if value == nil { + return nil + } + encoded, err := json.Marshal(value) + if err != nil { + return nil + } + return encoded +} diff --git a/internal/gateway/responses_test.go b/internal/gateway/responses_test.go index 11a88f76..2fe8a8d3 100644 --- a/internal/gateway/responses_test.go +++ b/internal/gateway/responses_test.go @@ -208,25 +208,31 @@ func TestParseStreamUsageLineCacheReadFallback(t *testing.T) { } } -func TestDecodeOpenAIToolCallsDropsInvalidArguments(t *testing.T) { +func TestDecodeOpenAIToolCallsNormalizesInvalidArguments(t *testing.T) { calls := decodeOpenAIToolCalls(json.RawMessage(`[ {"id":"call_bad","function":{"name":"mcp__fastctx__read","arguments":"{\"path\":\"x\",\"error_retry:: 240}"}}, {"id":"call_good","function":{"name":"mcp__fastctx__grep","arguments":"{\"pattern\":\"x\"}"}} ]`)) - if len(calls) != 1 || calls[0].ID != "call_good" { + if len(calls) != 2 { t.Fatalf("calls=%#v", calls) } + if calls[0].ID != "call_bad" || calls[0].Arguments != `{"path":"x"}` { + t.Fatalf("bad call was not normalized: %#v", calls[0]) + } + if calls[1].Arguments != `{"pattern":"x"}` { + t.Fatalf("good call changed: %#v", calls[1]) + } } -func TestRelayResponsesStreamRejectsInvalidToolArgumentsBeforeFinalize(t *testing.T) { +func TestRelayResponsesStreamNormalizesInvalidToolArguments(t *testing.T) { upstream := strings.NewReader( `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_bad","function":{"name":"mcp__fastctx__read","arguments":"{\"path\":\"x\",\"error_retry:: 240}"}}]}}]}` + "\n\n" + `data: {"choices":[{"finish_reason":"tool_calls"}]}` + "\n\n" + "data: [DONE]\n\n", ) var output strings.Builder - _, err := RelayResponsesStream(&output, upstream, "req", "model", nil) - if err == nil || !strings.Contains(err.Error(), "arguments are invalid JSON") { + stats, err := RelayResponsesStream(&output, upstream, "req", "model", nil) + if err != nil { t.Fatalf("error=%v", err) } body := output.String() @@ -235,8 +241,14 @@ func TestRelayResponsesStreamRejectsInvalidToolArgumentsBeforeFinalize(t *testin "event: response.output_item.done", "event: response.completed", } { - if strings.Contains(body, event) { - t.Fatalf("invalid tool call was finalized with %q:\n%s", event, body) + if !strings.Contains(body, event) { + t.Fatalf("missing %q in:\n%s", event, body) } } + if strings.Contains(body, "error_retry") { + t.Fatalf("garbage arguments leaked into the stream:\n%s", body) + } + if stats.FinishReason != "tool_calls" { + t.Fatalf("finish reason=%q", stats.FinishReason) + } } diff --git a/internal/gateway/toolargs_stream_test.go b/internal/gateway/toolargs_stream_test.go index 89315764..c442004c 100644 --- a/internal/gateway/toolargs_stream_test.go +++ b/internal/gateway/toolargs_stream_test.go @@ -1,6 +1,8 @@ package gateway import ( + "encoding/json" + "net/http/httptest" "strings" "testing" ) @@ -44,8 +46,8 @@ func TestStreamHandlesCumulativeArguments(t *testing.T) { if calls[0].Arguments != `{"path":"a.go","body":"x"}` { t.Fatalf("arguments = %q", calls[0].Arguments) } - if err := validateProxyToolCallArguments(calls); err != nil { - t.Fatalf("validate: %v", err) + if normalizeProxyToolCallArguments(calls) { + t.Fatal("valid arguments should not be reported as changed") } } @@ -108,23 +110,86 @@ func TestStreamSameToolTwiceStaysSeparate(t *testing.T) { } } -func TestValidateRepairsFormattingDamage(t *testing.T) { +func TestRelayOpenAIStreamNormalizesFragmentedToolArguments(t *testing.T) { + body := strings.Join([]string{ + `data: {"id":"c1","model":"m","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"write_file","arguments":"{\"path\":"}}]}}]}`, + "", + `data: {"id":"c1","model":"m","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"a.go\","}}]}}]}`, + "", + `data: {"id":"c1","model":"m","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"body\":\"par"}}]}}]}`, + "", + `data: {"id":"c1","model":"m","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}`, + "", + "data: [DONE]", + "", + }, "\n") + recorder := httptest.NewRecorder() + stats, err := RelayOpenAIStream(recorder, strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + if !stats.SawDone { + t.Fatalf("stats=%+v", stats) + } + var arguments []string + for _, line := range strings.Split(recorder.Body.String(), "\n") { + payload := strings.TrimSpace(strings.TrimPrefix(line, "data:")) + if payload == "" || payload == "[DONE]" { + continue + } + var chunk struct { + Choices []struct { + Delta struct { + ToolCalls []struct { + Function struct { + Arguments string `json:"arguments"` + } `json:"function"` + } `json:"tool_calls"` + } `json:"delta"` + } `json:"choices"` + } + if json.Unmarshal([]byte(payload), &chunk) != nil { + continue + } + for _, choice := range chunk.Choices { + for _, call := range choice.Delta.ToolCalls { + arguments = append(arguments, call.Function.Arguments) + } + } + } + if len(arguments) != 1 { + t.Fatalf("expected exactly one arguments frame, got %d: %#v", len(arguments), arguments) + } + // The body field was cut mid-string, so it is dropped rather than padded + // into a plausible-looking value; everything the model finished survives. + if arguments[0] != `{"path":"a.go"}` { + t.Fatalf("arguments = %q", arguments[0]) + } + if !json.Valid([]byte(arguments[0])) { + t.Fatalf("arguments not valid JSON: %q", arguments[0]) + } +} + +func TestNormalizeRepairsFormattingDamage(t *testing.T) { calls := []proxyToolCall{{ID: "call_1", Name: "write_file", Arguments: `{"path":"a.go",`}} - if err := validateProxyToolCallArguments(calls); err != nil { - t.Fatalf("validate: %v", err) + if !normalizeProxyToolCallArguments(calls) { + t.Fatal("expected repair to be reported") } - if !strings.HasSuffix(calls[0].Arguments, "}") { - t.Fatalf("arguments not repaired: %q", calls[0].Arguments) + if !json.Valid([]byte(calls[0].Arguments)) { + t.Fatalf("arguments not valid after normalize: %q", calls[0].Arguments) } } -func TestValidateRejectsTruncatedArguments(t *testing.T) { +func TestNormalizeTruncatedArgumentsNeverFails(t *testing.T) { calls := []proxyToolCall{{ID: "call_1", Name: "run_command", Arguments: `{"cmd":"rm -rf /tmp/fo`}} - err := validateProxyToolCallArguments(calls) - if err == nil { - t.Fatal("expected truncated arguments to stay an error") + if !normalizeProxyToolCallArguments(calls) { + t.Fatal("expected normalize to change truncated arguments") + } + if !json.Valid([]byte(calls[0].Arguments)) { + t.Fatalf("arguments still invalid: %q", calls[0].Arguments) } - if !strings.Contains(err.Error(), "invalid JSON") { - t.Fatalf("unexpected error: %v", err) + // The unfinished command must not survive as a runnable string. + if strings.Contains(calls[0].Arguments, "rm -rf") { + t.Fatalf("truncated command leaked into arguments: %q", calls[0].Arguments) } } diff --git a/internal/translate/toolargs.go b/internal/translate/toolargs.go index 35577e21..7ab618a1 100644 --- a/internal/translate/toolargs.go +++ b/internal/translate/toolargs.go @@ -7,13 +7,38 @@ import ( const maxCloseClosers = 24 -// RepairToolCallArguments turns the argument text a model streamed for a -// function tool into valid JSON when the damage is formatting-level: bare -// quotes inside a value, a trailing comma, or missing closing brackets after a -// complete value. It never pads a value that was cut mid-string, because -// repairing `{"command":"rm -rf /tmp/fo` into a legal string would run a -// command the model never finished writing; that case stays a hard error so -// the caller reports a truncated tool call instead of executing it. +// NormalizeToolCallArguments always returns valid JSON for a function tool's +// argument text, so a damaged tool call degrades into a call the model can +// retry instead of killing the whole turn. The bool reports whether anything +// had to change. +// +// Order: formatting repair first; then drop the trailing incomplete member +// (a value cut mid-string, usually by the output-token limit) and keep only +// fields the model finished writing; last resort an empty object. Dropping +// beats inventing: a tool called without its unfinished field validates and +// fails visibly, while padding a truncated `rm -rf /tmp/fo` would execute +// something the model never wrote. +func NormalizeToolCallArguments(raw string) (string, bool) { + text := strings.TrimSpace(raw) + if text == "" { + return "{}", true + } + if json.Valid([]byte(text)) { + return text, false + } + if repaired, ok := RepairToolCallArguments(text); ok { + return repaired, true + } + if trimmed, ok := dropIncompleteMember(text); ok { + return trimmed, true + } + return "{}", true +} + +// RepairToolCallArguments fixes formatting-level damage only: bare quotes +// inside a value, a trailing comma, missing closing brackets after a complete +// value, or prose appended after the object. It never pads a value that was +// cut mid-string and reports ok=false for that case. func RepairToolCallArguments(raw string) (string, bool) { text := strings.TrimSpace(raw) if text == "" { @@ -41,6 +66,62 @@ func RepairToolCallArguments(raw string) (string, bool) { return "", false } +// dropIncompleteMember keeps only the members the model finished writing: it +// cuts at the last top-level comma whose prefix can be closed into valid JSON. +func dropIncompleteMember(text string) (string, bool) { + if !strings.HasPrefix(text, "{") { + return "", false + } + commas := topLevelCommaPositions(text) + for index := len(commas) - 1; index >= 0; index-- { + prefix := strings.TrimSpace(strings.TrimSuffix(text[:commas[index]], ",")) + if prefix == "" || prefix == "{" { + continue + } + if closed, ok := closeArgumentTail(prefix); ok { + return closed, true + } + } + if closed, ok := closeArgumentTail("{"); ok { + return closed, true + } + return "", false +} + +// topLevelCommaPositions returns the byte offsets of commas that sit directly +// inside the outermost object, outside any nested structure or string. +func topLevelCommaPositions(text string) []int { + positions := make([]int, 0, 8) + depth := 0 + inString := false + for index := 0; index < len(text); index++ { + character := text[index] + if inString { + if character == '\\' { + index++ + continue + } + if character == '"' { + inString = false + } + continue + } + switch character { + case '"': + inString = true + case '{', '[': + depth++ + case '}', ']': + depth-- + case ',': + if depth == 1 { + positions = append(positions, index) + } + } + } + return positions +} + func argumentRepairCandidates(text string) []string { candidates := []string{text} if withoutTrailing := stripTrailingCommas(text); withoutTrailing != text { diff --git a/internal/translate/toolargs_normalize_test.go b/internal/translate/toolargs_normalize_test.go new file mode 100644 index 00000000..c2cb00e8 --- /dev/null +++ b/internal/translate/toolargs_normalize_test.go @@ -0,0 +1,36 @@ +package translate + +import ( + "encoding/json" + "testing" +) + +func TestNormalizeToolCallArgumentsNeverReturnsInvalidJSON(t *testing.T) { + cases := []struct { + name string + raw string + want string + wantChange bool + }{ + {name: "valid", raw: `{"path":"a.go"}`, want: `{"path":"a.go"}`}, + {name: "blank", raw: " ", want: "{}", wantChange: true}, + {name: "trailing comma", raw: `{"path":"a.go",}`, want: `{"path":"a.go"}`, wantChange: true}, + {name: "missing brace", raw: `{"path":"a.go"`, want: `{"path":"a.go"}`, wantChange: true}, + {name: "truncated last field dropped", raw: `{"path":"a.go","body":"partial`, want: `{"path":"a.go"}`, wantChange: true}, + {name: "truncated only field becomes empty", raw: `{"command":"rm -rf /tmp/fo`, want: "{}", wantChange: true}, + {name: "truncated nested field dropped", raw: `{"path":"a.go","edits":[{"old":"x","new":"y`, want: `{"path":"a.go"}`, wantChange: true}, + {name: "not json at all", raw: `please read the file`, want: "{}", wantChange: true}, + } + for _, tc := range cases { + got, changed := NormalizeToolCallArguments(tc.raw) + if !json.Valid([]byte(got)) { + t.Fatalf("%s: result is not valid JSON: %q", tc.name, got) + } + if got != tc.want { + t.Fatalf("%s: got %q, want %q", tc.name, got, tc.want) + } + if changed != tc.wantChange { + t.Fatalf("%s: changed = %v, want %v", tc.name, changed, tc.wantChange) + } + } +}