Description
Description:
When calling AddChunk, if the tool_calls field in the delta is an empty array, a panic occurs due to an out-of-range array access in https://github.com/openai/openai-[go/blob/main/streamaccumulator.go#L172](https://www.golinks.io/blob/main/streamaccumulator.go#L172?trackSource=github)
panic: runtime error: index out of range [0] with length 0
goroutine 59 [running]:
github.com/openai/openai-go.(*chatCompletionResponseState).update(_, {{0xc00053a277, 0x29}, {0xc00034f688, 0x1, 0x1}, 0x68673945, {0xc00053a2e1, 0xa}, {0xc00053a2ac, ...}, ...})
/Users/admin/Workspaces/Gomod/**/vendor/github.com/openai/openai-go/streamaccumulator.go:172 +0x1e5
github.com/openai/openai-go.(*ChatCompletionAccumulator).AddChunk(_, {{0xc00053a277, 0x29}, {0xc00034f688, 0x1, 0x1}, 0x68673945, {0xc00053a2e1, 0xa}, {0xc00053a2ac, ...}, ...})
Cause:
The panic is caused by delta.JSON.ToolCalls.Valid() returning true even when tool_calls is an empty array. The code then proceeds to access elements without checking the array length, assuming at least one item exists.
Reproduction:
This JSON response chunk triggers the issue:
{
"id": "chatcmpl-20299db6f3b64cc982ca667550aed702",
"choices": [
{
"delta": {
"content": "",
"function_call": {
"arguments": "",
"name": ""
},
"refusal": "",
"role": "assistant",
"tool_calls": null
},
"finish_reason": "",
"index": 0,
"logprobs": {
"content": null,
"refusal": null
}
}
],
"created": 1751595333,
"model": "qwen3-235b",
"object": "chat.completion.chunk",
"usage": {
"completion_tokens": 0,
"prompt_tokens": 0,
"total_tokens": 0,
"completion_tokens_details": {
"accepted_prediction_tokens": 0,
"audio_tokens": 0,
"reasoning_tokens": 0,
"rejected_prediction_tokens": 0
},
"prompt_tokens_details": {
"audio_tokens": 0,
"cached_tokens": 0
}
}
}
Expected Behavior:
The code should safely handle cases where tool_calls is null or empty, avoiding index access unless the array has valid entries.
Proposed Fix:
Add a length check before accessing tool_calls in update().