79 lines
2.2 KiB
JavaScript
79 lines
2.2 KiB
JavaScript
import { useCopilotKit } from "../providers/CopilotKitProvider.mjs";
|
|
import { defineToolCallRenderer } from "../types/defineToolCallRenderer.mjs";
|
|
import { useEffect } from "react";
|
|
|
|
//#region src/hooks/use-render-tool.tsx
|
|
const EMPTY_DEPS = [];
|
|
/**
|
|
* Registers a renderer entry in CopilotKit's `renderToolCalls` registry.
|
|
*
|
|
* Key behavior:
|
|
* - deduplicates by `agentId:name` (latest registration wins),
|
|
* - keeps renderer entries on cleanup so historical chat tool calls can still render,
|
|
* - refreshes registration when `deps` change.
|
|
*
|
|
* @typeParam S - Schema type describing tool call parameters.
|
|
* @param config - Renderer config for wildcard or named tools.
|
|
* @param deps - Optional dependencies to refresh registration.
|
|
*
|
|
* @example
|
|
* ```tsx
|
|
* useRenderTool(
|
|
* {
|
|
* name: "searchDocs",
|
|
* parameters: z.object({ query: z.string() }),
|
|
* render: ({ status, parameters, result }) => {
|
|
* if (status === "executing") return <div>Searching {parameters.query}</div>;
|
|
* if (status === "complete") return <div>{result}</div>;
|
|
* return <div>Preparing...</div>;
|
|
* },
|
|
* },
|
|
* [],
|
|
* );
|
|
* ```
|
|
*
|
|
* @example
|
|
* ```tsx
|
|
* useRenderTool(
|
|
* {
|
|
* name: "summarize",
|
|
* parameters: z.object({ text: z.string() }),
|
|
* agentId: "research-agent",
|
|
* render: ({ name, status }) => <div>{name}: {status}</div>,
|
|
* },
|
|
* [selectedAgentId],
|
|
* );
|
|
* ```
|
|
*/
|
|
function useRenderTool(config, deps) {
|
|
const { copilotkit } = useCopilotKit();
|
|
const extraDeps = deps ?? EMPTY_DEPS;
|
|
useEffect(() => {
|
|
const renderer = config.name === "*" && !config.parameters ? defineToolCallRenderer({
|
|
name: "*",
|
|
render: (props) => config.render({
|
|
...props,
|
|
parameters: props.args
|
|
}),
|
|
...config.agentId ? { agentId: config.agentId } : {}
|
|
}) : defineToolCallRenderer({
|
|
name: config.name,
|
|
args: config.parameters,
|
|
render: (props) => config.render({
|
|
...props,
|
|
parameters: props.args
|
|
}),
|
|
...config.agentId ? { agentId: config.agentId } : {}
|
|
});
|
|
copilotkit.addHookRenderToolCall(renderer);
|
|
}, [
|
|
config.name,
|
|
copilotkit,
|
|
extraDeps.length,
|
|
...extraDeps
|
|
]);
|
|
}
|
|
|
|
//#endregion
|
|
export { useRenderTool };
|
|
//# sourceMappingURL=use-render-tool.mjs.map
|