diff --git a/streamaccumulator.go b/streamaccumulator.go index 53b7069f..95e6e91d 100644 --- a/streamaccumulator.go +++ b/streamaccumulator.go @@ -125,8 +125,14 @@ func (cc *ChatCompletion) accumulateDelta(chunk ChatCompletionChunk) bool { for j := range delta.Delta.ToolCalls { deltaTool := &delta.Delta.ToolCalls[j] - choice.Message.ToolCalls = expandToFit(choice.Message.ToolCalls, int(deltaTool.Index)) - tool := &choice.Message.ToolCalls[deltaTool.Index] + // Handle negative tool call indices (sometimes -1) + toolIndex := int(deltaTool.Index) + if toolIndex < 0 { + toolIndex = 0 // Default to 0 for negative indices + } + + choice.Message.ToolCalls = expandToFit(choice.Message.ToolCalls, toolIndex) + tool := &choice.Message.ToolCalls[toolIndex] if deltaTool.ID != "" { tool.ID = deltaTool.ID @@ -169,7 +175,14 @@ func (prev *chatCompletionResponseState) update(chunk ChatCompletionChunk) (just new.state = refusalResponseState case delta.JSON.ToolCalls.Valid(): new.state = toolResponseState - new.index = int(delta.ToolCalls[0].Index) + // Handle negative tool call indices (sometimes -1) + if len(delta.ToolCalls) > 0 { + index := int(delta.ToolCalls[0].Index) + if index < 0 { + index = 0 // Default to 0 for negative indices + } + new.index = index + } default: new.state = finishedResponseState }