Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
00c5bd9
test(providers/openaicompat): cover tool calls without an index
mafredri Dec 2, 2026
81ce94d
fix(providers/openai): keep unindexed stream tool calls apart
mafredri Dec 2, 2026
33e0b0c
docs(providers/openai): document unindexed tool-call keying
mafredri Dec 2, 2026
3151eed
test(providers/openaicompat): cover unindexed call correlation
mafredri Dec 2, 2026
1290f3a
fix(providers/openai): correlate unindexed tool calls by id
mafredri Dec 2, 2026
f20dd8d
docs(providers/openai): document toolCallKeys and test helper
mafredri Dec 2, 2026
a1fa580
test(providers/openaicompat): cover id matches across index kinds
mafredri Dec 2, 2026
d01fedb
fix(providers/openai): bind wire indexes to calls by id
mafredri Dec 2, 2026
074e5ee
docs(providers/openai): update toolCallKeys comments for id binding
mafredri Dec 2, 2026
b820456
test(providers/openaicompat): cover duplicate and reused tool call ids
mafredri Dec 2, 2026
5e30fae
fix(providers/openai): keep duplicate tool call ids as separate calls
mafredri Dec 2, 2026
dc3589d
docs(providers/openai): document duplicate-id and index-reuse rules
mafredri Dec 2, 2026
17eb1f9
test(providers/openaicompat): cover shared index and fresh-id fragments
mafredri Dec 2, 2026
e40a5d0
refactor(providers/openai): resolve every tool call delta by one rule
mafredri Dec 2, 2026
0e7f826
fix(providers/openai): start a new call when the tool name changes
mafredri Dec 2, 2026
0a2a900
docs(providers/openai): document unified toolCallKeys rule
mafredri Dec 2, 2026
faa6075
test(providers/openaicompat): cover duplicate ids at out-of-order ind…
mafredri Dec 2, 2026
8875a84
fix(providers/openai): pick the newest call by creation order
mafredri Dec 2, 2026
1757bda
docs(providers/openai): document creation-order recency tracking
mafredri Dec 2, 2026
e886240
test(providers/openaicompat): cover same-tool calls sharing an index
mafredri Dec 2, 2026
28bf452
fix(providers/openai): split named calls on a new provider id
mafredri Dec 2, 2026
3cf333a
docs(providers/openai): document provider-id split and latest fallback
mafredri Dec 2, 2026
96f77e3
test(providers/openaicompat): cover index-less openers with indexed c…
mafredri Dec 2, 2026
bbcb29c
fix(providers/openai): continue unbound calls at a new wire index
mafredri Dec 2, 2026
5b578e5
docs(providers/openai): document unbound-call continuation rules
mafredri Dec 2, 2026
1614ec7
test(providers/openaicompat): cover finished and rebound unindexed calls
mafredri Dec 2, 2026
f74b1d9
fix(providers/openai): split finished or once-bound unbound candidates
mafredri Dec 2, 2026
f035e95
docs(providers/openai): document everBound and finished-call split
mafredri Dec 2, 2026
d33d5f1
test(providers/openaicompat): cover a same-id call at index 1 after a…
mafredri Dec 2, 2026
e73ee6d
fix(providers/openai): place never-bound calls at wire index 0
mafredri Dec 2, 2026
ed9e96b
docs(providers/openai): document index-0 rule for never-bound calls
mafredri Dec 2, 2026
69d0a51
test(providers/openaicompat): keep only supported unindexed tool call…
mafredri Dec 3, 2026
675ac9b
fix(providers/openai): key only index-less tool calls separately
mafredri Dec 3, 2026
db5e9e8
docs(providers/openai): document minimal index-less keying
mafredri Dec 3, 2026
771f5fe
refactor(providers/openai): build the fallback tool call id in one place
mafredri Dec 3, 2026
d19c4bc
style(providers/openai): gofmt the fallback number assignment
mafredri Dec 3, 2026
1362117
docs(providers/openai): qualify wire-index range for MinInt64 keys
mafredri Dec 3, 2026
59af7e4
test(providers/openaicompat): cover nameless fragments with fresh ids
mafredri Dec 3, 2026
5958874
fix(providers/openai): split index-less calls only on a named new id
mafredri Dec 3, 2026
655828c
docs(providers/openai): document named new-id split rule
mafredri Dec 3, 2026
d9f41d9
test(providers/openaicompat): cover id-less Gemini calls and indexed …
mafredri Dec 3, 2026
68c972a
fix(providers/openai): start index-less calls on a function name
mafredri Dec 3, 2026
4d74646
docs(providers/openai): document name-based index-less call split
mafredri Dec 3, 2026
ebc574d
test(providers/openaicompat): cover id-less named fragments of one call
mafredri Dec 3, 2026
dc9ed8c
fix(providers/openai): continue unfinished calls on id-less named fra…
mafredri Dec 3, 2026
cbdd3a9
docs(providers/openai): document unfinished-arguments continuation
mafredri Dec 3, 2026
42fdd7d
test(providers/openaicompat): cover an id-less call for another tool
mafredri Dec 3, 2026
c14c90f
fix(providers/openai): require the same name to continue unfinished c…
mafredri Dec 3, 2026
13eed89
docs(providers/openai): note same-name check on unfinished calls
mafredri Dec 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 55 additions & 4 deletions providers/openai/language_model.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"fmt"
"io"
"maps"
"math"
"net/http"
"reflect"
"slices"
Expand Down Expand Up @@ -149,6 +150,39 @@ type streamToolCall struct {
hasFinished 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'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 == "" {
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
}
}

if _, used := toolCalls[*next]; used {
*next++
}
return *next
}

// 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.
Expand Down Expand Up @@ -474,6 +508,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{},
Expand Down Expand Up @@ -560,6 +596,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
Expand All @@ -579,7 +629,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{
Expand Down Expand Up @@ -700,9 +750,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)
Expand Down
9 changes: 9 additions & 0 deletions providers/openaicompat/testdata/gemini_parallel_unindexed.sse
Original file line number Diff line number Diff line change
@@ -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]
241 changes: 241 additions & 0 deletions providers/openaicompat/unindexed_tool_calls_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
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) 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)
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: "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)
})
}
}
Loading