diff --git a/providers/openai/language_model.go b/providers/openai/language_model.go index fd8e37051..0f8cb1bee 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,6 +148,46 @@ type streamToolCall struct { name string arguments string hasFinished bool + // idFromWire is false when id is the synthesized tool-call-N fallback. + idFromWire bool +} + +// 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, +// 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 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 == "" { + return latest + } + + if delta.ID != "" && delta.ID == current.id { + return latest + } + + 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 + } + } + + if _, used := toolCalls[*next]; used { + *next++ + } + return *next } // responseCapture holds the raw HTTP response of a call so response headers @@ -474,6 +515,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) + latestKey := firstUnindexedToolCallKey + nextUnindexedKey := firstUnindexedToolCallKey providerMetadata := fantasy.ProviderMetadata{ Name: &ProviderMetadata{}, @@ -560,6 +603,20 @@ 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() { + toolCallDelta.Index = unindexedToolCallKey(toolCalls, latestKey, &nextUnindexedKey, toolCallDelta) + + // Number new index-less fallback IDs from 0; unused when continuing an existing call. + fallbackNumber = toolCallDelta.Index - firstUnindexedToolCallKey + } + + // 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 + } + if existingToolCall, ok := toolCalls[toolCallDelta.Index]; ok { if toolCallDelta.Function.Arguments != "" { existingToolCall.arguments += toolCallDelta.Function.Arguments @@ -579,7 +636,8 @@ 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)) + idFromWire := toolCallDelta.ID != "" + toolCallDelta.ID = cmp.Or(toolCallDelta.ID, fmt.Sprintf("tool-call-%d", fallbackNumber)) if toolCallDelta.Type != "function" { yield(fantasy.StreamPart{ @@ -597,9 +655,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 != "" { @@ -700,9 +759,10 @@ func (o languageModel) Stream(ctx context.Context, call fantasy.Call) (fantasy.S return } - // 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/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..374e96196 --- /dev/null +++ b/providers/openaicompat/unindexed_tool_calls_test.go @@ -0,0 +1,260 @@ +package openaicompat + +import ( + "fmt" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "charm.land/fantasy" + "github.com/stretchr/testify/require" +) + +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 +} + +func (c streamedCall) String() string { + return c.id + ":" + c.name + "=" + c.input +} + +// collectCalls checks each call's start, delta, end, and ToolCall sequence +// (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() + + type progress struct { + name string + deltas string + ended bool + called bool + } + + var ( + calls []string + finish fantasy.FinishReason + ) + seen := map[string]*progress{} + + for _, p := range parts { + switch p.Type { + case fantasy.StreamPartTypeError: + 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} + + 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.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: + 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) + } + calls = append(calls, streamedCall{id: p.ID, name: p.ToolCallName, input: p.ToolCallInput}.String()) + + case fantasy.StreamPartTypeFinish: + finish = p.FinishReason + } + } + + for id, c := range seen { + require.True(t, c.called, "no ToolCall for %s", id) + } + return calls, finish +} + +func TestStream_UnindexedGeminiParallelToolCalls(t *testing.T) { + t.Parallel() + + // 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) + + 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"}`, + }, calls) + 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 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 + want []string + }{ + { + 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:f={"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: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{ + chunk(`{"id":"a","type":"function","function":{"name":"f","arguments":"{\"x\":1}"}},{"id":"b","type":"function","function":{"name":"f","arguments":"{\"x\":2}"}}`), + }, + want: []string{`a:f={"x":1}`, `b:f={"x":2}`}, + }, + { + 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}`, `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: "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{ + 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{ + 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", + 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:f={"x":1}`, `b:g={"y":2}`}, + }, + { + 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(`{"index":0,"id":"b","type":"function","function":{"name":"g","arguments":"{\"y\":2}"}}`), + }, + want: []string{`a:f={"x":1}`, `b:g={"y":2}`}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + calls, finish := collectCalls(t, streamFrom(t, strings.Join(tt.chunks, "")+end)) + + require.Equal(t, tt.want, calls) + require.Equal(t, fantasy.FinishReasonStop, finish) + }) + } +}