Topic 2 of 4 · 5 min read
Accumulating text and tool-call deltas
Goal: Assemble streamed text and partial tool-call arguments into a complete message without parsing incomplete JSON fragments.
While a model streams, you only ever hold a prefix of the final answer, so append deltas to a buffer by block index and parse structured content only after its block has stopped. Text can be shown as it arrives. Tool-call arguments cannot be used until they are complete.
Check yourself · 1 of 3
When can your server safely call JSON.parse on a streamed tool call's arguments?
Why it matters
Showing text early makes an app feel fast. But the same stream also carries tool calls, and their arguments arrive as pieces of a JSON string. Calling JSON.parse on a half-received string throws, and a parser that guesses can run a tool with the wrong arguments.
How to do it
- Key buffers by content block index. Every delta says which block it belongs to. A reply can hold a text block, then a tool call block, then another. One shared string mixes them up.
- Append text deltas and render at once. For a chat UI, send each piece to the browser as it comes. Do not trim or re-wrap it, since a word or a multibyte character can be split between two deltas.
- Collect tool JSON as a string. For Claude,
input_json_deltaevents carry apartial_jsonstring. Concatenate them. Oncontent_block_stop, parse the whole string once. For OpenAI, argument delta events work the same way, and a done event gives the complete string. - Act on the full message. Run the tool only after the stop reason says the model wants tools (
tool_usefor Claude), and handle the case where the stream ended early. - Keep the raw events in debug logs. Replaying a captured stream is the easiest way to reproduce a parsing bug.
The SDKs offer helpers that do this assembly and give you the final message object. Use them unless you need custom forwarding. If you do forward to a browser, forward your own small event format, not the provider's raw events, so the provider's API never leaks into your front end.
Before and after
Weak:
let args = "";
for await (const ev of events) {
if (ev.delta?.partial_json) {
args += ev.delta.partial_json;
runTool(JSON.parse(args)); // throws on '{"city": "Pa'
}
}
Better:
const blocks = new Map<number, string>();
for await (const ev of events) {
if (ev.type === "content_block_delta" && ev.delta.type === "input_json_delta") {
blocks.set(ev.index, (blocks.get(ev.index) ?? "") + ev.delta.partial_json);
} else if (ev.type === "content_block_stop" && blocks.has(ev.index)) {
runTool(JSON.parse(blocks.get(ev.index)!));
}
}
What goes wrong
- Parsing too early. Partial JSON throws, or a lenient parser returns half the arguments.
- One buffer for everything. Text and several tool calls end up concatenated.
- Splitting bytes badly. Decoding each network chunk on its own corrupts characters that straddle chunks. Use a streaming decoder.
- Running a tool on a truncated call. A
max_tokensstop can cut the JSON off. Check the stop reason first.
Examples
A partial tool call on the wire
delta 1: {"city": "Pa
delta 2: ris", "unit":
delta 3: "celsius"}
None of the first two strings is valid JSON. Only the join of all three is. Parse it on content_block_stop, never after delta 1 or 2.
Forwarding to a browser
The server accumulates the provider's events but forwards only its own small events to the page, such as {"t":"text","v":"Hel"} and {"t":"done"}. If you change provider, the browser code does not change.
Key points
- Keep one buffer per content block index, not one shared string for the whole reply.
- Text deltas can be shown the moment they arrive; tool arguments cannot be used yet.
- Tool-call arguments arrive as pieces of a JSON string and parse only after the block stops.
- Decode bytes with a streaming decoder so characters split across chunks stay intact.
- Check the stop reason before running a tool, because a truncated call has invalid JSON.
Common mistakes
- Calling JSON.parse on the arguments after every delta.
- Using one string for the text block and every tool block together.
- Decoding each network chunk as a separate string and corrupting multibyte characters.
- Running a tool call when the stop reason was max_tokens and the JSON was cut off.
Check yourself · 2 of 3
A reply has a text block and then two tool-call blocks. How should deltas be buffered?
Check yourself · 3 of 3
A Node server decodes each network chunk with chunk.toString() and sometimes shows a broken character in streamed text. What is the fix?
Practice items, not counted towards your mastery.
Start here
- Streaming messages (Claude) (opens in a new tab)DocsFree
The full event sequence, delta types, partial tool JSON and mid-stream error behaviour of a Claude stream.
- Streaming API responses (OpenAI) (opens in a new tab)DocsFree
How another vendor names and orders its stream events, useful for comparing event shapes.
- Using server-sent events (MDN) (opens in a new tab)DocsFree
The wire format: data lines, blank-line separators, event names and the text/event-stream type.