From 00c5bd955e03baa823b0e26167b614726721e5a4 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 12:51:29 +0000 Subject: [PATCH 01/52] test(providers/openaicompat): cover tool calls without an index Google's OpenAI-compatible endpoint streams each parallel tool call as a whole chunk with a unique id and no index. The capture in testdata comes from gemini-4-neon through the Coder AI gateway. These tests fail until the stream accumulator stops keying such calls on the decoded index, which is 0 for every call. --- .../testdata/gemini_parallel_unindexed.sse | 9 + .../openaicompat/unindexed_tool_calls_test.go | 211 ++++++++++++++++++ 2 files changed, 220 insertions(+) create mode 100644 providers/openaicompat/testdata/gemini_parallel_unindexed.sse create mode 100644 providers/openaicompat/unindexed_tool_calls_test.go diff --git a/providers/openaicompat/testdata/gemini_parallel_unindexed.sse b/providers/openaicompat/testdata/gemini_parallel_unindexed.sse new file mode 100644 index 000000000..30941928c --- /dev/null +++ b/providers/openaicompat/testdata/gemini_parallel_unindexed.sse @@ -0,0 +1,9 @@ +data: {"choices":[{"delta":{"role":"assistant","tool_calls":[{"extra_content":{"google":{"thought_signature":"EuoCCucCAVjVB3t6HmSieGF3SklfonCozXVYYq01+8CaJnmzJy7NANzk+iQxsZQW2jRmhg3RZxcd2yKIozgDv4M1rMBo/lTuZE56s3dh14Y1FTvak5DBMbEHf4GVSUQZE4hciszCGQJCD9B/05GcjzFlaSeKIeVpokS2s9PKFuj/CAwZwKNur9+DpvIAeGCrdPf0TzCJn6jOQ1c6UJq8OLLgr59siZd1YJltTOULZ+oloi/9KE/f4wd8e17Ds98q39QCNyCRW71+6I/t6yqp59Qwb/IT8gwjx66cgEgV7ogMBNjG4xscbsNhifhV5EWP7WOv8ppD9h2zWeTcgKuD3tghJxT5gVHK68ix28jOq82spU7wTG2eYj5DOBl7tIZiJEoLN64RyCCgVAjVxGCSxVng4Q9xWKzUmX/MHsCxlBNUmB0AUleiTwEajkz1sJteIGk47b2JjKoWV/OUqQUtRHMZ2VfNY3vOkQ7lhVI="}},"function":{"arguments":"{\"city\":\"Paris\"}","name":"get_weather"},"id":"call_6886726613787760133","type":"function"}]},"index":0}],"created":1796206514,"id":"b5ae08af-8855-4e83-b7e9-4e1446b3c5c8","model":"gemini-4-neon","object":"chat.completion.chunk","usage":{"completion_tokens":16,"prompt_tokens":106,"total_tokens":163,"completion_tokens_details":{"accepted_prediction_tokens":0,"audio_tokens":0,"reasoning_tokens":0,"rejected_prediction_tokens":0},"prompt_tokens_details":{"audio_tokens":0,"cache_write_tokens":0,"cached_tokens":0}}} + +data: {"choices":[{"delta":{"role":"assistant","tool_calls":[{"function":{"arguments":"{\"city\":\"Tokyo\"}","name":"get_weather"},"id":"call_6886726613787759528","type":"function"}]},"index":0}],"created":1796206514,"id":"b5ae08af-8855-4e83-b7e9-4e1446b3c5c8","model":"gemini-4-neon","object":"chat.completion.chunk","usage":{"completion_tokens":32,"prompt_tokens":106,"total_tokens":179,"completion_tokens_details":{"accepted_prediction_tokens":0,"audio_tokens":0,"reasoning_tokens":0,"rejected_prediction_tokens":0},"prompt_tokens_details":{"audio_tokens":0,"cache_write_tokens":0,"cached_tokens":0}}} + +data: {"choices":[{"delta":{"role":"assistant","tool_calls":[{"function":{"arguments":"{\"city\":\"Lima\"}","name":"get_weather"},"id":"call_6886726613787761809","type":"function"}]},"index":0}],"created":1796206514,"id":"b5ae08af-8855-4e83-b7e9-4e1446b3c5c8","model":"gemini-4-neon","object":"chat.completion.chunk","usage":{"completion_tokens":48,"prompt_tokens":106,"total_tokens":195,"completion_tokens_details":{"accepted_prediction_tokens":0,"audio_tokens":0,"reasoning_tokens":0,"rejected_prediction_tokens":0},"prompt_tokens_details":{"audio_tokens":0,"cache_write_tokens":0,"cached_tokens":0}}} + +data: {"choices":[{"delta":{"role":"assistant"},"finish_reason":"stop","index":0}],"created":1796206514,"id":"b5ae08af-8855-4e83-b7e9-4e1446b3c5c8","model":"gemini-4-neon","object":"chat.completion.chunk","usage":{"completion_tokens":55,"prompt_tokens":106,"total_tokens":202,"completion_tokens_details":{"accepted_prediction_tokens":0,"audio_tokens":0,"reasoning_tokens":0,"rejected_prediction_tokens":0},"prompt_tokens_details":{"audio_tokens":0,"cache_write_tokens":0,"cached_tokens":0}}} + +data: [DONE] diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go new file mode 100644 index 000000000..5e1d1ed69 --- /dev/null +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -0,0 +1,211 @@ +package openaicompat + +import ( + "cmp" + "fmt" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "charm.land/fantasy" + "github.com/stretchr/testify/require" +) + +// PROSE: serveRawSSE answers every request with body verbatim as an SSE stream. +func serveRawSSE(t *testing.T, body string) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprint(w, body) + })) + t.Cleanup(srv.Close) + return srv +} + +func streamFrom(t *testing.T, body string) []fantasy.StreamPart { + t.Helper() + srv := serveRawSSE(t, body) + provider, err := New(WithBaseURL(srv.URL), WithAPIKey("x")) + require.NoError(t, err) + lm, err := provider.LanguageModel(t.Context(), "m") + require.NoError(t, err) + return streamParts(t, lm, fantasy.Prompt{fantasy.NewUserMessage("hi")}) +} + +type streamedCall struct { + id string + name string + input string + deltas string +} + +// PROSE: collectCalls returns the emitted tool calls in order with their concatenated input deltas, and the finish reason; it fails on stream errors and on a ToolInputStart count that differs from the ToolCall count. +func collectCalls(t *testing.T, parts []fantasy.StreamPart) ([]streamedCall, fantasy.FinishReason) { + t.Helper() + + var ( + calls []streamedCall + starts int + finish fantasy.FinishReason + ) + deltas := map[string]string{} + + for _, p := range parts { + switch p.Type { + case fantasy.StreamPartTypeError: + t.Fatalf("stream error: %v", p.Error) + case fantasy.StreamPartTypeToolInputStart: + starts++ + case fantasy.StreamPartTypeToolInputDelta: + deltas[p.ID] += p.Delta + case fantasy.StreamPartTypeToolCall: + calls = append(calls, streamedCall{id: p.ID, name: p.ToolCallName, input: p.ToolCallInput}) + case fantasy.StreamPartTypeFinish: + finish = p.FinishReason + } + } + + require.Equal(t, len(calls), starts, "one ToolInputStart per ToolCall") + for i := range calls { + calls[i].deltas = deltas[calls[i].id] + } + return calls, finish +} + +func TestStream_GeminiParallelToolCallsWithoutIndex(t *testing.T) { + t.Parallel() + + // PROSE: the testdata is a live capture of Google's OpenAI-compatible endpoint through the Coder AI gateway; each parallel call arrives whole in its own chunk with no index. + capture, err := os.ReadFile("testdata/gemini_parallel_unindexed.sse") + require.NoError(t, err) + + calls, finish := collectCalls(t, streamFrom(t, string(capture))) + + want := []struct{ id, input string }{ + {"call_6886726613787760133", `{"city":"Paris"}`}, + {"call_6886726613787759528", `{"city":"Tokyo"}`}, + {"call_6886726613787761809", `{"city":"Lima"}`}, + } + require.Len(t, calls, len(want)) + for i, w := range want { + require.Equal(t, w.id, calls[i].id) + require.Equal(t, "get_weather", calls[i].name) + require.Equal(t, w.input, calls[i].input) + require.Equal(t, w.input, calls[i].deltas, "streamed input deltas must match the final input") + } + + // PROSE: Google reports "stop" on tool-call turns and the provider keeps that reason. + require.Equal(t, fantasy.FinishReasonStop, finish) +} + +func TestStream_UnindexedToolCallShapes(t *testing.T) { + t.Parallel() + + chunk := func(toolCalls string) string { + return `data: {"id":"c","object":"chat.completion.chunk","created":1,"model":"m","choices":[{"index":0,"delta":{"tool_calls":[` + toolCalls + `]}}]}` + "\n\n" + } + const ( + finishStop = `data: {"id":"c","object":"chat.completion.chunk","created":1,"model":"m","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}` + "\n\n" + done = "data: [DONE]\n\n" + ) + + tests := []struct { + name string + chunks []string + noFinish bool + want []string + wantFinish fantasy.FinishReason + }{ + { + name: "one call split into id-less fragments", + chunks: []string{ + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), + chunk(`{"function":{"arguments":"1}"}}`), + }, + want: []string{`a={"x":1}`}, + }, + { + name: "fragments that repeat the id and name", + chunks: []string{ + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"1}"}}`), + }, + want: []string{`a={"x":1}`}, + }, + { + name: "two calls in one chunk", + chunks: []string{ + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":1}"}},{"id":"b","type":"function","function":{"name":"f","arguments":"{\"x\":2}"}}`), + }, + want: []string{`a={"x":1}`, `b={"x":2}`}, + }, + { + name: "calls without ids, same name", + chunks: []string{ + chunk(`{"type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), + chunk(`{"type":"function","function":{"name":"f","arguments":"{\"x\":2}"}}`), + }, + want: []string{`tool-call-0={"x":1}`, `tool-call-1={"x":2}`}, + }, + { + name: "id-less fragment repeating the name before the arguments complete", + chunks: []string{ + chunk(`{"type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), + chunk(`{"type":"function","function":{"name":"f","arguments":"1}"}}`), + }, + want: []string{`tool-call-0={"x":1}`}, + }, + { + name: "calls stay in arrival order", + chunks: []string{ + chunk(`{"id":"z","type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), + chunk(`{"id":"m","type":"function","function":{"name":"f","arguments":"{\"x\":2}"}}`), + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":3}"}}`), + }, + want: []string{`z={"x":1}`, `m={"x":2}`, `a={"x":3}`}, + }, + { + name: "complete calls in a stream without a finish reason", + chunks: []string{ + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), + chunk(`{"id":"b","type":"function","function":{"name":"f","arguments":"{\"x\":2}"}}`), + }, + noFinish: true, + want: []string{`a={"x":1}`, `b={"x":2}`}, + wantFinish: fantasy.FinishReasonToolCalls, + }, + { + name: "indexed deltas are unchanged", + chunks: []string{ + chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":""}},{"index":1,"id":"b","type":"function","function":{"name":"g","arguments":""}}`), + chunk(`{"index":1,"function":{"arguments":"{\"y\":2}"}}`), + chunk(`{"index":0,"function":{"arguments":"{\"x\":1}"}}`), + }, + want: []string{`a={"x":1}`, `b={"y":2}`}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + body := strings.Join(tt.chunks, "") + if !tt.noFinish { + body += finishStop + } + body += done + + calls, finish := collectCalls(t, streamFrom(t, body)) + + var got []string + for _, c := range calls { + require.Equal(t, c.input, c.deltas) + got = append(got, c.id+"="+c.input) + } + require.Equal(t, tt.want, got) + require.Equal(t, cmp.Or(tt.wantFinish, fantasy.FinishReasonStop), finish) + }) + } +} From 81ce94dd45ff857a7b875c805f174d8a42b1c33d Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 12:51:29 +0000 Subject: [PATCH 02/52] fix(providers/openai): keep unindexed stream tool calls apart Stream tool calls were keyed by index. A delta without an index decodes as 0, so every parallel call from Google's OpenAI-compatible endpoint merged into one call with concatenated arguments. A delta without an index now starts a new call when it carries a new id, or a name without an id after the previous call's arguments are complete JSON. Other unindexed deltas continue the latest call. Indexed deltas are handled as before. --- providers/openai/language_model.go | 40 ++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index fd8e37051..1e6141038 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -149,6 +149,39 @@ type streamToolCall struct { hasFinished bool } +// PROSE: unindexedToolCallKey picks the toolCalls key for a delta without an index (Gemini sends each parallel call whole, unindexed, and the SDK decodes the index as 0); explain when a delta starts a new call versus continues the latest one. +func unindexedToolCallKey(toolCalls map[int64]streamToolCall, latest int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { + if latest < 0 { + return nextToolCallKey(toolCalls) + } + + if startsNewToolCall(toolCalls[latest], delta) { + return latest + 1 + } + return latest +} + +// PROSE: nextToolCallKey returns the key after every existing call so the first unindexed call never collides with an indexed one. +func nextToolCallKey(toolCalls map[int64]streamToolCall) int64 { + next := int64(0) + for idx := range toolCalls { + next = max(next, idx+1) + } + return next +} + +// PROSE: startsNewToolCall reports whether delta opens a new call: a different id, or a name without an id once current's arguments are complete JSON; anything else is a fragment of current. +func startsNewToolCall(current streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) bool { + switch { + case delta.ID != "": + return delta.ID != current.id + case delta.Function.Name != "": + return json.Valid([]byte(current.arguments)) + default: + return false + } +} + // responseCapture holds the raw HTTP response of a call so response headers // can be surfaced through provider metadata. Capturing is only enabled when // a header func is configured on the language model. @@ -474,6 +507,8 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S stream := o.client.Chat.Completions.NewStreaming(ctx, *params, capture.requestOptions(o.headerFunc, append(callUARequestOptions(call), callHeadersRequestOptions(call)...))...) isActiveText := false toolCalls := make(map[int64]streamToolCall) + // PROSE: latestUnindexed is the toolCalls key of the latest call created from a delta without an index; -1 until the first one. + latestUnindexed := int64(-1) providerMetadata := fantasy.ProviderMetadata{ Name: &ProviderMetadata{}, @@ -560,6 +595,11 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S } for _, toolCallDelta := range choice.Delta.ToolCalls { + if !toolCallDelta.JSON.Index.Valid() { + latestUnindexed = unindexedToolCallKey(toolCalls, latestUnindexed, toolCallDelta) + toolCallDelta.Index = latestUnindexed + } + if existingToolCall, ok := toolCalls[toolCallDelta.Index]; ok { if toolCallDelta.Function.Arguments != "" { existingToolCall.arguments += toolCallDelta.Function.Arguments From 33e0b0c9e5ede0e9d2e956ab78186a082c9c9acd Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 13:43:13 +0000 Subject: [PATCH 03/52] docs(providers/openai): document unindexed tool-call keying Replace draft comment markers with brief rationale on the unindexed tool-call helpers and the streaming test fixture. --- providers/openai/language_model.go | 11 +++++++---- providers/openaicompat/unindexed_tool_calls_test.go | 7 +++---- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 1e6141038..e01786259 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -149,7 +149,9 @@ type streamToolCall struct { hasFinished bool } -// PROSE: unindexedToolCallKey picks the toolCalls key for a delta without an index (Gemini sends each parallel call whole, unindexed, and the SDK decodes the index as 0); explain when a delta starts a new call versus continues the latest one. +// unindexedToolCallKey assigns a toolCalls key to a delta whose JSON omitted +// the index field, which the SDK otherwise decodes as 0. Keeping keys +// monotonically increasing keeps calls in arrival order when finalized. func unindexedToolCallKey(toolCalls map[int64]streamToolCall, latest int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { if latest < 0 { return nextToolCallKey(toolCalls) @@ -161,7 +163,6 @@ func unindexedToolCallKey(toolCalls map[int64]streamToolCall, latest int64, delt return latest } -// PROSE: nextToolCallKey returns the key after every existing call so the first unindexed call never collides with an indexed one. func nextToolCallKey(toolCalls map[int64]streamToolCall) int64 { next := int64(0) for idx := range toolCalls { @@ -170,7 +171,10 @@ func nextToolCallKey(toolCalls map[int64]streamToolCall) int64 { return next } -// PROSE: startsNewToolCall reports whether delta opens a new call: a different id, or a name without an id once current's arguments are complete JSON; anything else is a fragment of current. +// startsNewToolCall reports whether an unindexed delta opens a new tool call: +// a new id always starts one, and a name without an id starts one only once +// the current call's arguments parse as complete JSON so repeated names on +// partial fragments still attach to the current call. func startsNewToolCall(current streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) bool { switch { case delta.ID != "": @@ -507,7 +511,6 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S stream := o.client.Chat.Completions.NewStreaming(ctx, *params, capture.requestOptions(o.headerFunc, append(callUARequestOptions(call), callHeadersRequestOptions(call)...))...) isActiveText := false toolCalls := make(map[int64]streamToolCall) - // PROSE: latestUnindexed is the toolCalls key of the latest call created from a delta without an index; -1 until the first one. latestUnindexed := int64(-1) providerMetadata := fantasy.ProviderMetadata{ diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index 5e1d1ed69..64049427a 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -13,7 +13,6 @@ import ( "github.com/stretchr/testify/require" ) -// PROSE: serveRawSSE answers every request with body verbatim as an SSE stream. func serveRawSSE(t *testing.T, body string) *httptest.Server { t.Helper() srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { @@ -41,7 +40,6 @@ type streamedCall struct { deltas string } -// PROSE: collectCalls returns the emitted tool calls in order with their concatenated input deltas, and the finish reason; it fails on stream errors and on a ToolInputStart count that differs from the ToolCall count. func collectCalls(t *testing.T, parts []fantasy.StreamPart) ([]streamedCall, fantasy.FinishReason) { t.Helper() @@ -77,7 +75,9 @@ func collectCalls(t *testing.T, parts []fantasy.StreamPart) ([]streamedCall, fan func TestStream_GeminiParallelToolCallsWithoutIndex(t *testing.T) { t.Parallel() - // PROSE: the testdata is a live capture of Google's OpenAI-compatible endpoint through the Coder AI gateway; each parallel call arrives whole in its own chunk with no index. + // Fixture models a stream where each parallel tool call arrives whole in + // its own chunk with a unique id, no index field, and a trailing "stop" + // finish reason. capture, err := os.ReadFile("testdata/gemini_parallel_unindexed.sse") require.NoError(t, err) @@ -96,7 +96,6 @@ func TestStream_GeminiParallelToolCallsWithoutIndex(t *testing.T) { require.Equal(t, w.input, calls[i].deltas, "streamed input deltas must match the final input") } - // PROSE: Google reports "stop" on tool-call turns and the provider keeps that reason. require.Equal(t, fantasy.FinishReasonStop, finish) } From 3151eed71170800763c80e84c3eda7a6d4b573b0 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 14:08:38 +0000 Subject: [PATCH 04/52] test(providers/openaicompat): cover unindexed call correlation Reviewers found shapes the index-less rule mishandles: an index 0 opener continued by unindexed fragments, interleaved fragments correlated only by id, a whitespace fragment after complete arguments, a name change on a call without arguments, and an explicit index that lands on a key a synthetic call already took. collectCalls now also checks the per-call part sequence and names. --- .../openaicompat/unindexed_tool_calls_test.go | 237 +++++++++++++----- 1 file changed, 177 insertions(+), 60 deletions(-) diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index 64049427a..26117d051 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -34,45 +34,90 @@ func streamFrom(t *testing.T, body string) []fantasy.StreamPart { } type streamedCall struct { - id string - name string - input string - deltas string + id string + name string + input string } -func collectCalls(t *testing.T, parts []fantasy.StreamPart) ([]streamedCall, fantasy.FinishReason) { +func (c streamedCall) String() string { + return c.id + ":" + c.name + "=" + c.input +} + +type toolCallStream struct { + calls []streamedCall + started []string + finish fantasy.FinishReason +} + +// PROSE: collectCalls checks the per-id part sequence (one ToolInputStart, deltas, one ToolInputEnd, at most one ToolCall with the start's name and the concatenated deltas as input, allowing the "{}" backfill for calls that streamed no arguments). +func collectCalls(t *testing.T, parts []fantasy.StreamPart) toolCallStream { t.Helper() - var ( - calls []streamedCall - starts int - finish fantasy.FinishReason - ) - deltas := map[string]string{} + type progress struct { + name string + deltas string + ended bool + called bool + } + + var out toolCallStream + seen := map[string]*progress{} for _, p := range parts { switch p.Type { case fantasy.StreamPartTypeError: t.Fatalf("stream error: %v", p.Error) + case fantasy.StreamPartTypeToolInputStart: - starts++ + require.NotContains(t, seen, p.ID, "second ToolInputStart for %s", p.ID) + seen[p.ID] = &progress{name: p.ToolCallName} + out.started = append(out.started, p.ID) + case fantasy.StreamPartTypeToolInputDelta: - deltas[p.ID] += p.Delta + c := seen[p.ID] + require.NotNil(t, c, "ToolInputDelta before ToolInputStart for %s", p.ID) + require.False(t, c.ended, "ToolInputDelta after ToolInputEnd for %s", p.ID) + c.deltas += p.Delta + + case fantasy.StreamPartTypeToolInputEnd: + c := seen[p.ID] + require.NotNil(t, c, "ToolInputEnd before ToolInputStart for %s", p.ID) + require.False(t, c.ended, "second ToolInputEnd for %s", p.ID) + c.ended = true + case fantasy.StreamPartTypeToolCall: - calls = append(calls, streamedCall{id: p.ID, name: p.ToolCallName, input: p.ToolCallInput}) + c := seen[p.ID] + require.NotNil(t, c, "ToolCall before ToolInputStart for %s", p.ID) + require.True(t, c.ended, "ToolCall before ToolInputEnd for %s", p.ID) + require.False(t, c.called, "second ToolCall for %s", p.ID) + c.called = true + + require.Equal(t, c.name, p.ToolCallName, "ToolCall name differs from ToolInputStart for %s", p.ID) + if c.deltas != "" || p.ToolCallInput != "{}" { + require.Equal(t, c.deltas, p.ToolCallInput, "streamed input deltas differ from the final input for %s", p.ID) + } + out.calls = append(out.calls, streamedCall{id: p.ID, name: p.ToolCallName, input: p.ToolCallInput}) + case fantasy.StreamPartTypeFinish: - finish = p.FinishReason + out.finish = p.FinishReason } } - require.Equal(t, len(calls), starts, "one ToolInputStart per ToolCall") - for i := range calls { - calls[i].deltas = deltas[calls[i].id] + for id, c := range seen { + require.True(t, c.ended, "no ToolInputEnd for %s", id) + } + return out +} + +func callStrings(calls []streamedCall) []string { + var out []string + for _, c := range calls { + out = append(out, c.String()) } - return calls, finish + return out } -func TestStream_GeminiParallelToolCallsWithoutIndex(t *testing.T) { +func TestStream_UnindexedGeminiParallelToolCalls(t *testing.T) { t.Parallel() // Fixture models a stream where each parallel tool call arrives whole in @@ -81,22 +126,14 @@ func TestStream_GeminiParallelToolCallsWithoutIndex(t *testing.T) { capture, err := os.ReadFile("testdata/gemini_parallel_unindexed.sse") require.NoError(t, err) - calls, finish := collectCalls(t, streamFrom(t, string(capture))) + got := collectCalls(t, streamFrom(t, string(capture))) - want := []struct{ id, input string }{ - {"call_6886726613787760133", `{"city":"Paris"}`}, - {"call_6886726613787759528", `{"city":"Tokyo"}`}, - {"call_6886726613787761809", `{"city":"Lima"}`}, - } - require.Len(t, calls, len(want)) - for i, w := range want { - require.Equal(t, w.id, calls[i].id) - require.Equal(t, "get_weather", calls[i].name) - require.Equal(t, w.input, calls[i].input) - require.Equal(t, w.input, calls[i].deltas, "streamed input deltas must match the final input") - } - - require.Equal(t, fantasy.FinishReasonStop, finish) + require.Equal(t, []string{ + `call_6886726613787760133:get_weather={"city":"Paris"}`, + `call_6886726613787759528:get_weather={"city":"Tokyo"}`, + `call_6886726613787761809:get_weather={"city":"Lima"}`, + }, callStrings(got.calls)) + require.Equal(t, fantasy.FinishReasonStop, got.finish) } func TestStream_UnindexedToolCallShapes(t *testing.T) { @@ -105,17 +142,19 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { chunk := func(toolCalls string) string { return `data: {"id":"c","object":"chat.completion.chunk","created":1,"model":"m","choices":[{"index":0,"delta":{"tool_calls":[` + toolCalls + `]}}]}` + "\n\n" } - const ( - finishStop = `data: {"id":"c","object":"chat.completion.chunk","created":1,"model":"m","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}` + "\n\n" - done = "data: [DONE]\n\n" - ) + finishChunk := func(reason string) string { + return `data: {"id":"c","object":"chat.completion.chunk","created":1,"model":"m","choices":[{"index":0,"delta":{},"finish_reason":"` + reason + `"}]}` + "\n\n" + } + const done = "data: [DONE]\n\n" tests := []struct { - name string - chunks []string - noFinish bool - want []string - wantFinish fantasy.FinishReason + name string + chunks []string + finish string + noFinish bool + want []string + wantStarted []string + wantFinish fantasy.FinishReason }{ { name: "one call split into id-less fragments", @@ -123,7 +162,7 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), chunk(`{"function":{"arguments":"1}"}}`), }, - want: []string{`a={"x":1}`}, + want: []string{`a:f={"x":1}`}, }, { name: "fragments that repeat the id and name", @@ -131,14 +170,14 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"1}"}}`), }, - want: []string{`a={"x":1}`}, + want: []string{`a:f={"x":1}`}, }, { name: "two calls in one chunk", chunks: []string{ chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":1}"}},{"id":"b","type":"function","function":{"name":"f","arguments":"{\"x\":2}"}}`), }, - want: []string{`a={"x":1}`, `b={"x":2}`}, + want: []string{`a:f={"x":1}`, `b:f={"x":2}`}, }, { name: "calls without ids, same name", @@ -146,7 +185,7 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { chunk(`{"type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), chunk(`{"type":"function","function":{"name":"f","arguments":"{\"x\":2}"}}`), }, - want: []string{`tool-call-0={"x":1}`, `tool-call-1={"x":2}`}, + want: []string{`tool-call-0:f={"x":1}`, `tool-call-1:f={"x":2}`}, }, { name: "id-less fragment repeating the name before the arguments complete", @@ -154,7 +193,7 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { chunk(`{"type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), chunk(`{"type":"function","function":{"name":"f","arguments":"1}"}}`), }, - want: []string{`tool-call-0={"x":1}`}, + want: []string{`tool-call-0:f={"x":1}`}, }, { name: "calls stay in arrival order", @@ -163,7 +202,7 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { chunk(`{"id":"m","type":"function","function":{"name":"f","arguments":"{\"x\":2}"}}`), chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":3}"}}`), }, - want: []string{`z={"x":1}`, `m={"x":2}`, `a={"x":3}`}, + want: []string{`z:f={"x":1}`, `m:f={"x":2}`, `a:f={"x":3}`}, }, { name: "complete calls in a stream without a finish reason", @@ -172,7 +211,7 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { chunk(`{"id":"b","type":"function","function":{"name":"f","arguments":"{\"x\":2}"}}`), }, noFinish: true, - want: []string{`a={"x":1}`, `b={"x":2}`}, + want: []string{`a:f={"x":1}`, `b:f={"x":2}`}, wantFinish: fantasy.FinishReasonToolCalls, }, { @@ -182,7 +221,81 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { chunk(`{"index":1,"function":{"arguments":"{\"y\":2}"}}`), chunk(`{"index":0,"function":{"arguments":"{\"x\":1}"}}`), }, - want: []string{`a={"x":1}`, `b={"y":2}`}, + want: []string{`a:f={"x":1}`, `b:g={"y":2}`}, + }, + { + name: "indexed opener continued by id-less fragments", + chunks: []string{ + chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":""}}`), + chunk(`{"function":{"arguments":"{\"x\":"}}`), + chunk(`{"function":{"arguments":"1}"}}`), + }, + want: []string{`a:f={"x":1}`}, + }, + { + name: "indexed opener continued by id-less fragments without a finish reason", + chunks: []string{ + chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":""}}`), + chunk(`{"function":{"arguments":"{\"x\":"}}`), + chunk(`{"function":{"arguments":"1}"}}`), + }, + noFinish: true, + want: []string{`a:f={"x":1}`}, + wantFinish: fantasy.FinishReasonToolCalls, + }, + { + name: "interleaved fragments correlated by id", + chunks: []string{ + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), + chunk(`{"id":"b","type":"function","function":{"name":"g","arguments":"{\"y\":"}}`), + chunk(`{"id":"a","function":{"arguments":"1}"}}`), + chunk(`{"id":"b","function":{"arguments":"2}"}}`), + }, + want: []string{`a:f={"x":1}`, `b:g={"y":2}`}, + }, + { + name: "whitespace fragment after complete arguments, same name, no id", + chunks: []string{ + chunk(`{"type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), + chunk(`{"type":"function","function":{"name":"f","arguments":" "}}`), + }, + want: []string{`tool-call-0:f={"x":1} `}, + }, + { + name: "different names without ids, first with empty arguments", + chunks: []string{ + chunk(`{"type":"function","function":{"name":"f","arguments":""}}`), + chunk(`{"type":"function","function":{"name":"g","arguments":"{\"y\":2}"}}`), + }, + want: []string{`tool-call-0:f={}`, `tool-call-1:g={"y":2}`}, + }, + { + name: "leading empty id-less delta", + chunks: []string{ + chunk(`{"type":"function","function":{"name":"","arguments":""}}`), + chunk(`{"type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), + chunk(`{"type":"function","function":{"name":"g","arguments":"{\"y\":2}"}}`), + }, + want: []string{`tool-call-0:f={"x":1}`, `tool-call-1:g={"y":2}`}, + }, + { + name: "explicit index after synthetic calls took its key", + chunks: []string{ + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), + chunk(`{"id":"b","type":"function","function":{"name":"g","arguments":"{\"y\":2}"}}`), + chunk(`{"index":0,"id":"c","type":"function","function":{"name":"h","arguments":""}}`), + chunk(`{"index":0,"function":{"arguments":"{\"z\":3}"}}`), + }, + want: []string{`a:f={"x":1}`, `b:g={"y":2}`, `c:h={"z":3}`}, + }, + { + name: "id-less stream cut mid-arguments by length", + chunks: []string{ + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), + }, + finish: "length", + wantStarted: []string{"a"}, + wantFinish: fantasy.FinishReasonLength, }, } @@ -192,19 +305,23 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { body := strings.Join(tt.chunks, "") if !tt.noFinish { - body += finishStop + body += finishChunk(cmp.Or(tt.finish, "stop")) } body += done - calls, finish := collectCalls(t, streamFrom(t, body)) + got := collectCalls(t, streamFrom(t, body)) + + require.Equal(t, tt.want, callStrings(got.calls)) - var got []string - for _, c := range calls { - require.Equal(t, c.input, c.deltas) - got = append(got, c.id+"="+c.input) + wantStarted := tt.wantStarted + if wantStarted == nil { + for _, c := range got.calls { + wantStarted = append(wantStarted, c.id) + } } - require.Equal(t, tt.want, got) - require.Equal(t, cmp.Or(tt.wantFinish, fantasy.FinishReasonStop), finish) + require.Equal(t, wantStarted, got.started) + + require.Equal(t, cmp.Or(tt.wantFinish, fantasy.FinishReasonStop), got.finish) }) } } From 1290f3a3e092def9ee91f34f9a80d3ce207d2038 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 14:08:38 +0000 Subject: [PATCH 05/52] fix(providers/openai): correlate unindexed tool calls by id The previous rule compared each unindexed delta only with the latest unindexed call and allocated keys as latest+1, so interleaved ids split, an indexed opener lost its unindexed fragments, and a later explicit index could overwrite a synthetic call. Unindexed deltas now continue the call with the same id, or the most recently touched call when they carry no id and do not look like a new call. Fresh keys never collide: an explicit index whose key is taken maps to a fresh key. Streams with only indexed deltas keep key equal to wire index. Skipped empty deltas no longer move any state. --- providers/openai/language_model.go | 115 ++++++++++++++++++++--------- 1 file changed, 81 insertions(+), 34 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index e01786259..24f57ab9e 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -149,41 +149,88 @@ type streamToolCall struct { hasFinished bool } -// unindexedToolCallKey assigns a toolCalls key to a delta whose JSON omitted -// the index field, which the SDK otherwise decodes as 0. Keeping keys -// monotonically increasing keeps calls in arrival order when finalized. -func unindexedToolCallKey(toolCalls map[int64]streamToolCall, latest int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { - if latest < 0 { - return nextToolCallKey(toolCalls) +// PROSE: toolCallKeys maps stream tool-call deltas to toolCalls keys: indexed-only streams keep key = wire index, deltas without an index are correlated by id or by the latest call, and keys never collide. +type toolCallKeys struct { + byWireIndex map[int64]int64 + used map[int64]bool + next int64 + latest int64 +} + +func newToolCallKeys() *toolCallKeys { + return &toolCallKeys{ + byWireIndex: make(map[int64]int64), + used: make(map[int64]bool), + latest: -1, } +} - if startsNewToolCall(toolCalls[latest], delta) { - return latest + 1 +// PROSE: resolve returns the key for delta without recording it, so a delta that is later skipped leaves no trace; commit records it. +func (k *toolCallKeys) resolve(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { + if delta.JSON.Index.Valid() { + return k.forWireIndex(delta.Index) } - return latest + return k.forUnindexed(toolCalls, delta) } -func nextToolCallKey(toolCalls map[int64]streamToolCall) int64 { - next := int64(0) - for idx := range toolCalls { - next = max(next, idx+1) +// PROSE: commit records key as used, maps the delta's wire index to it, and makes it the latest call. +func (k *toolCallKeys) commit(delta openai.ChatCompletionChunkChoiceDeltaToolCall, key int64) { + if delta.JSON.Index.Valid() { + k.byWireIndex[delta.Index] = key } - return next + k.used[key] = true + k.next = max(k.next, key+1) + k.latest = key } -// startsNewToolCall reports whether an unindexed delta opens a new tool call: -// a new id always starts one, and a name without an id starts one only once -// the current call's arguments parse as complete JSON so repeated names on -// partial fragments still attach to the current call. -func startsNewToolCall(current streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) bool { - switch { - case delta.ID != "": - return delta.ID != current.id - case delta.Function.Name != "": - return json.Valid([]byte(current.arguments)) - default: +// PROSE: forWireIndex keeps key = wire index unless a synthetic call already took that key, in which case the wire index gets a fresh key. +func (k *toolCallKeys) forWireIndex(index int64) int64 { + if key, ok := k.byWireIndex[index]; ok { + return key + } + if k.used[index] { + return k.next + } + return index +} + +// PROSE: forUnindexed correlates a delta without an index: by id when it has one, otherwise against the latest call; explain the rule and why a fresh key is k.next. +func (k *toolCallKeys) forUnindexed(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { + if delta.ID != "" { + for key, tc := range toolCalls { + if tc.id == delta.ID { + return key + } + } + return k.next + } + + latest, ok := toolCalls[k.latest] + if !ok || startsUnidentifiedToolCall(latest, delta) { + return k.next + } + return k.latest +} + +// PROSE: startsUnidentifiedToolCall decides whether a delta with no index and no id opens a new call after latest: a different name does; the same name does only when latest's arguments are complete JSON and the delta's arguments look like the start of new arguments. +func startsUnidentifiedToolCall(latest streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) bool { + name := delta.Function.Name + if name == "" { return false } + if name != latest.name { + return true + } + return json.Valid([]byte(latest.arguments)) && opensArguments(delta.Function.Arguments) +} + +// PROSE: opensArguments reports whether a fragment can begin a new call's arguments; a whitespace-only fragment cannot, since it is trailing whitespace of the latest call. +func opensArguments(arguments string) bool { + if arguments == "" { + return true + } + trimmed := strings.TrimSpace(arguments) + return strings.HasPrefix(trimmed, "{") || strings.HasPrefix(trimmed, "[") } // responseCapture holds the raw HTTP response of a call so response headers @@ -511,7 +558,7 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S stream := o.client.Chat.Completions.NewStreaming(ctx, *params, capture.requestOptions(o.headerFunc, append(callUARequestOptions(call), callHeadersRequestOptions(call)...))...) isActiveText := false toolCalls := make(map[int64]streamToolCall) - latestUnindexed := int64(-1) + callKeys := newToolCallKeys() providerMetadata := fantasy.ProviderMetadata{ Name: &ProviderMetadata{}, @@ -598,12 +645,9 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S } for _, toolCallDelta := range choice.Delta.ToolCalls { - if !toolCallDelta.JSON.Index.Valid() { - latestUnindexed = unindexedToolCallKey(toolCalls, latestUnindexed, toolCallDelta) - toolCallDelta.Index = latestUnindexed - } + key := callKeys.resolve(toolCalls, toolCallDelta) - if existingToolCall, ok := toolCalls[toolCallDelta.Index]; ok { + if existingToolCall, ok := toolCalls[key]; ok { if toolCallDelta.Function.Arguments != "" { existingToolCall.arguments += toolCallDelta.Function.Arguments if !yield(fantasy.StreamPart{ @@ -614,7 +658,8 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S return } } - toolCalls[toolCallDelta.Index] = existingToolCall + toolCalls[key] = existingToolCall + callKeys.commit(toolCallDelta, key) } else { // Some provider like Ollama may send empty tool calls or miss some fields. // We'll skip when we don't have enough info and also assume sane defaults. @@ -622,7 +667,7 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S continue } toolCallDelta.Type = cmp.Or(toolCallDelta.Type, "function") - toolCallDelta.ID = cmp.Or(toolCallDelta.ID, fmt.Sprintf("tool-call-%d", toolCallDelta.Index)) + toolCallDelta.ID = cmp.Or(toolCallDelta.ID, fmt.Sprintf("tool-call-%d", key)) if toolCallDelta.Type != "function" { yield(fantasy.StreamPart{ @@ -639,11 +684,12 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S }) { return } - toolCalls[toolCallDelta.Index] = streamToolCall{ + toolCalls[key] = streamToolCall{ id: toolCallDelta.ID, name: toolCallDelta.Function.Name, arguments: toolCallDelta.Function.Arguments, } + callKeys.commit(toolCallDelta, key) if toolCallDelta.Function.Arguments != "" { if !yield(fantasy.StreamPart{ @@ -743,6 +789,7 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S return } + // PROSE: stale, keys equal wire indexes only for indexed-only streams; synthetic and remapped calls sort in creation order. // Finalize tool calls in index order after the stream completes. // When truncated, skip ToolCall parts to prevent agents from // dispatching calls with incomplete arguments. From f20dd8deb314002689bd58c06dc669c8670e3b4f Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 14:16:09 +0000 Subject: [PATCH 06/52] docs(providers/openai): document toolCallKeys and test helper Replace draft comment markers on toolCallKeys and collectCalls, and update the tool-call finalization comment to reflect key ordering for synthetic and remapped calls. --- providers/openai/language_model.go | 37 +++++++++++++------ .../openaicompat/unindexed_tool_calls_test.go | 5 ++- 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 24f57ab9e..a00843179 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -149,7 +149,10 @@ type streamToolCall struct { hasFinished bool } -// PROSE: toolCallKeys maps stream tool-call deltas to toolCalls keys: indexed-only streams keep key = wire index, deltas without an index are correlated by id or by the latest call, and keys never collide. +// toolCallKeys assigns non-colliding toolCalls map keys to streamed tool-call +// deltas when a provider omits the index field, which the SDK decodes as 0. +// Indexed-only streams keep each wire index as its key; synthetic and remapped +// calls take keys above every key committed so far. type toolCallKeys struct { byWireIndex map[int64]int64 used map[int64]bool @@ -165,7 +168,8 @@ func newToolCallKeys() *toolCallKeys { } } -// PROSE: resolve returns the key for delta without recording it, so a delta that is later skipped leaves no trace; commit records it. +// resolve returns the toolCalls key for delta without recording it, leaving +// key allocation and latest unchanged until commit runs. func (k *toolCallKeys) resolve(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { if delta.JSON.Index.Valid() { return k.forWireIndex(delta.Index) @@ -173,7 +177,6 @@ func (k *toolCallKeys) resolve(toolCalls map[int64]streamToolCall, delta openai. return k.forUnindexed(toolCalls, delta) } -// PROSE: commit records key as used, maps the delta's wire index to it, and makes it the latest call. func (k *toolCallKeys) commit(delta openai.ChatCompletionChunkChoiceDeltaToolCall, key int64) { if delta.JSON.Index.Valid() { k.byWireIndex[delta.Index] = key @@ -183,7 +186,9 @@ func (k *toolCallKeys) commit(delta openai.ChatCompletionChunkChoiceDeltaToolCal k.latest = key } -// PROSE: forWireIndex keeps key = wire index unless a synthetic call already took that key, in which case the wire index gets a fresh key. +// forWireIndex keeps index as its own key unless another call already holds +// that key, in which case index is remapped once to k.next and reused on +// subsequent deltas. func (k *toolCallKeys) forWireIndex(index int64) int64 { if key, ok := k.byWireIndex[index]; ok { return key @@ -194,7 +199,10 @@ func (k *toolCallKeys) forWireIndex(index int64) int64 { return index } -// PROSE: forUnindexed correlates a delta without an index: by id when it has one, otherwise against the latest call; explain the rule and why a fresh key is k.next. +// forUnindexed matches an unindexed delta with an id against any existing call +// (indexed or not), and matches an id-less delta against k.latest. New calls +// take k.next so they do not collide with existing keys and sort in creation +// order. func (k *toolCallKeys) forUnindexed(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { if delta.ID != "" { for key, tc := range toolCalls { @@ -212,7 +220,10 @@ func (k *toolCallKeys) forUnindexed(toolCalls map[int64]streamToolCall, delta op return k.latest } -// PROSE: startsUnidentifiedToolCall decides whether a delta with no index and no id opens a new call after latest: a different name does; the same name does only when latest's arguments are complete JSON and the delta's arguments look like the start of new arguments. +// startsUnidentifiedToolCall reports whether an index-less, id-less delta opens +// a new call after latest. A different non-empty name starts a new call; a +// repeated name starts one only once latest has complete JSON arguments and the +// delta begins new arguments, so name-repeating fragments stay attached. func startsUnidentifiedToolCall(latest streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) bool { name := delta.Function.Name if name == "" { @@ -224,7 +235,10 @@ func startsUnidentifiedToolCall(latest streamToolCall, delta openai.ChatCompleti return json.Valid([]byte(latest.arguments)) && opensArguments(delta.Function.Arguments) } -// PROSE: opensArguments reports whether a fragment can begin a new call's arguments; a whitespace-only fragment cannot, since it is trailing whitespace of the latest call. +// opensArguments reports whether an arguments fragment can open a new call: +// empty (arguments arrive later) or starting with '{' or '[' after trimming +// whitespace. Whitespace-only fragments return false so trailing whitespace +// stays on the previous call. func opensArguments(arguments string) bool { if arguments == "" { return true @@ -789,10 +803,11 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S return } - // PROSE: stale, keys equal wire indexes only for indexed-only streams; synthetic and remapped calls sort in creation order. - // Finalize tool calls in index order after the stream completes. - // When truncated, skip ToolCall parts to prevent agents from - // dispatching calls with incomplete arguments. + // Finalize tool calls in key order (wire-index order for + // indexed-only streams; first-seen order for synthetic and + // remapped calls). When truncated, skip ToolCall parts to + // prevent agents from dispatching calls with incomplete + // arguments. indices := make([]int64, 0, len(toolCalls)) for idx := range toolCalls { indices = append(indices, idx) diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index 26117d051..00f19cd99 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -49,7 +49,10 @@ type toolCallStream struct { finish fantasy.FinishReason } -// PROSE: collectCalls checks the per-id part sequence (one ToolInputStart, deltas, one ToolInputEnd, at most one ToolCall with the start's name and the concatenated deltas as input, allowing the "{}" backfill for calls that streamed no arguments). +// collectCalls asserts the per-id lifecycle (ToolInputStart, deltas, +// ToolInputEnd, and at most one ToolCall matching the start name and +// concatenated deltas, allowing "{}" when no deltas streamed) and returns the +// emitted calls, started ids, and finish reason. func collectCalls(t *testing.T, parts []fantasy.StreamPart) toolCallStream { t.Helper() From a1fa5801906392328ad8ab7b3bdf43ebab7c6282 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 15:46:35 +0000 Subject: [PATCH 07/52] test(providers/openaicompat): cover id matches across index kinds Adds rows for an unindexed opener continued by indexed deltas with the same id, an unindexed delta continuing an indexed call by id, and a same-name delta with empty arguments after complete arguments. --- .../openaicompat/unindexed_tool_calls_test.go | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index 00f19cd99..c267d444f 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -291,6 +291,31 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { }, want: []string{`a:f={"x":1}`, `b:g={"y":2}`, `c:h={"z":3}`}, }, + { + name: "unindexed opener continued by indexed deltas with the same id", + chunks: []string{ + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), + chunk(`{"index":0,"id":"a","function":{"arguments":"1"}}`), + chunk(`{"index":0,"function":{"arguments":"}"}}`), + }, + want: []string{`a:f={"x":1}`}, + }, + { + name: "unindexed delta continues the indexed call with its id", + chunks: []string{ + chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":""}}`), + chunk(`{"id":"a","function":{"arguments":"{\"x\":1}"}}`), + }, + want: []string{`a:f={"x":1}`}, + }, + { + name: "same name with empty arguments after complete arguments, no id", + chunks: []string{ + chunk(`{"type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), + chunk(`{"type":"function","function":{"name":"f","arguments":""}}`), + }, + want: []string{`tool-call-0:f={"x":1}`}, + }, { name: "id-less stream cut mid-arguments by length", chunks: []string{ From d01fedba2f51ff695626e2c326f3953b3527b520 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 15:46:35 +0000 Subject: [PATCH 08/52] fix(providers/openai): bind wire indexes to calls by id An unindexed opener followed by a continuation that carries the same id and an index took a fresh key, so the call split into two calls with the same id. A wire index seen for the first time now binds to an existing call with the delta's id, as long as no wire index already maps to that call. Indexed-only streams never match, so their keys stay equal to the wire index. A same-name delta with empty arguments after complete arguments also started a phantom call dispatched with "{}". Only non-empty arguments that start with "{" or "[" now open a new same-name call. --- providers/openai/language_model.go | 31 ++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index a00843179..59261dd79 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -149,20 +149,24 @@ type streamToolCall struct { hasFinished bool } +// PROSE: stale, an unseen wire index can also bind to an existing unindexed call's key, not only its own key or a fresh one. // toolCallKeys assigns non-colliding toolCalls map keys to streamed tool-call // deltas when a provider omits the index field, which the SDK decodes as 0. // Indexed-only streams keep each wire index as its key; synthetic and remapped // calls take keys above every key committed so far. type toolCallKeys struct { byWireIndex map[int64]int64 - used map[int64]bool - next int64 - latest int64 + // PROSE: wireBound holds keys some wire index maps to, unlike used, which also holds keys of calls created from unindexed deltas. + wireBound map[int64]bool + used map[int64]bool + next int64 + latest int64 } func newToolCallKeys() *toolCallKeys { return &toolCallKeys{ byWireIndex: make(map[int64]int64), + wireBound: make(map[int64]bool), used: make(map[int64]bool), latest: -1, } @@ -172,7 +176,7 @@ func newToolCallKeys() *toolCallKeys { // key allocation and latest unchanged until commit runs. func (k *toolCallKeys) resolve(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { if delta.JSON.Index.Valid() { - return k.forWireIndex(delta.Index) + return k.forWireIndex(toolCalls, delta) } return k.forUnindexed(toolCalls, delta) } @@ -180,19 +184,32 @@ func (k *toolCallKeys) resolve(toolCalls map[int64]streamToolCall, delta openai. func (k *toolCallKeys) commit(delta openai.ChatCompletionChunkChoiceDeltaToolCall, key int64) { if delta.JSON.Index.Valid() { k.byWireIndex[delta.Index] = key + k.wireBound[key] = true } k.used[key] = true k.next = max(k.next, key+1) k.latest = key } +// PROSE: stale, forWireIndex now also binds an unseen wire index to an unindexed call that has the delta's id. // forWireIndex keeps index as its own key unless another call already holds // that key, in which case index is remapped once to k.next and reused on // subsequent deltas. -func (k *toolCallKeys) forWireIndex(index int64) int64 { +func (k *toolCallKeys) forWireIndex(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { + index := delta.Index if key, ok := k.byWireIndex[index]; ok { return key } + + // PROSE: an unindexed opener can be continued by an indexed delta with the same id; only calls no wire index has claimed are matched, so indexed-only streams never take this branch. + if delta.ID != "" { + for key, tc := range toolCalls { + if tc.id == delta.ID && !k.wireBound[key] { + return key + } + } + } + if k.used[index] { return k.next } @@ -235,14 +252,12 @@ func startsUnidentifiedToolCall(latest streamToolCall, delta openai.ChatCompleti return json.Valid([]byte(latest.arguments)) && opensArguments(delta.Function.Arguments) } +// PROSE: stale, empty arguments no longer open a new call; a same-name delta with empty arguments continues the latest call. // opensArguments reports whether an arguments fragment can open a new call: // empty (arguments arrive later) or starting with '{' or '[' after trimming // whitespace. Whitespace-only fragments return false so trailing whitespace // stays on the previous call. func opensArguments(arguments string) bool { - if arguments == "" { - return true - } trimmed := strings.TrimSpace(arguments) return strings.HasPrefix(trimmed, "{") || strings.HasPrefix(trimmed, "[") } From 074e5ee8a6f02dae951a76c08121510540d5de59 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 15:58:20 +0000 Subject: [PATCH 09/52] docs(providers/openai): update toolCallKeys comments for id binding Update toolCallKeys, forWireIndex, and opensArguments comments to match wire-index binding by id and the non-empty opening-arguments rule. --- providers/openai/language_model.go | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 59261dd79..52b09493e 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -149,14 +149,15 @@ type streamToolCall struct { hasFinished bool } -// PROSE: stale, an unseen wire index can also bind to an existing unindexed call's key, not only its own key or a fresh one. // toolCallKeys assigns non-colliding toolCalls map keys to streamed tool-call // deltas when a provider omits the index field, which the SDK decodes as 0. -// Indexed-only streams keep each wire index as its key; synthetic and remapped -// calls take keys above every key committed so far. +// Indexed-only streams keep each wire index as its key; an unseen wire index +// can bind to an existing unindexed call with the same id, and synthetic or +// remapped calls take keys above every key committed so far. type toolCallKeys struct { byWireIndex map[int64]int64 - // PROSE: wireBound holds keys some wire index maps to, unlike used, which also holds keys of calls created from unindexed deltas. + // wireBound tracks keys claimed by a wire index, whereas used also + // includes keys of calls created from unindexed deltas. wireBound map[int64]bool used map[int64]bool next int64 @@ -191,17 +192,17 @@ func (k *toolCallKeys) commit(delta openai.ChatCompletionChunkChoiceDeltaToolCal k.latest = key } -// PROSE: stale, forWireIndex now also binds an unseen wire index to an unindexed call that has the delta's id. -// forWireIndex keeps index as its own key unless another call already holds -// that key, in which case index is remapped once to k.next and reused on -// subsequent deltas. +// forWireIndex resolves an indexed delta: an already-bound wire index reuses +// its key; an unseen wire index binds to an unindexed call with the same id, +// keeps its own wire index when free, or remaps to k.next on collision. func (k *toolCallKeys) forWireIndex(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { index := delta.Index if key, ok := k.byWireIndex[index]; ok { return key } - // PROSE: an unindexed opener can be continued by an indexed delta with the same id; only calls no wire index has claimed are matched, so indexed-only streams never take this branch. + // Only match calls no wire index has claimed yet so indexed-only streams + // never take this branch. if delta.ID != "" { for key, tc := range toolCalls { if tc.id == delta.ID && !k.wireBound[key] { @@ -252,11 +253,10 @@ func startsUnidentifiedToolCall(latest streamToolCall, delta openai.ChatCompleti return json.Valid([]byte(latest.arguments)) && opensArguments(delta.Function.Arguments) } -// PROSE: stale, empty arguments no longer open a new call; a same-name delta with empty arguments continues the latest call. // opensArguments reports whether an arguments fragment can open a new call: -// empty (arguments arrive later) or starting with '{' or '[' after trimming -// whitespace. Whitespace-only fragments return false so trailing whitespace -// stays on the previous call. +// non-empty and starting with '{' or '[' after trimming whitespace. Empty and +// whitespace-only fragments return false so trailing deltas stay on the latest +// call. func opensArguments(arguments string) bool { trimmed := strings.TrimSpace(arguments) return strings.HasPrefix(trimmed, "{") || strings.HasPrefix(trimmed, "[") From b8204569b1b5d97b396b71db8d51e064e344008f Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 16:27:36 +0000 Subject: [PATCH 10/52] test(providers/openaicompat): cover duplicate and reused tool call ids coder/coder chatd fails closed on a duplicate tool use id, so a second call that reuses an id must reach it as its own call. Adds rows for a named delta reusing the id of a complete or incomplete unindexed call, with and without a new wire index, and for a different id at a bound wire index. collectCalls now tracks calls that share an id separately. --- .../openaicompat/unindexed_tool_calls_test.go | 77 +++++++++++++++---- 1 file changed, 63 insertions(+), 14 deletions(-) diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index c267d444f..e7ad5998e 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -49,6 +49,7 @@ type toolCallStream struct { finish fantasy.FinishReason } +// PROSE: stale, collectCalls now tracks each call separately when several calls share an id: deltas go to the newest open call with the id, and ToolInputEnd and ToolCall go to the oldest call still waiting for them. // collectCalls asserts the per-id lifecycle (ToolInputStart, deltas, // ToolInputEnd, and at most one ToolCall matching the start name and // concatenated deltas, allowing "{}" when no deltas streamed) and returns the @@ -64,7 +65,25 @@ func collectCalls(t *testing.T, parts []fantasy.StreamPart) toolCallStream { } var out toolCallStream - seen := map[string]*progress{} + seen := map[string][]*progress{} + + newestOpen := func(id string) *progress { + calls := seen[id] + for i := len(calls) - 1; i >= 0; i-- { + if !calls[i].ended { + return calls[i] + } + } + return nil + } + oldest := func(id string, waiting func(*progress) bool) *progress { + for _, c := range seen[id] { + if waiting(c) { + return c + } + } + return nil + } for _, p := range parts { switch p.Type { @@ -72,27 +91,23 @@ func collectCalls(t *testing.T, parts []fantasy.StreamPart) toolCallStream { t.Fatalf("stream error: %v", p.Error) case fantasy.StreamPartTypeToolInputStart: - require.NotContains(t, seen, p.ID, "second ToolInputStart for %s", p.ID) - seen[p.ID] = &progress{name: p.ToolCallName} + seen[p.ID] = append(seen[p.ID], &progress{name: p.ToolCallName}) out.started = append(out.started, p.ID) case fantasy.StreamPartTypeToolInputDelta: - c := seen[p.ID] - require.NotNil(t, c, "ToolInputDelta before ToolInputStart for %s", p.ID) - require.False(t, c.ended, "ToolInputDelta after ToolInputEnd for %s", p.ID) + c := newestOpen(p.ID) + require.NotNil(t, c, "ToolInputDelta without an open ToolInputStart for %s", p.ID) c.deltas += p.Delta case fantasy.StreamPartTypeToolInputEnd: - c := seen[p.ID] - require.NotNil(t, c, "ToolInputEnd before ToolInputStart for %s", p.ID) - require.False(t, c.ended, "second ToolInputEnd for %s", p.ID) + c := oldest(p.ID, func(c *progress) bool { return !c.ended }) + require.NotNil(t, c, "ToolInputEnd without an open ToolInputStart for %s", p.ID) c.ended = true case fantasy.StreamPartTypeToolCall: - c := seen[p.ID] - require.NotNil(t, c, "ToolCall before ToolInputStart for %s", p.ID) + c := oldest(p.ID, func(c *progress) bool { return !c.called }) + require.NotNil(t, c, "ToolCall without a ToolInputStart for %s", p.ID) require.True(t, c.ended, "ToolCall before ToolInputEnd for %s", p.ID) - require.False(t, c.called, "second ToolCall for %s", p.ID) c.called = true require.Equal(t, c.name, p.ToolCallName, "ToolCall name differs from ToolInputStart for %s", p.ID) @@ -106,8 +121,10 @@ func collectCalls(t *testing.T, parts []fantasy.StreamPart) toolCallStream { } } - for id, c := range seen { - require.True(t, c.ended, "no ToolInputEnd for %s", id) + for id, calls := range seen { + for _, c := range calls { + require.True(t, c.ended, "no ToolInputEnd for %s", id) + } } return out } @@ -316,6 +333,38 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { }, want: []string{`tool-call-0:f={"x":1}`}, }, + { + name: "named delta reusing the id of a complete unindexed call", + chunks: []string{ + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":2}"}}`), + }, + want: []string{`a:f={"x":1}`, `a:f={"x":2}`}, + }, + { + name: "named delta at a new wire index reusing the id of an incomplete unindexed call", + chunks: []string{ + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}},{"index":1,"id":"a","type":"function","function":{"name":"f","arguments":"{\"y\":2}"}}`), + }, + want: []string{`a:f={"x":`, `a:f={"y":2}`}, + }, + { + name: "named delta at wire index 0 reusing the id of an unindexed call", + chunks: []string{ + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{}"}}`), + chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"{\"y\":2}"}}`), + }, + want: []string{`a:f={}`, `a:f={"y":2}`}, + }, + { + name: "different id at a bound wire index", + chunks: []string{ + chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), + chunk(`{"index":0,"id":"b","type":"function","function":{"name":"g","arguments":"{\"y\":"}}`), + chunk(`{"index":0,"function":{"arguments":"2}"}}`), + }, + want: []string{`a:f={"x":1}`, `b:g={"y":2}`}, + }, { name: "id-less stream cut mid-arguments by length", chunks: []string{ From 5e30fae0f4b7258819db33e74107b02e877d9649 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 16:27:36 +0000 Subject: [PATCH 11/52] fix(providers/openai): keep duplicate tool call ids as separate calls d01fedb bound a first-seen wire index to any unindexed call with the same id, so a named second call with a duplicate id merged into the first and chatd no longer saw the collision. A wire index now binds only for a nameless continuation. An unindexed named delta whose id matches a call with complete arguments starts a second call with that id. A delta with a different non-empty id at a bound wire index now starts a new call, which separates parallel calls that Ollama and LiteLLM send on index 0. Spec streams send the id only on the first delta or repeat it, so their keys are unchanged. --- providers/openai/language_model.go | 56 +++++++++++++++++++++++------- 1 file changed, 43 insertions(+), 13 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 52b09493e..1dbc0cfc7 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -149,6 +149,7 @@ type streamToolCall struct { hasFinished bool } +// PROSE: stale, binding to an unindexed call now requires a nameless delta, and a bound wire index can remap when the id changes. // toolCallKeys assigns non-colliding toolCalls map keys to streamed tool-call // deltas when a provider omits the index field, which the SDK decodes as 0. // Indexed-only streams keep each wire index as its key; an unseen wire index @@ -192,23 +193,22 @@ func (k *toolCallKeys) commit(delta openai.ChatCompletionChunkChoiceDeltaToolCal k.latest = key } +// PROSE: stale, a bound wire index now also starts a new call when the delta has a different non-empty id, and an unseen wire index binds only for nameless deltas. // forWireIndex resolves an indexed delta: an already-bound wire index reuses // its key; an unseen wire index binds to an unindexed call with the same id, // keeps its own wire index when free, or remaps to k.next on collision. func (k *toolCallKeys) forWireIndex(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { index := delta.Index if key, ok := k.byWireIndex[index]; ok { + // PROSE: a different non-empty id at a bound wire index is a new call (Ollama and LiteLLM reuse index 0); spec streams send the id once or repeat it, so they never take this branch. + if delta.ID != "" && delta.ID != toolCalls[key].id { + return k.next + } return key } - // Only match calls no wire index has claimed yet so indexed-only streams - // never take this branch. - if delta.ID != "" { - for key, tc := range toolCalls { - if tc.id == delta.ID && !k.wireBound[key] { - return key - } - } + if key, ok := k.unboundContinuation(toolCalls, delta); ok { + return key } if k.used[index] { @@ -217,18 +217,30 @@ func (k *toolCallKeys) forWireIndex(toolCalls map[int64]streamToolCall, delta op return index } +// PROSE: unboundContinuation binds an unseen wire index to an unindexed call with the delta's id only when the delta has no name; a named delta is a new call, so a duplicate id stays visible to callers. +func (k *toolCallKeys) unboundContinuation(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) (int64, bool) { + if delta.ID == "" || delta.Function.Name != "" { + return 0, false + } + key, ok := latestKeyWithID(toolCalls, delta.ID) + if !ok || k.wireBound[key] { + return 0, false + } + return key, true +} + +// PROSE: stale, an id match no longer always continues: a named delta after complete arguments starts a duplicate-id call; the newest matching call is used. // forUnindexed matches an unindexed delta with an id against any existing call // (indexed or not), and matches an id-less delta against k.latest. New calls // take k.next so they do not collide with existing keys and sort in creation // order. func (k *toolCallKeys) forUnindexed(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { if delta.ID != "" { - for key, tc := range toolCalls { - if tc.id == delta.ID { - return key - } + key, ok := latestKeyWithID(toolCalls, delta.ID) + if !ok || startsDuplicateToolCall(toolCalls[key], delta) { + return k.next } - return k.next + return key } latest, ok := toolCalls[k.latest] @@ -238,6 +250,24 @@ func (k *toolCallKeys) forUnindexed(toolCalls map[int64]streamToolCall, delta op return k.latest } +// PROSE: latestKeyWithID returns the highest key among calls with id, which is the newest such call, so deltas for a duplicate id continue the newest call. +func latestKeyWithID(toolCalls map[int64]streamToolCall, id string) (int64, bool) { + found := false + var latest int64 + for key, tc := range toolCalls { + if tc.id == id && (!found || key > latest) { + latest = key + found = true + } + } + return latest, found +} + +// PROSE: startsDuplicateToolCall reports whether a named delta reuses the id of a call whose arguments are already complete JSON; that is a second call with the same id, kept separate so callers see the duplicate. Name-repeating fragments before the arguments complete still continue the call. +func startsDuplicateToolCall(existing streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) bool { + return delta.Function.Name != "" && json.Valid([]byte(existing.arguments)) +} + // startsUnidentifiedToolCall reports whether an index-less, id-less delta opens // a new call after latest. A different non-empty name starts a new call; a // repeated name starts one only once latest has complete JSON arguments and the From dc3589d5405b7c3a928e78665b1bd4b46af2550d Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 16:32:48 +0000 Subject: [PATCH 12/52] docs(providers/openai): document duplicate-id and index-reuse rules Update toolCallKeys and collectCalls comments for nameless id binding, bound-index id changes, duplicate-id separation, and per-call lifecycle tracking. --- providers/openai/language_model.go | 42 +++++++++++-------- .../openaicompat/unindexed_tool_calls_test.go | 8 ++-- 2 files changed, 29 insertions(+), 21 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 1dbc0cfc7..c26966937 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -149,12 +149,12 @@ type streamToolCall struct { hasFinished bool } -// PROSE: stale, binding to an unindexed call now requires a nameless delta, and a bound wire index can remap when the id changes. // toolCallKeys assigns non-colliding toolCalls map keys to streamed tool-call -// deltas when a provider omits the index field, which the SDK decodes as 0. -// Indexed-only streams keep each wire index as its key; an unseen wire index -// can bind to an existing unindexed call with the same id, and synthetic or -// remapped calls take keys above every key committed so far. +// deltas when a provider omits the index field, which the SDK decodes as 0, or +// reuses a wire index for distinct calls. Indexed-only streams that follow the +// spec keep each wire index as its key; an unseen wire index can bind to an +// unbound call with the same id for a nameless delta, and synthetic or remapped +// calls take keys above every key committed so far. type toolCallKeys struct { byWireIndex map[int64]int64 // wireBound tracks keys claimed by a wire index, whereas used also @@ -193,14 +193,16 @@ func (k *toolCallKeys) commit(delta openai.ChatCompletionChunkChoiceDeltaToolCal k.latest = key } -// PROSE: stale, a bound wire index now also starts a new call when the delta has a different non-empty id, and an unseen wire index binds only for nameless deltas. -// forWireIndex resolves an indexed delta: an already-bound wire index reuses -// its key; an unseen wire index binds to an unindexed call with the same id, +// forWireIndex resolves an indexed delta: a bound wire index reuses its key +// unless the delta carries a different non-empty id; an unseen wire index binds +// to an unbound call with the same id when the delta has no function name, // keeps its own wire index when free, or remaps to k.next on collision. func (k *toolCallKeys) forWireIndex(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { index := delta.Index if key, ok := k.byWireIndex[index]; ok { - // PROSE: a different non-empty id at a bound wire index is a new call (Ollama and LiteLLM reuse index 0); spec streams send the id once or repeat it, so they never take this branch. + // Ollama and LiteLLM reuse wire index 0 for distinct parallel calls; + // spec-compliant streams send the id once or repeat it, so they never + // take this branch. if delta.ID != "" && delta.ID != toolCalls[key].id { return k.next } @@ -217,7 +219,9 @@ func (k *toolCallKeys) forWireIndex(toolCalls map[int64]streamToolCall, delta op return index } -// PROSE: unboundContinuation binds an unseen wire index to an unindexed call with the delta's id only when the delta has no name; a named delta is a new call, so a duplicate id stays visible to callers. +// unboundContinuation matches a nameless indexed delta to the newest unbound +// call with the same id. A named delta starts a new call instead so duplicate +// ids remain visible to consumers. func (k *toolCallKeys) unboundContinuation(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) (int64, bool) { if delta.ID == "" || delta.Function.Name != "" { return 0, false @@ -229,11 +233,11 @@ func (k *toolCallKeys) unboundContinuation(toolCalls map[int64]streamToolCall, d return key, true } -// PROSE: stale, an id match no longer always continues: a named delta after complete arguments starts a duplicate-id call; the newest matching call is used. -// forUnindexed matches an unindexed delta with an id against any existing call -// (indexed or not), and matches an id-less delta against k.latest. New calls -// take k.next so they do not collide with existing keys and sort in creation -// order. +// forUnindexed matches an unindexed delta with an id against the newest call +// with that id (indexed or not), starting a new call on a duplicate id once the +// matched call's arguments are complete JSON and the delta carries a name; an +// id-less delta matches k.latest. New calls take k.next so they never collide +// and sort in creation order. func (k *toolCallKeys) forUnindexed(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { if delta.ID != "" { key, ok := latestKeyWithID(toolCalls, delta.ID) @@ -250,7 +254,8 @@ func (k *toolCallKeys) forUnindexed(toolCalls map[int64]streamToolCall, delta op return k.latest } -// PROSE: latestKeyWithID returns the highest key among calls with id, which is the newest such call, so deltas for a duplicate id continue the newest call. +// latestKeyWithID returns the highest key among calls with id, which is the +// newest call with that id so follow-up deltas attach to it. func latestKeyWithID(toolCalls map[int64]streamToolCall, id string) (int64, bool) { found := false var latest int64 @@ -263,7 +268,10 @@ func latestKeyWithID(toolCalls map[int64]streamToolCall, id string) (int64, bool return latest, found } -// PROSE: startsDuplicateToolCall reports whether a named delta reuses the id of a call whose arguments are already complete JSON; that is a second call with the same id, kept separate so callers see the duplicate. Name-repeating fragments before the arguments complete still continue the call. +// startsDuplicateToolCall reports whether a named delta reuses the id of a call +// whose arguments are already complete JSON, keeping the second call separate +// so consumers see the duplicate id while name-repeating partial fragments +// still continue the first call. func startsDuplicateToolCall(existing streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) bool { return delta.Function.Name != "" && json.Valid([]byte(existing.arguments)) } diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index e7ad5998e..fb944182c 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -49,11 +49,11 @@ type toolCallStream struct { finish fantasy.FinishReason } -// PROSE: stale, collectCalls now tracks each call separately when several calls share an id: deltas go to the newest open call with the id, and ToolInputEnd and ToolCall go to the oldest call still waiting for them. -// collectCalls asserts the per-id lifecycle (ToolInputStart, deltas, +// collectCalls asserts the per-call lifecycle (ToolInputStart, deltas, // ToolInputEnd, and at most one ToolCall matching the start name and -// concatenated deltas, allowing "{}" when no deltas streamed) and returns the -// emitted calls, started ids, and finish reason. +// concatenated deltas, allowing "{}" when no deltas streamed). When several +// calls share an id, deltas attach to the newest open call and ToolInputEnd +// and ToolCall pair with the oldest waiting call. func collectCalls(t *testing.T, parts []fantasy.StreamPart) toolCallStream { t.Helper() From 17eb1f971479d46e1c773f36a687c3c9c22728b9 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 17:12:28 +0000 Subject: [PATCH 13/52] test(providers/openaicompat): cover shared index and fresh-id fragments Two complete named calls on index 0 with one id must stay two calls so duplicate-id checks downstream can fail closed. Nameless fragments that carry a fresh id each on a bound index, as LiteLLM's oci provider sends, must stay one call. Two id-less, index-less calls with different names where the first opens with empty arguments now merge, as they do on coder_2_33. A changed name alone is no longer evidence of a new call. --- .../openaicompat/unindexed_tool_calls_test.go | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index fb944182c..82b8e71bc 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -282,12 +282,12 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { want: []string{`tool-call-0:f={"x":1} `}, }, { - name: "different names without ids, first with empty arguments", + name: "different names without ids, first with empty arguments, merge", chunks: []string{ chunk(`{"type":"function","function":{"name":"f","arguments":""}}`), chunk(`{"type":"function","function":{"name":"g","arguments":"{\"y\":2}"}}`), }, - want: []string{`tool-call-0:f={}`, `tool-call-1:g={"y":2}`}, + want: []string{`tool-call-0:f={"y":2}`}, }, { name: "leading empty id-less delta", @@ -365,6 +365,23 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { }, want: []string{`a:f={"x":1}`, `b:g={"y":2}`}, }, + { + name: "complete named calls with the same id at the same wire index", + chunks: []string{ + chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"{}"}}`), + chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"{\"y\":2}"}}`), + }, + want: []string{`a:f={}`, `a:f={"y":2}`}, + }, + { + name: "nameless fragments with a fresh id each at a bound wire index", + chunks: []string{ + chunk(`{"index":0,"id":"call_A","type":"function","function":{"name":"list_dir","arguments":""}}`), + chunk(`{"index":0,"id":"frag1","function":{"arguments":"{\"pa"}}`), + chunk(`{"index":0,"id":"frag2","function":{"arguments":"th\": \"repo\"}"}}`), + }, + want: []string{`call_A:list_dir={"path": "repo"}`}, + }, { name: "id-less stream cut mid-arguments by length", chunks: []string{ From e40a5d014f227394c15db58954ae97bd831446d2 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 17:12:28 +0000 Subject: [PATCH 14/52] refactor(providers/openai): resolve every tool call delta by one rule Indexed, id-matched, and id-less deltas each had their own rule for whether a delta continues a call, and each review round fixed a shape in one branch that stayed broken in another. Every delta now picks one candidate call: the call bound to its wire index, else the newest call with its id, else the latest call when it has neither. It starts a new call only when it carries a name and either the candidate's arguments are complete JSON and the delta brings more, or it has a wire index the candidate is not bound to. Ids and indexes only choose the candidate, so a changed id alone no longer splits a call. Spec streams send the name only on the first delta of each index, so they keep key equal to wire index. --- providers/openai/language_model.go | 126 +++++++++-------------------- 1 file changed, 38 insertions(+), 88 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index c26966937..83f6e9760 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -149,6 +149,7 @@ type streamToolCall struct { hasFinished bool } +// PROSE: stale, every delta now goes through one decision: pick a candidate call by bound wire index, then id, then latest call; continue it unless the delta shows evidence of a new call. Indexed-only spec streams still keep each wire index as its key. // toolCallKeys assigns non-colliding toolCalls map keys to streamed tool-call // deltas when a provider omits the index field, which the SDK decodes as 0, or // reuses a wire index for distinct calls. Indexed-only streams that follow the @@ -157,18 +158,14 @@ type streamToolCall struct { // calls take keys above every key committed so far. type toolCallKeys struct { byWireIndex map[int64]int64 - // wireBound tracks keys claimed by a wire index, whereas used also - // includes keys of calls created from unindexed deltas. - wireBound map[int64]bool - used map[int64]bool - next int64 - latest int64 + used map[int64]bool + next int64 + latest int64 } func newToolCallKeys() *toolCallKeys { return &toolCallKeys{ byWireIndex: make(map[int64]int64), - wireBound: make(map[int64]bool), used: make(map[int64]bool), latest: -1, } @@ -177,81 +174,66 @@ func newToolCallKeys() *toolCallKeys { // resolve returns the toolCalls key for delta without recording it, leaving // key allocation and latest unchanged until commit runs. func (k *toolCallKeys) resolve(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { - if delta.JSON.Index.Valid() { - return k.forWireIndex(toolCalls, delta) + key, ok := k.candidate(toolCalls, delta) + if ok && !k.startsNewToolCall(toolCalls[key], key, delta) { + return key } - return k.forUnindexed(toolCalls, delta) + return k.newKey(delta) } +// PROSE: commit records key as used and makes it the latest call; an indexed delta also binds its wire index to key, which rebinds the index after a split and binds an index-less opener to the index of its continuation. func (k *toolCallKeys) commit(delta openai.ChatCompletionChunkChoiceDeltaToolCall, key int64) { if delta.JSON.Index.Valid() { k.byWireIndex[delta.Index] = key - k.wireBound[key] = true } k.used[key] = true k.next = max(k.next, key+1) k.latest = key } -// forWireIndex resolves an indexed delta: a bound wire index reuses its key -// unless the delta carries a different non-empty id; an unseen wire index binds -// to an unbound call with the same id when the delta has no function name, -// keeps its own wire index when free, or remaps to k.next on collision. -func (k *toolCallKeys) forWireIndex(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { - index := delta.Index - if key, ok := k.byWireIndex[index]; ok { - // Ollama and LiteLLM reuse wire index 0 for distinct parallel calls; - // spec-compliant streams send the id once or repeat it, so they never - // take this branch. - if delta.ID != "" && delta.ID != toolCalls[key].id { - return k.next +// PROSE: candidate picks the call a delta most likely belongs to: the call bound to its wire index, else the newest call with its id, else (no index and no id) the latest call. Ids and indexes only choose the candidate; they never split a call on their own. +func (k *toolCallKeys) candidate(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) (int64, bool) { + indexed := delta.JSON.Index.Valid() + if indexed { + if key, ok := k.byWireIndex[delta.Index]; ok { + return key, true } - return key } - if key, ok := k.unboundContinuation(toolCalls, delta); ok { - return key + if delta.ID != "" { + return latestKeyWithID(toolCalls, delta.ID) } - if k.used[index] { - return k.next + if !indexed { + _, ok := toolCalls[k.latest] + return k.latest, ok } - return index + return 0, false } -// unboundContinuation matches a nameless indexed delta to the newest unbound -// call with the same id. A named delta starts a new call instead so duplicate -// ids remain visible to consumers. -func (k *toolCallKeys) unboundContinuation(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) (int64, bool) { - if delta.ID == "" || delta.Function.Name != "" { - return 0, false +// PROSE: startsNewToolCall requires a function name plus either complete JSON on the candidate and non-blank arguments on the delta, or an explicit index the candidate is not bound to (a named call at a new index that reuses an id, as in chatd's duplicate-id check). Spec continuations carry no name, so they always continue. +func (k *toolCallKeys) startsNewToolCall(current streamToolCall, key int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) bool { + if delta.Function.Name == "" { + return false } - key, ok := latestKeyWithID(toolCalls, delta.ID) - if !ok || k.wireBound[key] { - return 0, false + + if json.Valid([]byte(current.arguments)) && strings.TrimSpace(delta.Function.Arguments) != "" { + return true } - return key, true -} -// forUnindexed matches an unindexed delta with an id against the newest call -// with that id (indexed or not), starting a new call on a duplicate id once the -// matched call's arguments are complete JSON and the delta carries a name; an -// id-less delta matches k.latest. New calls take k.next so they never collide -// and sort in creation order. -func (k *toolCallKeys) forUnindexed(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { - if delta.ID != "" { - key, ok := latestKeyWithID(toolCalls, delta.ID) - if !ok || startsDuplicateToolCall(toolCalls[key], delta) { - return k.next - } - return key + if !delta.JSON.Index.Valid() { + return false } + bound, ok := k.byWireIndex[delta.Index] + return !ok || bound != key +} - latest, ok := toolCalls[k.latest] - if !ok || startsUnidentifiedToolCall(latest, delta) { - return k.next +// PROSE: newKey keeps the wire index as the key when it is free, so spec streams key by wire index; otherwise it takes the next key above every key used so far. +func (k *toolCallKeys) newKey(delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { + if delta.JSON.Index.Valid() && !k.used[delta.Index] { + return delta.Index } - return k.latest + return k.next } // latestKeyWithID returns the highest key among calls with id, which is the @@ -268,38 +250,6 @@ func latestKeyWithID(toolCalls map[int64]streamToolCall, id string) (int64, bool return latest, found } -// startsDuplicateToolCall reports whether a named delta reuses the id of a call -// whose arguments are already complete JSON, keeping the second call separate -// so consumers see the duplicate id while name-repeating partial fragments -// still continue the first call. -func startsDuplicateToolCall(existing streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) bool { - return delta.Function.Name != "" && json.Valid([]byte(existing.arguments)) -} - -// startsUnidentifiedToolCall reports whether an index-less, id-less delta opens -// a new call after latest. A different non-empty name starts a new call; a -// repeated name starts one only once latest has complete JSON arguments and the -// delta begins new arguments, so name-repeating fragments stay attached. -func startsUnidentifiedToolCall(latest streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) bool { - name := delta.Function.Name - if name == "" { - return false - } - if name != latest.name { - return true - } - return json.Valid([]byte(latest.arguments)) && opensArguments(delta.Function.Arguments) -} - -// opensArguments reports whether an arguments fragment can open a new call: -// non-empty and starting with '{' or '[' after trimming whitespace. Empty and -// whitespace-only fragments return false so trailing deltas stay on the latest -// call. -func opensArguments(arguments string) bool { - trimmed := strings.TrimSpace(arguments) - return strings.HasPrefix(trimmed, "{") || strings.HasPrefix(trimmed, "[") -} - // responseCapture holds the raw HTTP response of a call so response headers // can be surfaced through provider metadata. Capturing is only enabled when // a header func is configured on the language model. From 0e7f82625270c1c505b1f8eec0ce73c9874042ff Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 17:14:57 +0000 Subject: [PATCH 15/52] fix(providers/openai): start a new call when the tool name changes A named delta whose name differs from its candidate call's name was merged whenever the candidate's arguments were incomplete, so tool f could run with tool g's arguments. A different non-empty name now starts a new call. Spec continuations carry no name and still continue their call. --- providers/openai/language_model.go | 6 +++++- providers/openaicompat/unindexed_tool_calls_test.go | 12 ++++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 83f6e9760..861535975 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -211,12 +211,16 @@ func (k *toolCallKeys) candidate(toolCalls map[int64]streamToolCall, delta opena return 0, false } -// PROSE: startsNewToolCall requires a function name plus either complete JSON on the candidate and non-blank arguments on the delta, or an explicit index the candidate is not bound to (a named call at a new index that reuses an id, as in chatd's duplicate-id check). Spec continuations carry no name, so they always continue. +// PROSE: startsNewToolCall requires a function name plus one of: (a) complete JSON on the candidate and non-blank arguments on the delta; (b) an explicit index the candidate is not bound to (a named call at a new index that reuses an id, as in chatd's duplicate-id check); (c) a name that differs from the candidate's non-empty name, so one tool never runs with another tool's arguments. Spec continuations carry no name, so they always continue. func (k *toolCallKeys) startsNewToolCall(current streamToolCall, key int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) bool { if delta.Function.Name == "" { return false } + if current.name != "" && delta.Function.Name != current.name { + return true + } + if json.Valid([]byte(current.arguments)) && strings.TrimSpace(delta.Function.Arguments) != "" { return true } diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index 82b8e71bc..14b36b068 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -282,12 +282,20 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { want: []string{`tool-call-0:f={"x":1} `}, }, { - name: "different names without ids, first with empty arguments, merge", + name: "different names without ids, first with empty arguments", chunks: []string{ chunk(`{"type":"function","function":{"name":"f","arguments":""}}`), chunk(`{"type":"function","function":{"name":"g","arguments":"{\"y\":2}"}}`), }, - want: []string{`tool-call-0:f={"y":2}`}, + want: []string{`tool-call-0:f={}`, `tool-call-1:g={"y":2}`}, + }, + { + name: "different named call on a bound wire index before the first call completes", + chunks: []string{ + chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), + chunk(`{"index":0,"id":"b","type":"function","function":{"name":"g","arguments":"{\"y\":2}"}}`), + }, + want: []string{`a:f={"x":`, `b:g={"y":2}`}, }, { name: "leading empty id-less delta", From 0a2a900525573565d99cca68d53da4dd584579aa Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 17:17:26 +0000 Subject: [PATCH 16/52] docs(providers/openai): document unified toolCallKeys rule Update toolCallKeys comments to reflect the unified candidate selection and new-call decision across indexed and unindexed deltas. --- providers/openai/language_model.go | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 861535975..4435ad952 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -149,13 +149,12 @@ type streamToolCall struct { hasFinished bool } -// PROSE: stale, every delta now goes through one decision: pick a candidate call by bound wire index, then id, then latest call; continue it unless the delta shows evidence of a new call. Indexed-only spec streams still keep each wire index as its key. // toolCallKeys assigns non-colliding toolCalls map keys to streamed tool-call // deltas when a provider omits the index field, which the SDK decodes as 0, or -// reuses a wire index for distinct calls. Indexed-only streams that follow the -// spec keep each wire index as its key; an unseen wire index can bind to an -// unbound call with the same id for a nameless delta, and synthetic or remapped -// calls take keys above every key committed so far. +// reuses a wire index across calls. Every delta resolves through one rule: +// pick a candidate call by bound wire index, id, or latest call, and continue +// it unless the delta opens a new call. Spec-compliant indexed streams keep +// each wire index as its key. type toolCallKeys struct { byWireIndex map[int64]int64 used map[int64]bool @@ -181,7 +180,9 @@ func (k *toolCallKeys) resolve(toolCalls map[int64]streamToolCall, delta openai. return k.newKey(delta) } -// PROSE: commit records key as used and makes it the latest call; an indexed delta also binds its wire index to key, which rebinds the index after a split and binds an index-less opener to the index of its continuation. +// commit records key as used and sets it as latest. For indexed deltas it also +// binds the wire index to key, rebinding after a split and binding an +// index-less opener when a later continuation carries an explicit index. func (k *toolCallKeys) commit(delta openai.ChatCompletionChunkChoiceDeltaToolCall, key int64) { if delta.JSON.Index.Valid() { k.byWireIndex[delta.Index] = key @@ -191,7 +192,10 @@ func (k *toolCallKeys) commit(delta openai.ChatCompletionChunkChoiceDeltaToolCal k.latest = key } -// PROSE: candidate picks the call a delta most likely belongs to: the call bound to its wire index, else the newest call with its id, else (no index and no id) the latest call. Ids and indexes only choose the candidate; they never split a call on their own. +// candidate selects the call delta most likely continues: the call bound to +// its wire index, else the newest call with its non-empty id, else (for a +// delta with neither index nor id) the latest call. Indexes and ids only pick +// the candidate; they never split a call on their own. func (k *toolCallKeys) candidate(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) (int64, bool) { indexed := delta.JSON.Index.Valid() if indexed { @@ -211,7 +215,12 @@ func (k *toolCallKeys) candidate(toolCalls map[int64]streamToolCall, delta opena return 0, false } -// PROSE: startsNewToolCall requires a function name plus one of: (a) complete JSON on the candidate and non-blank arguments on the delta; (b) an explicit index the candidate is not bound to (a named call at a new index that reuses an id, as in chatd's duplicate-id check); (c) a name that differs from the candidate's non-empty name, so one tool never runs with another tool's arguments. Spec continuations carry no name, so they always continue. +// startsNewToolCall reports whether delta opens a new call instead of +// continuing current. A new call requires a function name plus one of: a name +// differing from current's non-empty name (so one tool never receives another +// tool's arguments); complete JSON arguments on current with non-blank +// arguments on delta; or an explicit wire index that current is not bound to. +// Spec continuations carry no function name and always continue. func (k *toolCallKeys) startsNewToolCall(current streamToolCall, key int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) bool { if delta.Function.Name == "" { return false @@ -232,7 +241,8 @@ func (k *toolCallKeys) startsNewToolCall(current streamToolCall, key int64, delt return !ok || bound != key } -// PROSE: newKey keeps the wire index as the key when it is free, so spec streams key by wire index; otherwise it takes the next key above every key used so far. +// newKey keeps an unused wire index as its key so indexed spec streams keep +// wire-index keys, and falls back to k.next above every key committed so far. func (k *toolCallKeys) newKey(delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { if delta.JSON.Index.Valid() && !k.used[delta.Index] { return delta.Index From faa60755dabc735403f3fd1ae3e90628ee77fa2c Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 18:20:44 +0000 Subject: [PATCH 17/52] test(providers/openaicompat): cover duplicate ids at out-of-order indexes A complete call at index 1 followed by a same-id call at index 0 gives the newer call the lower key. An unindexed continuation with that id must reach the newer call. collectCalls now pairs each ToolCall with the started call whose name and deltas match, because calls sharing an id finish in key order, not start order. --- .../openaicompat/unindexed_tool_calls_test.go | 66 +++++++++---------- 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index 14b36b068..31c03a2d1 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -49,6 +49,7 @@ type toolCallStream struct { finish fantasy.FinishReason } +// PROSE: stale, ToolInputEnd is now counted per id and each ToolCall pairs with the not-yet-called call whose name and deltas match its input, since calls that share an id can finish in a different order than they started. // collectCalls asserts the per-call lifecycle (ToolInputStart, deltas, // ToolInputEnd, and at most one ToolCall matching the start name and // concatenated deltas, allowing "{}" when no deltas streamed). When several @@ -60,29 +61,19 @@ func collectCalls(t *testing.T, parts []fantasy.StreamPart) toolCallStream { type progress struct { name string deltas string - ended bool called bool } var out toolCallStream seen := map[string][]*progress{} + ends := map[string]int{} + called := map[string]int{} - newestOpen := func(id string) *progress { - calls := seen[id] - for i := len(calls) - 1; i >= 0; i-- { - if !calls[i].ended { - return calls[i] - } - } - return nil - } - oldest := func(id string, waiting func(*progress) bool) *progress { - for _, c := range seen[id] { - if waiting(c) { - return c - } + matches := func(c *progress, p fantasy.StreamPart) bool { + if c.called || c.name != p.ToolCallName { + return false } - return nil + return c.deltas == p.ToolCallInput || (c.deltas == "" && p.ToolCallInput == "{}") } for _, p := range parts { @@ -95,25 +86,26 @@ func collectCalls(t *testing.T, parts []fantasy.StreamPart) toolCallStream { out.started = append(out.started, p.ID) case fantasy.StreamPartTypeToolInputDelta: - c := newestOpen(p.ID) - require.NotNil(t, c, "ToolInputDelta without an open ToolInputStart for %s", p.ID) - c.deltas += p.Delta + calls := seen[p.ID] + require.Greater(t, len(calls), ends[p.ID], "ToolInputDelta without an open ToolInputStart for %s", p.ID) + calls[len(calls)-1].deltas += p.Delta case fantasy.StreamPartTypeToolInputEnd: - c := oldest(p.ID, func(c *progress) bool { return !c.ended }) - require.NotNil(t, c, "ToolInputEnd without an open ToolInputStart for %s", p.ID) - c.ended = true + require.Greater(t, len(seen[p.ID]), ends[p.ID], "ToolInputEnd without an open ToolInputStart for %s", p.ID) + ends[p.ID]++ case fantasy.StreamPartTypeToolCall: - c := oldest(p.ID, func(c *progress) bool { return !c.called }) - require.NotNil(t, c, "ToolCall without a ToolInputStart for %s", p.ID) - require.True(t, c.ended, "ToolCall before ToolInputEnd for %s", p.ID) - c.called = true - - require.Equal(t, c.name, p.ToolCallName, "ToolCall name differs from ToolInputStart for %s", p.ID) - if c.deltas != "" || p.ToolCallInput != "{}" { - require.Equal(t, c.deltas, p.ToolCallInput, "streamed input deltas differ from the final input for %s", p.ID) + require.Greater(t, ends[p.ID], called[p.ID], "ToolCall before ToolInputEnd for %s", p.ID) + var c *progress + for _, candidate := range seen[p.ID] { + if matches(candidate, p) { + c = candidate + break + } } + require.NotNil(t, c, "ToolCall %s:%s=%s matches no started call's name and streamed deltas", p.ID, p.ToolCallName, p.ToolCallInput) + c.called = true + called[p.ID]++ out.calls = append(out.calls, streamedCall{id: p.ID, name: p.ToolCallName, input: p.ToolCallInput}) case fantasy.StreamPartTypeFinish: @@ -122,9 +114,7 @@ func collectCalls(t *testing.T, parts []fantasy.StreamPart) toolCallStream { } for id, calls := range seen { - for _, c := range calls { - require.True(t, c.ended, "no ToolInputEnd for %s", id) - } + require.Equal(t, len(calls), ends[id], "ToolInputEnd count differs from ToolInputStart count for %s", id) } return out } @@ -390,6 +380,16 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { }, want: []string{`call_A:list_dir={"path": "repo"}`}, }, + { + name: "id continuation after duplicate-id calls arrive at out-of-order indexes", + chunks: []string{ + chunk(`{"index":1,"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), + chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"{\"y\":"}}`), + chunk(`{"id":"a","function":{"arguments":"2}"}}`), + }, + want: []string{`a:f={"y":2}`, `a:f={"x":1}`}, + wantStarted: []string{"a", "a"}, + }, { name: "id-less stream cut mid-arguments by length", chunks: []string{ From 8875a84b206e40963caef13720661606cd5bd836 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 18:20:44 +0000 Subject: [PATCH 18/52] fix(providers/openai): pick the newest call by creation order The newest call with an id was taken to be the one with the highest key, which fails when explicit indexes arrive out of order. commit now records a creation sequence number per key, which also replaces the used set, and the id lookup compares those. --- providers/openai/language_model.go | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 4435ad952..ee2718a1b 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -157,15 +157,16 @@ type streamToolCall struct { // each wire index as its key. type toolCallKeys struct { byWireIndex map[int64]int64 - used map[int64]bool - next int64 - latest int64 + // PROSE: created holds each used key's creation sequence number, so the newest call is found by arrival rather than by key, which out-of-order wire indexes make unreliable; a key is used when it is present here. + created map[int64]int + next int64 + latest int64 } func newToolCallKeys() *toolCallKeys { return &toolCallKeys{ byWireIndex: make(map[int64]int64), - used: make(map[int64]bool), + created: make(map[int64]int), latest: -1, } } @@ -180,6 +181,7 @@ func (k *toolCallKeys) resolve(toolCalls map[int64]streamToolCall, delta openai. return k.newKey(delta) } +// PROSE: stale, commit now records the creation sequence number the first time a key is used, replacing the used set. // commit records key as used and sets it as latest. For indexed deltas it also // binds the wire index to key, rebinding after a split and binding an // index-less opener when a later continuation carries an explicit index. @@ -187,7 +189,9 @@ func (k *toolCallKeys) commit(delta openai.ChatCompletionChunkChoiceDeltaToolCal if delta.JSON.Index.Valid() { k.byWireIndex[delta.Index] = key } - k.used[key] = true + if _, ok := k.created[key]; !ok { + k.created[key] = len(k.created) + } k.next = max(k.next, key+1) k.latest = key } @@ -205,7 +209,7 @@ func (k *toolCallKeys) candidate(toolCalls map[int64]streamToolCall, delta opena } if delta.ID != "" { - return latestKeyWithID(toolCalls, delta.ID) + return k.newestWithID(toolCalls, delta.ID) } if !indexed { @@ -244,24 +248,25 @@ func (k *toolCallKeys) startsNewToolCall(current streamToolCall, key int64, delt // newKey keeps an unused wire index as its key so indexed spec streams keep // wire-index keys, and falls back to k.next above every key committed so far. func (k *toolCallKeys) newKey(delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { - if delta.JSON.Index.Valid() && !k.used[delta.Index] { + if _, used := k.created[delta.Index]; delta.JSON.Index.Valid() && !used { return delta.Index } return k.next } +// PROSE: stale, newestWithID picks the most recently created call with id by creation sequence, not the highest key. // latestKeyWithID returns the highest key among calls with id, which is the // newest call with that id so follow-up deltas attach to it. -func latestKeyWithID(toolCalls map[int64]streamToolCall, id string) (int64, bool) { +func (k *toolCallKeys) newestWithID(toolCalls map[int64]streamToolCall, id string) (int64, bool) { found := false - var latest int64 + var newest int64 for key, tc := range toolCalls { - if tc.id == id && (!found || key > latest) { - latest = key + if tc.id == id && (!found || k.created[key] > k.created[newest]) { + newest = key found = true } } - return latest, found + return newest, found } // responseCapture holds the raw HTTP response of a call so response headers From 1757bda46561a82f0fb2c6ef373dd87fa0dec39e Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 18:23:07 +0000 Subject: [PATCH 19/52] docs(providers/openai): document creation-order recency tracking Update toolCallKeys and collectCalls comments for creation-sequence recency on duplicate ids and per-id End/ToolCall matching. --- providers/openai/language_model.go | 18 ++++++++++-------- .../openaicompat/unindexed_tool_calls_test.go | 10 ++++------ 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index ee2718a1b..0f1729b04 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -157,7 +157,9 @@ type streamToolCall struct { // each wire index as its key. type toolCallKeys struct { byWireIndex map[int64]int64 - // PROSE: created holds each used key's creation sequence number, so the newest call is found by arrival rather than by key, which out-of-order wire indexes make unreliable; a key is used when it is present here. + // created maps each used key to its creation sequence number so recency + // follows arrival order even when wire indexes arrive out of order. + // Presence in this map marks a key as used. created map[int64]int next int64 latest int64 @@ -181,10 +183,10 @@ func (k *toolCallKeys) resolve(toolCalls map[int64]streamToolCall, delta openai. return k.newKey(delta) } -// PROSE: stale, commit now records the creation sequence number the first time a key is used, replacing the used set. -// commit records key as used and sets it as latest. For indexed deltas it also -// binds the wire index to key, rebinding after a split and binding an -// index-less opener when a later continuation carries an explicit index. +// commit records key's creation sequence on first use and sets it as latest. +// For indexed deltas it also binds the wire index to key, rebinding after a +// split and binding an index-less opener when a later continuation carries an +// explicit index. func (k *toolCallKeys) commit(delta openai.ChatCompletionChunkChoiceDeltaToolCall, key int64) { if delta.JSON.Index.Valid() { k.byWireIndex[delta.Index] = key @@ -254,9 +256,9 @@ func (k *toolCallKeys) newKey(delta openai.ChatCompletionChunkChoiceDeltaToolCal return k.next } -// PROSE: stale, newestWithID picks the most recently created call with id by creation sequence, not the highest key. -// latestKeyWithID returns the highest key among calls with id, which is the -// newest call with that id so follow-up deltas attach to it. +// newestWithID returns the most recently created call with id by creation +// sequence so follow-up deltas attach to it even when wire indexes arrive out +// of order. func (k *toolCallKeys) newestWithID(toolCalls map[int64]streamToolCall, id string) (int64, bool) { found := false var newest int64 diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index 31c03a2d1..25a386548 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -49,12 +49,10 @@ type toolCallStream struct { finish fantasy.FinishReason } -// PROSE: stale, ToolInputEnd is now counted per id and each ToolCall pairs with the not-yet-called call whose name and deltas match its input, since calls that share an id can finish in a different order than they started. -// collectCalls asserts the per-call lifecycle (ToolInputStart, deltas, -// ToolInputEnd, and at most one ToolCall matching the start name and -// concatenated deltas, allowing "{}" when no deltas streamed). When several -// calls share an id, deltas attach to the newest open call and ToolInputEnd -// and ToolCall pair with the oldest waiting call. +// collectCalls verifies tool-call stream parts: ToolInputEnd counts must match +// ToolInputStart counts per id, deltas attach to the most recently started call +// for that id, and each ToolCall pairs with an uncalled started call whose name +// and streamed deltas match its input (allowing "{}" when no deltas streamed). func collectCalls(t *testing.T, parts []fantasy.StreamPart) toolCallStream { t.Helper() From e8862405aee5c4f8b21356363c43d67fe1a2c326 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 18:55:43 +0000 Subject: [PATCH 20/52] test(providers/openaicompat): cover same-tool calls sharing an index Parallel calls to one tool on index 0 with distinct ids, as LiteLLM's Responses bridge and Ollama send, must stay separate whether the second opener has empty or partial arguments. Nameless fragments with a fresh id each and no index must stay one call. A named delta carrying an id after an id-less indexed opener continues that call. --- .../openaicompat/unindexed_tool_calls_test.go | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index 25a386548..2c098f376 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -388,6 +388,41 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { want: []string{`a:f={"y":2}`, `a:f={"x":1}`}, wantStarted: []string{"a", "a"}, }, + { + name: "same-name openers with new ids and empty arguments on one wire index", + chunks: []string{ + chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":""}}`), + chunk(`{"index":0,"function":{"arguments":"{\"x\":1}"}}`), + chunk(`{"index":0,"id":"b","type":"function","function":{"name":"f","arguments":""}}`), + chunk(`{"index":0,"function":{"arguments":"{\"x\":2}"}}`), + }, + want: []string{`a:f={"x":1}`, `b:f={"x":2}`}, + }, + { + name: "same-name call with a new id on one wire index before the first completes", + chunks: []string{ + chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), + chunk(`{"index":0,"id":"b","type":"function","function":{"name":"f","arguments":"{\"y\":2}"}}`), + }, + want: []string{`a:f={"x":`, `b:f={"y":2}`}, + }, + { + name: "nameless fragments with a fresh id each and no index", + chunks: []string{ + chunk(`{"id":"call_A","type":"function","function":{"name":"list_dir","arguments":""}}`), + chunk(`{"id":"frag1","function":{"arguments":"{\"pa"}}`), + chunk(`{"id":"frag2","function":{"arguments":"th\": 1}"}}`), + }, + want: []string{`call_A:list_dir={"path": 1}`}, + }, + { + name: "indexed opener without id continued by a named delta carrying an id", + chunks: []string{ + chunk(`{"index":0,"type":"function","function":{"name":"f","arguments":""}}`), + chunk(`{"index":0,"id":"x","type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), + }, + want: []string{`tool-call-0:f={"x":1}`}, + }, { name: "id-less stream cut mid-arguments by length", chunks: []string{ From 28bf4529eb08ab56e984e1c7747a68be6d11839e Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 18:55:43 +0000 Subject: [PATCH 21/52] fix(providers/openai): split named calls on a new provider id A named opener with a new id continued the previous call on a bound index when the tool name matched and its arguments were incomplete, merging parallel calls to one tool. A named delta whose id differs from the candidate's provider-sent id now starts a new call. The tool-call-N fallback does not count as a provider id. A nameless index-less delta with an unmatched id now continues the latest call instead of starting a nameless call. --- providers/openai/language_model.go | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 0f1729b04..c11d19310 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -147,6 +147,8 @@ type streamToolCall struct { name string arguments string hasFinished bool + // PROSE: idFromWire is false when id is the tool-call-N fallback, so the fallback never counts as the provider's id when comparing ids for a new call. + idFromWire bool } // toolCallKeys assigns non-colliding toolCalls map keys to streamed tool-call @@ -198,6 +200,7 @@ func (k *toolCallKeys) commit(delta openai.ChatCompletionChunkChoiceDeltaToolCal k.latest = key } +// PROSE: stale, without an index the latest call is now the candidate even when the delta carries an unmatched id. // candidate selects the call delta most likely continues: the call bound to // its wire index, else the newest call with its non-empty id, else (for a // delta with neither index nor id) the latest call. Indexes and ids only pick @@ -211,7 +214,9 @@ func (k *toolCallKeys) candidate(toolCalls map[int64]streamToolCall, delta opena } if delta.ID != "" { - return k.newestWithID(toolCalls, delta.ID) + if key, ok := k.newestWithID(toolCalls, delta.ID); ok { + return key, true + } } if !indexed { @@ -221,6 +226,7 @@ func (k *toolCallKeys) candidate(toolCalls map[int64]streamToolCall, delta opena return 0, false } +// PROSE: stale, startsNewToolCall has a fourth evidence: a named delta whose non-empty id differs from the candidate's provider-sent id. // startsNewToolCall reports whether delta opens a new call instead of // continuing current. A new call requires a function name plus one of: a name // differing from current's non-empty name (so one tool never receives another @@ -236,6 +242,11 @@ func (k *toolCallKeys) startsNewToolCall(current streamToolCall, key int64, delt return true } + // PROSE: a named delta with a provider-sent id that differs from the candidate's provider-sent id opens a new call (parallel calls to one tool on index 0, Google's whole-call chunks); nameless deltas never reach this, so fresh-id fragments still continue. + if delta.ID != "" && current.idFromWire && delta.ID != current.id { + return true + } + if json.Valid([]byte(current.arguments)) && strings.TrimSpace(delta.Function.Arguments) != "" { return true } @@ -705,6 +716,7 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S continue } toolCallDelta.Type = cmp.Or(toolCallDelta.Type, "function") + idFromWire := toolCallDelta.ID != "" toolCallDelta.ID = cmp.Or(toolCallDelta.ID, fmt.Sprintf("tool-call-%d", key)) if toolCallDelta.Type != "function" { @@ -723,9 +735,10 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S return } toolCalls[key] = streamToolCall{ - id: toolCallDelta.ID, - name: toolCallDelta.Function.Name, - arguments: toolCallDelta.Function.Arguments, + id: toolCallDelta.ID, + name: toolCallDelta.Function.Name, + arguments: toolCallDelta.Function.Arguments, + idFromWire: idFromWire, } callKeys.commit(toolCallDelta, key) From 3cf333a88e052bda3417ba11e5557564917d23fd Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 18:58:29 +0000 Subject: [PATCH 22/52] docs(providers/openai): document provider-id split and latest fallback Update streamToolCall.idFromWire, candidate, and startsNewToolCall comments for the unmatched-id latest fallback and provider-sent id split. --- providers/openai/language_model.go | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index c11d19310..6ffd79b0c 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -147,7 +147,8 @@ type streamToolCall struct { name string arguments string hasFinished bool - // PROSE: idFromWire is false when id is the tool-call-N fallback, so the fallback never counts as the provider's id when comparing ids for a new call. + // idFromWire is false when id is the synthesized tool-call-N fallback, + // so the fallback never counts as a provider-sent id. idFromWire bool } @@ -200,11 +201,11 @@ func (k *toolCallKeys) commit(delta openai.ChatCompletionChunkChoiceDeltaToolCal k.latest = key } -// PROSE: stale, without an index the latest call is now the candidate even when the delta carries an unmatched id. // candidate selects the call delta most likely continues: the call bound to -// its wire index, else the newest call with its non-empty id, else (for a -// delta with neither index nor id) the latest call. Indexes and ids only pick -// the candidate; they never split a call on their own. +// its wire index, else the newest call with its non-empty id, else (for any +// delta without an explicit index, even with an unmatched id) the latest call. +// Indexes and ids only pick the candidate; a nameless delta never splits on an +// id. func (k *toolCallKeys) candidate(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) (int64, bool) { indexed := delta.JSON.Index.Valid() if indexed { @@ -226,13 +227,13 @@ func (k *toolCallKeys) candidate(toolCalls map[int64]streamToolCall, delta opena return 0, false } -// PROSE: stale, startsNewToolCall has a fourth evidence: a named delta whose non-empty id differs from the candidate's provider-sent id. // startsNewToolCall reports whether delta opens a new call instead of // continuing current. A new call requires a function name plus one of: a name // differing from current's non-empty name (so one tool never receives another -// tool's arguments); complete JSON arguments on current with non-blank -// arguments on delta; or an explicit wire index that current is not bound to. -// Spec continuations carry no function name and always continue. +// tool's arguments); a non-empty id differing from current's provider-sent id; +// complete JSON arguments on current with non-blank arguments on delta; or an +// explicit wire index that current is not bound to. Spec continuations carry +// no function name and always continue. func (k *toolCallKeys) startsNewToolCall(current streamToolCall, key int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) bool { if delta.Function.Name == "" { return false @@ -242,7 +243,9 @@ func (k *toolCallKeys) startsNewToolCall(current streamToolCall, key int64, delt return true } - // PROSE: a named delta with a provider-sent id that differs from the candidate's provider-sent id opens a new call (parallel calls to one tool on index 0, Google's whole-call chunks); nameless deltas never reach this, so fresh-id fragments still continue. + // Parallel calls to the same tool on a shared wire index and whole-call + // chunks without an index carry a new provider id; nameless deltas return + // above so fresh-id fragments still continue the call. if delta.ID != "" && current.idFromWire && delta.ID != current.id { return true } From 96f77e3d7231ce1b3f789188bb6a25f841741b0f Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 19:42:10 +0000 Subject: [PATCH 23/52] test(providers/openaicompat): cover index-less openers with indexed continuations An index-less opener continued at index 0, by a delta repeating its id and name or by a nameless id-less fragment, must stay one call. The duplicate-id row moves to the fully indexed shape that chatd's fixture now sends: an incomplete call at index 0 and a named call with the same id at index 1 stay two calls. --- .../openaicompat/unindexed_tool_calls_test.go | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index 2c098f376..1f26ed8a3 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -338,12 +338,28 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { want: []string{`a:f={"x":1}`, `a:f={"x":2}`}, }, { - name: "named delta at a new wire index reusing the id of an incomplete unindexed call", + name: "named delta at a new wire index reusing the id of an incomplete indexed call", chunks: []string{ - chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}},{"index":1,"id":"a","type":"function","function":{"name":"f","arguments":"{\"y\":2}"}}`), + chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}},{"index":1,"id":"a","type":"function","function":{"name":"f","arguments":"{\"y\":2}"}}`), }, want: []string{`a:f={"x":`, `a:f={"y":2}`}, }, + { + name: "unindexed opener continued by an indexed delta repeating its id and name", + chunks: []string{ + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), + chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"1}"}}`), + }, + want: []string{`a:f={"x":1}`}, + }, + { + name: "unindexed opener continued by a nameless id-less indexed delta", + chunks: []string{ + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), + chunk(`{"index":0,"function":{"arguments":"1}"}}`), + }, + want: []string{`a:f={"x":1}`}, + }, { name: "named delta at wire index 0 reusing the id of an unindexed call", chunks: []string{ From bbcb29c1703dfe51fd4baab9cb98d8919b82ba30 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 19:42:10 +0000 Subject: [PATCH 24/52] fix(providers/openai): continue unbound calls at a new wire index An index-less opener has no wire index, so an indexed continuation counted as arriving at a different index and split off, and a nameless id-less indexed fragment found no candidate at all. An indexed delta at an unseen index now falls back to the latest call when no wire index is bound to it, and only a candidate bound to a different index is split. Spec streams always have a bound latest call, so an unseen index still opens a new call there. --- providers/openai/language_model.go | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 6ffd79b0c..027eb0a5d 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -201,6 +201,7 @@ func (k *toolCallKeys) commit(delta openai.ChatCompletionChunkChoiceDeltaToolCal k.latest = key } +// PROSE: stale (CRF-54), the candidate rule now also picks the latest call for an indexed delta when no wire index is bound to that call, and "indexes and ids only pick the candidate" is wrong: startsNewToolCall splits named deltas on a new provider id or a different bound index; only nameless deltas never split. // candidate selects the call delta most likely continues: the call bound to // its wire index, else the newest call with its non-empty id, else (for any // delta without an explicit index, even with an unmatched id) the latest call. @@ -220,13 +221,24 @@ func (k *toolCallKeys) candidate(toolCalls map[int64]streamToolCall, delta opena } } - if !indexed { + if !indexed || !k.boundToWireIndex(k.latest) { _, ok := toolCalls[k.latest] return k.latest, ok } return 0, false } +// PROSE: boundToWireIndex reports whether any wire index maps to key; a call opened without an index stays unbound until an indexed continuation binds it. +func (k *toolCallKeys) boundToWireIndex(key int64) bool { + for _, bound := range k.byWireIndex { + if bound == key { + return true + } + } + return false +} + +// PROSE: stale, the last evidence is now an explicit wire index while current is bound to a different wire index; an unbound current is continued. // startsNewToolCall reports whether delta opens a new call instead of // continuing current. A new call requires a function name plus one of: a name // differing from current's non-empty name (so one tool never receives another @@ -257,8 +269,9 @@ func (k *toolCallKeys) startsNewToolCall(current streamToolCall, key int64, delt if !delta.JSON.Index.Valid() { return false } + // PROSE: an indexed delta splits only from a candidate bound to a different wire index; an unbound candidate (opened without an index) is continued and its index gets bound in commit. bound, ok := k.byWireIndex[delta.Index] - return !ok || bound != key + return (!ok || bound != key) && k.boundToWireIndex(key) } // newKey keeps an unused wire index as its key so indexed spec streams keep From 5b578e527d542d026daef52bf8a14614e77d9698 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 19:44:50 +0000 Subject: [PATCH 25/52] docs(providers/openai): document unbound-call continuation rules Update candidate, boundToWireIndex, and startsNewToolCall comments for unbound latest-call fallback and splitting only when bound to a different wire index. --- providers/openai/language_model.go | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 027eb0a5d..235e4bc8e 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -201,12 +201,10 @@ func (k *toolCallKeys) commit(delta openai.ChatCompletionChunkChoiceDeltaToolCal k.latest = key } -// PROSE: stale (CRF-54), the candidate rule now also picks the latest call for an indexed delta when no wire index is bound to that call, and "indexes and ids only pick the candidate" is wrong: startsNewToolCall splits named deltas on a new provider id or a different bound index; only nameless deltas never split. // candidate selects the call delta most likely continues: the call bound to -// its wire index, else the newest call with its non-empty id, else (for any -// delta without an explicit index, even with an unmatched id) the latest call. -// Indexes and ids only pick the candidate; a nameless delta never splits on an -// id. +// its wire index, else the newest call with its non-empty id, else the latest +// call when delta has no explicit index or the latest call is not bound to any +// wire index. Only nameless deltas never split from their candidate. func (k *toolCallKeys) candidate(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) (int64, bool) { indexed := delta.JSON.Index.Valid() if indexed { @@ -228,7 +226,8 @@ func (k *toolCallKeys) candidate(toolCalls map[int64]streamToolCall, delta opena return 0, false } -// PROSE: boundToWireIndex reports whether any wire index maps to key; a call opened without an index stays unbound until an indexed continuation binds it. +// boundToWireIndex reports whether any wire index maps to key; a call opened +// without an index remains unbound until an indexed continuation binds it. func (k *toolCallKeys) boundToWireIndex(key int64) bool { for _, bound := range k.byWireIndex { if bound == key { @@ -238,13 +237,13 @@ func (k *toolCallKeys) boundToWireIndex(key int64) bool { return false } -// PROSE: stale, the last evidence is now an explicit wire index while current is bound to a different wire index; an unbound current is continued. // startsNewToolCall reports whether delta opens a new call instead of // continuing current. A new call requires a function name plus one of: a name // differing from current's non-empty name (so one tool never receives another // tool's arguments); a non-empty id differing from current's provider-sent id; // complete JSON arguments on current with non-blank arguments on delta; or an -// explicit wire index that current is not bound to. Spec continuations carry +// explicit wire index while current is bound to a different wire index (an +// unbound current is continued and bound in commit). Spec continuations carry // no function name and always continue. func (k *toolCallKeys) startsNewToolCall(current streamToolCall, key int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) bool { if delta.Function.Name == "" { @@ -269,7 +268,9 @@ func (k *toolCallKeys) startsNewToolCall(current streamToolCall, key int64, delt if !delta.JSON.Index.Valid() { return false } - // PROSE: an indexed delta splits only from a candidate bound to a different wire index; an unbound candidate (opened without an index) is continued and its index gets bound in commit. + // Split only when current is already bound to a different wire index; an + // unbound candidate (opened without an index) is continued and bound in + // commit. bound, ok := k.byWireIndex[delta.Index] return (!ok || bound != key) && k.boundToWireIndex(key) } From 1614ec76f472b84c3d2bf8c6ecf86b401c81939a Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 20:17:29 +0000 Subject: [PATCH 26/52] test(providers/openaicompat): cover finished and rebound unindexed calls A spec opener at a new wire index after an index-less call with complete arguments must start its own call. A named call that reuses the id of a call whose wire index was taken by a split must also start its own call, so the duplicate id stays visible. --- .../openaicompat/unindexed_tool_calls_test.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index 1f26ed8a3..deaa8893d 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -439,6 +439,24 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { }, want: []string{`tool-call-0:f={"x":1}`}, }, + { + name: "spec opener at a new wire index after a complete unindexed call", + chunks: []string{ + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), + chunk(`{"index":1,"type":"function","function":{"name":"f","arguments":""}}`), + chunk(`{"index":1,"function":{"arguments":"{\"x\":2}"}}`), + }, + want: []string{`a:f={"x":1}`, `tool-call-1:f={"x":2}`}, + }, + { + name: "named call reusing the id of a call that lost its wire index to a split", + chunks: []string{ + chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), + chunk(`{"index":0,"id":"b","type":"function","function":{"name":"f","arguments":"{\"y\":2}"}}`), + chunk(`{"index":1,"id":"a","type":"function","function":{"name":"f","arguments":"{\"z\":3}"}}`), + }, + want: []string{`a:f={"x":`, `b:f={"y":2}`, `a:f={"z":3}`}, + }, { name: "id-less stream cut mid-arguments by length", chunks: []string{ From f74b1d9956e23b0f61bb93318c5a434c08694fff Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 20:17:29 +0000 Subject: [PATCH 27/52] fix(providers/openai): split finished or once-bound unbound candidates bbcb29c continued any candidate without a current wire binding at a new index. That merged a spec opener into a finished index-less call, and let a call whose index moved to a split absorb a later named call with its id. An unbound candidate with complete JSON arguments now splits, and "bound" means bound at any point, tracked in commit. --- providers/openai/language_model.go | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 235e4bc8e..8bd1f05ee 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -164,14 +164,17 @@ type toolCallKeys struct { // follows arrival order even when wire indexes arrive out of order. // Presence in this map marks a key as used. created map[int64]int - next int64 - latest int64 + // PROSE: everBound holds keys a wire index has bound at any point, so a call that lost its index to a split still counts as bound and does not absorb a later named call. + everBound map[int64]bool + next int64 + latest int64 } func newToolCallKeys() *toolCallKeys { return &toolCallKeys{ byWireIndex: make(map[int64]int64), created: make(map[int64]int), + everBound: make(map[int64]bool), latest: -1, } } @@ -193,6 +196,7 @@ func (k *toolCallKeys) resolve(toolCalls map[int64]streamToolCall, delta openai. func (k *toolCallKeys) commit(delta openai.ChatCompletionChunkChoiceDeltaToolCall, key int64) { if delta.JSON.Index.Valid() { k.byWireIndex[delta.Index] = key + k.everBound[key] = true } if _, ok := k.created[key]; !ok { k.created[key] = len(k.created) @@ -201,6 +205,7 @@ func (k *toolCallKeys) commit(delta openai.ChatCompletionChunkChoiceDeltaToolCal k.latest = key } +// PROSE: stale, "not bound to any wire index" now means never bound (everBound), not currently bound. // candidate selects the call delta most likely continues: the call bound to // its wire index, else the newest call with its non-empty id, else the latest // call when delta has no explicit index or the latest call is not bound to any @@ -219,24 +224,14 @@ func (k *toolCallKeys) candidate(toolCalls map[int64]streamToolCall, delta opena } } - if !indexed || !k.boundToWireIndex(k.latest) { + if !indexed || !k.everBound[k.latest] { _, ok := toolCalls[k.latest] return k.latest, ok } return 0, false } -// boundToWireIndex reports whether any wire index maps to key; a call opened -// without an index remains unbound until an indexed continuation binds it. -func (k *toolCallKeys) boundToWireIndex(key int64) bool { - for _, bound := range k.byWireIndex { - if bound == key { - return true - } - } - return false -} - +// PROSE: stale, the last evidence is now an explicit wire index while current was ever bound to a different wire index, or current is unbound with complete JSON arguments. // startsNewToolCall reports whether delta opens a new call instead of // continuing current. A new call requires a function name plus one of: a name // differing from current's non-empty name (so one tool never receives another @@ -268,11 +263,15 @@ func (k *toolCallKeys) startsNewToolCall(current streamToolCall, key int64, delt if !delta.JSON.Index.Valid() { return false } + // PROSE: stale, an unbound candidate is now split when its arguments are already complete JSON (a finished index-less call followed by a spec opener at a new index); only an unfinished unbound candidate is continued. "Bound" means bound at any point (everBound). // Split only when current is already bound to a different wire index; an // unbound candidate (opened without an index) is continued and bound in // commit. bound, ok := k.byWireIndex[delta.Index] - return (!ok || bound != key) && k.boundToWireIndex(key) + if ok && bound == key { + return false + } + return k.everBound[key] || json.Valid([]byte(current.arguments)) } // newKey keeps an unused wire index as its key so indexed spec streams keep From f035e952ff048948a5b731814acc3033154e244d Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 20:19:46 +0000 Subject: [PATCH 28/52] docs(providers/openai): document everBound and finished-call split Update toolCallKeys.everBound, candidate, and startsNewToolCall comments for never-bound tracking and splitting complete unbound candidates. --- providers/openai/language_model.go | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 8bd1f05ee..f9b6e2ecd 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -164,7 +164,8 @@ type toolCallKeys struct { // follows arrival order even when wire indexes arrive out of order. // Presence in this map marks a key as used. created map[int64]int - // PROSE: everBound holds keys a wire index has bound at any point, so a call that lost its index to a split still counts as bound and does not absorb a later named call. + // everBound tracks keys bound to a wire index at any point, so a call + // that lost its wire index to a split still counts as bound. everBound map[int64]bool next int64 latest int64 @@ -205,11 +206,10 @@ func (k *toolCallKeys) commit(delta openai.ChatCompletionChunkChoiceDeltaToolCal k.latest = key } -// PROSE: stale, "not bound to any wire index" now means never bound (everBound), not currently bound. // candidate selects the call delta most likely continues: the call bound to // its wire index, else the newest call with its non-empty id, else the latest -// call when delta has no explicit index or the latest call is not bound to any -// wire index. Only nameless deltas never split from their candidate. +// call when delta has no explicit index or the latest call was never bound to +// a wire index. Only nameless deltas never split from their candidate. func (k *toolCallKeys) candidate(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) (int64, bool) { indexed := delta.JSON.Index.Valid() if indexed { @@ -231,15 +231,14 @@ func (k *toolCallKeys) candidate(toolCalls map[int64]streamToolCall, delta opena return 0, false } -// PROSE: stale, the last evidence is now an explicit wire index while current was ever bound to a different wire index, or current is unbound with complete JSON arguments. // startsNewToolCall reports whether delta opens a new call instead of // continuing current. A new call requires a function name plus one of: a name // differing from current's non-empty name (so one tool never receives another // tool's arguments); a non-empty id differing from current's provider-sent id; // complete JSON arguments on current with non-blank arguments on delta; or an -// explicit wire index while current is bound to a different wire index (an -// unbound current is continued and bound in commit). Spec continuations carry -// no function name and always continue. +// explicit wire index that current is not bound to when current was ever bound +// to a wire index or already has complete JSON arguments. Spec continuations +// carry no function name and always continue. func (k *toolCallKeys) startsNewToolCall(current streamToolCall, key int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) bool { if delta.Function.Name == "" { return false @@ -263,10 +262,9 @@ func (k *toolCallKeys) startsNewToolCall(current streamToolCall, key int64, delt if !delta.JSON.Index.Valid() { return false } - // PROSE: stale, an unbound candidate is now split when its arguments are already complete JSON (a finished index-less call followed by a spec opener at a new index); only an unfinished unbound candidate is continued. "Bound" means bound at any point (everBound). - // Split only when current is already bound to a different wire index; an - // unbound candidate (opened without an index) is continued and bound in - // commit. + // Continue only a never-bound candidate with incomplete arguments (which + // gets its index bound in commit); split if current was ever bound to + // another index or already has complete JSON arguments. bound, ok := k.byWireIndex[delta.Index] if ok && bound == key { return false From d33d5f1777f1e52dc4ba794c92169f9aa2d73180 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 20:27:33 +0000 Subject: [PATCH 29/52] test(providers/openaicompat): cover a same-id call at index 1 after an unindexed one An index-less call with incomplete arguments followed by a named call with the same id at index 1 must stay two calls, so chatd sees the duplicate id and fails closed. --- providers/openaicompat/unindexed_tool_calls_test.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index deaa8893d..8d8c9d637 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -457,6 +457,14 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { }, want: []string{`a:f={"x":`, `b:f={"y":2}`, `a:f={"z":3}`}, }, + { + name: "named same-id call at wire index 1 after an incomplete unindexed call", + chunks: []string{ + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"path\":"}}`), + chunk(`{"index":1,"id":"a","type":"function","function":{"name":"f","arguments":"{\"path\":\"b\"}"}}`), + }, + want: []string{`a:f={"path":`, `a:f={"path":"b"}`}, + }, { name: "id-less stream cut mid-arguments by length", chunks: []string{ From e73ee6dce47902bf6efeae3fcb3e1a139aa2e34e Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 20:27:33 +0000 Subject: [PATCH 30/52] fix(providers/openai): place never-bound calls at wire index 0 The SDK decodes a missing index as 0, so a call opened without an index now counts as being at index 0. An indexed named delta at any other index splits from it, which keeps a same-id call at index 1 separate. At index 0 it continues the call only while its arguments are incomplete. --- providers/openai/language_model.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index f9b6e2ecd..fd6b45453 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -231,6 +231,7 @@ func (k *toolCallKeys) candidate(toolCalls map[int64]streamToolCall, delta opena return 0, false } +// PROSE: stale, the index evidence is now: the candidate's index (its bound index, or 0 when never bound) differs from the delta's, or the candidate was never bound and has complete JSON arguments. // startsNewToolCall reports whether delta opens a new call instead of // continuing current. A new call requires a function name plus one of: a name // differing from current's non-empty name (so one tool never receives another @@ -262,6 +263,7 @@ func (k *toolCallKeys) startsNewToolCall(current streamToolCall, key int64, delt if !delta.JSON.Index.Valid() { return false } + // PROSE: stale, a never-bound candidate now counts as being at wire index 0 (how the SDK decodes a missing index), so it is continued only by an index 0 delta while its arguments are incomplete; a delta at any other index splits. // Continue only a never-bound candidate with incomplete arguments (which // gets its index bound in commit); split if current was ever bound to // another index or already has complete JSON arguments. @@ -269,7 +271,10 @@ func (k *toolCallKeys) startsNewToolCall(current streamToolCall, key int64, delt if ok && bound == key { return false } - return k.everBound[key] || json.Valid([]byte(current.arguments)) + if k.everBound[key] || delta.Index != 0 { + return true + } + return json.Valid([]byte(current.arguments)) } // newKey keeps an unused wire index as its key so indexed spec streams keep From ed9e96bef173f2e99d7d6b6ebc93b9ecce6fbc9c Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Wed, 2 Dec 2026 20:29:36 +0000 Subject: [PATCH 31/52] docs(providers/openai): document index-0 rule for never-bound calls Update startsNewToolCall comments to reflect that a never-bound call counts as sitting at wire index 0 and splits on any other wire index. --- providers/openai/language_model.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index fd6b45453..f87594d92 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -231,15 +231,15 @@ func (k *toolCallKeys) candidate(toolCalls map[int64]streamToolCall, delta opena return 0, false } -// PROSE: stale, the index evidence is now: the candidate's index (its bound index, or 0 when never bound) differs from the delta's, or the candidate was never bound and has complete JSON arguments. // startsNewToolCall reports whether delta opens a new call instead of // continuing current. A new call requires a function name plus one of: a name // differing from current's non-empty name (so one tool never receives another // tool's arguments); a non-empty id differing from current's provider-sent id; // complete JSON arguments on current with non-blank arguments on delta; or an -// explicit wire index that current is not bound to when current was ever bound -// to a wire index or already has complete JSON arguments. Spec continuations -// carry no function name and always continue. +// explicit wire index that differs from current's index (its bound wire index, +// or 0 when never bound), or a never-bound current whose arguments already +// parse as complete JSON. Spec continuations carry no function name and always +// continue. func (k *toolCallKeys) startsNewToolCall(current streamToolCall, key int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) bool { if delta.Function.Name == "" { return false @@ -263,10 +263,10 @@ func (k *toolCallKeys) startsNewToolCall(current streamToolCall, key int64, delt if !delta.JSON.Index.Valid() { return false } - // PROSE: stale, a never-bound candidate now counts as being at wire index 0 (how the SDK decodes a missing index), so it is continued only by an index 0 delta while its arguments are incomplete; a delta at any other index splits. - // Continue only a never-bound candidate with incomplete arguments (which - // gets its index bound in commit); split if current was ever bound to - // another index or already has complete JSON arguments. + // A never-bound candidate counts as sitting at wire index 0 (how the SDK + // decodes an absent index), so only an index 0 delta continues it while its + // arguments are incomplete; any other index or a complete or ever-bound + // candidate splits. bound, ok := k.byWireIndex[delta.Index] if ok && bound == key { return false From 69d0a51ccd8c58c0368d067793a7df0347677869 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 11:57:18 +0000 Subject: [PATCH 32/52] test(providers/openaicompat): keep only supported unindexed tool call shapes Reduce the table to the shapes the narrowed fix handles: id-less fragments, fragments that repeat the id and name, two whole calls in one chunk, id-less whole calls continuing one call, an unchanged indexed stream, and indexed and index-less calls in one stream. The remaining rows covered index reuse and other shapes no provider is known to send. collectCalls goes back to one call per id. --- .../openaicompat/unindexed_tool_calls_test.go | 396 ++---------------- 1 file changed, 45 insertions(+), 351 deletions(-) diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index 8d8c9d637..6ed3249bc 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -1,7 +1,6 @@ package openaicompat import ( - "cmp" "fmt" "net/http" "net/http/httptest" @@ -43,36 +42,22 @@ func (c streamedCall) String() string { return c.id + ":" + c.name + "=" + c.input } -type toolCallStream struct { - calls []streamedCall - started []string - finish fantasy.FinishReason -} - -// collectCalls verifies tool-call stream parts: ToolInputEnd counts must match -// ToolInputStart counts per id, deltas attach to the most recently started call -// for that id, and each ToolCall pairs with an uncalled started call whose name -// and streamed deltas match its input (allowing "{}" when no deltas streamed). -func collectCalls(t *testing.T, parts []fantasy.StreamPart) toolCallStream { +// PROSE: collectCalls returns the emitted tool calls and the finish reason, and checks each call's part sequence: one ToolInputStart, its deltas, one ToolInputEnd, then one ToolCall whose name matches the start and whose input equals the concatenated deltas. +func collectCalls(t *testing.T, parts []fantasy.StreamPart) ([]string, fantasy.FinishReason) { t.Helper() type progress struct { name string deltas string + ended bool called bool } - var out toolCallStream - seen := map[string][]*progress{} - ends := map[string]int{} - called := map[string]int{} - - matches := func(c *progress, p fantasy.StreamPart) bool { - if c.called || c.name != p.ToolCallName { - return false - } - return c.deltas == p.ToolCallInput || (c.deltas == "" && p.ToolCallInput == "{}") - } + var ( + calls []string + finish fantasy.FinishReason + ) + seen := map[string]*progress{} for _, p := range parts { switch p.Type { @@ -80,49 +65,41 @@ func collectCalls(t *testing.T, parts []fantasy.StreamPart) toolCallStream { t.Fatalf("stream error: %v", p.Error) case fantasy.StreamPartTypeToolInputStart: - seen[p.ID] = append(seen[p.ID], &progress{name: p.ToolCallName}) - out.started = append(out.started, p.ID) + require.NotContains(t, seen, p.ID, "second ToolInputStart for %s", p.ID) + seen[p.ID] = &progress{name: p.ToolCallName} case fantasy.StreamPartTypeToolInputDelta: - calls := seen[p.ID] - require.Greater(t, len(calls), ends[p.ID], "ToolInputDelta without an open ToolInputStart for %s", p.ID) - calls[len(calls)-1].deltas += p.Delta + c := seen[p.ID] + require.NotNil(t, c, "ToolInputDelta before ToolInputStart for %s", p.ID) + require.False(t, c.ended, "ToolInputDelta after ToolInputEnd for %s", p.ID) + c.deltas += p.Delta case fantasy.StreamPartTypeToolInputEnd: - require.Greater(t, len(seen[p.ID]), ends[p.ID], "ToolInputEnd without an open ToolInputStart for %s", p.ID) - ends[p.ID]++ + c := seen[p.ID] + require.NotNil(t, c, "ToolInputEnd before ToolInputStart for %s", p.ID) + require.False(t, c.ended, "second ToolInputEnd for %s", p.ID) + c.ended = true case fantasy.StreamPartTypeToolCall: - require.Greater(t, ends[p.ID], called[p.ID], "ToolCall before ToolInputEnd for %s", p.ID) - var c *progress - for _, candidate := range seen[p.ID] { - if matches(candidate, p) { - c = candidate - break - } - } - require.NotNil(t, c, "ToolCall %s:%s=%s matches no started call's name and streamed deltas", p.ID, p.ToolCallName, p.ToolCallInput) + c := seen[p.ID] + require.NotNil(t, c, "ToolCall before ToolInputStart for %s", p.ID) + require.True(t, c.ended, "ToolCall before ToolInputEnd for %s", p.ID) + require.False(t, c.called, "second ToolCall for %s", p.ID) c.called = true - called[p.ID]++ - out.calls = append(out.calls, streamedCall{id: p.ID, name: p.ToolCallName, input: p.ToolCallInput}) + + require.Equal(t, c.name, p.ToolCallName, "ToolCall name differs from ToolInputStart for %s", p.ID) + require.Equal(t, c.deltas, p.ToolCallInput, "streamed input deltas differ from the final input for %s", p.ID) + calls = append(calls, streamedCall{id: p.ID, name: p.ToolCallName, input: p.ToolCallInput}.String()) case fantasy.StreamPartTypeFinish: - out.finish = p.FinishReason + finish = p.FinishReason } } - for id, calls := range seen { - require.Equal(t, len(calls), ends[id], "ToolInputEnd count differs from ToolInputStart count for %s", id) + for id, c := range seen { + require.True(t, c.called, "no ToolCall for %s", id) } - return out -} - -func callStrings(calls []streamedCall) []string { - var out []string - for _, c := range calls { - out = append(out, c.String()) - } - return out + return calls, finish } func TestStream_UnindexedGeminiParallelToolCalls(t *testing.T) { @@ -134,14 +111,14 @@ func TestStream_UnindexedGeminiParallelToolCalls(t *testing.T) { capture, err := os.ReadFile("testdata/gemini_parallel_unindexed.sse") require.NoError(t, err) - got := collectCalls(t, streamFrom(t, string(capture))) + calls, finish := collectCalls(t, streamFrom(t, string(capture))) require.Equal(t, []string{ `call_6886726613787760133:get_weather={"city":"Paris"}`, `call_6886726613787759528:get_weather={"city":"Tokyo"}`, `call_6886726613787761809:get_weather={"city":"Lima"}`, - }, callStrings(got.calls)) - require.Equal(t, fantasy.FinishReasonStop, got.finish) + }, calls) + require.Equal(t, fantasy.FinishReasonStop, finish) } func TestStream_UnindexedToolCallShapes(t *testing.T) { @@ -150,19 +127,13 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { chunk := func(toolCalls string) string { return `data: {"id":"c","object":"chat.completion.chunk","created":1,"model":"m","choices":[{"index":0,"delta":{"tool_calls":[` + toolCalls + `]}}]}` + "\n\n" } - finishChunk := func(reason string) string { - return `data: {"id":"c","object":"chat.completion.chunk","created":1,"model":"m","choices":[{"index":0,"delta":{},"finish_reason":"` + reason + `"}]}` + "\n\n" - } - const done = "data: [DONE]\n\n" + const end = `data: {"id":"c","object":"chat.completion.chunk","created":1,"model":"m","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}` + "\n\n" + + "data: [DONE]\n\n" tests := []struct { - name string - chunks []string - finish string - noFinish bool - want []string - wantStarted []string - wantFinish fantasy.FinishReason + name string + chunks []string + want []string }{ { name: "one call split into id-less fragments", @@ -188,39 +159,12 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { want: []string{`a:f={"x":1}`, `b:f={"x":2}`}, }, { - name: "calls without ids, same name", + name: "id-less whole calls continue one call", chunks: []string{ chunk(`{"type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), chunk(`{"type":"function","function":{"name":"f","arguments":"{\"x\":2}"}}`), }, - want: []string{`tool-call-0:f={"x":1}`, `tool-call-1:f={"x":2}`}, - }, - { - name: "id-less fragment repeating the name before the arguments complete", - chunks: []string{ - chunk(`{"type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), - chunk(`{"type":"function","function":{"name":"f","arguments":"1}"}}`), - }, - want: []string{`tool-call-0:f={"x":1}`}, - }, - { - name: "calls stay in arrival order", - chunks: []string{ - chunk(`{"id":"z","type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), - chunk(`{"id":"m","type":"function","function":{"name":"f","arguments":"{\"x\":2}"}}`), - chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":3}"}}`), - }, - want: []string{`z:f={"x":1}`, `m:f={"x":2}`, `a:f={"x":3}`}, - }, - { - name: "complete calls in a stream without a finish reason", - chunks: []string{ - chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), - chunk(`{"id":"b","type":"function","function":{"name":"f","arguments":"{\"x\":2}"}}`), - }, - noFinish: true, - want: []string{`a:f={"x":1}`, `b:f={"x":2}`}, - wantFinish: fantasy.FinishReasonToolCalls, + want: []string{`tool-call-0:f={"x":1}{"x":2}`}, }, { name: "indexed deltas are unchanged", @@ -232,273 +176,23 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { want: []string{`a:f={"x":1}`, `b:g={"y":2}`}, }, { - name: "indexed opener continued by id-less fragments", - chunks: []string{ - chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":""}}`), - chunk(`{"function":{"arguments":"{\"x\":"}}`), - chunk(`{"function":{"arguments":"1}"}}`), - }, - want: []string{`a:f={"x":1}`}, - }, - { - name: "indexed opener continued by id-less fragments without a finish reason", - chunks: []string{ - chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":""}}`), - chunk(`{"function":{"arguments":"{\"x\":"}}`), - chunk(`{"function":{"arguments":"1}"}}`), - }, - noFinish: true, - want: []string{`a:f={"x":1}`}, - wantFinish: fantasy.FinishReasonToolCalls, - }, - { - name: "interleaved fragments correlated by id", - chunks: []string{ - chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), - chunk(`{"id":"b","type":"function","function":{"name":"g","arguments":"{\"y\":"}}`), - chunk(`{"id":"a","function":{"arguments":"1}"}}`), - chunk(`{"id":"b","function":{"arguments":"2}"}}`), - }, - want: []string{`a:f={"x":1}`, `b:g={"y":2}`}, - }, - { - name: "whitespace fragment after complete arguments, same name, no id", - chunks: []string{ - chunk(`{"type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), - chunk(`{"type":"function","function":{"name":"f","arguments":" "}}`), - }, - want: []string{`tool-call-0:f={"x":1} `}, - }, - { - name: "different names without ids, first with empty arguments", - chunks: []string{ - chunk(`{"type":"function","function":{"name":"f","arguments":""}}`), - chunk(`{"type":"function","function":{"name":"g","arguments":"{\"y\":2}"}}`), - }, - want: []string{`tool-call-0:f={}`, `tool-call-1:g={"y":2}`}, - }, - { - name: "different named call on a bound wire index before the first call completes", - chunks: []string{ - chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), - chunk(`{"index":0,"id":"b","type":"function","function":{"name":"g","arguments":"{\"y\":2}"}}`), - }, - want: []string{`a:f={"x":`, `b:g={"y":2}`}, - }, - { - name: "leading empty id-less delta", - chunks: []string{ - chunk(`{"type":"function","function":{"name":"","arguments":""}}`), - chunk(`{"type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), - chunk(`{"type":"function","function":{"name":"g","arguments":"{\"y\":2}"}}`), - }, - want: []string{`tool-call-0:f={"x":1}`, `tool-call-1:g={"y":2}`}, - }, - { - name: "explicit index after synthetic calls took its key", + name: "indexed and index-less calls in one stream do not collide", chunks: []string{ chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), - chunk(`{"id":"b","type":"function","function":{"name":"g","arguments":"{\"y\":2}"}}`), - chunk(`{"index":0,"id":"c","type":"function","function":{"name":"h","arguments":""}}`), - chunk(`{"index":0,"function":{"arguments":"{\"z\":3}"}}`), - }, - want: []string{`a:f={"x":1}`, `b:g={"y":2}`, `c:h={"z":3}`}, - }, - { - name: "unindexed opener continued by indexed deltas with the same id", - chunks: []string{ - chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), - chunk(`{"index":0,"id":"a","function":{"arguments":"1"}}`), - chunk(`{"index":0,"function":{"arguments":"}"}}`), - }, - want: []string{`a:f={"x":1}`}, - }, - { - name: "unindexed delta continues the indexed call with its id", - chunks: []string{ - chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":""}}`), - chunk(`{"id":"a","function":{"arguments":"{\"x\":1}"}}`), - }, - want: []string{`a:f={"x":1}`}, - }, - { - name: "same name with empty arguments after complete arguments, no id", - chunks: []string{ - chunk(`{"type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), - chunk(`{"type":"function","function":{"name":"f","arguments":""}}`), - }, - want: []string{`tool-call-0:f={"x":1}`}, - }, - { - name: "named delta reusing the id of a complete unindexed call", - chunks: []string{ - chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), - chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":2}"}}`), - }, - want: []string{`a:f={"x":1}`, `a:f={"x":2}`}, - }, - { - name: "named delta at a new wire index reusing the id of an incomplete indexed call", - chunks: []string{ - chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}},{"index":1,"id":"a","type":"function","function":{"name":"f","arguments":"{\"y\":2}"}}`), - }, - want: []string{`a:f={"x":`, `a:f={"y":2}`}, - }, - { - name: "unindexed opener continued by an indexed delta repeating its id and name", - chunks: []string{ - chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), - chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"1}"}}`), - }, - want: []string{`a:f={"x":1}`}, - }, - { - name: "unindexed opener continued by a nameless id-less indexed delta", - chunks: []string{ - chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), - chunk(`{"index":0,"function":{"arguments":"1}"}}`), - }, - want: []string{`a:f={"x":1}`}, - }, - { - name: "named delta at wire index 0 reusing the id of an unindexed call", - chunks: []string{ - chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{}"}}`), - chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"{\"y\":2}"}}`), - }, - want: []string{`a:f={}`, `a:f={"y":2}`}, - }, - { - name: "different id at a bound wire index", - chunks: []string{ - chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), - chunk(`{"index":0,"id":"b","type":"function","function":{"name":"g","arguments":"{\"y\":"}}`), - chunk(`{"index":0,"function":{"arguments":"2}"}}`), + chunk(`{"index":0,"id":"b","type":"function","function":{"name":"g","arguments":"{\"y\":2}"}}`), }, want: []string{`a:f={"x":1}`, `b:g={"y":2}`}, }, - { - name: "complete named calls with the same id at the same wire index", - chunks: []string{ - chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"{}"}}`), - chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"{\"y\":2}"}}`), - }, - want: []string{`a:f={}`, `a:f={"y":2}`}, - }, - { - name: "nameless fragments with a fresh id each at a bound wire index", - chunks: []string{ - chunk(`{"index":0,"id":"call_A","type":"function","function":{"name":"list_dir","arguments":""}}`), - chunk(`{"index":0,"id":"frag1","function":{"arguments":"{\"pa"}}`), - chunk(`{"index":0,"id":"frag2","function":{"arguments":"th\": \"repo\"}"}}`), - }, - want: []string{`call_A:list_dir={"path": "repo"}`}, - }, - { - name: "id continuation after duplicate-id calls arrive at out-of-order indexes", - chunks: []string{ - chunk(`{"index":1,"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), - chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"{\"y\":"}}`), - chunk(`{"id":"a","function":{"arguments":"2}"}}`), - }, - want: []string{`a:f={"y":2}`, `a:f={"x":1}`}, - wantStarted: []string{"a", "a"}, - }, - { - name: "same-name openers with new ids and empty arguments on one wire index", - chunks: []string{ - chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":""}}`), - chunk(`{"index":0,"function":{"arguments":"{\"x\":1}"}}`), - chunk(`{"index":0,"id":"b","type":"function","function":{"name":"f","arguments":""}}`), - chunk(`{"index":0,"function":{"arguments":"{\"x\":2}"}}`), - }, - want: []string{`a:f={"x":1}`, `b:f={"x":2}`}, - }, - { - name: "same-name call with a new id on one wire index before the first completes", - chunks: []string{ - chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), - chunk(`{"index":0,"id":"b","type":"function","function":{"name":"f","arguments":"{\"y\":2}"}}`), - }, - want: []string{`a:f={"x":`, `b:f={"y":2}`}, - }, - { - name: "nameless fragments with a fresh id each and no index", - chunks: []string{ - chunk(`{"id":"call_A","type":"function","function":{"name":"list_dir","arguments":""}}`), - chunk(`{"id":"frag1","function":{"arguments":"{\"pa"}}`), - chunk(`{"id":"frag2","function":{"arguments":"th\": 1}"}}`), - }, - want: []string{`call_A:list_dir={"path": 1}`}, - }, - { - name: "indexed opener without id continued by a named delta carrying an id", - chunks: []string{ - chunk(`{"index":0,"type":"function","function":{"name":"f","arguments":""}}`), - chunk(`{"index":0,"id":"x","type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), - }, - want: []string{`tool-call-0:f={"x":1}`}, - }, - { - name: "spec opener at a new wire index after a complete unindexed call", - chunks: []string{ - chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), - chunk(`{"index":1,"type":"function","function":{"name":"f","arguments":""}}`), - chunk(`{"index":1,"function":{"arguments":"{\"x\":2}"}}`), - }, - want: []string{`a:f={"x":1}`, `tool-call-1:f={"x":2}`}, - }, - { - name: "named call reusing the id of a call that lost its wire index to a split", - chunks: []string{ - chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), - chunk(`{"index":0,"id":"b","type":"function","function":{"name":"f","arguments":"{\"y\":2}"}}`), - chunk(`{"index":1,"id":"a","type":"function","function":{"name":"f","arguments":"{\"z\":3}"}}`), - }, - want: []string{`a:f={"x":`, `b:f={"y":2}`, `a:f={"z":3}`}, - }, - { - name: "named same-id call at wire index 1 after an incomplete unindexed call", - chunks: []string{ - chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"path\":"}}`), - chunk(`{"index":1,"id":"a","type":"function","function":{"name":"f","arguments":"{\"path\":\"b\"}"}}`), - }, - want: []string{`a:f={"path":`, `a:f={"path":"b"}`}, - }, - { - name: "id-less stream cut mid-arguments by length", - chunks: []string{ - chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), - }, - finish: "length", - wantStarted: []string{"a"}, - wantFinish: fantasy.FinishReasonLength, - }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - body := strings.Join(tt.chunks, "") - if !tt.noFinish { - body += finishChunk(cmp.Or(tt.finish, "stop")) - } - body += done - - got := collectCalls(t, streamFrom(t, body)) - - require.Equal(t, tt.want, callStrings(got.calls)) - - wantStarted := tt.wantStarted - if wantStarted == nil { - for _, c := range got.calls { - wantStarted = append(wantStarted, c.id) - } - } - require.Equal(t, wantStarted, got.started) + calls, finish := collectCalls(t, streamFrom(t, strings.Join(tt.chunks, "")+end)) - require.Equal(t, cmp.Or(tt.wantFinish, fantasy.FinishReasonStop), got.finish) + require.Equal(t, tt.want, calls) + require.Equal(t, fantasy.FinishReasonStop, finish) }) } } From 675ac9ba73011d8c1f29d5ed6ab729a6432e36be Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 11:57:18 +0000 Subject: [PATCH 33/52] fix(providers/openai): key only index-less tool calls separately Replace the general resolver with the minimum the Gemini stream needs. Indexed deltas take the coder_2_33 path again with key equal to wire index, so index reuse by Ollama or LiteLLM behaves as before. A delta without an index starts a new call when it is the first one or carries an id different from the latest index-less call's id, and otherwise continues that call. Index-less keys start at math.MinInt64, so they never collide with wire indexes and finalize before indexed calls. --- providers/openai/language_model.go | 195 +++++------------------------ 1 file changed, 31 insertions(+), 164 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index f87594d92..e89a009b0 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -8,6 +8,7 @@ import ( "fmt" "io" "maps" + "math" "net/http" "reflect" "slices" @@ -147,158 +148,22 @@ type streamToolCall struct { name string arguments string hasFinished bool - // idFromWire is false when id is the synthesized tool-call-N fallback, - // so the fallback never counts as a provider-sent id. - idFromWire bool } -// toolCallKeys assigns non-colliding toolCalls map keys to streamed tool-call -// deltas when a provider omits the index field, which the SDK decodes as 0, or -// reuses a wire index across calls. Every delta resolves through one rule: -// pick a candidate call by bound wire index, id, or latest call, and continue -// it unless the delta opens a new call. Spec-compliant indexed streams keep -// each wire index as its key. -type toolCallKeys struct { - byWireIndex map[int64]int64 - // created maps each used key to its creation sequence number so recency - // follows arrival order even when wire indexes arrive out of order. - // Presence in this map marks a key as used. - created map[int64]int - // everBound tracks keys bound to a wire index at any point, so a call - // that lost its wire index to a split still counts as bound. - everBound map[int64]bool - next int64 - latest int64 -} - -func newToolCallKeys() *toolCallKeys { - return &toolCallKeys{ - byWireIndex: make(map[int64]int64), - created: make(map[int64]int), - everBound: make(map[int64]bool), - latest: -1, - } -} - -// resolve returns the toolCalls key for delta without recording it, leaving -// key allocation and latest unchanged until commit runs. -func (k *toolCallKeys) resolve(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { - key, ok := k.candidate(toolCalls, delta) - if ok && !k.startsNewToolCall(toolCalls[key], key, delta) { - return key - } - return k.newKey(delta) -} - -// commit records key's creation sequence on first use and sets it as latest. -// For indexed deltas it also binds the wire index to key, rebinding after a -// split and binding an index-less opener when a later continuation carries an -// explicit index. -func (k *toolCallKeys) commit(delta openai.ChatCompletionChunkChoiceDeltaToolCall, key int64) { - if delta.JSON.Index.Valid() { - k.byWireIndex[delta.Index] = key - k.everBound[key] = true - } - if _, ok := k.created[key]; !ok { - k.created[key] = len(k.created) - } - k.next = max(k.next, key+1) - k.latest = key -} - -// candidate selects the call delta most likely continues: the call bound to -// its wire index, else the newest call with its non-empty id, else the latest -// call when delta has no explicit index or the latest call was never bound to -// a wire index. Only nameless deltas never split from their candidate. -func (k *toolCallKeys) candidate(toolCalls map[int64]streamToolCall, delta openai.ChatCompletionChunkChoiceDeltaToolCall) (int64, bool) { - indexed := delta.JSON.Index.Valid() - if indexed { - if key, ok := k.byWireIndex[delta.Index]; ok { - return key, true - } - } - - if delta.ID != "" { - if key, ok := k.newestWithID(toolCalls, delta.ID); ok { - return key, true - } - } - - if !indexed || !k.everBound[k.latest] { - _, ok := toolCalls[k.latest] - return k.latest, ok - } - return 0, false -} - -// startsNewToolCall reports whether delta opens a new call instead of -// continuing current. A new call requires a function name plus one of: a name -// differing from current's non-empty name (so one tool never receives another -// tool's arguments); a non-empty id differing from current's provider-sent id; -// complete JSON arguments on current with non-blank arguments on delta; or an -// explicit wire index that differs from current's index (its bound wire index, -// or 0 when never bound), or a never-bound current whose arguments already -// parse as complete JSON. Spec continuations carry no function name and always -// continue. -func (k *toolCallKeys) startsNewToolCall(current streamToolCall, key int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) bool { - if delta.Function.Name == "" { - return false - } - - if current.name != "" && delta.Function.Name != current.name { - return true - } +// PROSE: index-less calls take keys from math.MinInt64 upward, a range no wire index uses, so they never collide with indexed calls and finalize first, in arrival order. +const firstUnindexedToolCallKey int64 = math.MinInt64 - // Parallel calls to the same tool on a shared wire index and whole-call - // chunks without an index carry a new provider id; nameless deltas return - // above so fresh-id fragments still continue the call. - if delta.ID != "" && current.idFromWire && delta.ID != current.id { - return true - } - - if json.Valid([]byte(current.arguments)) && strings.TrimSpace(delta.Function.Arguments) != "" { - return true - } - - if !delta.JSON.Index.Valid() { - return false - } - // A never-bound candidate counts as sitting at wire index 0 (how the SDK - // decodes an absent index), so only an index 0 delta continues it while its - // arguments are incomplete; any other index or a complete or ever-bound - // candidate splits. - bound, ok := k.byWireIndex[delta.Index] - if ok && bound == key { - return false - } - if k.everBound[key] || delta.Index != 0 { - return true +// PROSE: unindexedToolCallKey returns the key for a delta without an index (Google's OpenAI-compatible endpoint omits it): a non-empty id that differs from the latest index-less call's id starts a new call; anything else continues the latest one. latest is reused until a call is stored there, so a skipped empty delta allocates nothing. +func unindexedToolCallKey(toolCalls map[int64]streamToolCall, latest int64, id string) int64 { + current, ok := toolCalls[latest] + if !ok { + return latest } - return json.Valid([]byte(current.arguments)) -} -// newKey keeps an unused wire index as its key so indexed spec streams keep -// wire-index keys, and falls back to k.next above every key committed so far. -func (k *toolCallKeys) newKey(delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { - if _, used := k.created[delta.Index]; delta.JSON.Index.Valid() && !used { - return delta.Index + if id != "" && id != current.id { + return latest + 1 } - return k.next -} - -// newestWithID returns the most recently created call with id by creation -// sequence so follow-up deltas attach to it even when wire indexes arrive out -// of order. -func (k *toolCallKeys) newestWithID(toolCalls map[int64]streamToolCall, id string) (int64, bool) { - found := false - var newest int64 - for key, tc := range toolCalls { - if tc.id == id && (!found || k.created[key] > k.created[newest]) { - newest = key - found = true - } - } - return newest, found + return latest } // responseCapture holds the raw HTTP response of a call so response headers @@ -626,7 +491,7 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S stream := o.client.Chat.Completions.NewStreaming(ctx, *params, capture.requestOptions(o.headerFunc, append(callUARequestOptions(call), callHeadersRequestOptions(call)...))...) isActiveText := false toolCalls := make(map[int64]streamToolCall) - callKeys := newToolCallKeys() + latestUnindexedKey := firstUnindexedToolCallKey providerMetadata := fantasy.ProviderMetadata{ Name: &ProviderMetadata{}, @@ -713,9 +578,16 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S } for _, toolCallDelta := range choice.Delta.ToolCalls { - key := callKeys.resolve(toolCalls, toolCallDelta) + if !toolCallDelta.JSON.Index.Valid() { + latestUnindexedKey = unindexedToolCallKey(toolCalls, latestUnindexedKey, toolCallDelta.ID) + toolCallDelta.Index = latestUnindexedKey + + // PROSE: the tool-call-N fallback numbers index-less calls from 0 instead of using the huge negative key. + fallbackID := fmt.Sprintf("tool-call-%d", latestUnindexedKey-firstUnindexedToolCallKey) + toolCallDelta.ID = cmp.Or(toolCallDelta.ID, fallbackID) + } - if existingToolCall, ok := toolCalls[key]; ok { + if existingToolCall, ok := toolCalls[toolCallDelta.Index]; ok { if toolCallDelta.Function.Arguments != "" { existingToolCall.arguments += toolCallDelta.Function.Arguments if !yield(fantasy.StreamPart{ @@ -726,8 +598,7 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S return } } - toolCalls[key] = existingToolCall - callKeys.commit(toolCallDelta, key) + toolCalls[toolCallDelta.Index] = existingToolCall } else { // Some provider like Ollama may send empty tool calls or miss some fields. // We'll skip when we don't have enough info and also assume sane defaults. @@ -735,8 +606,7 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S continue } toolCallDelta.Type = cmp.Or(toolCallDelta.Type, "function") - idFromWire := toolCallDelta.ID != "" - toolCallDelta.ID = cmp.Or(toolCallDelta.ID, fmt.Sprintf("tool-call-%d", key)) + toolCallDelta.ID = cmp.Or(toolCallDelta.ID, fmt.Sprintf("tool-call-%d", toolCallDelta.Index)) if toolCallDelta.Type != "function" { yield(fantasy.StreamPart{ @@ -753,13 +623,11 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S }) { return } - toolCalls[key] = streamToolCall{ - id: toolCallDelta.ID, - name: toolCallDelta.Function.Name, - arguments: toolCallDelta.Function.Arguments, - idFromWire: idFromWire, + toolCalls[toolCallDelta.Index] = streamToolCall{ + id: toolCallDelta.ID, + name: toolCallDelta.Function.Name, + arguments: toolCallDelta.Function.Arguments, } - callKeys.commit(toolCallDelta, key) if toolCallDelta.Function.Arguments != "" { if !yield(fantasy.StreamPart{ @@ -859,11 +727,10 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S return } - // Finalize tool calls in key order (wire-index order for - // indexed-only streams; first-seen order for synthetic and - // remapped calls). When truncated, skip ToolCall parts to - // prevent agents from dispatching calls with incomplete - // arguments. + // PROSE: stale, keys are wire indexes for indexed calls and a separate range below them for index-less calls, so "index order" means index-less calls in arrival order, then indexed calls by wire index. + // Finalize tool calls in index order after the stream completes. + // When truncated, skip ToolCall parts to prevent agents from + // dispatching calls with incomplete arguments. indices := make([]int64, 0, len(toolCalls)) for idx := range toolCalls { indices = append(indices, idx) From db5e9e85a1dd3bd2598ec6d3e322802008bb5489 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 11:59:47 +0000 Subject: [PATCH 34/52] docs(providers/openai): document minimal index-less keying Replace comment markers on the index-less key range, helper, fallback ID numbering, finalization order, and test helper. --- providers/openai/language_model.go | 17 ++++++++++------- .../openaicompat/unindexed_tool_calls_test.go | 4 +++- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index e89a009b0..263401859 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -150,10 +150,13 @@ type streamToolCall struct { hasFinished bool } -// PROSE: index-less calls take keys from math.MinInt64 upward, a range no wire index uses, so they never collide with indexed calls and finalize first, in arrival order. +// firstUnindexedToolCallKey starts index-less call keys at math.MinInt64 so +// they never collide with wire indexes and sort before them in arrival order. const firstUnindexedToolCallKey int64 = math.MinInt64 -// PROSE: unindexedToolCallKey returns the key for a delta without an index (Google's OpenAI-compatible endpoint omits it): a non-empty id that differs from the latest index-less call's id starts a new call; anything else continues the latest one. latest is reused until a call is stored there, so a skipped empty delta allocates nothing. +// unindexedToolCallKey returns the toolCalls key for a delta without an index, +// which the SDK decodes as 0. A new non-empty id starts a new call; anything +// else continues latest, which stays reusable until a call is stored there. func unindexedToolCallKey(toolCalls map[int64]streamToolCall, latest int64, id string) int64 { current, ok := toolCalls[latest] if !ok { @@ -582,7 +585,7 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S latestUnindexedKey = unindexedToolCallKey(toolCalls, latestUnindexedKey, toolCallDelta.ID) toolCallDelta.Index = latestUnindexedKey - // PROSE: the tool-call-N fallback numbers index-less calls from 0 instead of using the huge negative key. + // Number index-less fallback IDs from 0 instead of the negative map key. fallbackID := fmt.Sprintf("tool-call-%d", latestUnindexedKey-firstUnindexedToolCallKey) toolCallDelta.ID = cmp.Or(toolCallDelta.ID, fallbackID) } @@ -727,10 +730,10 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S return } - // PROSE: stale, keys are wire indexes for indexed calls and a separate range below them for index-less calls, so "index order" means index-less calls in arrival order, then indexed calls by wire index. - // Finalize tool calls in index order after the stream completes. - // When truncated, skip ToolCall parts to prevent agents from - // dispatching calls with incomplete arguments. + // Finalize tool calls in key order (index-less calls in arrival + // order, then indexed calls by wire index). When truncated, + // skip ToolCall parts to prevent agents from dispatching calls + // with incomplete arguments. indices := make([]int64, 0, len(toolCalls)) for idx := range toolCalls { indices = append(indices, idx) diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index 6ed3249bc..6592910e9 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -42,7 +42,9 @@ func (c streamedCall) String() string { return c.id + ":" + c.name + "=" + c.input } -// PROSE: collectCalls returns the emitted tool calls and the finish reason, and checks each call's part sequence: one ToolInputStart, its deltas, one ToolInputEnd, then one ToolCall whose name matches the start and whose input equals the concatenated deltas. +// collectCalls checks each call's start, delta, end, and ToolCall sequence +// (matching name and concatenated deltas) and returns the emitted calls and +// finish reason. func collectCalls(t *testing.T, parts []fantasy.StreamPart) ([]string, fantasy.FinishReason) { t.Helper() From 771f5fef13b4a7ef5731aae12dfbd476b3420fb8 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 12:06:30 +0000 Subject: [PATCH 35/52] refactor(providers/openai): build the fallback tool call id in one place The index-less branch built a fallback id for every delta, including continuations that never use it. It now only sets the number, and the existing creation site formats the id when a new call has no id. --- providers/openai/language_model.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 263401859..2a645812f 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -581,13 +581,13 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S } for _, toolCallDelta := range choice.Delta.ToolCalls { - if !toolCallDelta.JSON.Index.Valid() { + fallbackNumber := toolCallDelta.Index + if !toolCallDelta.JSON.Index.Valid() { latestUnindexedKey = unindexedToolCallKey(toolCalls, latestUnindexedKey, toolCallDelta.ID) - toolCallDelta.Index = latestUnindexedKey + toolCallDelta.Index = latestUnindexedKey // Number index-less fallback IDs from 0 instead of the negative map key. - fallbackID := fmt.Sprintf("tool-call-%d", latestUnindexedKey-firstUnindexedToolCallKey) - toolCallDelta.ID = cmp.Or(toolCallDelta.ID, fallbackID) + fallbackNumber = latestUnindexedKey - firstUnindexedToolCallKey } if existingToolCall, ok := toolCalls[toolCallDelta.Index]; ok { @@ -609,7 +609,7 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S continue } toolCallDelta.Type = cmp.Or(toolCallDelta.Type, "function") - toolCallDelta.ID = cmp.Or(toolCallDelta.ID, fmt.Sprintf("tool-call-%d", toolCallDelta.Index)) + toolCallDelta.ID = cmp.Or(toolCallDelta.ID, fmt.Sprintf("tool-call-%d", fallbackNumber)) if toolCallDelta.Type != "function" { yield(fantasy.StreamPart{ From d19c4bc2da77be1cdb79a4d32bca16bf0acbdfa5 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 12:06:42 +0000 Subject: [PATCH 36/52] style(providers/openai): gofmt the fallback number assignment --- providers/openai/language_model.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 2a645812f..47793dc2e 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -582,9 +582,9 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S for _, toolCallDelta := range choice.Delta.ToolCalls { fallbackNumber := toolCallDelta.Index - if !toolCallDelta.JSON.Index.Valid() { + if !toolCallDelta.JSON.Index.Valid() { latestUnindexedKey = unindexedToolCallKey(toolCalls, latestUnindexedKey, toolCallDelta.ID) - toolCallDelta.Index = latestUnindexedKey + toolCallDelta.Index = latestUnindexedKey // Number index-less fallback IDs from 0 instead of the negative map key. fallbackNumber = latestUnindexedKey - firstUnindexedToolCallKey From 13621175a33fd8411f73a3e5bcaac38d983914c9 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 12:08:51 +0000 Subject: [PATCH 37/52] docs(providers/openai): qualify wire-index range for MinInt64 keys Avoid claiming index-less keys can never collide with wire indexes, since providers such as Bedrock can send negative wire indexes. --- providers/openai/language_model.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 47793dc2e..7c95ce38b 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -150,8 +150,9 @@ type streamToolCall struct { hasFinished bool } -// firstUnindexedToolCallKey starts index-less call keys at math.MinInt64 so -// they never collide with wire indexes and sort before them in arrival order. +// firstUnindexedToolCallKey starts index-less call keys at math.MinInt64, +// staying far below any wire index providers send so they sort before indexed +// calls in arrival order. const firstUnindexedToolCallKey int64 = math.MinInt64 // unindexedToolCallKey returns the toolCalls key for a delta without an index, From 59af7e450937faca9965cdb853ba77e019c20511 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 12:33:04 +0000 Subject: [PATCH 38/52] test(providers/openaicompat): cover nameless fragments with fresh ids Some servers send each argument fragment with its own id and no name. Without an index those fragments must still form one call, as they do on coder_2_33. --- providers/openaicompat/unindexed_tool_calls_test.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index 6592910e9..0f7a7626c 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -153,6 +153,15 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { }, want: []string{`a:f={"x":1}`}, }, + { + name: "nameless fragments with a fresh id each", + chunks: []string{ + chunk(`{"id":"call_A","type":"function","function":{"name":"list_dir","arguments":""}}`), + chunk(`{"id":"frag1","function":{"arguments":"{\"pa"}}`), + chunk(`{"id":"frag2","function":{"arguments":"th\": 1}"}}`), + }, + want: []string{`call_A:list_dir={"path": 1}`}, + }, { name: "two calls in one chunk", chunks: []string{ From 59588747a4c49962ba2ccc481f4f0f281103238f Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 12:33:04 +0000 Subject: [PATCH 39/52] fix(providers/openai): split index-less calls only on a named new id Any new non-empty id started an index-less call, so nameless fragments that carry a fresh id each split into broken calls, and an empty delta with a new id moved the key past the empty-delta skip. A new call now also requires a function name. --- providers/openai/language_model.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 7c95ce38b..c15e96878 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -155,16 +155,17 @@ type streamToolCall struct { // calls in arrival order. const firstUnindexedToolCallKey int64 = math.MinInt64 +// PROSE: stale, only a named delta with a new non-empty id starts a new call; nameless fragments and empty deltas continue latest whatever their id. // unindexedToolCallKey returns the toolCalls key for a delta without an index, // which the SDK decodes as 0. A new non-empty id starts a new call; anything // else continues latest, which stays reusable until a call is stored there. -func unindexedToolCallKey(toolCalls map[int64]streamToolCall, latest int64, id string) int64 { +func unindexedToolCallKey(toolCalls map[int64]streamToolCall, latest int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { current, ok := toolCalls[latest] if !ok { return latest } - if id != "" && id != current.id { + if delta.Function.Name != "" && delta.ID != "" && delta.ID != current.id { return latest + 1 } return latest @@ -584,7 +585,7 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S for _, toolCallDelta := range choice.Delta.ToolCalls { fallbackNumber := toolCallDelta.Index if !toolCallDelta.JSON.Index.Valid() { - latestUnindexedKey = unindexedToolCallKey(toolCalls, latestUnindexedKey, toolCallDelta.ID) + latestUnindexedKey = unindexedToolCallKey(toolCalls, latestUnindexedKey, toolCallDelta) toolCallDelta.Index = latestUnindexedKey // Number index-less fallback IDs from 0 instead of the negative map key. From 655828cde5a7e999349aec5025103254d6bc96c9 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 12:37:25 +0000 Subject: [PATCH 40/52] docs(providers/openai): document named new-id split rule Update unindexedToolCallKey comment to reflect requiring both a function name and a new non-empty id to start a new index-less call. --- providers/openai/language_model.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index c15e96878..efd703376 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -155,10 +155,11 @@ type streamToolCall struct { // calls in arrival order. const firstUnindexedToolCallKey int64 = math.MinInt64 -// PROSE: stale, only a named delta with a new non-empty id starts a new call; nameless fragments and empty deltas continue latest whatever their id. // unindexedToolCallKey returns the toolCalls key for a delta without an index, -// which the SDK decodes as 0. A new non-empty id starts a new call; anything -// else continues latest, which stays reusable until a call is stored there. +// which the SDK decodes as 0. The first call uses latest, and a later delta +// starts a new call only when it carries a function name and a non-empty id +// different from the latest index-less call's id; nameless fragments and empty +// deltas continue latest, which stays reusable until a call is stored there. func unindexedToolCallKey(toolCalls map[int64]streamToolCall, latest int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { current, ok := toolCalls[latest] if !ok { From d9f41d9fc2b4b4a7c1742fb4ac8bb0f556379904 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 13:12:16 +0000 Subject: [PATCH 41/52] test(providers/openaicompat): cover id-less Gemini calls and indexed openers Gemini's OpenAI-compatible endpoint is reported to sometimes send parallel calls with an empty id, so two whole id-less calls must stay two calls. An indexed opener continued by an index-less fragment must stay one call, as on coder_2_33. --- providers/openaicompat/unindexed_tool_calls_test.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index 0f7a7626c..a1841ab2f 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -170,12 +170,20 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { want: []string{`a:f={"x":1}`, `b:f={"x":2}`}, }, { - name: "id-less whole calls continue one call", + name: "id-less whole calls start one call each", chunks: []string{ chunk(`{"type":"function","function":{"name":"f","arguments":"{\"x\":1}"}}`), chunk(`{"type":"function","function":{"name":"f","arguments":"{\"x\":2}"}}`), }, - want: []string{`tool-call-0:f={"x":1}{"x":2}`}, + want: []string{`tool-call-0:f={"x":1}`, `tool-call-1:f={"x":2}`}, + }, + { + name: "indexed opener continued by an index-less fragment", + chunks: []string{ + chunk(`{"index":0,"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), + chunk(`{"function":{"arguments":"1}"}}`), + }, + want: []string{`a:f={"x":1}`}, }, { name: "indexed deltas are unchanged", From 68c972a2760b8b409be97e18ea4ab73de42172b3 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 13:12:16 +0000 Subject: [PATCH 42/52] fix(providers/openai): start index-less calls on a function name A named index-less delta with an empty id continued the latest call, merging id-less parallel calls into invalid JSON, and an index-less fragment after an indexed opener started a separate nameless call. A named index-less delta now starts a new call unless its id equals the latest call's id. A nameless one continues the latest call of either kind, so the latest key now follows indexed calls too. --- providers/openai/language_model.go | 31 +++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index efd703376..00e7430bc 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -155,21 +155,24 @@ type streamToolCall struct { // calls in arrival order. const firstUnindexedToolCallKey int64 = math.MinInt64 +// PROSE: stale, a named index-less delta now starts a new call unless its non-empty id equals the latest call's id, and a nameless delta continues the latest call of any kind (indexed or index-less), or starts one when there is none; new keys come from next, which advances only once a call is stored there. // unindexedToolCallKey returns the toolCalls key for a delta without an index, // which the SDK decodes as 0. The first call uses latest, and a later delta // starts a new call only when it carries a function name and a non-empty id // different from the latest index-less call's id; nameless fragments and empty // deltas continue latest, which stays reusable until a call is stored there. -func unindexedToolCallKey(toolCalls map[int64]streamToolCall, latest int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { - current, ok := toolCalls[latest] - if !ok { - return latest +func unindexedToolCallKey(toolCalls map[int64]streamToolCall, latest int64, next *int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { + if current, ok := toolCalls[latest]; ok { + sameCall := delta.ID != "" && delta.ID == current.id + if delta.Function.Name == "" || sameCall { + return latest + } } - if delta.Function.Name != "" && delta.ID != "" && delta.ID != current.id { - return latest + 1 + if _, used := toolCalls[*next]; used { + *next++ } - return latest + return *next } // responseCapture holds the raw HTTP response of a call so response headers @@ -497,7 +500,8 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S stream := o.client.Chat.Completions.NewStreaming(ctx, *params, capture.requestOptions(o.headerFunc, append(callUARequestOptions(call), callHeadersRequestOptions(call)...))...) isActiveText := false toolCalls := make(map[int64]streamToolCall) - latestUnindexedKey := firstUnindexedToolCallKey + latestKey := firstUnindexedToolCallKey + nextUnindexedKey := firstUnindexedToolCallKey providerMetadata := fantasy.ProviderMetadata{ Name: &ProviderMetadata{}, @@ -586,11 +590,16 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S for _, toolCallDelta := range choice.Delta.ToolCalls { fallbackNumber := toolCallDelta.Index if !toolCallDelta.JSON.Index.Valid() { - latestUnindexedKey = unindexedToolCallKey(toolCalls, latestUnindexedKey, toolCallDelta) - toolCallDelta.Index = latestUnindexedKey + toolCallDelta.Index = unindexedToolCallKey(toolCalls, latestKey, &nextUnindexedKey, toolCallDelta) + // PROSE: stale, the number is only used when the delta creates an index-less call; when it continues an indexed call the value is meaningless and unused. // Number index-less fallback IDs from 0 instead of the negative map key. - fallbackNumber = latestUnindexedKey - firstUnindexedToolCallKey + fallbackNumber = toolCallDelta.Index - firstUnindexedToolCallKey + } + + // PROSE: latestKey follows the latest call of either kind that a non-empty delta touched, so an index-less fragment can continue an indexed opener as it did on coder_2_33. + if toolCallDelta.Function.Name != "" || toolCallDelta.Function.Arguments != "" { + latestKey = toolCallDelta.Index } if existingToolCall, ok := toolCalls[toolCallDelta.Index]; ok { From 4d7464692327dffbc0aa564f546d5172e5c1944b Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 13:15:08 +0000 Subject: [PATCH 43/52] docs(providers/openai): document name-based index-less call split Update unindexedToolCallKey, fallbackNumber, and latestKey comments for starting new index-less calls on a function name and continuing the latest call of either kind on nameless deltas. --- providers/openai/language_model.go | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 00e7430bc..7f933c6e4 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -155,12 +155,11 @@ type streamToolCall struct { // calls in arrival order. const firstUnindexedToolCallKey int64 = math.MinInt64 -// PROSE: stale, a named index-less delta now starts a new call unless its non-empty id equals the latest call's id, and a nameless delta continues the latest call of any kind (indexed or index-less), or starts one when there is none; new keys come from next, which advances only once a call is stored there. // unindexedToolCallKey returns the toolCalls key for a delta without an index, -// which the SDK decodes as 0. The first call uses latest, and a later delta -// starts a new call only when it carries a function name and a non-empty id -// different from the latest index-less call's id; nameless fragments and empty -// deltas continue latest, which stays reusable until a call is stored there. +// which the SDK decodes as 0. A named delta starts a new call from *next unless +// its non-empty id equals toolCalls[latest]'s id; a nameless delta continues +// latest (indexed or index-less), or starts a new call when none exists. *next +// advances only after a call is stored there. func unindexedToolCallKey(toolCalls map[int64]streamToolCall, latest int64, next *int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { if current, ok := toolCalls[latest]; ok { sameCall := delta.ID != "" && delta.ID == current.id @@ -592,12 +591,12 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S if !toolCallDelta.JSON.Index.Valid() { toolCallDelta.Index = unindexedToolCallKey(toolCalls, latestKey, &nextUnindexedKey, toolCallDelta) - // PROSE: stale, the number is only used when the delta creates an index-less call; when it continues an indexed call the value is meaningless and unused. - // Number index-less fallback IDs from 0 instead of the negative map key. + // Number new index-less fallback IDs from 0; unused when continuing an existing call. fallbackNumber = toolCallDelta.Index - firstUnindexedToolCallKey } - // PROSE: latestKey follows the latest call of either kind that a non-empty delta touched, so an index-less fragment can continue an indexed opener as it did on coder_2_33. + // Track the latest call of either kind touched by a non-empty delta + // so an index-less fragment can continue an indexed opener. if toolCallDelta.Function.Name != "" || toolCallDelta.Function.Arguments != "" { latestKey = toolCallDelta.Index } From ebc574deada007cc28e30699c3d00674446c1eed Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 13:50:02 +0000 Subject: [PATCH 44/52] test(providers/openaicompat): cover id-less named fragments of one call Id-less fragments that repeat the function name before the arguments complete, alone or after an opener with an id, must stay one call as on coder_2_33. --- .../openaicompat/unindexed_tool_calls_test.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index a1841ab2f..56b3f580e 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -177,6 +177,22 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { }, want: []string{`tool-call-0:f={"x":1}`, `tool-call-1:f={"x":2}`}, }, + { + name: "id-less fragments repeating the name before the arguments complete", + chunks: []string{ + chunk(`{"type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), + chunk(`{"type":"function","function":{"name":"f","arguments":"1}"}}`), + }, + want: []string{`tool-call-0:f={"x":1}`}, + }, + { + name: "opener with an id continued by id-less named fragments", + chunks: []string{ + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), + chunk(`{"type":"function","function":{"name":"f","arguments":"1}"}}`), + }, + want: []string{`a:f={"x":1}`}, + }, { name: "indexed opener continued by an index-less fragment", chunks: []string{ From dc9ed8c2330fb2aa9cdba0555aac4fff267e0c69 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 13:50:02 +0000 Subject: [PATCH 45/52] fix(providers/openai): continue unfinished calls on id-less named fragments An id-less delta with a function name always started a new index-less call, splitting fragments that repeat the name into calls with unparseable input. Such a delta now continues the latest call while that call's arguments are non-empty and not yet valid JSON. --- providers/openai/language_model.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 7f933c6e4..4056dc38f 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -155,6 +155,7 @@ type streamToolCall struct { // calls in arrival order. const firstUnindexedToolCallKey int64 = math.MinInt64 +// PROSE: stale, a named delta without an id also continues latest while latest's arguments are non-empty and not yet valid JSON. // unindexedToolCallKey returns the toolCalls key for a delta without an index, // which the SDK decodes as 0. A named delta starts a new call from *next unless // its non-empty id equals toolCalls[latest]'s id; a nameless delta continues @@ -163,7 +164,8 @@ const firstUnindexedToolCallKey int64 = math.MinInt64 func unindexedToolCallKey(toolCalls map[int64]streamToolCall, latest int64, next *int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { if current, ok := toolCalls[latest]; ok { sameCall := delta.ID != "" && delta.ID == current.id - if delta.Function.Name == "" || sameCall { + unfinished := delta.ID == "" && current.arguments != "" && !json.Valid([]byte(current.arguments)) + if delta.Function.Name == "" || sameCall || unfinished { return latest } } From cbdd3a9e46e8f3650390b0a4d8bb014d1fd83846 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 13:55:59 +0000 Subject: [PATCH 46/52] docs(providers/openai): document unfinished-arguments continuation Update unindexedToolCallKey comment to note that an id-less named delta continues latest while latest's arguments are non-empty and incomplete JSON. --- providers/openai/language_model.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 4056dc38f..bf21c37c3 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -155,12 +155,12 @@ type streamToolCall struct { // calls in arrival order. const firstUnindexedToolCallKey int64 = math.MinInt64 -// PROSE: stale, a named delta without an id also continues latest while latest's arguments are non-empty and not yet valid JSON. // unindexedToolCallKey returns the toolCalls key for a delta without an index, // which the SDK decodes as 0. A named delta starts a new call from *next unless -// its non-empty id equals toolCalls[latest]'s id; a nameless delta continues -// latest (indexed or index-less), or starts a new call when none exists. *next -// advances only after a call is stored there. +// its non-empty id equals toolCalls[latest]'s id, or it has no id while +// latest's arguments are non-empty and not yet valid JSON; a nameless delta +// continues latest (indexed or index-less), or starts a new call when none +// exists. *next advances only after a call is stored there. func unindexedToolCallKey(toolCalls map[int64]streamToolCall, latest int64, next *int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { if current, ok := toolCalls[latest]; ok { sameCall := delta.ID != "" && delta.ID == current.id From 42fdd7d144144cbf9a2ce8a6e54815dcf0e0aa28 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 14:15:12 +0000 Subject: [PATCH 47/52] test(providers/openaicompat): cover an id-less call for another tool An id-less named delta for tool g after an unfinished call to f must start its own call, so f never runs with g's arguments. --- providers/openaicompat/unindexed_tool_calls_test.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index 56b3f580e..59235bf2d 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -193,6 +193,14 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { }, want: []string{`a:f={"x":1}`}, }, + { + name: "id-less named call for another tool after an unfinished call", + chunks: []string{ + chunk(`{"type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), + chunk(`{"type":"function","function":{"name":"g","arguments":"{\"y\":2}"}}`), + }, + want: []string{`tool-call-0:f={"x":`, `tool-call-1:g={"y":2}`}, + }, { name: "indexed opener continued by an index-less fragment", chunks: []string{ From c14c90f0f544e7e720c3b0071b2671a26f9fb9dc Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 14:15:12 +0000 Subject: [PATCH 48/52] fix(providers/openai): require the same name to continue unfinished calls An id-less named delta continued any unfinished call, so a call to a different tool could append its arguments to the previous one. It now continues only when the name matches. The JSON check also moves behind the name and id checks, so nameless fragments no longer re-parse the accumulated arguments on every delta. --- providers/openai/language_model.go | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index bf21c37c3..0833beabc 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -155,6 +155,7 @@ type streamToolCall struct { // calls in arrival order. const firstUnindexedToolCallKey int64 = math.MinInt64 +// PROSE: stale, the unfinished-arguments continuation now also requires the delta's name to equal latest's name; a different name starts a new call. // unindexedToolCallKey returns the toolCalls key for a delta without an index, // which the SDK decodes as 0. A named delta starts a new call from *next unless // its non-empty id equals toolCalls[latest]'s id, or it has no id while @@ -163,9 +164,16 @@ const firstUnindexedToolCallKey int64 = math.MinInt64 // exists. *next advances only after a call is stored there. func unindexedToolCallKey(toolCalls map[int64]streamToolCall, latest int64, next *int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { if current, ok := toolCalls[latest]; ok { - sameCall := delta.ID != "" && delta.ID == current.id - unfinished := delta.ID == "" && current.arguments != "" && !json.Valid([]byte(current.arguments)) - if delta.Function.Name == "" || sameCall || unfinished { + if delta.Function.Name == "" { + return latest + } + + if delta.ID != "" && delta.ID == current.id { + return latest + } + + sameName := delta.ID == "" && delta.Function.Name == current.name + if sameName && current.arguments != "" && !json.Valid([]byte(current.arguments)) { return latest } } From 13eed89e6d34bdf86a5766b773f07ff3f9d13a9c Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 14:17:08 +0000 Subject: [PATCH 49/52] docs(providers/openai): note same-name check on unfinished calls Update unindexedToolCallKey comment to reflect that id-less unfinished continuation requires the same tool name. --- providers/openai/language_model.go | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index 0833beabc..ac884eab2 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -155,13 +155,12 @@ type streamToolCall struct { // calls in arrival order. const firstUnindexedToolCallKey int64 = math.MinInt64 -// PROSE: stale, the unfinished-arguments continuation now also requires the delta's name to equal latest's name; a different name starts a new call. // unindexedToolCallKey returns the toolCalls key for a delta without an index, // which the SDK decodes as 0. A named delta starts a new call from *next unless -// its non-empty id equals toolCalls[latest]'s id, or it has no id while -// latest's arguments are non-empty and not yet valid JSON; a nameless delta -// continues latest (indexed or index-less), or starts a new call when none -// exists. *next advances only after a call is stored there. +// its non-empty id equals toolCalls[latest]'s id, or it has no id with the same +// tool name while latest's arguments are non-empty and not yet valid JSON; a +// nameless delta continues latest (indexed or index-less), or starts a new call +// when none exists. *next advances only after a call is stored there. func unindexedToolCallKey(toolCalls map[int64]streamToolCall, latest int64, next *int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { if current, ok := toolCalls[latest]; ok { if delta.Function.Name == "" { From 0bed9ac0646f1593d7598a724ee9bc03aca4080d Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 14:57:31 +0000 Subject: [PATCH 50/52] test(providers/openaicompat): cover openers with empty arguments After an index-less opener with a provider id and empty arguments, id-less fragments that repeat the name must stay one call, as on coder_2_33. Two fully id-less parameterless calls stay two calls. collectCalls accepts the "{}" filled in for calls with no arguments. --- .../openaicompat/unindexed_tool_calls_test.go | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index 59235bf2d..c939e2654 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -42,6 +42,7 @@ func (c streamedCall) String() string { return c.id + ":" + c.name + "=" + c.input } +// PROSE: stale, the input check now allows the "{}" the provider fills in for a call that streamed no arguments. // collectCalls checks each call's start, delta, end, and ToolCall sequence // (matching name and concatenated deltas) and returns the emitted calls and // finish reason. @@ -90,7 +91,9 @@ func collectCalls(t *testing.T, parts []fantasy.StreamPart) ([]string, fantasy.F c.called = true require.Equal(t, c.name, p.ToolCallName, "ToolCall name differs from ToolInputStart for %s", p.ID) - require.Equal(t, c.deltas, p.ToolCallInput, "streamed input deltas differ from the final input for %s", p.ID) + if c.deltas != "" || p.ToolCallInput != "{}" { + require.Equal(t, c.deltas, p.ToolCallInput, "streamed input deltas differ from the final input for %s", p.ID) + } calls = append(calls, streamedCall{id: p.ID, name: p.ToolCallName, input: p.ToolCallInput}.String()) case fantasy.StreamPartTypeFinish: @@ -193,6 +196,23 @@ func TestStream_UnindexedToolCallShapes(t *testing.T) { }, want: []string{`a:f={"x":1}`}, }, + { + name: "opener with an id and empty arguments continued by id-less named fragments", + chunks: []string{ + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":""}}`), + chunk(`{"type":"function","function":{"name":"f","arguments":"{\"x\":"}}`), + chunk(`{"type":"function","function":{"name":"f","arguments":"1}"}}`), + }, + want: []string{`a:f={"x":1}`}, + }, + { + name: "id-less parameterless calls start one call each", + chunks: []string{ + chunk(`{"type":"function","function":{"name":"now","arguments":""}}`), + chunk(`{"type":"function","function":{"name":"now","arguments":""}}`), + }, + want: []string{`tool-call-0:now={}`, `tool-call-1:now={}`}, + }, { name: "id-less named call for another tool after an unfinished call", chunks: []string{ From 95ec9aca3535abddeffe71bc49e002e2714f697c Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 14:57:31 +0000 Subject: [PATCH 51/52] fix(providers/openai): continue provider-opened calls on same-name fragments An index-less opener with a provider id and empty arguments was split from the id-less fragments that repeat its name. Those fragments now continue it. A call with a fallback id and empty arguments still gets a new call per named delta, so id-less parameterless calls stay separate. --- providers/openai/language_model.go | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index ac884eab2..c778ab9f8 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -148,6 +148,8 @@ type streamToolCall struct { name string arguments string hasFinished bool + // PROSE: idFromWire is false when id is the tool-call-N fallback; an opener with a provider-sent id and empty arguments is the only empty-argument call that id-less same-name fragments continue. + idFromWire bool } // firstUnindexedToolCallKey starts index-less call keys at math.MinInt64, @@ -155,6 +157,7 @@ type streamToolCall struct { // calls in arrival order. const firstUnindexedToolCallKey int64 = math.MinInt64 +// PROSE: stale, an id-less same-name delta also continues latest when latest has a provider-sent id and empty arguments; with a fallback id and empty arguments it still starts a new call. // unindexedToolCallKey returns the toolCalls key for a delta without an index, // which the SDK decodes as 0. A named delta starts a new call from *next unless // its non-empty id equals toolCalls[latest]'s id, or it has no id with the same @@ -172,6 +175,9 @@ func unindexedToolCallKey(toolCalls map[int64]streamToolCall, latest int64, next } sameName := delta.ID == "" && delta.Function.Name == current.name + if sameName && current.arguments == "" && current.idFromWire { + return latest + } if sameName && current.arguments != "" && !json.Valid([]byte(current.arguments)) { return latest } @@ -629,6 +635,7 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S continue } toolCallDelta.Type = cmp.Or(toolCallDelta.Type, "function") + idFromWire := toolCallDelta.ID != "" toolCallDelta.ID = cmp.Or(toolCallDelta.ID, fmt.Sprintf("tool-call-%d", fallbackNumber)) if toolCallDelta.Type != "function" { @@ -647,9 +654,10 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S return } toolCalls[toolCallDelta.Index] = streamToolCall{ - id: toolCallDelta.ID, - name: toolCallDelta.Function.Name, - arguments: toolCallDelta.Function.Arguments, + id: toolCallDelta.ID, + name: toolCallDelta.Function.Name, + arguments: toolCallDelta.Function.Arguments, + idFromWire: idFromWire, } if toolCallDelta.Function.Arguments != "" { From 3400701d1cf21caf88767c88d7b4434621031293 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 3 Dec 2026 15:01:15 +0000 Subject: [PATCH 52/52] docs(providers/openai): document idFromWire empty-args continuation Update streamToolCall.idFromWire, unindexedToolCallKey, and collectCalls comments for provider-opened empty-argument continuation and "{}" input. --- providers/openai/language_model.go | 11 ++++++----- providers/openaicompat/unindexed_tool_calls_test.go | 5 ++--- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index c778ab9f8..0f8cb1bee 100644 --- a/providers/openai/language_model.go +++ b/providers/openai/language_model.go @@ -148,7 +148,7 @@ type streamToolCall struct { name string arguments string hasFinished bool - // PROSE: idFromWire is false when id is the tool-call-N fallback; an opener with a provider-sent id and empty arguments is the only empty-argument call that id-less same-name fragments continue. + // idFromWire is false when id is the synthesized tool-call-N fallback. idFromWire bool } @@ -157,13 +157,14 @@ type streamToolCall struct { // calls in arrival order. const firstUnindexedToolCallKey int64 = math.MinInt64 -// PROSE: stale, an id-less same-name delta also continues latest when latest has a provider-sent id and empty arguments; with a fallback id and empty arguments it still starts a new call. // unindexedToolCallKey returns the toolCalls key for a delta without an index, // which the SDK decodes as 0. A named delta starts a new call from *next unless // its non-empty id equals toolCalls[latest]'s id, or it has no id with the same -// tool name while latest's arguments are non-empty and not yet valid JSON; a -// nameless delta continues latest (indexed or index-less), or starts a new call -// when none exists. *next advances only after a call is stored there. +// tool name while latest has empty arguments and a provider-sent id (with a +// fallback id each named delta starts a new call so parameterless calls stay +// separate) or non-empty incomplete JSON arguments; a nameless delta continues +// latest (indexed or index-less), or starts a new call when none exists. *next +// advances only after a call is stored there. func unindexedToolCallKey(toolCalls map[int64]streamToolCall, latest int64, next *int64, delta openai.ChatCompletionChunkChoiceDeltaToolCall) int64 { if current, ok := toolCalls[latest]; ok { if delta.Function.Name == "" { diff --git a/providers/openaicompat/unindexed_tool_calls_test.go b/providers/openaicompat/unindexed_tool_calls_test.go index c939e2654..374e96196 100644 --- a/providers/openaicompat/unindexed_tool_calls_test.go +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -42,10 +42,9 @@ func (c streamedCall) String() string { return c.id + ":" + c.name + "=" + c.input } -// PROSE: stale, the input check now allows the "{}" the provider fills in for a call that streamed no arguments. // collectCalls checks each call's start, delta, end, and ToolCall sequence -// (matching name and concatenated deltas) and returns the emitted calls and -// finish reason. +// (matching name and concatenated deltas, allowing "{}" when no deltas +// streamed) and returns the emitted calls and finish reason. func collectCalls(t *testing.T, parts []fantasy.StreamPart) ([]string, fantasy.FinishReason) { t.Helper()