Why does streaming tool call arguments split JSON keys across multiple delta chunks and how do you buffer them? | A1Lab@HamzaM to AI & LLMEnglish • 4 days ago

Why does streaming tool call arguments split JSON keys across multiple delta chunks and how do you buffer them?

message-square
0

Why Streaming Tool Call Arguments Split Across Delta Chunks

When an LLM streams tool calls, it generates function.arguments as a raw string token-by-token, not as pre-parsed JSON objects. Because tokenizers break strings along subword token boundaries rather than JSON syntax boundaries, a single key, colon, quote, or value can split across multiple chunks—for example {"lo, cation": ", New York"}.

Two extra gotchas trip up streaming tool call accumulators:

  • Metadata only appears on the first delta of each tool call: In Chat Completions streams (delta.tool_calls[]), id and function.name are typically populated on the opening chunk for a given index, while subsequent chunks for that same index set id to null/undefined and append more function.arguments fragments.
  • Parallel tool calls interleave by index: When the model invokes multiple tools in parallel, chunks arrive with distinct index values (0, 1, 2, …). If you append function.arguments into a single string instead of keying buffers by index, arguments from different tool calls get concatenated into broken JSON.

How to Buffer Tool Call Arguments Safely

  1. Key a buffer map by toolCallDelta.index: Initialize { id, name, arguments: "" } when a new index appears, and append delta.function.arguments to that index’s buffer on every subsequent chunk.
  2. Do not call JSON.parse() on mid-stream fragments: Intermediate buffers are syntactically incomplete and will throw parse errors until the full argument string is received.
  3. Parse and validate only after the stream finishes: Once the stream ends (or finish_reason === "tool_calls"), parse each buffered arguments string inside a try/catch and validate it against your schema before executing the tool.

TypeScript Example: Buffering Parallel Tool Call Deltas

import OpenAI from "openai";

interface BufferedToolCall {
  index: number;
  id: string;
  name: string;
  arguments: string;
}

export async function collectStreamedToolCalls(
  openai: OpenAI,
  params: Omit<OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming, "stream">
): Promise<{
  content: string;
  finishReason: string | null;
  toolCalls: Array<{ id: string; name: string; args: Record<string, unknown> }>;
}> {
  const stream = await openai.chat.completions.create({
    ...params,
    stream: true,
  });

  const buffers = new Map<number, BufferedToolCall>();
  let content = "";
  let finishReason: string | null = null;

  for await (const chunk of stream) {
    const choice = chunk.choices[0];
    if (!choice) continue;

    if (choice.finish_reason) {
      finishReason = choice.finish_reason;
    }

    if (choice.delta?.content) {
      content += choice.delta.content;
    }

    for (const tcDelta of choice.delta?.tool_calls ?? []) {
      const idx = tcDelta.index;
      let entry = buffers.get(idx);

      if (!entry) {
        entry = {
          index: idx,
          id: tcDelta.id ?? "",
          name: tcDelta.function?.name ?? "",
          arguments: "",
        };
        buffers.set(idx, entry);
      } else {
        // Later chunks often omit id/name, so only overwrite when present
        if (tcDelta.id) entry.id = tcDelta.id;
        if (tcDelta.function?.name) entry.name += tcDelta.function.name;
      }

      if (tcDelta.function?.arguments) {
        entry.arguments += tcDelta.function.arguments;
      }
    }
  }

  // Parse complete argument strings in index order once streaming finishes
  const toolCalls = Array.from(buffers.values())
    .sort((a, b) => a.index - b.index)
    .map((buf) => {
      let parsed: unknown;
      try {
        parsed = JSON.parse(buf.arguments || "{}");
      } catch (err) {
        const msg = err instanceof Error ? err.message : "Invalid JSON";
        throw new Error(
          `Malformed JSON arguments for tool '\${buf.name}' (${buf.id}):${msg} | raw=${buf.arguments}` ); }  if (!parsed \vert{}\vert{} typeof parsed !== "object" \vert{}\vert{} Array.isArray(parsed)) { throw new Error(`Tool '${buf.name}' arguments must be a JSON object`);
      }

      return {
        id: buf.id,
        name: buf.name,
        args: parsed as Record<string, unknown>,
      };
    });

  return { content, finishReason, toolCalls };
}

Helpful Tips for Streaming Tool Calls

  • Check finish_reason before executing: If finish_reason === "length", the model may have hit its token limit mid-argument, leaving truncated JSON that fails JSON.parse().
  • Keep UI previews separate from execution inputs: If you show live argument previews in the UI via a tolerant partial parser, never pass partial UI state to your actual tool executor—only execute from the finalized, validated buffer.
  • Watch API event shapes across endpoints: Chat Completions uses delta.tool_calls with index, while Responses API streams emit distinct events (response.output_item.added and response.function_call_arguments.delta correlated by item_id).