903. Assemble streamed tool-call deltas
Why it matters Every agent framework that streams has to rebuild tool calls from deltas, and bugs here show up as tools called with half their arguments.
Streaming LLM APIs send tool calls in pieces. Each chunk carries the index of the tool call it belongs to and may carry the call id, the function name and a fragment of the JSON arguments.
Write assemble_tool_calls(chunks).
- chunks: list of dicts with key "index" (int) and optional keys "id", "name" (str) and "args" (a str fragment). The first chunk that gives an id or name for an index sets it; later ones are ignored.
- Concatenate the "args" fragments for each index in arrival order.
- Parse the joined string with json.loads. An empty string means {}. If parsing fails, or the result is not a dict, arguments is None and error is "invalid json"; otherwise error is None.
Return a list of dicts {"index", "id", "name", "arguments", "error"} sorted by index. A missing id or name is None.
def assemble_tool_calls(chunks)Example 1
Input: assemble_tool_calls([{'index': 0, 'id': 'call_1', 'name': 'search', 'args': '{"q": "pa'}, {'index': 0, 'args': 'ris"}'}])
Output: [{'index': 0, 'id': 'call_1', 'name': 'search', 'arguments': {'q': 'paris'}, 'error': None}]
Example 2
Input: chunks = [{'index': 1, 'id': 'b', 'name': 'get_time'}, {'index': 0, 'id': 'a', 'name': 'add', 'args': '{"x": 1,'}, {'index': 1, 'args': ''}, {'index': 0, 'args': ' "y": 2}'}]
Output: [{'index': 0, 'id': 'a', 'name': 'add', 'arguments': {'x': 1, 'y': 2}, 'error': None}, {'index': 1, 'id': 'b', 'name': 'get_time', 'arguments': {}, 'error': None}]
Example 3
Input: chunks = [{'index': 0, 'name': 'run', 'args': '{"cmd": "ls"'}]
Output: [{'index': 0, 'id': None, 'name': 'run', 'arguments': None, 'error': 'invalid json'}]
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 5 tests to be accepted.
Hint 1
Use a dict keyed by index with id, name and a list of fragments.
Hint 2
Join fragments, then json.loads inside try/except.
Hint 3
Sort by index for the output.
Common mistakes
- Parsing each fragment separately.
- Letting a later chunk overwrite the id.
- Treating a JSON list as valid arguments.
Understand the idea
Group chunks by index, keep the first id and name, and append argument fragments in order. Only parse once the stream is complete, since partial JSON is invalid by design. Treat an empty argument string as {} (tools with no parameters) and report a truncated stream as an error instead of guessing.
Shapes and data flow
List of dicts in, list of dicts out.