@copilotkit/react-core
Version:
<div align="center"> <a href="https://copilotkit.ai" target="_blank"> <img src="https://github.com/copilotkit/copilotkit/raw/main/assets/banner.png" alt="CopilotKit Logo"> </a>
1 lines • 14 kB
Source Map (JSON)
{"version":3,"sources":["../src/hooks/use-copilot-chat.ts"],"sourcesContent":["/**\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 * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCopilotChat } from \"@copilotkit/react-core\";\n * import { Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\n *\n * export function YourComponent() {\n * const { appendMessage } = useCopilotChat();\n *\n * appendMessage(\n * new TextMessage({\n * content: \"Hello World\",\n * role: Role.User,\n * }),\n * );\n *\n * // optionally, you can append a message without running chat completion\n * appendMessage(yourMessage, { followUp: false });\n * }\n * ```\n *\n * `useCopilotChat` returns an object with the following properties:\n *\n * ```tsx\n * const {\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 * reset, // A function to reset the chat.\n * isLoading, // A boolean indicating if the chat is loading.\n * } = useCopilotChat();\n * ```\n */\nimport { useRef, useEffect, useCallback } from \"react\";\nimport { AgentSession, useCopilotContext } from \"../context/copilot-context\";\nimport { Message, Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useChat, AppendMessageOptions } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { CoAgentStateRenderHandlerArguments } from \"@copilotkit/shared\";\nimport { useCopilotMessagesContext } from \"../context\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\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 * 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, options?: AppendMessageOptions) => Promise<void>;\n setMessages: (messages: Message[]) => void;\n deleteMessage: (messageId: string) => void;\n reloadMessages: () => Promise<void>;\n stopGeneration: () => void;\n reset: () => void;\n isLoading: boolean;\n runChatCompletion: () => Promise<Message[]>;\n}\n\nexport function useCopilotChat({\n makeSystemMessage,\n ...options\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const {\n getContextString,\n getFunctionCallHandler,\n copilotApiConfig,\n isLoading,\n setIsLoading,\n chatInstructions,\n actions,\n coagentStatesRef,\n setCoagentStatesWithRef,\n coAgentStateRenders,\n agentSession,\n setAgentSession,\n forwardedParameters,\n agentLock,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n extensions,\n setExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n } = useCopilotContext();\n const { messages, setMessages } = useCopilotMessagesContext();\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 onCoAgentStateRender = useAsyncCallback(\n async (args: CoAgentStateRenderHandlerArguments) => {\n const { name, nodeName, state } = args;\n let action = Object.values(coAgentStateRenders).find(\n (action) => action.name === name && action.nodeName === nodeName,\n );\n if (!action) {\n action = Object.values(coAgentStateRenders).find(\n (action) => action.name === name && !action.nodeName,\n );\n }\n if (action) {\n await action.handler?.({ state, nodeName });\n }\n },\n [coAgentStateRenders],\n );\n\n const { append, reload, stop, runChatCompletion } = useChat({\n ...options,\n actions: Object.values(actions),\n copilotConfig: copilotApiConfig,\n initialMessages: options.initialMessages || [],\n onFunctionCall: getFunctionCallHandler(),\n onCoAgentStateRender,\n messages,\n setMessages,\n makeSystemMessageCallback,\n isLoading,\n setIsLoading,\n coagentStatesRef,\n setCoagentStatesWithRef,\n agentSession,\n setAgentSession,\n forwardedParameters,\n threadId,\n setThreadId,\n runId,\n setRunId,\n chatAbortControllerRef,\n agentLock,\n extensions,\n setExtensions,\n langGraphInterruptAction,\n setLangGraphInterruptAction,\n });\n\n // this is a workaround born out of a bug that Athena incessantly ran into.\n // We could not find the origin of the bug, however, it was clear that an outdated version of the append function was being used somehow --\n // it referenced the old state of the messages array, and not the latest one.\n //\n // We want to make copilotkit as abuse-proof as possible, so we are adding this workaround to ensure that the latest version of the append function is always used.\n //\n // How does this work?\n // we store the relevant function in a ref that is always up-to-date, and then we use that ref in the callback.\n const latestAppend = useUpdatedRef(append);\n const latestAppendFunc = useAsyncCallback(\n async (message: Message, options?: AppendMessageOptions) => {\n return await latestAppend.current(message, options);\n },\n [latestAppend],\n );\n\n const latestReload = useUpdatedRef(reload);\n const latestReloadFunc = useAsyncCallback(async () => {\n return await latestReload.current();\n }, [latestReload]);\n\n const latestStop = useUpdatedRef(stop);\n const latestStopFunc = useCallback(() => {\n return latestStop.current();\n }, [latestStop]);\n\n const latestDelete = useUpdatedRef(deleteMessage);\n const latestDeleteFunc = useCallback(\n (messageId: string) => {\n return latestDelete.current(messageId);\n },\n [latestDelete],\n );\n\n const latestSetMessages = useUpdatedRef(setMessages);\n const latestSetMessagesFunc = useCallback(\n (messages: Message[]) => {\n return latestSetMessages.current(messages);\n },\n [latestSetMessages],\n );\n\n const latestRunChatCompletion = useUpdatedRef(runChatCompletion);\n const latestRunChatCompletionFunc = useAsyncCallback(async () => {\n return await latestRunChatCompletion.current!();\n }, [latestRunChatCompletion]);\n\n const reset = useCallback(() => {\n latestStopFunc();\n setMessages([]);\n setRunId(null);\n setCoagentStatesWithRef({});\n let initialAgentSession: AgentSession | null = null;\n if (agentLock) {\n initialAgentSession = {\n agentName: agentLock,\n };\n }\n setAgentSession(initialAgentSession);\n }, [\n latestStopFunc,\n setMessages,\n setThreadId,\n setCoagentStatesWithRef,\n setAgentSession,\n agentLock,\n ]);\n\n const latestReset = useUpdatedRef(reset);\n const latestResetFunc = useCallback(() => {\n return latestReset.current();\n }, [latestReset]);\n\n return {\n visibleMessages: messages,\n appendMessage: latestAppendFunc,\n setMessages: latestSetMessagesFunc,\n reloadMessages: latestReloadFunc,\n stopGeneration: latestStopFunc,\n reset: latestResetFunc,\n deleteMessage: latestDeleteFunc,\n runChatCompletion: latestRunChatCompletionFunc,\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.\nIn case of a function error:\n- If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.\n- If the error's source is unclear or seems unrelated to your input, do not attempt further retries.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAS,QAAQ,WAAW,mBAAmB;AAE/C,SAAkB,MAAM,mBAAmB;AA2CpC,SAAS,eAAe,KAGJ,CAAC,GAAyB;AAHtB,eAC7B;AAAA;AAAA,EA1FF,IAyF+B,IAE1B,oBAF0B,IAE1B;AAAA,IADH;AAAA;AAGA,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI,kBAAkB;AACtB,QAAM,EAAE,UAAU,YAAY,IAAI,0BAA0B;AAI5D,QAAM,yBAAyB,cAAc,gBAAgB;AAC7D,QAAM,gBAAgB;AAAA,IACpB,CAAC,cAAsB;AACrB,kBAAY,CAAC,SAAS,KAAK,OAAO,CAAC,YAAY,QAAQ,OAAO,SAAS,CAAC;AAAA,IAC1E;AAAA,IACA,CAAC,WAAW;AAAA,EACd;AAEA,QAAM,4BAA4B,YAAY,MAAM;AAClD,UAAM,qBAAqB,qBAAqB;AAEhD,UAAM,gBAAgB,uBAAuB,QAAQ,CAAC,GAAG,+BAA+B;AAExF,WAAO,IAAI,YAAY;AAAA,MACrB,SAAS,mBAAmB,eAAe,gBAAgB;AAAA,MAC3D,MAAM,KAAK;AAAA,IACb,CAAC;AAAA,EACH,GAAG,CAAC,kBAAkB,mBAAmB,gBAAgB,CAAC;AAE1D,QAA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