UNPKG

@assistant-ui/react

Version:

Typescript/React library for AI Chat

1 lines 3.93 kB
{"version":3,"sources":["../../../../src/runtimes/edge/streams/toolResultStream.ts"],"sourcesContent":["import { Tool } from \"../../../model-context/ModelContextTypes\";\nimport { z } from \"zod\";\nimport { AssistantMessage, ToolExecutionStream } from \"assistant-stream\";\nimport { ToolResponse } from \"assistant-stream\";\n\nfunction getToolResponse(\n tools: Record<string, Tool<any, any>> | undefined,\n abortSignal: AbortSignal,\n toolCall: {\n toolCallId: string;\n toolName: string;\n args: unknown;\n },\n) {\n const tool = tools?.[toolCall.toolName];\n if (!tool || !tool.execute) return undefined;\n\n let executeFn = tool.execute;\n\n if (tool.parameters instanceof z.ZodType) {\n const result = tool.parameters.safeParse(toolCall.args);\n if (!result.success) {\n executeFn =\n tool.experimental_onSchemaValidationError ??\n (() => {\n throw new Error(\n `Function parameter validation failed. ${JSON.stringify(result.error.issues)}`,\n );\n });\n }\n }\n\n const getResult = async () => {\n const result = await executeFn(toolCall.args, {\n toolCallId: toolCall.toolCallId,\n abortSignal,\n });\n if (result instanceof ToolResponse) return result;\n return new ToolResponse({\n result: result === undefined ? \"<no result>\" : result,\n });\n };\n\n return getResult();\n}\n\nexport async function unstable_runPendingTools(\n message: AssistantMessage,\n tools: Record<string, Tool<any, any>> | undefined,\n abortSignal: AbortSignal,\n) {\n // TODO parallel tool calling\n for (const part of message.parts) {\n if (part.type === \"tool-call\") {\n const promiseOrUndefined = getToolResponse(tools, abortSignal, part);\n if (promiseOrUndefined) {\n const result = await promiseOrUndefined;\n const updatedParts = message.parts.map((p) => {\n if (p.type === \"tool-call\" && p.toolCallId === part.toolCallId) {\n return {\n ...p,\n state: \"result\" as const,\n artifact: result.artifact,\n result: result.result,\n isError: result.isError,\n };\n }\n return p;\n });\n message = {\n ...message,\n parts: updatedParts,\n content: updatedParts,\n };\n }\n }\n }\n return message;\n}\n\nexport function toolResultStream(\n tools: Record<string, Tool<any, any>> | undefined,\n abortSignal: AbortSignal,\n)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