@assistant-ui/react
Version:
React components for AI chat.
83 lines • 2.71 kB
JavaScript
// src/runtimes/edge/streams/toolResultStream.ts
import { z } from "zod";
import sjson from "secure-json-parse";
function toolResultStream(tools, abortSignal) {
const toolCallExecutions = /* @__PURE__ */ new Map();
return new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk);
const chunkType = chunk.type;
switch (chunkType) {
case "tool-call": {
const { toolCallId, toolCallType, toolName, args: argsText } = chunk;
const tool = tools?.[toolName];
if (!tool || !tool.execute) return;
const args = sjson.parse(argsText);
if (tool.parameters instanceof z.ZodType) {
const result = tool.parameters.safeParse(args);
if (!result.success) {
controller.enqueue({
type: "tool-result",
toolCallType,
toolCallId,
toolName,
result: "Function parameter validation failed. " + JSON.stringify(result.error.issues),
isError: true
});
return;
} else {
toolCallExecutions.set(
toolCallId,
(async () => {
if (!tool.execute) return;
try {
const result2 = await tool.execute(args, { abortSignal });
controller.enqueue({
type: "tool-result",
toolCallType,
toolCallId,
toolName,
result: result2
});
} catch (error) {
controller.enqueue({
type: "tool-result",
toolCallType,
toolCallId,
toolName,
result: "Error: " + error,
isError: true
});
} finally {
toolCallExecutions.delete(toolCallId);
}
})()
);
}
}
break;
}
// ignore other parts
case "text-delta":
case "tool-call-delta":
case "tool-result":
case "step-finish":
case "finish":
case "error":
case "response-metadata":
break;
default: {
const unhandledType = chunkType;
throw new Error(`Unhandled chunk type: ${unhandledType}`);
}
}
},
async flush() {
await Promise.all(toolCallExecutions.values());
}
});
}
export {
toolResultStream
};
//# sourceMappingURL=toolResultStream.mjs.map