test(ai): stream two interleaved tool calls through the compatibility routes (#4739)

* test(ai): stream two interleaved tool calls through the compatibility routes

The route tests for the OpenAI chat, Responses and Anthropic messages
routes stub the chat driver, and the HTTP tests that run a fake vendor
through the real driver only stream text. Nothing checked that a
vendor's streamed tool calls reach a client of those routes intact.

A new HTTP test boots the backend, plays Chat Completions, Responses and
Anthropic vendors at the fetch boundary with two tool calls whose
arguments arrive in pieces, interleaved for Chat Completions, and
rebuilds the calls from each route's stream. The fuzz test's healthy
upstream answers a streamed request that offers tools with the same
fixtures, and the misbehaving case offers a tool on half its requests,
so corrupted tool-call streams are exercised too.

* test(ai): review follow-ups for streamed tool-call tests

The fuzz test fed Mistral the piece-by-piece Chat Completions fixture,
which Mistral's SDK rejects because it requires a name on every
tool-call delta, and the fuzz test still passed. Mistral now gets every
call whole in one chunk, the shape it sends, and the HTTP test gains a
Mistral row and a whole-calls row for the OpenAI SDK.

The piece-by-piece fixture now opens each call with empty arguments, as
OpenAI does. The HTTP test also checks that the chat route numbers calls
from 0 and sends a call's id and name only once, that Anthropic blocks
never overlap, and that each route ends its stream the way clients wait
for.
This commit is contained in:
HanadHassan authored and GitHub committed 2026-11-23 11:07:15 -07:00
1 parent 0692132771
commit f8ead99d32
4 files changed
+755

No files matched your search

@@ -0,0 +1,367 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Puter is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Puter. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Two streamed tool calls from a vendor, through the real driver and provider,
* out of each compatibility route. The vendor is played at the fetch boundary.
*/
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import {
upstream,
type UpstreamReply,
} from '../../drivers/ai/shared/fuzzTestUtil.js';
import {
anthropicToolStream,
chatCompletionsToolStream,
chatToolCallDeltas,
chatWholeToolCallDeltas,
responsesToolStream,
STREAMED_TOOL_CALLS,
} from '../../drivers/ai/shared/toolCallStreamTestUtil.js';
import { setupPuterTestEnv, type PuterTestEnv } from '../../testUtil.js';
vi.mock('undici', async (importOriginal) => ({
...(await importOriginal<typeof import('undici')>()),
fetch: (input: unknown, init?: RequestInit) => upstream.fetch(input, init),
}));
// Requests to Puter itself go over the network; `upstream` replaces the global.
const realFetch = globalThis.fetch;
type Data = Record<string, any>;
type ToolCalls = {
calls: { id: string; name: string; args: string; pieces: number }[];
stop: unknown;
};
const schema = {
type: 'object',
properties: { city: { type: 'string' } },
};
/** Reads an SSE body into its events' parsed `data`, skipping `[DONE]`. */
const readEvents = (text: string): Data[] =>
text
.split('\n\n')
.map((frame) =>
frame
.split('\n')
.filter((line) => line.startsWith('data: '))
.map((line) => line.slice('data: '.length))
.join('\n'),
)
.filter((data) => data && data !== '[DONE]')
.map((data) => JSON.parse(data));
const chatToolCalls = (events: Data[]): ToolCalls => {
const calls = new Map<number, ToolCalls['calls'][number]>();
let stop: unknown;
for (const choice of events.flatMap((event) => event.choices ?? [])) {
for (const delta of choice.delta?.tool_calls ?? []) {
const seen = calls.get(delta.index);
// Clients join a call's deltas by index, so a repeated id or name
// would be appended to the first.
if (seen) expect(delta.id ?? delta.function?.name).toBeUndefined();
const call = seen ?? { id: '', name: '', args: '', pieces: 0 };
if (delta.id) call.id = delta.id;
if (delta.function?.name) call.name = delta.function.name;
if (delta.function?.arguments) {
call.args += delta.function.arguments;
call.pieces++;
}
calls.set(delta.index, call);
}
if (choice.finish_reason) stop = choice.finish_reason;
}
expect([...calls.keys()]).toEqual(STREAMED_TOOL_CALLS.map((_, i) => i));
return { calls: [...calls.values()], stop };
};
const responsesToolCalls = (events: Data[]): ToolCalls => {
const calls = new Map<string, ToolCalls['calls'][number]>();
let stop: unknown;
for (const event of events) {
if (
event.type === 'response.output_item.added' &&
event.item.type === 'function_call'
) {
calls.set(event.item.id, {
id: event.item.call_id,
name: event.item.name,
args: '',
pieces: 0,
});
}
if (event.type === 'response.function_call_arguments.delta') {
const call = calls.get(event.item_id)!;
call.args += event.delta;
call.pieces++;
}
// The closing event repeats the whole arguments; they must agree.
if (event.type === 'response.function_call_arguments.done') {
expect(event.arguments).toBe(calls.get(event.item_id)!.args);
}
if (event.type === 'response.completed') {
stop = event.response.output.map((item: Data) => item.type);
}
}
return { calls: [...calls.values()], stop };
};
const anthropicToolCalls = (events: Data[]): ToolCalls => {
const calls = new Map<number, ToolCalls['calls'][number]>();
let stop: unknown;
let open: number | null = null;
for (const event of events) {
// Blocks can't overlap: every delta and stop belongs to the open one.
if (event.type === 'content_block_start') {
expect(open).toBeNull();
open = event.index;
} else if (event.type === 'content_block_delta') {
expect(event.index).toBe(open);
} else if (event.type === 'content_block_stop') {
expect(event.index).toBe(open);
open = null;
}
if (
event.type === 'content_block_start' &&
event.content_block.type === 'tool_use'
) {
calls.set(event.index, {
id: event.content_block.id,
name: event.content_block.name,
args: '',
pieces: 0,
});
}
if (event.delta?.type === 'input_json_delta') {
const call = calls.get(event.index)!;
call.args += event.delta.partial_json;
call.pieces++;
}
if (event.type === 'message_delta') stop = event.delta.stop_reason;
}
return { calls: [...calls.values()], stop };
};
const ROUTES = {
chat: {
path: '/puterai/openai/v1/chat/completions',
body: (model: string, provider: string) => ({
model,
provider,
stream: true,
messages: [{ role: 'user', content: 'hi' }],
tools: STREAMED_TOOL_CALLS.map(({ name }) => ({
type: 'function',
function: { name, parameters: schema },
})),
}),
read: chatToolCalls,
stop: 'tool_calls',
end: 'data: [DONE]',
},
responses: {
path: '/puterai/openai/v1/responses',
// This route only accepts its own provider name; the model picks.
body: (model: string) => ({
model,
stream: true,
input: 'hi',
tools: STREAMED_TOOL_CALLS.map(({ name }) => ({
type: 'function',
name,
parameters: schema,
})),
}),
read: responsesToolCalls,
stop: ['function_call', 'function_call'],
end: 'event: response.completed',
},
anthropic: {
path: '/puterai/anthropic/v1/messages',
body: (model: string, provider: string) => ({
model,
provider,
stream: true,
max_tokens: 64,
messages: [{ role: 'user', content: 'hi' }],
tools: STREAMED_TOOL_CALLS.map(({ name }) => ({
name,
input_schema: schema,
})),
}),
read: anthropicToolCalls,
stop: 'tool_use',
end: 'event: message_stop',
},
};
const VENDORS = {
'chat sequential': {
model: 'deepseek-flash',
provider: 'deepseek',
endpoint: 'api.deepseek.com/chat/completions',
streamsPieces: true,
sse: () =>
chatCompletionsToolStream(
chatToolCallDeltas({ interleave: false }),
),
},
'chat interleaved': {
model: 'deepseek-flash',
provider: 'deepseek',
endpoint: 'api.deepseek.com/chat/completions',
streamsPieces: true,
sse: () =>
chatCompletionsToolStream(chatToolCallDeltas({ interleave: true })),
},
'chat whole calls': {
model: 'deepseek-flash',
provider: 'deepseek',
endpoint: 'api.deepseek.com/chat/completions',
streamsPieces: false,
sse: () => chatCompletionsToolStream(chatWholeToolCallDeltas()),
},
mistral: {
model: 'mistral-large-4',
provider: 'mistral',
endpoint: 'api.mistral.ai/v1/chat/completions',
streamsPieces: false,
sse: () => chatCompletionsToolStream(chatWholeToolCallDeltas()),
},
responses: {
model: 'gpt-6.1-sol',
provider: 'openai-responses',
endpoint: 'api.openai.com/v1/responses',
// The provider passes each call on whole once the vendor finishes it.
streamsPieces: false,
sse: responsesToolStream,
},
anthropic: {
model: 'claude-haiku-5-5',
provider: 'claude',
endpoint: 'api.anthropic.com/v1/messages',
streamsPieces: true,
sse: anthropicToolStream,
},
};
const rows = (Object.keys(VENDORS) as (keyof typeof VENDORS)[])
.flatMap((vendor) =>
(Object.keys(ROUTES) as (keyof typeof ROUTES)[]).map((route) => ({
vendor,
route,
})),
)
// Left out until AnthropicSseWriter keeps a call's later pieces after the
// next call opens.
.filter(
({ vendor, route }) =>
!(vendor === 'chat interleaved' && route === 'anthropic'),
);
describe('streamed tool calls through the compatibility routes', () => {
let env: PuterTestEnv;
let reply: UpstreamReply['sse'];
let endpoint = '';
const asked = new Set<string>();
beforeAll(async () => {
upstream.install();
upstream.respond = ({ url }) => {
if (url.pathname.endsWith('/messages/count_tokens')) {
return { body: { input_tokens: 3 } };
}
asked.add(`${url.hostname}${url.pathname}`);
return `${url.hostname}${url.pathname}` === endpoint
? { sse: reply }
: undefined;
};
const key = { apiKey: 'tool-calls-key' };
env = await setupPuterTestEnv({
providers: {
deepseek: key,
'openai-completion': key,
claude: key,
mistral: key,
},
meteringEnforcement: { subscriptions: false },
// Back-to-back streamed requests otherwise get a 429 while the previous
// request's usage hold is still held.
unlimitedMetering: true,
} as never);
await vi.waitFor(async () => {
const ids = (await env.server.drivers.aiChat.models()).map(
(model) => model.id,
);
for (const { model } of Object.values(VENDORS)) {
expect(ids).toContain(model);
}
});
}, 120_000);
afterAll(async () => {
await env?.shutdown();
upstream.uninstall();
});
it.each(rows)(
'$vendor through the $route route rebuilds both tool calls',
async ({ vendor, route }) => {
const { model, provider, sse } = VENDORS[vendor];
const { path, body, read, stop, end } = ROUTES[route];
reply = sse();
endpoint = VENDORS[vendor].endpoint;
asked.clear();
const res = await realFetch(new URL(path, env.apiOrigin), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${env.users.user.apiToken}`,
Origin: env.apiOrigin,
},
body: JSON.stringify(body(model, provider)),
});
const text = await res.text();
expect(res.status, text).toBe(200);
expect([...asked]).toEqual([endpoint]);
const result = read(readEvents(text));
expect(
result.calls.map(({ id, name, args }) => ({
id,
name,
input: JSON.parse(args),
})),
).toEqual(STREAMED_TOOL_CALLS);
expect(result.stop).toEqual(stop);
expect(text).toContain(end);
// The route must pass a call's pieces on, not one joined piece.
if (VENDORS[vendor].streamsPieces) {
for (const call of result.calls) {
expect(call.pieces, call.id).toBeGreaterThan(1);
}
}
},
);
});
@@ -49,6 +49,13 @@ import {
readStreamResult,
withTestActor,
} from '../../shared/integrationTestUtil.js';
import {
anthropicToolStream,
chatCompletionsToolStream,
chatToolCallDeltas,
chatWholeToolCallDeltas,
responsesToolStream,
} from '../../shared/toolCallStreamTestUtil.js';
import { ChatCompletionDriver } from './ChatCompletionDriver.js';
import type { ICompleteArguments } from './types.js';
import { clearUnhealthyRoutes } from './utils/providerHealth.js';
@@ -176,6 +183,9 @@ const responsesEvents = [
{ type: 'response.completed', response: responsesBody },
];
// Counts the tool-call replies served, so a run that stops reaching them fails.
let toolRepliesServed = 0;
/** A well-formed answer from whichever vendor API the request went to. */
const healthyUpstream = ({
url,
@@ -231,6 +241,24 @@ const healthyUpstream = ({
return { body: 'video-bytes', contentType: 'video/mp4' };
}
const streaming = (json as { stream?: unknown } | undefined)?.stream;
const tools = (json as { tools?: unknown } | undefined)?.tools;
if (streaming && Array.isArray(tools) && tools.length) {
const sse = path.endsWith('/chat/completions')
? chatCompletionsToolStream(
url.hostname === 'api.mistral.ai'
? chatWholeToolCallDeltas()
: chatToolCallDeltas({ interleave: true }),
)
: path.endsWith('/responses')
? responsesToolStream()
: path.endsWith('/messages')
? anthropicToolStream()
: undefined;
if (sse) {
toolRepliesServed++;
return { sse };
}
}
if (path.endsWith('/chat/completions')) {
if (!streaming) {
return {
@@ -770,6 +798,7 @@ describe('ChatCompletionDriver seeded fuzzing', () => {
clearUnhealthyRoutes();
const findings = new Findings();
let answered = 0;
const toolRepliesBefore = toolRepliesServed;
for (let index = 0; index < fuzzCases(3000); index++) {
const random = caseRandom(0xc4a7, index);
@@ -814,11 +843,13 @@ describe('ChatCompletionDriver seeded fuzzing', () => {
findings.assertNone();
// A run where nothing is answered has stopped reaching the providers.
expect(answered).toBeGreaterThan(0);
expect(toolRepliesServed).toBeGreaterThan(toolRepliesBefore);
}, 600_000);
it('ends every request with an answer or a classified error when the upstream misbehaves', async () => {
const findings = new Findings();
const askedBefore = upstream.asked;
const toolRepliesBefore = toolRepliesServed;
for (let index = 0; index < fuzzCases(2000); index++) {
const random = caseRandom(0x0b5e, index);
@@ -836,6 +867,7 @@ describe('ChatCompletionDriver seeded fuzzing', () => {
model: route.id,
stream: random() < 0.5,
fallback: random() < 0.5,
tools: random() < 0.5 ? [weatherTool] : undefined,
});
const unclassified = error && unclassifiedFailure(error);
if (unclassified) {
@@ -858,6 +890,7 @@ describe('ChatCompletionDriver seeded fuzzing', () => {
}
findings.assertNone();
expect(upstream.asked).toBeGreaterThan(askedBefore);
expect(toolRepliesServed).toBeGreaterThan(toolRepliesBefore);
}, 1_800_000);
it('classifies a 200 whose JSON body is cut short, on every provider', async () => {
@@ -0,0 +1,109 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Puter is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Puter. If not, see <https://www.gnu.org/licenses/>.
*/
import { describe, expect, it } from 'vitest';
import {
anthropicToolStream,
argumentPieces,
chatCompletionsToolStream,
chatToolCallDeltas,
chatWholeToolCallDeltas,
responsesToolStream,
STREAMED_TOOL_CALLS,
} from './toolCallStreamTestUtil.js';
type Data = Record<string, any>;
const inputs = STREAMED_TOOL_CALLS.map((call) => call.input);
/** Joins pieces into one string per key, in the order the keys first appear. */
const joinBy = (pieces: [unknown, string][]): string[] => {
const joined = new Map<unknown, string>();
for (const [key, piece] of pieces) {
joined.set(key, (joined.get(key) ?? '') + piece);
}
return [...joined.values()];
};
describe('toolCallStreamTestUtil', () => {
it("argumentPieces rebuilds each call's input", () => {
for (const call of STREAMED_TOOL_CALLS) {
const pieces = argumentPieces(call);
expect(pieces).toHaveLength(3);
expect(JSON.parse(pieces.join(''))).toEqual(call.input);
}
// A piece boundary inside an escape: `\` ends one piece, `"` starts the next.
const notes = argumentPieces(STREAMED_TOOL_CALLS[1]);
expect(notes[0].endsWith('\\')).toBe(true);
expect(notes[1].startsWith('"')).toBe(true);
});
it('chatToolCallDeltas interleaves calls', () => {
const indexes = (interleave: boolean) =>
chatToolCallDeltas({ interleave })
.slice(0, 3)
.map((chunk) => chunk[0].index);
expect(indexes(true)).toEqual([0, 1, 0]);
expect(indexes(false)).toEqual([0, 0, 0]);
});
it("each vendor stream carries both calls' pieces in order", () => {
for (const deltas of [
chatToolCallDeltas({ interleave: false }),
chatToolCallDeltas({ interleave: true }),
chatWholeToolCallDeltas(),
]) {
const chat = chatCompletionsToolStream(deltas);
const chatPieces = chat.flatMap(({ data }) =>
((data as Data).choices?.[0]?.delta?.tool_calls ?? []).map(
(call: Data): [unknown, string] => [
call.index,
call.function.arguments,
],
),
);
expect(joinBy(chatPieces).map((a) => JSON.parse(a))).toEqual(
inputs,
);
}
const responsesPieces = responsesToolStream()
.map(({ data }) => data as Data)
.filter(
(data) =>
data.type === 'response.function_call_arguments.delta',
)
.map((data): [unknown, string] => [data.item_id, data.delta]);
expect(joinBy(responsesPieces).map((a) => JSON.parse(a))).toEqual(
inputs,
);
const anthropicPieces = anthropicToolStream()
.map(({ data }) => data as Data)
.filter((data) => data.delta?.type === 'input_json_delta')
.map((data): [unknown, string] => [
data.index,
data.delta.partial_json,
]);
expect(joinBy(anthropicPieces).map((a) => JSON.parse(a))).toEqual(
inputs,
);
});
});
@@ -0,0 +1,246 @@
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Puter is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Puter. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Vendor streams that answer with two tool calls in one turn, in each wire
* format a chat provider reads: Chat Completions, Responses and Anthropic.
*/
import type { UpstreamReply } from './fuzzTestUtil.js';
export interface StreamedToolCall {
id: string;
name: string;
input: Record<string, unknown>;
}
export type SseEvents = NonNullable<UpstreamReply['sse']>;
/** One entry of a Chat Completions chunk's `delta.tool_calls`. */
export type ChatToolCallDelta = Record<string, unknown>;
export const STREAMED_TOOL_CALLS: readonly StreamedToolCall[] = [
{
id: 'call_weather',
name: 'get_weather',
input: { city: 'Paris', units: { temp: 'C', wind: ['kph', 'm/s'] } },
},
{
id: 'call_notes',
name: 'search_notes',
input: { query: 'say "hi"\n\tback\\slash é 🚀', limit: 2 },
},
];
/**
* A call's arguments as JSON text in three pieces. When the text has an escape,
* the first cut lands inside it, between the `\` and what it escapes.
*/
export const argumentPieces = (call: StreamedToolCall): string[] => {
const text = JSON.stringify(call.input);
const backslash = text.indexOf('\\');
const first = backslash >= 0 ? backslash + 1 : Math.floor(text.length / 3);
const second = Math.max(first + 1, Math.floor((text.length * 2) / 3));
return [
text.slice(0, first),
text.slice(first, second),
text.slice(second),
];
};
/**
* Each chunk's `delta.tool_calls`, shaped as OpenAI streams them: a call's
* first delta carries its `index`, `id`, name and empty arguments, and the
* pieces follow with only `index`. Interleaving the calls' pieces is no known
* vendor's shape; it checks that calls are kept apart by `index`.
*/
export const chatToolCallDeltas = (options: {
interleave: boolean;
}): ChatToolCallDelta[][] => {
const perCall = STREAMED_TOOL_CALLS.map(
(call, index): ChatToolCallDelta[] => [
{
index,
id: call.id,
type: 'function',
function: { name: call.name, arguments: '' },
},
...argumentPieces(call).map((piece) => ({
index,
function: { arguments: piece },
})),
],
);
const ordered = options.interleave
? perCall[0].flatMap((_, n) => perCall.map((pieces) => pieces[n]))
: perCall.flat();
return ordered.map((delta) => [delta]);
};
/**
* Every call whole in one chunk, as Mistral sends them: its SDK requires a name
* on each tool-call delta, so it can't read the piece-by-piece shape.
*/
export const chatWholeToolCallDeltas = (): ChatToolCallDelta[][] => [
STREAMED_TOOL_CALLS.map((call, index) => ({
index,
id: call.id,
type: 'function',
function: { name: call.name, arguments: JSON.stringify(call.input) },
})),
];
const chatUsage = { prompt_tokens: 3, completion_tokens: 5, total_tokens: 8 };
const chatChunk = (delta: object, finish: string | null) => ({
id: 'chatcmpl-tools',
object: 'chat.completion.chunk',
created: 1,
model: 'm',
choices: [{ index: 0, delta, finish_reason: finish }],
});
/** A Chat Completions stream with one chunk per entry of `deltas`. */
export const chatCompletionsToolStream = (
deltas: ChatToolCallDelta[][],
): SseEvents => [
{ data: chatChunk({ role: 'assistant' }, null) },
...deltas.map((toolCalls) => ({
data: chatChunk({ tool_calls: toolCalls }, null),
})),
{ data: chatChunk({}, 'tool_calls') },
{ data: { ...chatChunk({}, null), choices: [], usage: chatUsage } },
{ data: '[DONE]' },
];
const responsesItem = (call: StreamedToolCall, n: number, done: boolean) => ({
type: 'function_call',
id: `fc_${n}`,
call_id: call.id,
name: call.name,
arguments: done ? JSON.stringify(call.input) : '',
status: done ? 'completed' : 'in_progress',
});
/** An OpenAI Responses stream that calls both tools, one after the other. */
export const responsesToolStream = (): SseEvents => {
const response = {
id: 'resp_tools',
object: 'response',
model: 'm',
};
const events: Record<string, unknown>[] = [
{
type: 'response.created',
response: { ...response, status: 'in_progress', output: [] },
},
];
STREAMED_TOOL_CALLS.forEach((call, n) => {
const item_id = `fc_${n}`;
events.push(
{
type: 'response.output_item.added',
output_index: n,
item: responsesItem(call, n, false),
},
...argumentPieces(call).map((delta) => ({
type: 'response.function_call_arguments.delta',
item_id,
output_index: n,
delta,
})),
{
type: 'response.function_call_arguments.done',
item_id,
output_index: n,
arguments: JSON.stringify(call.input),
},
{
type: 'response.output_item.done',
output_index: n,
item: responsesItem(call, n, true),
},
);
});
events.push({
type: 'response.completed',
response: {
...response,
status: 'completed',
output: STREAMED_TOOL_CALLS.map((call, n) =>
responsesItem(call, n, true),
),
usage: {
input_tokens: 3,
output_tokens: 5,
total_tokens: 8,
input_tokens_details: { cached_tokens: 0 },
output_tokens_details: { reasoning_tokens: 0 },
},
},
});
return events.map((data) => ({ event: data.type as string, data }));
};
/** An Anthropic Messages stream with one `tool_use` block per call. */
export const anthropicToolStream = (): SseEvents => {
const events: Record<string, unknown>[] = [
{
type: 'message_start',
message: {
id: 'msg_tools',
type: 'message',
role: 'assistant',
model: 'm',
content: [],
stop_reason: null,
stop_sequence: null,
usage: { input_tokens: 3, output_tokens: 1 },
},
},
];
STREAMED_TOOL_CALLS.forEach((call, index) => {
events.push(
{
type: 'content_block_start',
index,
content_block: {
type: 'tool_use',
id: call.id,
name: call.name,
input: {},
},
},
...argumentPieces(call).map((partial_json) => ({
type: 'content_block_delta',
index,
delta: { type: 'input_json_delta', partial_json },
})),
{ type: 'content_block_stop', index },
);
});
events.push(
{
type: 'message_delta',
delta: { stop_reason: 'tool_use', stop_sequence: null },
usage: { output_tokens: 5 },
},
{ type: 'message_stop' },
);
return events.map((data) => ({ event: data.type as string, data }));
};