UNPKG

@copilotkit/react-core

Version:

<img src="https://github.com/user-attachments/assets/0a6b64d9-e193-4940-a3f6-60334ac34084" alt="banner" style="border-radius: 12px; border: 2px solid #d6d4fa;" />

1 lines 9.69 kB
{"version":3,"sources":["../src/hooks/use-copilot-action.ts"],"sourcesContent":["/**\n * Example usage of useCopilotAction with complex parameters:\n *\n * @example\n * useCopilotAction({\n * name: \"myAction\",\n * parameters: [\n * { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n * { name: \"arg2\", type: \"number\" },\n * {\n * name: \"arg3\",\n * type: \"object\",\n * attributes: [\n * { name: \"nestedArg1\", type: \"boolean\" },\n * { name: \"xyz\", required: false },\n * ],\n * },\n * { name: \"arg4\", type: \"number[]\" },\n * ],\n * handler: ({ arg1, arg2, arg3, arg4 }) => {\n * const x = arg3.nestedArg1;\n * const z = arg3.xyz;\n * console.log(arg1, arg2, arg3);\n * },\n * });\n *\n * @example\n * // Simple action without parameters\n * useCopilotAction({\n * name: \"myAction\",\n * handler: () => {\n * console.log(\"No parameters provided.\");\n * },\n * });\n *\n * @example\n * // Interactive action with UI rendering and response handling\n * useCopilotAction({\n * name: \"handleMeeting\",\n * description: \"Handle a meeting by booking or canceling\",\n * parameters: [\n * {\n * name: \"meeting\",\n * type: \"string\",\n * description: \"The meeting to handle\",\n * required: true,\n * },\n * {\n * name: \"date\",\n * type: \"string\",\n * description: \"The date of the meeting\",\n * required: true,\n * },\n * {\n * name: \"title\",\n * type: \"string\",\n * description: \"The title of the meeting\",\n * required: true,\n * },\n * ],\n * renderAndWaitForResponse: ({ args, respond, status }) => {\n * const { meeting, date, title } = args;\n * return (\n * <MeetingConfirmationDialog\n * meeting={meeting}\n * date={date}\n * title={title}\n * onConfirm={() => respond('meeting confirmed')}\n * onCancel={() => respond('meeting canceled')}\n * />\n * );\n * },\n * });\n *\n * @example\n * // Catch all action allows you to render actions that are not defined in the frontend\n * useCopilotAction({\n * name: \"*\",\n * render: ({ name, args, status, result, handler, respond }) => {\n * return <div>Rendering action: {name}</div>;\n * },\n * });\n */\n\n/**\n * <img src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-action/useCopilotAction.gif\" width=\"500\" />\n * `useCopilotAction` is a React hook that you can use in your application to provide\n * custom actions that can be called by the AI. Essentially, it allows the Copilot to\n * execute these actions contextually during a chat, based on the user's interactions\n * and needs.\n *\n * Here's how it works:\n *\n * Use `useCopilotAction` to set up actions that the Copilot can call. To provide\n * more context to the Copilot, you can provide it with a `description` (for example to explain\n * what the action does, under which conditions it can be called, etc.).\n *\n * Then you define the parameters of the action, which can be simple, e.g. primitives like strings or numbers,\n * or complex, e.g. objects or arrays.\n *\n * Finally, you provide a `handler` function that receives the parameters and returns a result.\n * CopilotKit takes care of automatically inferring the parameter types, so you get type safety\n * and autocompletion for free.\n *\n * To render a custom UI for the action, you can provide a `render()` function. This function\n * lets you render a custom component or return a string to display.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * useCopilotAction({\n * name: \"sayHello\",\n * description: \"Say hello to someone.\",\n * parameters: [\n * {\n * name: \"name\",\n * type: \"string\",\n * description: \"name of the person to say greet\",\n * },\n * ],\n * handler: async ({ name }) => {\n * alert(`Hello, ${name}!`);\n * },\n * });\n * ```\n *\n * ## Generative UI\n *\n * This hooks enables you to dynamically generate UI elements and render them in the copilot chat. For more information, check out the [Generative UI](/guides/generative-ui) page.\n */\nimport { useEffect, useRef, useState } from \"react\";\nimport { Parameter } from \"@copilotkit/shared\";\nimport { CatchAllFrontendAction, FrontendAction } from \"../types/frontend-action\";\nimport { useFrontendTool, UseFrontendToolArgs } from \"./use-frontend-tool\";\nimport { useRenderToolCall, UseRenderToolCallArgs } from \"./use-render-tool-call\";\nimport { useHumanInTheLoop, UseHumanInTheLoopArgs } from \"./use-human-in-the-loop\";\nimport { useCopilotContext } from \"../context\";\n\n// Helper to determine which component and action config to use\nfunction getActionConfig<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n) {\n if (action.name === \"*\") {\n return {\n type: \"render\" as const,\n action: action as UseRenderToolCallArgs<T>,\n };\n }\n\n if (\"renderAndWaitForResponse\" in action || \"renderAndWait\" in action) {\n let render = action.render;\n if (!render && \"renderAndWaitForResponse\" in action) {\n // @ts-expect-error -- renderAndWaitForResponse is deprecated, but we need to support it for backwards compatibility\n render = action.renderAndWaitForResponse;\n }\n if (!render && \"renderAndWait\" in action) {\n // @ts-expect-error -- renderAndWait is deprecated, but we need to support it for backwards compatibility\n render = action.renderAndWait;\n }\n\n return {\n type: \"hitl\" as const,\n action: { ...action, render } as UseHumanInTheLoopArgs<T>,\n };\n }\n\n if (\"available\" in action) {\n if (action.available === \"enabled\" || action.available === \"remote\") {\n return {\n type: \"frontend\" as const,\n action: action as UseFrontendToolArgs<T>,\n };\n }\n if (action.available === \"frontend\" || action.available === \"disabled\") {\n return {\n type: \"render\" as const,\n action: action as UseRenderToolCallArgs<T>,\n };\n }\n }\n\n if (\"handler\" in action) {\n return {\n type: \"frontend\" as const,\n action: action as UseFrontendToolArgs<T>,\n };\n }\n\n throw new Error(\"Invalid action configuration\");\n}\n\n/**\n * useCopilotAction is a legacy hook maintained for backwards compatibility.\n *\n * To avoid violating React's Rules of Hooks (which prohibit conditional hook calls),\n * we use a registration pattern:\n * 1. This hook registers the action configuration with the CopilotContext\n * 2. A renderer component in CopilotKit actually renders the appropriate hook wrapper\n * 3. React properly manages hook state since components are rendered, not conditionally called\n *\n * This allows action types to change between renders without corrupting React's hook state.\n */\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T> | CatchAllFrontendAction,\n dependencies?: any[],\n): void {\n const [initialActionConfig] = useState(getActionConfig(action));\n const currentActionConfig = getActionConfig(action);\n\n /**\n * Calling hooks conditionally violates React's Rules of Hooks. This rule exists because\n * React maintains the call stack for hooks like useEffect or useState, and conditionally\n * calling a hook would result in inconsistent call stacks between renders.\n *\n * Unfortunately, useCopilotAction _has_ to conditionally call a hook based on the\n * supplied parameters. In order to avoid breaking React's call stack tracking, while\n * breaking the Rule of Hooks, we use a ref to store the initial action configuration\n * and throw an error if the _configuration_ changes such that we would call a different hook.\n */\n if (initialActionConfig.type !== currentActionConfig.type) {\n throw new Error(\"Action configuration changed between renders\");\n }\n\n switch (currentActionConfig.type) {\n case \"render\":\n return useRenderToolCall(currentActionConfig.action, dependencies);\n case \"hitl\":\n return useHumanInTheLoop(currentActionConfig.action, dependencies);\n case \"frontend\":\n return useFrontendTool(currentActionConfig.action, dependencies);\n default:\n throw new Error(\"Invalid action configuration\");\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoIA,SAA4B,gBAAgB;AAS5C,SAAS,gBACP,QACA;AACA,MAAI,OAAO,SAAS,KAAK;AACvB,WAAO;AAAA,MACL,MAAM;AAAA,MACN;AAAA,IACF;AAAA,EACF;AAEA,MAAI,8BAA8B,UAAU,mBAAmB,QAAQ;AACrE,QAAI,SAAS,OAAO;AACpB,QAAI,CAAC,UAAU,8BAA8B,QAAQ;AAEnD,eAAS,OAAO;AAAA,IAClB;AACA,QAAI,CAAC,UAAU,mBAAmB,QAAQ;AAExC,eAAS,OAAO;AAAA,IAClB;AAEA,WAAO;AAAA,MACL,MAAM;AAAA,MACN,QAAQ,iCAAK,SAAL,EAAa,OAAO;AAAA,IAC9B;AAAA,EACF;AAEA,MAAI,eAAe,QAAQ;AACzB,QAAI,OAAO,cAAc,aAAa,OAAO,cAAc,UAAU;AACnE,aAAO;AAAA,QACL,MAAM;AAAA,QACN;AAAA,MACF;AAAA,IACF;AACA,QAAI,OAAO,cAAc,cAAc,OAAO,cAAc,YAAY;AACtE,aAAO;AAAA,QACL,MAAM;AAAA,QACN;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,MAAI,aAAa,QAAQ;AACvB,WAAO;AAAA,MACL,MAAM;AAAA,MACN;AAAA,IACF;AAAA,EACF;AAEA,QAAM,IAAI,MAAM,8BAA8B;AAChD;AAaO,SAAS,iBACd,QACA,cACM;AACN,QAAM,CAAC,mBAAmB,IAAI,SAAS,gBAAgB,MAAM,CAAC;AAC9D,QAAM,sBAAsB,gBAAgB,MAAM;AAYlD,MAAI,oBAAoB,SAAS,oBAAoB,MAAM;AACzD,UAAM,IAAI,MAAM,8CAA8C;AAAA,EAChE;AAEA,UAAQ,oBAAoB,MAAM;AAAA,IAChC,KAAK;AACH,aAAO,kBAAkB,oBAAoB,QAAQ,YAAY;AAAA,IACnE,KAAK;AACH,aAAO,kBAAkB,oBAAoB,QAAQ,YAAY;AAAA,IACnE,KAAK;AACH,aAAO,gBAAgB,oBAAoB,QAAQ,YAAY;AAAA,IACjE;AACE,YAAM,IAAI,MAAM,8BAA8B;AAAA,EAClD;AACF;","names":[]}