@@ -259,7 +259,10 @@ export class AIMessageChunk extends BaseMessageChunk {
259259 invalid_tool_calls : [ ] ,
260260 tool_call_chunks : [ ] ,
261261 } ;
262- } else if ( fields . tool_call_chunks === undefined ) {
262+ } else if (
263+ fields . tool_call_chunks === undefined ||
264+ fields . tool_call_chunks . length === 0
265+ ) {
263266 initParams = {
264267 ...fields ,
265268 tool_calls : fields . tool_calls ?? [ ] ,
@@ -271,37 +274,35 @@ export class AIMessageChunk extends BaseMessageChunk {
271274 : undefined ,
272275 } ;
273276 } else {
274- const groupedToolCallChunks = fields . tool_call_chunks . reduce (
275- ( acc , chunk ) => {
276- const matchedChunkIndex = acc . findIndex ( ( [ match ] ) => {
277- // If chunk has an id and index, match if both are present
278- if (
279- "id" in chunk &&
280- chunk . id &&
281- "index" in chunk &&
282- chunk . index !== undefined
283- ) {
284- return chunk . id === match . id && chunk . index === match . index ;
285- }
286- // If chunk has an id, we match on id
287- if ( "id" in chunk && chunk . id ) {
288- return chunk . id === match . id ;
289- }
290- // If chunk has an index, we match on index
291- if ( "index" in chunk && chunk . index !== undefined ) {
292- return chunk . index === match . index ;
293- }
294- return false ;
295- } ) ;
296- if ( matchedChunkIndex !== - 1 ) {
297- acc [ matchedChunkIndex ] . push ( chunk ) ;
298- } else {
299- acc . push ( [ chunk ] ) ;
277+ const toolCallChunks = fields . tool_call_chunks ?? [ ] ;
278+ const groupedToolCallChunks = toolCallChunks . reduce ( ( acc , chunk ) => {
279+ const matchedChunkIndex = acc . findIndex ( ( [ match ] ) => {
280+ // If chunk has an id and index, match if both are present
281+ if (
282+ "id" in chunk &&
283+ chunk . id &&
284+ "index" in chunk &&
285+ chunk . index !== undefined
286+ ) {
287+ return chunk . id === match . id && chunk . index === match . index ;
300288 }
301- return acc ;
302- } ,
303- [ ] as ToolCallChunk [ ] [ ]
304- ) ;
289+ // If chunk has an id, we match on id
290+ if ( "id" in chunk && chunk . id ) {
291+ return chunk . id === match . id ;
292+ }
293+ // If chunk has an index, we match on index
294+ if ( "index" in chunk && chunk . index !== undefined ) {
295+ return chunk . index === match . index ;
296+ }
297+ return false ;
298+ } ) ;
299+ if ( matchedChunkIndex !== - 1 ) {
300+ acc [ matchedChunkIndex ] . push ( chunk ) ;
301+ } else {
302+ acc . push ( [ chunk ] ) ;
303+ }
304+ return acc ;
305+ } , [ ] as ToolCallChunk [ ] [ ] ) ;
305306
306307 const toolCalls : ToolCall [ ] = [ ] ;
307308 const invalidToolCalls : InvalidToolCall [ ] = [ ] ;
0 commit comments