@copilotkit/react-core 0.37.0 → 0.38.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/.turbo/turbo-build.log +187 -234
  2. package/CHANGELOG.md +12 -0
  3. package/dist/{chunk-HUKLBIUK.mjs → chunk-5CKW6KE7.mjs} +13 -22
  4. package/dist/chunk-5CKW6KE7.mjs.map +1 -0
  5. package/dist/{chunk-S5LWO5V3.mjs → chunk-7GPIOOXB.mjs} +2 -2
  6. package/dist/{chunk-LLU5URI5.mjs → chunk-DDHJCFFV.mjs} +18 -33
  7. package/dist/chunk-DDHJCFFV.mjs.map +1 -0
  8. package/dist/{chunk-SR4RW4CU.mjs → chunk-IQCLNCGL.mjs} +6 -6
  9. package/dist/chunk-IQCLNCGL.mjs.map +1 -0
  10. package/dist/{chunk-DY63PD22.mjs → chunk-K6EV2CNB.mjs} +4 -5
  11. package/dist/chunk-K6EV2CNB.mjs.map +1 -0
  12. package/dist/{chunk-NSUYO6TP.mjs → chunk-LZVHW3T3.mjs} +9 -9
  13. package/dist/chunk-LZVHW3T3.mjs.map +1 -0
  14. package/dist/{chunk-Z5FB4WBL.mjs → chunk-NY6QSOU7.mjs} +43 -40
  15. package/dist/chunk-NY6QSOU7.mjs.map +1 -0
  16. package/dist/chunk-PHMHNAYC.mjs +192 -0
  17. package/dist/chunk-PHMHNAYC.mjs.map +1 -0
  18. package/dist/{chunk-B244LK6F.mjs → chunk-QNJQKKD4.mjs} +2 -2
  19. package/dist/{chunk-4OIVQMEM.mjs → chunk-WU3I3G3G.mjs} +60 -42
  20. package/dist/chunk-WU3I3G3G.mjs.map +1 -0
  21. package/dist/chunk-YJLRG5U3.mjs +1 -0
  22. package/dist/{chunk-MNZXQ6UH.mjs → chunk-YM2JV2YQ.mjs} +2 -2
  23. package/dist/components/copilot-provider/copilotkit-props.d.ts +2 -2
  24. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  25. package/dist/components/copilot-provider/copilotkit.js +18 -33
  26. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  27. package/dist/components/copilot-provider/copilotkit.mjs +2 -2
  28. package/dist/components/copilot-provider/index.js +18 -33
  29. package/dist/components/copilot-provider/index.js.map +1 -1
  30. package/dist/components/copilot-provider/index.mjs +2 -2
  31. package/dist/components/index.js +18 -33
  32. package/dist/components/index.js.map +1 -1
  33. package/dist/components/index.mjs +2 -2
  34. package/dist/context/copilot-context.d.ts +7 -18
  35. package/dist/context/copilot-context.js +3 -4
  36. package/dist/context/copilot-context.js.map +1 -1
  37. package/dist/context/copilot-context.mjs +1 -1
  38. package/dist/context/index.d.ts +1 -0
  39. package/dist/context/index.js +3 -4
  40. package/dist/context/index.js.map +1 -1
  41. package/dist/context/index.mjs +1 -1
  42. package/dist/hooks/index.d.ts +2 -1
  43. package/dist/hooks/index.js +140 -229
  44. package/dist/hooks/index.js.map +1 -1
  45. package/dist/hooks/index.mjs +9 -10
  46. package/dist/hooks/use-chat.d.ts +25 -51
  47. package/dist/hooks/use-chat.js +109 -203
  48. package/dist/hooks/use-chat.js.map +1 -1
  49. package/dist/hooks/use-chat.mjs +1 -2
  50. package/dist/hooks/use-copilot-action.js +10 -11
  51. package/dist/hooks/use-copilot-action.js.map +1 -1
  52. package/dist/hooks/use-copilot-action.mjs +2 -2
  53. package/dist/hooks/use-copilot-chat.d.ts +1 -1
  54. package/dist/hooks/use-copilot-chat.js +123 -212
  55. package/dist/hooks/use-copilot-chat.js.map +1 -1
  56. package/dist/hooks/use-copilot-chat.mjs +4 -5
  57. package/dist/hooks/use-copilot-readable.js +3 -4
  58. package/dist/hooks/use-copilot-readable.js.map +1 -1
  59. package/dist/hooks/use-copilot-readable.mjs +2 -2
  60. package/dist/hooks/use-make-copilot-actionable.js +7 -8
  61. package/dist/hooks/use-make-copilot-actionable.js.map +1 -1
  62. package/dist/hooks/use-make-copilot-actionable.mjs +2 -2
  63. package/dist/hooks/use-make-copilot-document-readable.js +3 -4
  64. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  65. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  66. package/dist/hooks/use-make-copilot-readable.js +3 -4
  67. package/dist/hooks/use-make-copilot-readable.js.map +1 -1
  68. package/dist/hooks/use-make-copilot-readable.mjs +2 -2
  69. package/dist/index.d.ts +1 -3
  70. package/dist/index.js +239 -497
  71. package/dist/index.js.map +1 -1
  72. package/dist/index.mjs +12 -31
  73. package/dist/lib/copilot-task.d.ts +1 -0
  74. package/dist/lib/copilot-task.js +34 -110
  75. package/dist/lib/copilot-task.js.map +1 -1
  76. package/dist/lib/copilot-task.mjs +3 -4
  77. package/dist/lib/index.d.ts +1 -0
  78. package/dist/lib/index.js +36 -110
  79. package/dist/lib/index.js.map +1 -1
  80. package/dist/lib/index.mjs +3 -4
  81. package/dist/utils/extract.d.ts +1 -0
  82. package/dist/utils/extract.js +53 -109
  83. package/dist/utils/extract.js.map +1 -1
  84. package/dist/utils/extract.mjs +3 -4
  85. package/dist/utils/index.d.ts +1 -1
  86. package/dist/utils/index.js +56 -132
  87. package/dist/utils/index.js.map +1 -1
  88. package/dist/utils/index.mjs +5 -13
  89. package/package.json +6 -5
  90. package/src/components/copilot-provider/copilotkit-props.tsx +2 -2
  91. package/src/components/copilot-provider/copilotkit.tsx +16 -37
  92. package/src/context/copilot-context.tsx +11 -30
  93. package/src/hooks/use-chat.ts +179 -208
  94. package/src/hooks/use-copilot-action.ts +7 -8
  95. package/src/hooks/use-copilot-chat.ts +9 -23
  96. package/src/hooks/use-make-copilot-actionable.ts +4 -4
  97. package/src/index.tsx +0 -1
  98. package/src/lib/copilot-task.ts +45 -42
  99. package/src/utils/extract.ts +64 -36
  100. package/src/utils/index.ts +0 -7
  101. package/dist/chunk-2EQGN5QK.mjs +0 -137
  102. package/dist/chunk-2EQGN5QK.mjs.map +0 -1
  103. package/dist/chunk-4OIVQMEM.mjs.map +0 -1
  104. package/dist/chunk-7GFKOIO7.mjs +0 -1
  105. package/dist/chunk-B2H3NC4E.mjs +0 -204
  106. package/dist/chunk-B2H3NC4E.mjs.map +0 -1
  107. package/dist/chunk-BABVSMJR.mjs +0 -1
  108. package/dist/chunk-BABVSMJR.mjs.map +0 -1
  109. package/dist/chunk-CYDWEPFL.mjs +0 -1
  110. package/dist/chunk-CYDWEPFL.mjs.map +0 -1
  111. package/dist/chunk-DY63PD22.mjs.map +0 -1
  112. package/dist/chunk-FRAKUJWH.mjs +0 -1
  113. package/dist/chunk-FRAKUJWH.mjs.map +0 -1
  114. package/dist/chunk-HUKLBIUK.mjs.map +0 -1
  115. package/dist/chunk-LLU5URI5.mjs.map +0 -1
  116. package/dist/chunk-MJKBCG4U.mjs +0 -91
  117. package/dist/chunk-MJKBCG4U.mjs.map +0 -1
  118. package/dist/chunk-NSUYO6TP.mjs.map +0 -1
  119. package/dist/chunk-SR4RW4CU.mjs.map +0 -1
  120. package/dist/chunk-Z5FB4WBL.mjs.map +0 -1
  121. package/dist/chunk-ZFS5SQUT.mjs +0 -31
  122. package/dist/chunk-ZFS5SQUT.mjs.map +0 -1
  123. package/dist/openai-assistants/hooks/index.d.ts +0 -2
  124. package/dist/openai-assistants/hooks/index.js +0 -277
  125. package/dist/openai-assistants/hooks/index.js.map +0 -1
  126. package/dist/openai-assistants/hooks/index.mjs +0 -18
  127. package/dist/openai-assistants/hooks/index.mjs.map +0 -1
  128. package/dist/openai-assistants/hooks/use-assistants.d.ts +0 -17
  129. package/dist/openai-assistants/hooks/use-assistants.js +0 -154
  130. package/dist/openai-assistants/hooks/use-assistants.js.map +0 -1
  131. package/dist/openai-assistants/hooks/use-assistants.mjs +0 -92
  132. package/dist/openai-assistants/hooks/use-assistants.mjs.map +0 -1
  133. package/dist/openai-assistants/hooks/use-copilot-chat-v2.d.ts +0 -44
  134. package/dist/openai-assistants/hooks/use-copilot-chat-v2.js +0 -277
  135. package/dist/openai-assistants/hooks/use-copilot-chat-v2.js.map +0 -1
  136. package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs +0 -19
  137. package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs.map +0 -1
  138. package/dist/openai-assistants/index.d.ts +0 -3
  139. package/dist/openai-assistants/index.js +0 -279
  140. package/dist/openai-assistants/index.js.map +0 -1
  141. package/dist/openai-assistants/index.mjs +0 -22
  142. package/dist/openai-assistants/index.mjs.map +0 -1
  143. package/dist/openai-assistants/utils/index.d.ts +0 -1
  144. package/dist/openai-assistants/utils/index.js +0 -73
  145. package/dist/openai-assistants/utils/index.js.map +0 -1
  146. package/dist/openai-assistants/utils/index.mjs +0 -9
  147. package/dist/openai-assistants/utils/index.mjs.map +0 -1
  148. package/dist/openai-assistants/utils/process-message-stream.d.ts +0 -3
  149. package/dist/openai-assistants/utils/process-message-stream.js +0 -71
  150. package/dist/openai-assistants/utils/process-message-stream.js.map +0 -1
  151. package/dist/openai-assistants/utils/process-message-stream.mjs +0 -8
  152. package/dist/openai-assistants/utils/process-message-stream.mjs.map +0 -1
  153. package/dist/utils/fetch-chat-completion.d.ts +0 -36
  154. package/dist/utils/fetch-chat-completion.js +0 -141
  155. package/dist/utils/fetch-chat-completion.js.map +0 -1
  156. package/dist/utils/fetch-chat-completion.mjs +0 -12
  157. package/dist/utils/fetch-chat-completion.mjs.map +0 -1
  158. package/src/openai-assistants/hooks/index.ts +0 -9
  159. package/src/openai-assistants/hooks/use-assistants.ts +0 -112
  160. package/src/openai-assistants/hooks/use-copilot-chat-v2.ts +0 -189
  161. package/src/openai-assistants/index.ts +0 -2
  162. package/src/openai-assistants/utils/index.ts +0 -1
  163. package/src/openai-assistants/utils/process-message-stream.ts +0 -25
  164. package/src/utils/fetch-chat-completion.ts +0 -120
  165. /package/dist/{chunk-S5LWO5V3.mjs.map → chunk-7GPIOOXB.mjs.map} +0 -0
  166. /package/dist/{chunk-B244LK6F.mjs.map → chunk-QNJQKKD4.mjs.map} +0 -0
  167. /package/dist/{chunk-7GFKOIO7.mjs.map → chunk-YJLRG5U3.mjs.map} +0 -0
  168. /package/dist/{chunk-MNZXQ6UH.mjs.map → chunk-YM2JV2YQ.mjs.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/index.ts","../../src/hooks/use-copilot-chat.ts","../../src/context/copilot-context.tsx","../../src/hooks/use-chat.ts","../../src/utils/fetch-chat-completion.ts","../../src/components/copilot-provider/copilotkit.tsx","../../src/hooks/use-make-copilot-actionable.ts","../../src/hooks/use-copilot-action.ts","../../src/hooks/use-make-copilot-readable.ts","../../src/hooks/use-make-copilot-document-readable.ts","../../src/hooks/use-copilot-readable.ts"],"sourcesContent":["export { useCopilotChat } from \"./use-copilot-chat\";\nexport type { UseCopilotChatOptions } from \"./use-copilot-chat\";\nexport type { UseCopilotChatReturn } from \"./use-copilot-chat\";\n\nexport { useMakeCopilotActionable } from \"./use-make-copilot-actionable\";\nexport { useCopilotAction } from \"./use-copilot-action\";\nexport { useMakeCopilotReadable } from \"./use-make-copilot-readable\";\nexport { useMakeCopilotDocumentReadable } from \"./use-make-copilot-document-readable\";\nexport { type UseChatHelpers } from \"./use-chat\";\nexport { useCopilotReadable } from \"./use-copilot-readable\";\n","/**\n * A hook for accessing Copilot's chat API.\n *\n * `useCopilotChat` is a React hook that lets you directly interact with the\n * Copilot instance. Use to implement a fully custom UI (headless UI) or to\n * programmatically interact with the Copilot instance managed by the default\n * UI.\n *\n * <RequestExample>\n * ```jsx useCopilotChat Example\n * import { useCopilotChat }\n * from \"@copilotkit/react-core\";\n *\n * const { appendMessage } = useCopilotChat();\n * appendMessage({ content: \"Hello, world!\", role: \"user\", id: \"1\" });\n * ```\n * </RequestExample>\n *\n * useCopilotChat returns an object with the following properties:\n * - `visibleMessages`: An array of messages that are currently visible in the chat.\n * - `appendMessage`: A function to append a message to the chat.\n * - `setMessages`: A function to set the messages in the chat.\n * - `deleteMessage`: A function to delete a message from the chat.\n * - `reloadMessages`: A function to reload the messages from the API.\n * - `stopGeneration`: A function to stop the generation of the next message.\n * - `isLoading`: A boolean indicating if the chat is loading.\n *\n */\nimport { useMemo, useContext, useRef, useEffect, useCallback } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { Message, ToolDefinition } from \"@copilotkit/shared\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useChat } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\n\nexport interface UseCopilotChatOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * Extra body object to be sent with the API request.\n * @example\n * Send a `sessionId` to the API along with the messages.\n * ```js\n * useChat({\n * body: {\n * sessionId: '123',\n * }\n * })\n * ```\n */\n body?: object;\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n}\n\nexport interface UseCopilotChatReturn {\n visibleMessages: Message[];\n appendMessage: (message: Message) => Promise<void>;\n setMessages: (messages: Message[]) => void;\n deleteMessage: (messageId: string) => void;\n reloadMessages: () => Promise<void>;\n stopGeneration: () => void;\n isLoading: boolean;\n}\n\nexport function useCopilotChat({\n makeSystemMessage,\n ...options\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const {\n getContextString,\n getChatCompletionFunctionDescriptions,\n getFunctionCallHandler,\n copilotApiConfig,\n messages,\n setMessages,\n isLoading,\n setIsLoading,\n chatInstructions,\n } = useContext(CopilotContext);\n\n // We need to ensure that makeSystemMessageCallback always uses the latest\n // useCopilotReadable data.\n const latestGetContextString = useUpdatedRef(getContextString);\n const deleteMessage = useCallback(\n (messageId: string) => {\n setMessages((prev) => prev.filter((message) => message.id !== messageId));\n },\n [setMessages],\n );\n\n const makeSystemMessageCallback = useCallback(() => {\n const systemMessageMaker = makeSystemMessage || defaultSystemMessage;\n // this always gets the latest context string\n const contextString = latestGetContextString.current([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return {\n id: \"system\",\n content: systemMessageMaker(contextString, chatInstructions),\n role: \"system\",\n } as Message;\n }, [getContextString, makeSystemMessage, chatInstructions]);\n\n const functionDescriptions: ToolDefinition[] = useMemo(() => {\n return getChatCompletionFunctionDescriptions();\n }, [getChatCompletionFunctionDescriptions]);\n\n const { append, reload, stop } = useChat({\n ...options,\n copilotConfig: copilotApiConfig,\n id: options.id,\n initialMessages: options.initialMessages || [],\n tools: functionDescriptions,\n onFunctionCall: getFunctionCallHandler(),\n headers: { ...options.headers },\n body: {\n ...options.body,\n },\n messages,\n setMessages,\n makeSystemMessageCallback,\n isLoading,\n setIsLoading,\n });\n\n const visibleMessages = messages.filter(\n (message) =>\n message.role === \"user\" || message.role === \"assistant\" || message.role === \"function\",\n );\n\n return {\n visibleMessages,\n appendMessage: append,\n setMessages,\n reloadMessages: reload,\n stopGeneration: stop,\n deleteMessage,\n isLoading,\n };\n}\n\n// store `value` in a ref and update\n// it whenever it changes.\nfunction useUpdatedRef<T>(value: T) {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref;\n}\n\nexport function defaultSystemMessage(\n contextString: string,\n additionalInstructions?: string,\n): string {\n return (\n `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n","import {\n CopilotCloudConfig,\n FunctionCallHandler,\n Message,\n ToolDefinition,\n} from \"@copilotkit/shared\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * The endpoint for the chat API v2.\n */\n chatApiEndpointV2: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Additional body params to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'message': 'Hello, world!'\n * }\n * ```\n */\n body: Record<string, any>;\n\n /**\n * Backend only props that will be combined to body params to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n backendOnlyProps?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n}\n\nexport type InChatRenderFunction = (props: ActionRenderProps<any>) => string | JSX.Element;\n\nexport interface CopilotContextParams {\n // function-calling\n entryPoints: Record<string, FrontendAction<any>>;\n setEntryPoint: (id: string, entryPoint: FrontendAction<any>) => void;\n removeEntryPoint: (id: string) => void;\n chatComponentsCache: React.RefObject<Record<string, InChatRenderFunction | string>>;\n getChatCompletionFunctionDescriptions: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => ToolDefinition[];\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n // chat\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n entryPoints: {},\n setEntryPoint: () => {},\n removeEntryPoint: () => {},\n\n chatComponentsCache: { current: {} },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n\n getChatCompletionFunctionDescriptions: () => returnAndThrowInDebug([]),\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n messages: [],\n setMessages: () => returnAndThrowInDebug([]),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n get chatApiEndpointV2(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n return React.useContext(CopilotContext);\n}\n\nfunction returnAndThrowInDebug<T>(value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n return value;\n}\n","import { useRef, useState, useContext, useEffect } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport {\n Message,\n ToolDefinition,\n FunctionCallHandler,\n encodeResult,\n FunctionCall,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n} from \"@copilotkit/shared\";\n\nimport { nanoid } from \"nanoid\";\nimport { fetchAndDecodeChatCompletion } from \"../utils/fetch-chat-completion\";\nimport { CopilotApiConfig } from \"../context\";\nimport untruncateJson from \"untruncate-json\";\n\nexport type UseChatOptions = {\n /**\n * The API endpoint that accepts a `{ messages: Message[] }` object and returns\n * a stream of tokens of the AI chat response. Defaults to `/api/chat`.\n */\n api?: string;\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n /**\n * Callback function to be called when a function call is received.\n * If the function returns a `ChatRequest` object, the request will be sent\n * automatically to the API and will be used to update the chat.\n */\n onFunctionCall?: FunctionCallHandler;\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n /**\n * Extra body object to be sent with the API request.\n * @example\n * Send a `sessionId` to the API along with the messages.\n * ```js\n * useChat({\n * body: {\n * sessionId: '123',\n * }\n * })\n * ```\n */\n body?: object;\n /**\n * Function definitions to be sent to the API.\n */\n tools?: ToolDefinition[];\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: () => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n};\n\nexport type UseChatOptionsWithCopilotConfig = UseChatOptions & {\n copilotConfig: CopilotApiConfig;\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * A callback to get the latest system message.\n */\n makeSystemMessageCallback: () => Message;\n\n /**\n * Whether the API request is in progress\n */\n isLoading: boolean;\n\n /**\n * setState-powered method to update the isChatLoading value\n */\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n};\n\nexport function useChat(options: UseChatOptionsWithCopilotConfig): UseChatHelpers {\n const { messages, setMessages, makeSystemMessageCallback } = options;\n const abortControllerRef = useRef<AbortController>();\n const threadIdRef = useRef<string | null>(null);\n const runIdRef = useRef<string | null>(null);\n const publicApiKey = options.copilotConfig.publicApiKey;\n const headers = {\n ...(options.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const runChatCompletion = async (messages: Message[]): Promise<Message[]> => {\n options.setIsLoading(true);\n\n const newMessages: Message[] = [\n {\n id: nanoid(),\n createdAt: new Date(),\n content: \"\",\n role: \"assistant\",\n },\n ];\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setMessages([...messages, ...newMessages]);\n // add threadId and runId to the body if it exists\n const copilotConfigBody = options.copilotConfig.body || {};\n if (threadIdRef.current) {\n copilotConfigBody.threadId = threadIdRef.current;\n }\n if (runIdRef.current) {\n copilotConfigBody.runId = runIdRef.current;\n }\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(options.initialMessages || []), ...messages];\n const response = await fetchAndDecodeChatCompletion({\n copilotConfig: { ...options.copilotConfig, body: copilotConfigBody },\n messages: messagesWithContext,\n tools: options.tools,\n headers: headers,\n signal: abortController.signal,\n });\n\n if (response.headers.get(\"threadid\")) {\n threadIdRef.current = response.headers.get(\"threadid\");\n }\n\n if (response.headers.get(\"runid\")) {\n runIdRef.current = response.headers.get(\"runid\");\n }\n\n if (!response.events) {\n setMessages([\n ...messages,\n {\n id: nanoid(),\n createdAt: new Date(),\n content: response.statusText,\n role: \"assistant\",\n },\n ]);\n options.setIsLoading(false);\n throw new Error(\"Failed to fetch chat completion\");\n }\n\n const reader = response.events.getReader();\n\n // Whether to feed back the new messages to GPT\n let feedback = false;\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n let currentMessage = Object.assign({}, newMessages[newMessages.length - 1]);\n\n if (value.type === \"content\") {\n if (currentMessage.function_call || currentMessage.role === \"function\") {\n // Create a new message if the previous one is a function call or result\n currentMessage = {\n id: nanoid(),\n createdAt: new Date(),\n content: \"\",\n role: \"assistant\",\n };\n newMessages.push(currentMessage);\n }\n currentMessage.content += value.content;\n newMessages[newMessages.length - 1] = currentMessage;\n setMessages([...messages, ...newMessages]);\n } else if (value.type === \"result\") {\n // When we get a result message, it is already complete\n currentMessage = {\n id: nanoid(),\n role: \"function\",\n content: value.content,\n name: value.name,\n };\n newMessages.push(currentMessage);\n setMessages([...messages, ...newMessages]);\n\n // After receiving a result, feed back the new messages to GPT\n feedback = true;\n } else if (value.type === \"function\" || value.type === \"partial\") {\n // Create a new message if the previous one is not empty\n if (\n currentMessage.content != \"\" ||\n currentMessage.function_call ||\n currentMessage.role == \"function\"\n ) {\n currentMessage = {\n id: nanoid(),\n createdAt: new Date(),\n content: \"\",\n role: \"assistant\",\n };\n newMessages.push(currentMessage);\n }\n if (value.type === \"function\") {\n currentMessage.function_call = {\n name: value.name,\n arguments: JSON.stringify(value.arguments),\n scope: value.scope,\n };\n } else if (value.type === \"partial\") {\n let partialArguments: any = {};\n try {\n partialArguments = JSON.parse(untruncateJson(value.arguments));\n } catch (e) {}\n\n currentMessage.partialFunctionCall = {\n name: value.name,\n arguments: partialArguments,\n };\n }\n\n newMessages[newMessages.length - 1] = currentMessage;\n setMessages([...messages, ...newMessages]);\n\n if (value.type === \"function\") {\n // Execute the function call\n try {\n if (options.onFunctionCall && value.scope === \"client\") {\n const result = await options.onFunctionCall(\n messages,\n currentMessage.function_call as FunctionCall,\n );\n\n currentMessage = {\n id: nanoid(),\n role: \"function\",\n content: encodeResult(result),\n name: (currentMessage.function_call! as FunctionCall).name!,\n };\n newMessages.push(currentMessage);\n setMessages([...messages, ...newMessages]);\n\n // After a function call, feed back the new messages to GPT\n feedback = true;\n }\n } catch (error) {\n console.error(\"Failed to execute function call\", error);\n // TODO: Handle error\n // this should go to the message itself\n }\n }\n }\n }\n\n // If we want feedback, run the completion again and return the results\n if (feedback) {\n // wait for next tick to make sure all the react state updates\n // TODO: This is a hack, is there a more robust way to do this?\n // - tried using react-dom's flushSync, but it did not work\n await new Promise((resolve) => setTimeout(resolve, 10));\n\n return await runChatCompletion([...messages, ...newMessages]);\n }\n // otherwise, return the new messages\n else {\n return newMessages.slice();\n }\n } finally {\n options.setIsLoading(false);\n }\n };\n\n const runChatCompletionAndHandleFunctionCall = async (messages: Message[]): Promise<void> => {\n await runChatCompletion(messages);\n };\n\n const append = async (message: Message): Promise<void> => {\n if (options.isLoading) {\n return;\n }\n const newMessages = [...messages, message];\n setMessages(newMessages);\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const reload = async (): Promise<void> => {\n if (options.isLoading || messages.length === 0) {\n return;\n }\n let newMessages = [...messages];\n const lastMessage = messages[messages.length - 1];\n\n if (lastMessage.role === \"assistant\") {\n newMessages = newMessages.slice(0, -1);\n }\n setMessages(newMessages);\n\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const stop = (): void => {\n abortControllerRef.current?.abort();\n };\n\n return {\n append,\n reload,\n stop,\n };\n}\n","import {\n Message,\n ToolDefinition,\n ChatCompletionEvent,\n decodeChatCompletion,\n parseChatCompletion,\n decodeChatCompletionAsText,\n EXCLUDE_FROM_FORWARD_PROPS_KEYS,\n} from \"@copilotkit/shared\";\nimport { CopilotApiConfig } from \"../context\";\n\nexport interface FetchChatCompletionParams {\n copilotConfig: CopilotApiConfig;\n model?: string;\n messages: Message[];\n tools?: ToolDefinition[];\n temperature?: number;\n maxTokens?: number;\n headers?: Record<string, string> | Headers;\n body?: object;\n signal?: AbortSignal;\n toolChoice?: string | { type: \"function\"; function: { name: string } };\n}\n\nexport async function fetchChatCompletion({\n copilotConfig,\n model,\n messages,\n tools,\n temperature,\n headers,\n body,\n signal,\n toolChoice,\n}: FetchChatCompletionParams): Promise<Response> {\n temperature ||= 0.5;\n tools ||= [];\n\n // clean up any extra properties from messages\n const cleanedMessages = messages.map((message) => {\n const { content, role, name, function_call } = message;\n return { content, role, name, function_call };\n });\n\n toolChoice ||= \"auto\";\n\n const response = await fetch(copilotConfig.chatApiEndpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...copilotConfig.headers,\n ...(headers ? { ...headers } : {}),\n },\n body: JSON.stringify({\n model,\n messages: cleanedMessages,\n stream: true,\n ...(tools.length ? { tools } : {}),\n ...(temperature ? { temperature } : {}),\n ...(tools.length != 0 ? { tool_choice: toolChoice } : {}),\n ...copilotConfig.body,\n ...copilotConfig.backendOnlyProps,\n ...excludeBackendOnlyProps(copilotConfig),\n ...(body ? { ...body } : {}),\n ...(copilotConfig.cloud ? { cloud: copilotConfig.cloud } : {}),\n }),\n signal,\n credentials: copilotConfig.credentials,\n });\n\n return response;\n}\n\nfunction excludeBackendOnlyProps(copilotConfig: any) {\n const backendOnlyProps = copilotConfig.backendOnlyProps ?? {};\n if (Object.keys(backendOnlyProps).length > 0) {\n return {\n [EXCLUDE_FROM_FORWARD_PROPS_KEYS]: Object.keys(backendOnlyProps),\n };\n } else {\n return {};\n }\n}\n\nexport interface DecodedChatCompletionResponse extends Response {\n events: ReadableStream<ChatCompletionEvent> | null;\n}\n\nexport async function fetchAndDecodeChatCompletion(\n params: FetchChatCompletionParams,\n): Promise<DecodedChatCompletionResponse> {\n const response = await fetchChatCompletion(params);\n if (!response.ok || !response.body) {\n (response as any).events = null;\n } else {\n const events = await decodeChatCompletion(parseChatCompletion(response.body));\n (response as any).events = events;\n }\n return response as any;\n}\n\nexport interface DecodedChatCompletionResponseAsText extends Response {\n events: ReadableStream<string> | null;\n}\n\nexport async function fetchAndDecodeChatCompletionAsText(\n params: FetchChatCompletionParams,\n): Promise<DecodedChatCompletionResponseAsText> {\n const response = await fetchChatCompletion(params);\n if (!response.ok || !response.body) {\n (response as any).events = null;\n } else {\n const events = await decodeChatCompletionAsText(\n decodeChatCompletion(parseChatCompletion(response.body)),\n );\n (response as any).events = events;\n }\n\n return response as any;\n}\n","/**\n * Provides the Copilot context to its children.\n * \n * <img\n * referrerPolicy=\"no-referrer-when-downgrade\"\n * src=\"https://static.scarf.sh/a.png?x-pxid=a9b290bb-38f9-4518-ac3b-8f54fdbf43be\"\n * />\n * \n * This component provides the Copilot context to its children.\n * It can be configured either with a chat API endpoint or a `CopilotApiConfig`.\n * \n * <Note>\n * The backend can use OpenAI, or you can bring your own LLM. For examples of the\n * backend api implementation, see `examples/next-openai` or the [runtime\n * docs](https://docs.copilotkit.ai/getting-started/quickstart-runtime).\n * </Note>\n * \n * <RequestExample>\n * ```jsx CopilotKit Example\n * import { CopilotKit } from \"@copilotkit/react-core\";\n * \n * <CopilotKit \n * runtimeUrl=\"https://your.copilotkit.api\">\n * <YourApp/>\n * </CopilotKit>\n * ```\n * </RequestExample>\n * \n * ## Example usage\n * \n * ```jsx\n * <CopilotKit publicApiKey=\"the api key or self host (see below)\">\n * <App />\n * </CopilotKit>\n```\n */\nimport { Ref, useCallback, useRef, useState } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n InChatRenderFunction,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { CopilotChatSuggestionConfiguration, DocumentPointer } from \"../../types\";\n\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n Message,\n actionToChatCompletionFunction,\n} from \"@copilotkit/shared\";\n\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { ToolDefinition } from \"@copilotkit/shared\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n // Compute all the functions and properties that we need to pass\n // to the CopilotContext.\n\n if (!props.runtimeUrl && !props.url && !props.publicApiKey) {\n throw new Error(\"Please provide either a url or a publicApiKey to the CopilotKit component.\");\n }\n\n const chatApiEndpoint = props.runtimeUrl || props.url || COPILOT_CLOUD_CHAT_URL;\n\n const [entryPoints, setEntryPoints] = useState<Record<string, FrontendAction<any>>>({});\n const chatComponentsCache = useRef<Record<string, InChatRenderFunction | string>>({});\n const { addElement, removeElement, printTree } = useTree();\n const [messages, setMessages] = useState<Message[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n const setEntryPoint = useCallback((id: string, entryPoint: FrontendAction<any>) => {\n setEntryPoints((prevPoints) => {\n return {\n ...prevPoints,\n [id]: entryPoint,\n };\n });\n }, []);\n\n const removeEntryPoint = useCallback((id: string) => {\n setEntryPoints((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getChatCompletionFunctionDescriptions = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToChatCompletionFunctions(Object.values(customEntryPoints || entryPoints));\n },\n [entryPoints],\n );\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || entryPoints));\n },\n [entryPoints],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n if (!props.publicApiKey) {\n if (props.cloudRestrictToTopic) {\n throw new Error(\n \"To use the cloudRestrictToTopic feature, please sign up at https://copilotkit.ai and provide a publicApiKey.\",\n );\n }\n }\n\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (props.publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: props.cloudRestrictToTopic ? true : false,\n validTopics: props.cloudRestrictToTopic?.validTopics || [],\n invalidTopics: props.cloudRestrictToTopic?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = {\n publicApiKey: props.publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n chatApiEndpointV2: `${props.url}/v2`,\n headers: props.headers || {},\n body: {\n ...props.body,\n ...props.backendOnlyProps,\n },\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n };\n\n const removeChatSuggestionConfiguration = (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n };\n\n return (\n <CopilotContext.Provider\n value={{\n entryPoints,\n chatComponentsCache,\n getChatCompletionFunctionDescriptions,\n getFunctionCallHandler,\n setEntryPoint,\n removeEntryPoint,\n getContextString,\n addContext,\n removeContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n messages,\n setMessages,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n }}\n >\n {children}\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToChatCompletionFunctions(actions: FrontendAction<any>[]): ToolDefinition[] {\n return actions.map(actionToChatCompletionFunction);\n}\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async (chatMessages, functionCall) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[functionCall.name || \"\"];\n if (action) {\n let functionCallArguments: Record<string, any>[] = [];\n if (functionCall.arguments) {\n functionCallArguments = JSON.parse(functionCall.arguments);\n }\n return await action.handler(functionCallArguments);\n }\n };\n}\n","import { useRef, useContext, useEffect, useMemo } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { AnnotatedFunction } from \"@copilotkit/shared\";\nimport { nanoid } from \"nanoid\";\nimport { annotatedFunctionToAction } from \"@copilotkit/shared\";\n\n/**\n * @deprecated Use the useCopilotAction function instead.\n */\nexport function useMakeCopilotActionable<ActionInput extends any[]>(\n annotatedFunction: AnnotatedFunction<ActionInput>,\n dependencies: any[],\n) {\n const idRef = useRef(nanoid()); // generate a unique id\n const { setEntryPoint, removeEntryPoint } = useContext(CopilotContext);\n\n const memoizedAnnotatedFunction: AnnotatedFunction<ActionInput> = useMemo(\n () => ({\n name: annotatedFunction.name,\n description: annotatedFunction.description,\n argumentAnnotations: annotatedFunction.argumentAnnotations,\n implementation: annotatedFunction.implementation,\n }),\n dependencies,\n );\n\n useEffect(() => {\n const action = annotatedFunctionToAction(memoizedAnnotatedFunction as AnnotatedFunction<any[]>);\n setEntryPoint(idRef.current, action);\n\n return () => {\n removeEntryPoint(idRef.current);\n };\n }, [memoizedAnnotatedFunction, setEntryPoint, removeEntryPoint]);\n}\n","import { useRef, useContext, useEffect } from \"react\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { nanoid } from \"nanoid\";\nimport { Parameter } from \"@copilotkit/shared\";\n\n// We implement useCopilotAction dependency handling so that\n// the developer has the option to not provide any dependencies.\n// In this case, we assume they want to update the handler on each rerender.\n// To avoid getting stuck in an infinite loop, we update the handler directly,\n// skipping React state updates.\n// This is ok in this case, because the handler is not part of any UI that\n// needs to be updated.\n// useCallback, useMemo or other memoization techniques are not suitable here,\n// because they will cause a infinite rerender loop.\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { setEntryPoint, removeEntryPoint, entryPoints, chatComponentsCache } =\n useContext(CopilotContext);\n const idRef = useRef<string>(nanoid());\n\n // If the developer doesn't provide dependencies, we assume they want to\n // update handler and render function when the action object changes.\n // This ensures that any captured variables in the handler are up to date.\n if (dependencies === undefined) {\n if (entryPoints[idRef.current]) {\n entryPoints[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current[action.name] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n setEntryPoint(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current[action.name] = action.render;\n }\n return () => {\n // NOTE: For now, we don't remove the chatComponentsCache entry when the action is removed.\n // This is because we currently don't have access to the messages array in CopilotContext.\n removeEntryPoint(idRef.current);\n };\n }, [\n setEntryPoint,\n removeEntryPoint,\n action.description,\n action.name,\n // This should be faster than deep equality checking\n // In addition, all major JS engines guarantee the order of object keys\n JSON.stringify(action.parameters),\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n\n// Usage 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// useCopilotAction({\n// name: \"myAction\",\n// handler: () => {\n// console.log(\"No parameters provided.\");\n// },\n// });\n","import { useContext, useEffect, useRef } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\n\n/**\n * @deprecated Use the useCopilotReadable function instead.\n */\nexport function useMakeCopilotReadable(\n information: string,\n parentId?: string,\n categories?: string[],\n): string | undefined {\n const { addContext, removeContext } = useContext(CopilotContext);\n const idRef = useRef<string>();\n\n useEffect(() => {\n const id = addContext(information, parentId, categories);\n idRef.current = id;\n\n return () => {\n removeContext(id);\n };\n }, [information, parentId, addContext, removeContext]);\n\n return idRef.current;\n}\n","import { useContext, useEffect, useRef } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { DocumentPointer } from \"../types\";\n\n/**\n * Makes a document readable by Copilot.\n * @param document The document to make readable.\n * @param categories The categories to associate with the document.\n * @param dependencies The dependencies to use for the effect.\n * @returns The id of the document.\n */\nexport function useMakeCopilotDocumentReadable(\n document: DocumentPointer,\n categories?: string[],\n dependencies: any[] = [],\n): string | undefined {\n const { addDocumentContext, removeDocumentContext } = useContext(CopilotContext);\n const idRef = useRef<string>();\n\n useEffect(() => {\n const id = addDocumentContext(document, categories);\n idRef.current = id;\n\n return () => {\n removeDocumentContext(id);\n };\n }, [addDocumentContext, removeDocumentContext, ...dependencies]);\n\n return idRef.current;\n}\n","/**\n * A hook for providing app-state & other information to the Copilot.\n *\n * <img referrerPolicy=\"no-referrer-when-downgrade\" src=\"https://static.scarf.sh/a.png?x-pxid=a9b290bb-38f9-4518-ac3b-8f54fdbf43be\" />\n *\n * `useCopilotReadable` is a React hook that provides app-state and other information\n * to the Copilot. Optionally, the hook can also handle hierarchical state within your\n * application, passing these parent-child relationships to the Copilot.\n *\n * <RequestExample>\n * ```jsx useCopilotReadable Example\n * import { useCopilotReadable }\n * from \"@copilotkit/react-core\";\n *\n * const myAppState = ...;\n * useCopilotReadable({\n * description: \"The current state of the app\",\n * value: myAppState\n * });\n * ```\n * </RequestExample>\n *\n * In its most basic usage, useCopilotReadable accepts a single string argument\n * representing any piece of app state, making it available for the Copilot to use\n * as context when responding to user input.\n *\n * For example:\n *\n * ```jsx simple state example\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * const userName = \"Rust Cohle\";\n * useCopilotReadable({\n * description: \"The name of the user\",\n * value: userName\n * });\n * ```\n *\n * You can also pass in an object representing your app state,\n * for example:\n *\n * ```jsx using state\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * const myAppState = {\n * userName: \"Rust Cohle\",\n * userAddress: {\n * street: \"4500 Old Spanish Trail\",\n * city: \"New Orleans\",\n * state: \"LA\",\n * zip: \"70129\"\n * }\n * };\n * useCopilotReadable({\n * description: \"The current state of the app\",\n * value: myAppState\n * });\n * ```\n *\n * Optionally, you can maintain the hierarchical structure of information by passing\n * `parentId`:\n *\n * ```jsx parentId example\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n *\n * function Employee(props: EmployeeProps) {\n * const { employeeName, workProfile, metadata } = props;\n *\n * // propagate any information copilot\n * const employeeContextId = useCopilotReadable({\n * description: \"Employee name\",\n * value: employeeName\n * });\n *\n * // Pass a parentID to maintain a hierarchical structure.\n * // Especially useful with child React components, list elements, etc.\n * useCopilotReadable({\n * description: \"Work profile\",\n * value: workProfile.description(),\n * parentId: employeeContextId\n * });\n * useCopilotReadable({\n * description: \"Employee metadata\",\n * value: metadata.description(),\n * parentId: employeeContextId\n * });\n *\n * return (\n * // Render as usual...\n * );\n * }\n * ```\n */\nimport { useContext, useEffect, useRef } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\n\n/**\n * Options for the useCopilotReadable hook.\n */\nexport interface UseCopilotReadableOptions {\n /**\n * The description of the information to be added to the Copilot context.\n */\n description: string;\n /**\n * The value to be added to the Copilot context.\n */\n value: any;\n /**\n * The ID of the parent context, if any.\n */\n parentId?: string;\n /**\n * An array of categories to control which context are visible where. Particularly useful\n * with CopilotTextarea (see `useMakeAutosuggestionFunction`)\n */\n categories?: string[];\n\n /**\n * A custom conversion function to use to serialize the value to a string. If not provided, the value\n * will be serialized using `JSON.stringify`.\n */\n convert?: (description: string, value: any) => string;\n}\n\nfunction convertToJSON(description: string, value: any): string {\n return `${description}: ${typeof value === \"string\" ? value : JSON.stringify(value)}`;\n}\n\n/**\n * Adds the given information to the Copilot context to make it readable by Copilot.\n */\nexport function useCopilotReadable(\n { description, value, parentId, categories, convert }: UseCopilotReadableOptions,\n dependencies?: any[],\n): string | undefined {\n const { addContext, removeContext } = useContext(CopilotContext);\n const idRef = useRef<string>();\n convert = convert || convertToJSON;\n\n const information = convert(description, value);\n\n useEffect(() => {\n const id = addContext(information, parentId, categories);\n idRef.current = id;\n\n return () => {\n removeContext(id);\n };\n }, [information, parentId, addContext, removeContext, ...(dependencies || [])]);\n\n return idRef.current;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC4BA,IAAAA,gBAAoE;;;ACrBpE,mBAAkB;AAgIlB,IAAM,sBAA4C;AAAA,EAChD,aAAa,CAAC;AAAA,EACd,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,kBAAkB,MAAM;AAAA,EAAC;AAAA,EAEzB,qBAAqB,EAAE,SAAS,CAAC,EAAE;AAAA,EACnC,kBAAkB,CAAC,WAA8B,eAC/C,sBAAsB,EAAE;AAAA,EAC1B,YAAY,MAAM;AAAA,EAClB,eAAe,MAAM;AAAA,EAAC;AAAA,EAEtB,uCAAuC,MAAM,sBAAsB,CAAC,CAAC;AAAA,EACrE,wBAAwB,MAAM,sBAAsB,MAAY;AAAA,EAAC,EAAC;AAAA,EAElE,UAAU,CAAC;AAAA,EACX,aAAa,MAAM,sBAAsB,CAAC,CAAC;AAAA,EAE3C,WAAW;AAAA,EACX,cAAc,MAAM,sBAAsB,KAAK;AAAA,EAE/C,kBAAkB;AAAA,EAClB,qBAAqB,MAAM,sBAAsB,EAAE;AAAA,EAEnD,qBAAqB,CAAC,eAAyB,sBAAsB,CAAC,CAAC;AAAA,EACvE,oB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c,QAAI,0BAAW,cAAc;AAC/D,QAAM,YAAQ,sBAAe;AAC7B,YAAU,WAAW;AAErB,QAAM,cAAc,QAAQ,aAAa,KAAK;AAE9C,+BAAU,MAAM;AACd,UAAM,KAAK,WAAW,aAAa,UAAU,UAAU;AACvD,UAAM,UAAU;AAEhB,WAAO,MAAM;AACX,oBAAc,EAAE;AAAA,IAClB;AAAA,EACF,GAAG,CAAC,aAAa,UAAU,YAAY,eAAe,GAAI,gBAAgB,CAAC,CAAE,CAAC;AAE9E,SAAO,MAAM;AACf;","names":["import_react","React","import_react","import_shared","messages","untruncateJson","import_react","import_shared","import_react","import_nanoid","import_shared","import_react","import_nanoid","import_react","import_react","import_react"]}
1
+ {"version":3,"sources":["../../src/hooks/index.ts","../../src/hooks/use-copilot-chat.ts","../../src/context/copilot-context.tsx","../../src/hooks/use-chat.ts","../../src/components/copilot-provider/copilotkit.tsx","../../src/hooks/use-make-copilot-actionable.ts","../../src/hooks/use-copilot-action.ts","../../src/hooks/use-make-copilot-readable.ts","../../src/hooks/use-make-copilot-document-readable.ts","../../src/hooks/use-copilot-readable.ts"],"sourcesContent":["export { useCopilotChat } from \"./use-copilot-chat\";\nexport type { UseCopilotChatOptions } from \"./use-copilot-chat\";\nexport type { UseCopilotChatReturn } from \"./use-copilot-chat\";\n\nexport { useMakeCopilotActionable } from \"./use-make-copilot-actionable\";\nexport { useCopilotAction } from \"./use-copilot-action\";\nexport { useMakeCopilotReadable } from \"./use-make-copilot-readable\";\nexport { useMakeCopilotDocumentReadable } from \"./use-make-copilot-document-readable\";\nexport { type UseChatHelpers } from \"./use-chat\";\nexport { useCopilotReadable } from \"./use-copilot-readable\";\n","/**\n * A hook for accessing Copilot's chat API.\n *\n * `useCopilotChat` is a React hook that lets you directly interact with the\n * Copilot instance. Use to implement a fully custom UI (headless UI) or to\n * programmatically interact with the Copilot instance managed by the default\n * UI.\n *\n * <RequestExample>\n * ```jsx useCopilotChat Example\n * import { useCopilotChat }\n * from \"@copilotkit/react-core\";\n *\n * const { appendMessage } = useCopilotChat();\n * appendMessage({ content: \"Hello, world!\", role: \"user\", id: \"1\" });\n * ```\n * </RequestExample>\n *\n * useCopilotChat returns an object with the following properties:\n * - `visibleMessages`: An array of messages that are currently visible in the chat.\n * - `appendMessage`: A function to append a message to the chat.\n * - `setMessages`: A function to set the messages in the chat.\n * - `deleteMessage`: A function to delete a message from the chat.\n * - `reloadMessages`: A function to reload the messages from the API.\n * - `stopGeneration`: A function to stop the generation of the next message.\n * - `isLoading`: A boolean indicating if the chat is loading.\n *\n */\nimport { useContext, useRef, useEffect, useCallback } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { Message, Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useChat } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { MessageStatusCode } from \"@copilotkit/runtime-client-gql\";\n\nexport interface UseCopilotChatOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * Extra body object to be sent with the API request.\n * @example\n * Send a `sessionId` to the API along with the messages.\n * ```js\n * useChat({\n * body: {\n * sessionId: '123',\n * }\n * })\n * ```\n */\n body?: object;\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n}\n\nexport interface UseCopilotChatReturn {\n visibleMessages: Message[];\n appendMessage: (message: Message) => Promise<void>;\n setMessages: (messages: Message[]) => void;\n deleteMessage: (messageId: string) => void;\n reloadMessages: () => Promise<void>;\n stopGeneration: () => void;\n isLoading: boolean;\n}\n\nexport function useCopilotChat({\n makeSystemMessage,\n ...options\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const {\n getContextString,\n getFunctionCallHandler,\n copilotApiConfig,\n messages,\n setMessages,\n isLoading,\n setIsLoading,\n chatInstructions,\n actions,\n } = useContext(CopilotContext);\n\n // We need to ensure that makeSystemMessageCallback always uses the latest\n // useCopilotReadable data.\n const latestGetContextString = useUpdatedRef(getContextString);\n const deleteMessage = useCallback(\n (messageId: string) => {\n setMessages((prev) => prev.filter((message) => message.id !== messageId));\n },\n [setMessages],\n );\n\n const makeSystemMessageCallback = useCallback(() => {\n const systemMessageMaker = makeSystemMessage || defaultSystemMessage;\n // this always gets the latest context string\n const contextString = latestGetContextString.current([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return new TextMessage({\n content: systemMessageMaker(contextString, chatInstructions),\n role: Role.System,\n });\n }, [getContextString, makeSystemMessage, chatInstructions]);\n\n const { append, reload, stop } = useChat({\n ...options,\n actions: Object.values(actions),\n copilotConfig: copilotApiConfig,\n initialMessages: options.initialMessages || [],\n onFunctionCall: getFunctionCallHandler(),\n messages,\n setMessages,\n makeSystemMessageCallback,\n isLoading,\n setIsLoading,\n });\n\n return {\n visibleMessages: messages,\n appendMessage: append,\n setMessages,\n reloadMessages: reload,\n stopGeneration: stop,\n deleteMessage,\n isLoading,\n };\n}\n\n// store `value` in a ref and update\n// it whenever it changes.\nfunction useUpdatedRef<T>(value: T) {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref;\n}\n\nexport function defaultSystemMessage(\n contextString: string,\n additionalInstructions?: string,\n): string {\n return (\n `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n","import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\nimport { Message } from \"@copilotkit/runtime-client-gql\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * The endpoint for the chat API v2.\n */\n chatApiEndpointV2: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Custom properties to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n properties?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n}\n\nexport type InChatRenderFunction = (props: ActionRenderProps<any>) => string | JSX.Element;\n\nexport interface CopilotContextParams {\n // function-calling\n actions: Record<string, FrontendAction<any>>;\n setAction: (id: string, action: FrontendAction<any>) => void;\n removeAction: (id: string) => void;\n chatComponentsCache: React.RefObject<Record<string, InChatRenderFunction | string>>;\n\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n // chat\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n chatComponentsCache: { current: {} },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n messages: [],\n setMessages: () => returnAndThrowInDebug([]),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n get chatApiEndpointV2(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n return React.useContext(CopilotContext);\n}\n\nfunction returnAndThrowInDebug<T>(value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n return value;\n}\n","import { useRef } from \"react\";\nimport {\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n Action,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport {\n Message,\n TextMessage,\n ActionExecutionMessage,\n ResultMessage,\n CopilotRuntimeClient,\n convertMessagesToGqlInput,\n convertGqlOutputToMessages,\n MessageStatusCode,\n MessageRole,\n Role,\n} from \"@copilotkit/runtime-client-gql\";\n\nimport { CopilotApiConfig } from \"../context\";\n\nexport type UseChatOptions = {\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n /**\n * Callback function to be called when a function call is received.\n * If the function returns a `ChatRequest` object, the request will be sent\n * automatically to the API and will be used to update the chat.\n */\n onFunctionCall?: FunctionCallHandler;\n /**\n * Function definitions to be sent to the API.\n */\n actions: Action[];\n\n /**\n * The CopilotKit API configuration.\n */\n copilotConfig: CopilotApiConfig;\n\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * A callback to get the latest system message.\n */\n makeSystemMessageCallback: () => TextMessage;\n\n /**\n * Whether the API request is in progress\n */\n isLoading: boolean;\n\n /**\n * setState-powered method to update the isChatLoading value\n */\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: () => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n};\n\nexport function useChat(options: UseChatOptions): UseChatHelpers {\n const {\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n } = options;\n const abortControllerRef = useRef<AbortController>();\n const threadIdRef = useRef<string | null>(null);\n const runIdRef = useRef<string | null>(null);\n const publicApiKey = copilotConfig.publicApiKey;\n const headers = {\n ...(copilotConfig.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const runtimeClient = new CopilotRuntimeClient({\n url: copilotConfig.chatApiEndpoint,\n publicApiKey: copilotConfig.publicApiKey,\n headers,\n });\n\n const runChatCompletion = async (previousMessages: Message[]): Promise<Message[]> => {\n setIsLoading(true);\n\n // this message is just a placeholder. It will disappear once the first real message\n // is received\n let newMessages: Message[] = [\n new TextMessage({\n content: \"\",\n role: Role.Assistant,\n }),\n ];\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setMessages([...previousMessages, ...newMessages]);\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(initialMessages || []), ...previousMessages];\n\n const stream = CopilotRuntimeClient.asStream(\n runtimeClient.generateCopilotResponse(\n {\n frontend: {\n actions: actions.map((action) => ({\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n })),\n },\n threadId: threadIdRef.current,\n runId: runIdRef.current,\n messages: convertMessagesToGqlInput(messagesWithContext),\n ...(copilotConfig.cloud\n ? {\n cloud: {\n guardrails: {\n inputValidationRules: {\n allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,\n denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics,\n },\n },\n },\n }\n : {}),\n },\n copilotConfig.properties,\n abortControllerRef.current?.signal,\n ),\n );\n\n const guardrailsEnabled =\n copilotConfig.cloud?.guardrails?.input?.restrictToTopic.enabled || false;\n\n const reader = stream.getReader();\n\n let results: { [id: string]: string } = {};\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (!value?.generateCopilotResponse) {\n continue;\n }\n\n threadIdRef.current = value.generateCopilotResponse.threadId || null;\n runIdRef.current = value.generateCopilotResponse.runId || null;\n\n const messages = convertGqlOutputToMessages(value.generateCopilotResponse.messages);\n\n if (messages.length === 0) {\n continue;\n }\n\n newMessages = [];\n\n // request failed, display error message\n if (\n value.generateCopilotResponse.status?.__typename === \"FailedResponseStatus\" &&\n value.generateCopilotResponse.status.reason === \"GUARDRAILS_VALIDATION_FAILED\"\n ) {\n newMessages = [\n new TextMessage({\n role: MessageRole.Assistant,\n content: value.generateCopilotResponse.status.details?.guardrailsReason || \"\",\n }),\n ];\n }\n\n // add messages to the chat\n else {\n for (const message of messages) {\n newMessages.push(message);\n\n if (\n message instanceof ActionExecutionMessage &&\n message.status.code !== MessageStatusCode.Pending &&\n message.scope === \"client\" &&\n onFunctionCall\n ) {\n if (!(message.id in results)) {\n // Do not execute a function call if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute action\n const result = await onFunctionCall({\n messages: previousMessages,\n name: message.name,\n args: message.arguments,\n });\n results[message.id] = result;\n }\n\n // add the result message\n newMessages.push(\n new ResultMessage({\n result: ResultMessage.encodeResult(results[message.id]),\n actionExecutionId: message.id,\n actionName: message.name,\n }),\n );\n }\n }\n }\n\n if (newMessages.length > 0) {\n setMessages([...previousMessages, ...newMessages]);\n }\n }\n\n if (\n // if we have client side results\n Object.values(results).length ||\n // or the last message we received is a result\n (newMessages.length && newMessages[newMessages.length - 1] instanceof ResultMessage)\n ) {\n // run the completion again and return the result\n\n // wait for next tick to make sure all the react state updates\n // - tried using react-dom's flushSync, but it did not work\n await new Promise((resolve) => setTimeout(resolve, 10));\n\n return await runChatCompletion([...previousMessages, ...newMessages]);\n } else {\n return newMessages.slice();\n }\n } finally {\n setIsLoading(false);\n }\n };\n\n const runChatCompletionAndHandleFunctionCall = async (messages: Message[]): Promise<void> => {\n await runChatCompletion(messages);\n };\n\n const append = async (message: Message): Promise<void> => {\n if (isLoading) {\n return;\n }\n const newMessages = [...messages, message];\n setMessages(newMessages);\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const reload = async (): Promise<void> => {\n if (isLoading || messages.length === 0) {\n return;\n }\n let newMessages = [...messages];\n const lastMessage = messages[messages.length - 1];\n\n if (lastMessage instanceof TextMessage && lastMessage.role === \"assistant\") {\n newMessages = newMessages.slice(0, -1);\n }\n\n setMessages(newMessages);\n\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const stop = (): void => {\n abortControllerRef.current?.abort();\n };\n\n return {\n append,\n reload,\n stop,\n };\n}\n","/**\n * Provides the Copilot context to its children.\n * \n * <img\n * referrerPolicy=\"no-referrer-when-downgrade\"\n * src=\"https://static.scarf.sh/a.png?x-pxid=a9b290bb-38f9-4518-ac3b-8f54fdbf43be\"\n * />\n * \n * This component provides the Copilot context to its children.\n * It can be configured either with a chat API endpoint or a `CopilotApiConfig`.\n * \n * <Note>\n * The backend can use OpenAI, or you can bring your own LLM. For examples of the\n * backend api implementation, see `examples/next-openai` or the [runtime\n * docs](https://docs.copilotkit.ai/getting-started/quickstart-runtime).\n * </Note>\n * \n * <RequestExample>\n * ```jsx CopilotKit Example\n * import { CopilotKit } from \"@copilotkit/react-core\";\n * \n * <CopilotKit \n * runtimeUrl=\"https://your.copilotkit.api\">\n * <YourApp/>\n * </CopilotKit>\n * ```\n * </RequestExample>\n * \n * ## Example usage\n * \n * ```jsx\n * <CopilotKit publicApiKey=\"the api key or self host (see below)\">\n * <App />\n * </CopilotKit>\n```\n */\nimport { Ref, useCallback, useRef, useState } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n InChatRenderFunction,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { CopilotChatSuggestionConfiguration, DocumentPointer } from \"../../types\";\n\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n} from \"@copilotkit/shared\";\nimport { Message } from \"@copilotkit/runtime-client-gql\";\n\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n // Compute all the functions and properties that we need to pass\n // to the CopilotContext.\n\n if (!props.runtimeUrl && !props.url && !props.publicApiKey) {\n throw new Error(\"Please provide either a url or a publicApiKey to the CopilotKit component.\");\n }\n\n const chatApiEndpoint = props.runtimeUrl || props.url || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n const chatComponentsCache = useRef<Record<string, InChatRenderFunction | string>>({});\n const { addElement, removeElement, printTree } = useTree();\n const [messages, setMessages] = useState<Message[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n const setAction = useCallback((id: string, action: FrontendAction<any>) => {\n setActions((prevPoints) => {\n return {\n ...prevPoints,\n [id]: action,\n };\n });\n }, []);\n\n const removeAction = useCallback((id: string) => {\n setActions((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));\n },\n [actions],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n if (!props.publicApiKey) {\n if (props.cloudRestrictToTopic) {\n throw new Error(\n \"To use the cloudRestrictToTopic feature, please sign up at https://copilotkit.ai and provide a publicApiKey.\",\n );\n }\n }\n\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (props.publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: props.cloudRestrictToTopic ? true : false,\n validTopics: props.cloudRestrictToTopic?.validTopics || [],\n invalidTopics: props.cloudRestrictToTopic?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = {\n publicApiKey: props.publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n chatApiEndpointV2: `${props.url}/v2`,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n };\n\n const removeChatSuggestionConfiguration = (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n };\n\n return (\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n getContextString,\n addContext,\n removeContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n messages,\n setMessages,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n }}\n >\n {children}\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async ({ messages, name, args }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n if (action) {\n return await action.handler(args);\n }\n };\n}\n","import { useRef, useContext, useEffect, useMemo } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { AnnotatedFunction } from \"@copilotkit/shared\";\nimport { nanoid } from \"nanoid\";\nimport { annotatedFunctionToAction } from \"@copilotkit/shared\";\n\n/**\n * @deprecated Use the useCopilotAction function instead.\n */\nexport function useMakeCopilotActionable<ActionInput extends any[]>(\n annotatedFunction: AnnotatedFunction<ActionInput>,\n dependencies: any[],\n) {\n const idRef = useRef(nanoid()); // generate a unique id\n const { setAction, removeAction } = useContext(CopilotContext);\n\n const memoizedAnnotatedFunction: AnnotatedFunction<ActionInput> = useMemo(\n () => ({\n name: annotatedFunction.name,\n description: annotatedFunction.description,\n argumentAnnotations: annotatedFunction.argumentAnnotations,\n implementation: annotatedFunction.implementation,\n }),\n dependencies,\n );\n\n useEffect(() => {\n const action = annotatedFunctionToAction(memoizedAnnotatedFunction as AnnotatedFunction<any[]>);\n setAction(idRef.current, action);\n\n return () => {\n removeAction(idRef.current);\n };\n }, [memoizedAnnotatedFunction, setAction, removeAction]);\n}\n","import { useRef, useContext, useEffect } from \"react\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { nanoid } from \"nanoid\";\nimport { Parameter } from \"@copilotkit/shared\";\n\n// We implement useCopilotAction dependency handling so that\n// the developer has the option to not provide any dependencies.\n// In this case, we assume they want to update the handler on each rerender.\n// To avoid getting stuck in an infinite loop, we update the handler directly,\n// skipping React state updates.\n// This is ok in this case, because the handler is not part of any UI that\n// needs to be updated.\n// useCallback, useMemo or other memoization techniques are not suitable here,\n// because they will cause a infinite rerender loop.\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { setAction, removeAction, actions, chatComponentsCache } = useContext(CopilotContext);\n const idRef = useRef<string>(nanoid());\n\n // If the developer doesn't provide dependencies, we assume they want to\n // update handler and render function when the action object changes.\n // This ensures that any captured variables in the handler are up to date.\n if (dependencies === undefined) {\n if (actions[idRef.current]) {\n actions[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current[action.name] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n setAction(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current[action.name] = action.render;\n }\n return () => {\n // NOTE: For now, we don't remove the chatComponentsCache entry when the action is removed.\n // This is because we currently don't have access to the messages array in CopilotContext.\n removeAction(idRef.current);\n };\n }, [\n setAction,\n removeAction,\n action.description,\n action.name,\n // This should be faster than deep equality checking\n // In addition, all major JS engines guarantee the order of object keys\n JSON.stringify(action.parameters),\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n\n// Usage 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// useCopilotAction({\n// name: \"myAction\",\n// handler: () => {\n// console.log(\"No parameters provided.\");\n// },\n// });\n","import { useContext, useEffect, useRef } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\n\n/**\n * @deprecated Use the useCopilotReadable function instead.\n */\nexport function useMakeCopilotReadable(\n information: string,\n parentId?: string,\n categories?: string[],\n): string | undefined {\n const { addContext, removeContext } = useContext(CopilotContext);\n const idRef = useRef<string>();\n\n useEffect(() => {\n const id = addContext(information, parentId, categories);\n idRef.current = id;\n\n return () => {\n removeContext(id);\n };\n }, [information, parentId, addContext, removeContext]);\n\n return idRef.current;\n}\n","import { useContext, useEffect, useRef } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { DocumentPointer } from \"../types\";\n\n/**\n * Makes a document readable by Copilot.\n * @param document The document to make readable.\n * @param categories The categories to associate with the document.\n * @param dependencies The dependencies to use for the effect.\n * @returns The id of the document.\n */\nexport function useMakeCopilotDocumentReadable(\n document: DocumentPointer,\n categories?: string[],\n dependencies: any[] = [],\n): string | undefined {\n const { addDocumentContext, removeDocumentContext } = useContext(CopilotContext);\n const idRef = useRef<string>();\n\n useEffect(() => {\n const id = addDocumentContext(document, categories);\n idRef.current = id;\n\n return () => {\n removeDocumentContext(id);\n };\n }, [addDocumentContext, removeDocumentContext, ...dependencies]);\n\n return idRef.current;\n}\n","/**\n * A hook for providing app-state & other information to the Copilot.\n *\n * <img referrerPolicy=\"no-referrer-when-downgrade\" src=\"https://static.scarf.sh/a.png?x-pxid=a9b290bb-38f9-4518-ac3b-8f54fdbf43be\" />\n *\n * `useCopilotReadable` is a React hook that provides app-state and other information\n * to the Copilot. Optionally, the hook can also handle hierarchical state within your\n * application, passing these parent-child relationships to the Copilot.\n *\n * <RequestExample>\n * ```jsx useCopilotReadable Example\n * import { useCopilotReadable }\n * from \"@copilotkit/react-core\";\n *\n * const myAppState = ...;\n * useCopilotReadable({\n * description: \"The current state of the app\",\n * value: myAppState\n * });\n * ```\n * </RequestExample>\n *\n * In its most basic usage, useCopilotReadable accepts a single string argument\n * representing any piece of app state, making it available for the Copilot to use\n * as context when responding to user input.\n *\n * For example:\n *\n * ```jsx simple state example\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * const userName = \"Rust Cohle\";\n * useCopilotReadable({\n * description: \"The name of the user\",\n * value: userName\n * });\n * ```\n *\n * You can also pass in an object representing your app state,\n * for example:\n *\n * ```jsx using state\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n * const myAppState = {\n * userName: \"Rust Cohle\",\n * userAddress: {\n * street: \"4500 Old Spanish Trail\",\n * city: \"New Orleans\",\n * state: \"LA\",\n * zip: \"70129\"\n * }\n * };\n * useCopilotReadable({\n * description: \"The current state of the app\",\n * value: myAppState\n * });\n * ```\n *\n * Optionally, you can maintain the hierarchical structure of information by passing\n * `parentId`:\n *\n * ```jsx parentId example\n * import { useCopilotReadable } from \"@copilotkit/react-core\";\n *\n *\n * function Employee(props: EmployeeProps) {\n * const { employeeName, workProfile, metadata } = props;\n *\n * // propagate any information copilot\n * const employeeContextId = useCopilotReadable({\n * description: \"Employee name\",\n * value: employeeName\n * });\n *\n * // Pass a parentID to maintain a hierarchical structure.\n * // Especially useful with child React components, list elements, etc.\n * useCopilotReadable({\n * description: \"Work profile\",\n * value: workProfile.description(),\n * parentId: employeeContextId\n * });\n * useCopilotReadable({\n * description: \"Employee metadata\",\n * value: metadata.description(),\n * parentId: employeeContextId\n * });\n *\n * return (\n * // Render as usual...\n * );\n * }\n * ```\n */\nimport { useContext, useEffect, useRef } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\n\n/**\n * Options for the useCopilotReadable hook.\n */\nexport interface UseCopilotReadableOptions {\n /**\n * The description of the information to be added to the Copilot context.\n */\n description: string;\n /**\n * The value to be added to the Copilot context.\n */\n value: any;\n /**\n * The ID of the parent context, if any.\n */\n parentId?: string;\n /**\n * An array of categories to control which context are visible where. Particularly useful\n * with CopilotTextarea (see `useMakeAutosuggestionFunction`)\n */\n categories?: string[];\n\n /**\n * A custom conversion function to use to serialize the value to a string. If not provided, the value\n * will be serialized using `JSON.stringify`.\n */\n convert?: (description: string, value: any) => string;\n}\n\nfunction convertToJSON(description: string, value: any): string {\n return `${description}: ${typeof value === \"string\" ? value : JSON.stringify(value)}`;\n}\n\n/**\n * Adds the given information to the Copilot context to make it readable by Copilot.\n */\nexport function useCopilotReadable(\n { description, value, parentId, categories, convert }: UseCopilotReadableOptions,\n dependencies?: any[],\n): string | undefined {\n const { addContext, removeContext } = useContext(CopilotContext);\n const idRef = useRef<string>();\n convert = convert || convertToJSON;\n\n const information = convert(description, value);\n\n useEffect(() => {\n const id = addContext(information, parentId, categories);\n idRef.current = id;\n\n return () => {\n removeContext(id);\n };\n }, [information, parentId, addContext, removeContext, ...(dependencies || [])]);\n\n return idRef.current;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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BAAU,MAAM;AACd,UAAM,KAAK,WAAW,aAAa,UAAU,UAAU;AACvD,UAAM,UAAU;AAEhB,WAAO,MAAM;AACX,oBAAc,EAAE;AAAA,IAClB;AAAA,EACF,GAAG,CAAC,aAAa,UAAU,YAAY,aAAa,CAAC;AAErD,SAAO,MAAM;AACf;;;ACxBA,IAAAC,gBAA8C;AAWvC,SAAS,+BACd,UACA,YACA,eAAsB,CAAC,GACH;AACpB,QAAM,EAAE,oBAAoB,sBAAsB,QAAI,0BAAW,cAAc;AAC/E,QAAM,YAAQ,sBAAe;AAE7B,+BAAU,MAAM;AACd,UAAM,KAAK,mBAAmB,UAAU,UAAU;AAClD,UAAM,UAAU;AAEhB,WAAO,MAAM;AACX,4BAAsB,EAAE;AAAA,IAC1B;AAAA,EACF,GAAG,CAAC,oBAAoB,uBAAuB,GAAG,YAAY,CAAC;AAE/D,SAAO,MAAM;AACf;;;ACiEA,IAAAC,gBAA8C;AAgC9C,SAAS,cAAc,aAAqB,OAAoB;AAC9D,SAAO,GAAG,gBAAgB,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,KAAK;AACpF;AAKO,SAAS,mBACd,EAAE,aAAa,OAAO,UAAU,YAAY,QAAQ,GACpD,cACoB;AACpB,QAAM,EAAE,YAAY,cAAc,QAAI,0BAAW,cAAc;AAC/D,QAAM,YAAQ,sBAAe;AAC7B,YAAU,WAAW;AAErB,QAAM,cAAc,QAAQ,aAAa,KAAK;AAE9C,+BAAU,MAAM;AACd,UAAM,KAAK,WAAW,aAAa,UAAU,UAAU;AACvD,UAAM,UAAU;AAEhB,WAAO,MAAM;AACX,oBAAc,EAAE;AAAA,IAClB;AAAA,EACF,GAAG,CAAC,aAAa,UAAU,YAAY,eAAe,GAAI,gBAAgB,CAAC,CAAE,CAAC;AAE9E,SAAO,MAAM;AACf;","names":["import_react","React","import_runtime_client_gql","import_react","messages","import_react","import_shared","import_react","import_shared","import_react","import_nanoid","import_react","import_react","import_react"]}
@@ -1,30 +1,29 @@
1
1
  import "../chunk-EYKDJBDE.mjs";
2
2
  import {
3
3
  useCopilotReadable
4
- } from "../chunk-MNZXQ6UH.mjs";
4
+ } from "../chunk-YM2JV2YQ.mjs";
5
5
  import {
6
6
  useMakeCopilotActionable
7
- } from "../chunk-SR4RW4CU.mjs";
7
+ } from "../chunk-IQCLNCGL.mjs";
8
8
  import {
9
9
  useMakeCopilotDocumentReadable
10
- } from "../chunk-S5LWO5V3.mjs";
10
+ } from "../chunk-7GPIOOXB.mjs";
11
11
  import {
12
12
  useMakeCopilotReadable
13
- } from "../chunk-B244LK6F.mjs";
13
+ } from "../chunk-QNJQKKD4.mjs";
14
14
  import {
15
15
  useCopilotAction
16
- } from "../chunk-NSUYO6TP.mjs";
16
+ } from "../chunk-LZVHW3T3.mjs";
17
17
  import {
18
18
  useCopilotChat
19
- } from "../chunk-HUKLBIUK.mjs";
19
+ } from "../chunk-5CKW6KE7.mjs";
20
20
  import "../chunk-JD7BAH7U.mjs";
21
21
  import "../chunk-SPCZTZCY.mjs";
22
- import "../chunk-LLU5URI5.mjs";
22
+ import "../chunk-DDHJCFFV.mjs";
23
23
  import "../chunk-YULKJPY3.mjs";
24
24
  import "../chunk-YWITCRBI.mjs";
25
- import "../chunk-B2H3NC4E.mjs";
26
- import "../chunk-MJKBCG4U.mjs";
27
- import "../chunk-DY63PD22.mjs";
25
+ import "../chunk-PHMHNAYC.mjs";
26
+ import "../chunk-K6EV2CNB.mjs";
28
27
  import "../chunk-SKC7AJIV.mjs";
29
28
  export {
30
29
  useCopilotAction,
@@ -1,4 +1,5 @@
1
- import { Message, FunctionCallHandler, ToolDefinition } from '@copilotkit/shared';
1
+ import { FunctionCallHandler, Action } from '@copilotkit/shared';
2
+ import { Message, TextMessage } from '@copilotkit/runtime-client-gql';
2
3
  import { CopilotApiConfig } from '../context/copilot-context.js';
3
4
  import '../types/frontend-action.js';
4
5
  import 'react';
@@ -7,17 +8,6 @@ import '../types/document-pointer.js';
7
8
  import '../types/chat-suggestion-configuration.js';
8
9
 
9
10
  type UseChatOptions = {
10
- /**
11
- * The API endpoint that accepts a `{ messages: Message[] }` object and returns
12
- * a stream of tokens of the AI chat response. Defaults to `/api/chat`.
13
- */
14
- api?: string;
15
- /**
16
- * A unique identifier for the chat. If not provided, a random one will be
17
- * generated. When provided, the `useChat` hook with the same `id` will
18
- * have shared states across components.
19
- */
20
- id?: string;
21
11
  /**
22
12
  * System messages of the chat. Defaults to an empty array.
23
13
  */
@@ -28,47 +18,13 @@ type UseChatOptions = {
28
18
  * automatically to the API and will be used to update the chat.
29
19
  */
30
20
  onFunctionCall?: FunctionCallHandler;
31
- /**
32
- * HTTP headers to be sent with the API request.
33
- */
34
- headers?: Record<string, string> | Headers;
35
- /**
36
- * Extra body object to be sent with the API request.
37
- * @example
38
- * Send a `sessionId` to the API along with the messages.
39
- * ```js
40
- * useChat({
41
- * body: {
42
- * sessionId: '123',
43
- * }
44
- * })
45
- * ```
46
- */
47
- body?: object;
48
21
  /**
49
22
  * Function definitions to be sent to the API.
50
23
  */
51
- tools?: ToolDefinition[];
52
- };
53
- type UseChatHelpers = {
54
- /**
55
- * Append a user message to the chat list. This triggers the API call to fetch
56
- * the assistant's response.
57
- * @param message The message to append
58
- */
59
- append: (message: Message) => Promise<void>;
24
+ actions: Action[];
60
25
  /**
61
- * Reload the last AI chat response for the given chat history. If the last
62
- * message isn't from the assistant, it will request the API to generate a
63
- * new response.
26
+ * The CopilotKit API configuration.
64
27
  */
65
- reload: () => Promise<void>;
66
- /**
67
- * Abort the current request immediately, keep the generated tokens if any.
68
- */
69
- stop: () => void;
70
- };
71
- type UseChatOptionsWithCopilotConfig = UseChatOptions & {
72
28
  copilotConfig: CopilotApiConfig;
73
29
  /**
74
30
  * The current list of messages in the chat.
@@ -81,7 +37,7 @@ type UseChatOptionsWithCopilotConfig = UseChatOptions & {
81
37
  /**
82
38
  * A callback to get the latest system message.
83
39
  */
84
- makeSystemMessageCallback: () => Message;
40
+ makeSystemMessageCallback: () => TextMessage;
85
41
  /**
86
42
  * Whether the API request is in progress
87
43
  */
@@ -91,6 +47,24 @@ type UseChatOptionsWithCopilotConfig = UseChatOptions & {
91
47
  */
92
48
  setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;
93
49
  };
94
- declare function useChat(options: UseChatOptionsWithCopilotConfig): UseChatHelpers;
50
+ type UseChatHelpers = {
51
+ /**
52
+ * Append a user message to the chat list. This triggers the API call to fetch
53
+ * the assistant's response.
54
+ * @param message The message to append
55
+ */
56
+ append: (message: Message) => Promise<void>;
57
+ /**
58
+ * Reload the last AI chat response for the given chat history. If the last
59
+ * message isn't from the assistant, it will request the API to generate a
60
+ * new response.
61
+ */
62
+ reload: () => Promise<void>;
63
+ /**
64
+ * Abort the current request immediately, keep the generated tokens if any.
65
+ */
66
+ stop: () => void;
67
+ };
68
+ declare function useChat(options: UseChatOptions): UseChatHelpers;
95
69
 
96
- export { UseChatHelpers, UseChatOptions, UseChatOptionsWithCopilotConfig, useChat };
70
+ export { UseChatHelpers, UseChatOptions, useChat };