langchain.js
    Preparing search index...

    Function collapseToolCallChunks

    • Collapses an array of tool call chunks into complete tool calls.

      This function groups tool call chunks by their id and/or index, then attempts to parse and validate the accumulated arguments for each group. Successfully parsed tool calls are returned as valid ToolCall objects, while malformed ones are returned as InvalidToolCall objects.

      Parameters

      • chunks: ToolCallChunk<string>[]

        An array of ToolCallChunk objects to collapse

      Returns {
          invalid_tool_calls: InvalidToolCall<string>[];
          tool_call_chunks: ToolCallChunk<string>[];
          tool_calls: ToolCall<string, Record<string, any>>[];
      }

      An object containing:

      • tool_call_chunks: The original input chunks
      • tool_calls: An array of successfully parsed and validated tool calls
      • invalid_tool_calls: An array of tool calls that failed parsing or validation

      Chunks are grouped using the following matching logic:

      • If a chunk has both an id and index, it matches chunks with the same id and index
      • If a chunk has only an id, it matches chunks with the same id
      • If a chunk has only an index, it matches chunks with the same index

      For each group, the function:

      1. Concatenates all args strings from the chunks
      2. Attempts to parse the concatenated string as JSON
      3. Validates that the result is a non-null object with a valid id
      4. Creates either a ToolCall (if valid) or InvalidToolCall (if invalid)