UNPKG

@assistant-ui/react

Version:

Typescript/React library for AI Chat

68 lines 2.13 kB
// src/runtimes/edge/streams/toolResultStream.ts import { z } from "zod"; import { ToolExecutionStream } from "assistant-stream"; import { ToolResponse } from "assistant-stream"; function getToolResponse(tools, abortSignal, toolCall) { const tool = tools?.[toolCall.toolName]; if (!tool || !tool.execute) return void 0; let executeFn = tool.execute; if (tool.parameters instanceof z.ZodType) { const result = tool.parameters.safeParse(toolCall.args); if (!result.success) { executeFn = tool.experimental_onSchemaValidationError ?? (() => { throw new Error( `Function parameter validation failed. ${JSON.stringify(result.error.issues)}` ); }); } } const getResult = async () => { const result = await executeFn(toolCall.args, { toolCallId: toolCall.toolCallId, abortSignal }); if (result instanceof ToolResponse) return result; return new ToolResponse({ result: result === void 0 ? "<no result>" : result }); }; return getResult(); } async function unstable_runPendingTools(message, tools, abortSignal) { for (const part of message.parts) { if (part.type === "tool-call") { const promiseOrUndefined = getToolResponse(tools, abortSignal, part); if (promiseOrUndefined) { const result = await promiseOrUndefined; const updatedParts = message.parts.map((p) => { if (p.type === "tool-call" && p.toolCallId === part.toolCallId) { return { ...p, state: "result", artifact: result.artifact, result: result.result, isError: result.isError }; } return p; }); message = { ...message, parts: updatedParts, content: updatedParts }; } } } return message; } function toolResultStream(tools, abortSignal) { return new ToolExecutionStream( (toolCall) => getToolResponse(tools, abortSignal, toolCall) ); } export { toolResultStream, unstable_runPendingTools }; //# sourceMappingURL=toolResultStream.mjs.map