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[]),idandfunction.nameare typically populated on the opening chunk for a givenindex, while subsequent chunks for that sameindexsetidtonull/undefinedand append morefunction.argumentsfragments. - Parallel tool calls interleave by
index: When the model invokes multiple tools in parallel, chunks arrive with distinctindexvalues (0,1,2, …). If you appendfunction.argumentsinto a single string instead of keying buffers byindex, arguments from different tool calls get concatenated into broken JSON.
How to Buffer Tool Call Arguments Safely
- Key a buffer map by
toolCallDelta.index: Initialize{ id, name, arguments: "" }when a newindexappears, and appenddelta.function.argumentsto thatindex’s buffer on every subsequent chunk. - 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. - Parse and validate only after the stream finishes: Once the stream ends (or
finish_reason === "tool_calls"), parse each bufferedargumentsstring inside atry/catchand 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_reasonbefore executing: Iffinish_reason === "length", the model may have hit its token limit mid-argument, leaving truncated JSON that failsJSON.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_callswithindex, while Responses API streams emit distinct events (response.output_item.addedandresponse.function_call_arguments.deltacorrelated byitem_id).
You must log in or register to comment.
