fix(ai): streamed tool calls keep their arguments when an upstream's deltas differ from OpenAI's (#4713)

* fix(ai): streamed tool calls keep their arguments when an upstream's deltas differ from OpenAI's

The OpenAI-compatible stream handler slotted tool-call deltas by index
alone and appended function.arguments as it arrived. Parallel calls that
shared an index, or sent none, merged into one block whose JSON could not
parse, and the second call was lost. A delta without arguments started the
buffer with "undefined", and object arguments, which Mistral's SDK allows,
became "[object Object]". Each reached the caller as a tool call with
input {}. A delta carrying both content and tool_calls emitted only the
text.

A delta with an index still continues the call at that index, unless it
brings a new id and its own name, which opens another call. A delta with
no index resolves by id, then to the call in progress. Arguments are read
as JSON text, and a delta's tool calls are handled after its text.
Arguments that still don't parse pass as {} as before, and the call's
name, id and length are logged.

* fix(ai): review follow-ups for streamed tool calls

Two calls that shared an index were told apart only when the second one
opened. After that the index pointed at the second call, so a later
delta carrying the first call's id was appended to the second, and both
came back with arguments that don't parse when their pieces alternated.

Each index now remembers the calls opened on it by id, and a delta whose
id matches one of them continues that call. The lookup stays within the
index, so calls at different indexes that repeat an id stay apart.
This commit is contained in:
HanadHassan authored and GitHub committed 2026-11-23 11:05:57 -07:00
1 parent b3dad7a996
commit 4e82cd27df
4 files changed
+336 -18

No files matched your search

@@ -100,6 +100,10 @@ export class AIChatToolUseStream extends AIChatConstructStream {
try {
input = JSON.parse(this.buffer);
} catch {
// Arguments are user data: log only enough to find the call.
console.warn(
`[ai-chat] tool call arguments were not valid JSON; passing {} (${this.contentBlock.name}, ${this.contentBlock.id}, ${this.buffer.length} chars)`,
);
input = {};
}
this.chatStream.writeChunk(
@@ -18,7 +18,7 @@
*/
import { Writable } from 'node:stream';
import { describe, expect, it } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
// @ts-expect-error — sibling JS module without an adjacent .d.ts
import Streaming, {
AIChatMessageStream,
@@ -411,6 +411,29 @@ describe('AIChatToolUseStream (via message().contentBlock)', () => {
expect(event.input).toEqual({});
});
it("warns with the call's name and id, not its arguments, when the JSON is malformed", () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
const h = makeHarness();
const block = h.chatStream.message().contentBlock({
type: 'tool_use',
id: 'call_5',
name: 'lookup',
});
block.addPartialJSON('{"q": "unterminat');
block.end();
expect(warn).toHaveBeenCalledTimes(1);
const message = String(warn.mock.calls[0][0]);
expect(message).toContain('lookup');
expect(message).toContain('call_5');
expect(message).not.toContain('unterminat');
expect(h.events()[0].input).toEqual({});
} finally {
warn.mockRestore();
}
});
it('emits tool_use_start and tool_input_delta only when streamToolInput is set', () => {
const h = makeHarness();
const withDeltas = new AIChatStream({
@@ -558,8 +558,7 @@ export const splitCachedPrompt = (usage) => {
* @param {{ writeTtl?: '5m' | '30m' }} [opts] The lifetime `cache_write_tokens`
* were written with: 5m unless the provider says otherwise (OpenAI's default
* entries live 30m).
* @returns {import('../../interfaces/chat/types.js').UsageDetails
* | undefined}
* @returns {import('../../interfaces/chat/types.js').UsageDetails | undefined}
*/
export const usageDetailsFromTrackedUsage = (
trackedUsage,
@@ -624,6 +623,19 @@ export const normalizeReasoningContent = (result) => {
}
};
/**
* A tool-call delta's `arguments` as JSON text. Some upstreams leave it out of
* a delta, and Mistral's SDK can hand back an already-parsed object.
*
* @param {unknown} args
* @returns {string}
*/
const toolCallArgumentsText = (args) => {
if (typeof args === 'string') return args;
if (args === null || args === undefined) return '';
return JSON.stringify(args);
};
export const create_chat_stream_handler =
({ deviations, completion, usage_calculator }) =>
async ({ chatStream }) => {
@@ -643,7 +655,25 @@ export const create_chat_stream_handler =
let textblock = message.contentBlock({ type: 'text' });
let toolblock = null;
let mode = 'text';
const tool_call_blocks = [];
// Some upstreams reuse one index for parallel calls or send no index,
// so an index alone doesn't always name a call.
const blocksById = new Map();
/**
* The latest call at each index, and every call opened there by id.
*
* @type {Map<
* number,
* {
* block: import('../../interfaces/chat/utils/Streaming.js').AIChatToolUseStream;
* id?: string;
* byId: Map<
* string,
* import('../../interfaces/chat/utils/Streaming.js').AIChatToolUseStream
* >;
* }
* >}
*/
const blocksByIndex = new Map();
// A parallel tool-call turn opens one block per call; each is ended
// exactly once, in open order, so every call reaches the stream.
const opened_tool_blocks = [];
@@ -684,6 +714,9 @@ export const create_chat_stream_handler =
// A: For now, reasoning_content and content never appear together, but I’m not sure if they’ll always be mutually exclusive.
}
const tool_calls =
deviations.index_tool_calls_from_stream_choice(choice);
if (choice.delta.content) {
if (mode === 'tool') {
endToolBlock(toolblock);
@@ -691,7 +724,8 @@ export const create_chat_stream_handler =
textblock = message.contentBlock({ type: 'text' });
}
textblock.addText(choice.delta.content);
continue;
// Some upstreams put the call in the same delta as its preamble.
if (!tool_calls?.length) continue;
}
if (choice.delta.extra_content) {
@@ -710,29 +744,59 @@ export const create_chat_stream_handler =
textblock.addExtraContent(choice.delta.extra_content);
}
const tool_calls =
deviations.index_tool_calls_from_stream_choice(choice);
if (tool_calls) {
if (mode === 'text') {
mode = 'tool';
textblock.end();
}
for (const tool_call of tool_calls) {
if (!tool_call_blocks[tool_call.index]) {
toolblock = message.contentBlock({
const id = tool_call.id || undefined;
const index = Number.isInteger(tool_call.index)
? tool_call.index
: undefined;
const atIndex =
index !== undefined
? blocksByIndex.get(index)
: undefined;
let block;
if (atIndex) {
// An id already opened at this index continues that
// call, even after another call took the index. A new
// id that brings its own name is another call; without
// a name it continues the latest one.
block =
id !== undefined ? atIndex.byId.get(id) : undefined;
const startsAnother =
id !== undefined &&
id !== atIndex.id &&
!!tool_call.function?.name;
if (!block && !startsAnother) block = atIndex.block;
} else if (index === undefined) {
block =
id !== undefined ? blocksById.get(id) : toolblock;
}
if (!block) {
block = message.contentBlock({
type: 'tool_use',
id: tool_call.id,
name: tool_call.function.name,
id,
name: tool_call.function?.name,
...(tool_call.extra_content
? { extra_content: tool_call.extra_content }
: {}),
});
tool_call_blocks[tool_call.index] = toolblock;
opened_tool_blocks.push(toolblock);
} else {
toolblock = tool_call_blocks[tool_call.index];
opened_tool_blocks.push(block);
if (id !== undefined) blocksById.set(id, block);
if (index !== undefined) {
const byId = atIndex?.byId ?? new Map();
if (id !== undefined) byId.set(id, block);
blocksByIndex.set(index, { block, id, byId });
}
}
toolblock.addPartialJSON(tool_call.function.arguments);
toolblock = block;
const args = toolCallArgumentsText(
tool_call.function?.arguments,
);
if (args) block.addPartialJSON(args);
}
}
}
@@ -45,7 +45,7 @@ import { AIChatStream } from '../../interfaces/chat/utils/Streaming.js';
// captured chunks back out so assertions can inspect the live
// shape — no method spies on the stream classes.
const makeCapturingChatStream = () => {
const makeCapturingChatStream = (opts: { streamToolInput?: boolean } = {}) => {
const chunks: string[] = [];
const sink = new Writable({
write(chunk, _enc, cb) {
@@ -53,7 +53,7 @@ const makeCapturingChatStream = () => {
cb();
},
});
const chatStream = new AIChatStream({ stream: sink });
const chatStream = new AIChatStream({ stream: sink, ...opts });
return {
chatStream,
events: () =>
@@ -1277,6 +1277,233 @@ describe('create_chat_stream_handler', () => {
const usage = events.find((e) => e.type === 'usage');
expect(usage?.usage).toEqual({ prompt_tokens: 1 });
});
describe('tool-call deltas that differ from OpenAI’s shape', () => {
const toolCallChunk = (toolCalls: unknown[]) => ({
choices: [{ delta: { tool_calls: toolCalls } }],
});
/** Every chunk the stream wrote for `chunks` plus a closing usage chunk. */
const streamEvents = async (
chunks: unknown[],
opts: { streamToolInput?: boolean } = {},
) => {
const init = create_chat_stream_handler({
deviations: undefined,
completion: asAsyncIterable([
...chunks,
{
choices: [{ delta: {}, finish_reason: 'tool_calls' }],
usage: { prompt_tokens: 1 },
},
]),
usage_calculator: () => ({}),
});
const harness = makeCapturingChatStream(opts);
await init({ chatStream: harness.chatStream });
return harness.events();
};
const streamToolUses = async (chunks: unknown[]) =>
(await streamEvents(chunks)).filter((e) => e.type === 'tool_use');
const twoCalls = [
{
index: 0,
id: 'a',
function: { name: 'f', arguments: '{"x":1}' },
},
{
index: 0,
id: 'b',
function: { name: 'g', arguments: '{"y":2}' },
},
];
it('opens a separate call for each id that shares an index', async () => {
const tools = await streamToolUses([toolCallChunk(twoCalls)]);
expect(tools.map((e) => [e.id, e.name, e.input])).toEqual([
['a', 'f', { x: 1 }],
['b', 'g', { y: 2 }],
]);
});
it('routes pieces by id when calls sharing an index alternate', async () => {
const piece = (id: string, args: string, name?: string) =>
toolCallChunk([
{
index: 0,
id,
function: name
? { name, arguments: args }
: { arguments: args },
},
]);
const tools = await streamToolUses([
piece('a', '{"x":', 'f'),
piece('b', '{"y":', 'g'),
piece('a', '1}'),
piece('b', '2}'),
]);
expect(tools.map((e) => [e.id, e.name, e.input])).toEqual([
['a', 'f', { x: 1 }],
['b', 'g', { y: 2 }],
]);
});
it('keys calls by id when the upstream omits index', async () => {
const tools = await streamToolUses([
toolCallChunk(
twoCalls.map(({ index: _index, ...call }) => call),
),
]);
expect(tools.map((e) => [e.id, e.name, e.input])).toEqual([
['a', 'f', { x: 1 }],
['b', 'g', { y: 2 }],
]);
});
it('keeps a call together when every delta repeats its id', async () => {
const tools = await streamToolUses([
toolCallChunk([
{
index: 0,
id: 'a',
function: { name: 'f', arguments: '{"q":' },
},
]),
toolCallChunk([
{ index: 0, id: 'a', function: { arguments: '"p"}' } },
]),
]);
expect(tools).toHaveLength(1);
expect(tools[0].input).toEqual({ q: 'p' });
});
it('treats an empty id on a continuation as no id', async () => {
const tools = await streamToolUses([
toolCallChunk([
{
index: 0,
id: 'a',
function: { name: 'f', arguments: '{"q":' },
},
]),
toolCallChunk([
{ index: 0, id: '', function: { arguments: '"p"}' } },
]),
]);
expect(tools).toHaveLength(1);
expect(tools[0].id).toBe('a');
expect(tools[0].input).toEqual({ q: 'p' });
});
it('keeps a continuation that brings a new id but no name on its call', async () => {
const tools = await streamToolUses([
toolCallChunk([
{
index: 0,
id: 'a',
function: { name: 'f', arguments: '{"x":' },
},
]),
toolCallChunk([
{ index: 0, id: 'a2', function: { arguments: '1}' } },
]),
]);
expect(tools.map((e) => [e.id, e.name, e.input])).toEqual([
['a', 'f', { x: 1 }],
]);
});
it('keeps calls at different indexes apart when they repeat an id', async () => {
const tools = await streamToolUses([
toolCallChunk([
{
index: 0,
id: 'a',
function: { name: 'f', arguments: '{"x":1}' },
},
]),
toolCallChunk([
{
index: 1,
id: 'a',
function: { name: 'g', arguments: '{"y":2}' },
},
]),
]);
expect(tools.map((e) => [e.name, e.input])).toEqual([
['f', { x: 1 }],
['g', { y: 2 }],
]);
});
it('treats a delta without arguments as empty', async () => {
const tools = await streamToolUses([
toolCallChunk([{ index: 0, id: 'a', function: { name: 'f' } }]),
toolCallChunk([
{ index: 0, function: { arguments: '{"x":1}' } },
]),
]);
expect(tools).toHaveLength(1);
expect(tools[0].input).toEqual({ x: 1 });
});
it('serializes object arguments', async () => {
const tools = await streamToolUses([
toolCallChunk([
{
index: 0,
id: 'a',
function: { name: 'f', arguments: { x: 1 } },
},
]),
]);
expect(tools).toHaveLength(1);
expect(tools[0].input).toEqual({ x: 1 });
});
it('emits the tool call when content and tool_calls share a delta', async () => {
const events = (
await streamEvents([
{
choices: [
{
delta: {
content: 'calling',
tool_calls: [
{
index: 0,
id: 'a',
function: {
name: 'f',
arguments: '{"x":1}',
},
},
],
},
},
],
},
])
).filter((e) => e.type === 'text' || e.type === 'tool_use');
expect(events.map((e) => e.type)).toEqual(['text', 'tool_use']);
expect(events[0].text).toBe('calling');
expect(events[1].input).toEqual({ x: 1 });
});
it('streams one tool_use_start per call when streamToolInput is set', async () => {
const events = await streamEvents([toolCallChunk(twoCalls)], {
streamToolInput: true,
});
expect(
events
.filter((e) => e.type === 'tool_use_start')
.map((e) => e.id),
).toEqual(['a', 'b']);
});
});
});
// ── create_chat_stream_handler_responses_api ────────────────────────