UNPKG

@copilotkit/react-core

Version:

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

332 lines (323 loc) • 10.5 kB
import { useLangGraphInterruptRender } from "./chunk-ZVOLWJCY.mjs"; import { useChat } from "./chunk-OT5NHMEC.mjs"; import { defaultCopilotContextCategories, reloadSuggestions } from "./chunk-CI4KD357.mjs"; import { useAsyncCallback } from "./chunk-N4WEHORG.mjs"; import { useCopilotContext } from "./chunk-EUX2P2E7.mjs"; import { useCopilotMessagesContext } from "./chunk-ZLQVRPDS.mjs"; import { __async, __spreadProps, __spreadValues } from "./chunk-SKC7AJIV.mjs"; // src/hooks/use-copilot-chat_internal.ts import { useRef, useEffect, useCallback, useState, useMemo } from "react"; import { Role as gqlRole, TextMessage, aguiToGQL, gqlToAGUI, Message as DeprecatedGqlMessage } from "@copilotkit/runtime-client-gql"; var globalSuggestionPromise = null; function useCopilotChat(options = {}) { var _a; const makeSystemMessage = (_a = options.makeSystemMessage) != null ? _a : defaultSystemMessage; const { getContextString, getFunctionCallHandler, copilotApiConfig, isLoading, setIsLoading, chatInstructions, actions, coagentStatesRef, setCoagentStatesWithRef, coAgentStateRenders, agentSession, setAgentSession, forwardedParameters, agentLock, threadId, setThreadId, runId, setRunId, chatAbortControllerRef, extensions, setExtensions, langGraphInterruptAction, setLangGraphInterruptAction, chatSuggestionConfiguration, runtimeClient } = useCopilotContext(); const { messages, setMessages, suggestions, setSuggestions } = useCopilotMessagesContext(); const [mcpServers, setLocalMcpServers] = useState([]); const suggestionsAbortControllerRef = useRef(null); const isLoadingSuggestionsRef = useRef(false); const abortSuggestions = useCallback( (clear = true) => { var _a2; (_a2 = suggestionsAbortControllerRef.current) == null ? void 0 : _a2.abort("suggestions aborted by user"); suggestionsAbortControllerRef.current = null; if (clear) { setSuggestions([]); } }, [setSuggestions] ); const stableContext = useMemo(() => { return { actions, copilotApiConfig, chatSuggestionConfiguration, messages, setMessages, getContextString, runtimeClient }; }, [ JSON.stringify(Object.keys(actions)), copilotApiConfig.chatApiEndpoint, messages.length, Object.keys(chatSuggestionConfiguration).length ]); const generateSuggestionsFunc = useCallback(() => __async(this, null, function* () { if (globalSuggestionPromise) { return globalSuggestionPromise; } globalSuggestionPromise = (() => __async(this, null, function* () { try { abortSuggestions(); isLoadingSuggestionsRef.current = true; suggestionsAbortControllerRef.current = new AbortController(); setSuggestions([]); yield reloadSuggestions( stableContext, chatSuggestionConfiguration, setSuggestions, suggestionsAbortControllerRef ); } catch (error) { throw error; } finally { isLoadingSuggestionsRef.current = false; globalSuggestionPromise = null; } }))(); return globalSuggestionPromise; }), [stableContext, chatSuggestionConfiguration, setSuggestions, abortSuggestions]); const resetSuggestions = useCallback(() => { setSuggestions([]); }, [setSuggestions]); useEffect(() => { if (mcpServers.length > 0) { const serversCopy = [...mcpServers]; copilotApiConfig.mcpServers = serversCopy; if (!copilotApiConfig.properties) { copilotApiConfig.properties = {}; } copilotApiConfig.properties.mcpServers = serversCopy; } }, [mcpServers, copilotApiConfig]); const setMcpServers = useCallback((servers) => { setLocalMcpServers(servers); }, []); const onCoAgentStateRender = useAsyncCallback( (args) => __async(this, null, function* () { var _a2; const { name, nodeName, state } = args; let action = Object.values(coAgentStateRenders).find( (action2) => action2.name === name && action2.nodeName === nodeName ); if (!action) { action = Object.values(coAgentStateRenders).find( (action2) => action2.name === name && !action2.nodeName ); } if (action) { yield (_a2 = action.handler) == null ? void 0 : _a2.call(action, { state, nodeName }); } }), [coAgentStateRenders] ); const makeSystemMessageCallback = useCallback(() => { const systemMessageMaker = makeSystemMessage || defaultSystemMessage; const contextString = getContextString([], defaultCopilotContextCategories); return new TextMessage({ content: systemMessageMaker(contextString, chatInstructions), role: gqlRole.System }); }, [getContextString, makeSystemMessage, chatInstructions]); const deleteMessage = useCallback( (messageId) => { setMessages((prev) => prev.filter((message) => message.id !== messageId)); }, [setMessages] ); const { append, reload, stop, runChatCompletion } = useChat(__spreadProps(__spreadValues({}, options), { actions: Object.values(actions), copilotConfig: copilotApiConfig, initialMessages: aguiToGQL(options.initialMessages || []), onFunctionCall: getFunctionCallHandler(), onCoAgentStateRender, messages, setMessages, makeSystemMessageCallback, isLoading, setIsLoading, coagentStatesRef, setCoagentStatesWithRef, agentSession, setAgentSession, forwardedParameters, threadId, setThreadId, runId, setRunId, chatAbortControllerRef, agentLock, extensions, setExtensions, langGraphInterruptAction, setLangGraphInterruptAction, disableSystemMessage: options.disableSystemMessage })); const latestAppend = useUpdatedRef(append); const latestAppendFunc = useAsyncCallback( (message, options2) => __async(this, null, function* () { abortSuggestions(options2 == null ? void 0 : options2.clearSuggestions); return yield latestAppend.current(message, options2); }), [latestAppend] ); const latestSendMessageFunc = useAsyncCallback( (message, options2) => __async(this, null, function* () { abortSuggestions(options2 == null ? void 0 : options2.clearSuggestions); return yield latestAppend.current(aguiToGQL([message])[0], options2); }), [latestAppend] ); const latestReload = useUpdatedRef(reload); const latestReloadFunc = useAsyncCallback( (messageId) => __async(this, null, function* () { return yield latestReload.current(messageId); }), [latestReload] ); const latestStop = useUpdatedRef(stop); const latestStopFunc = useCallback(() => { return latestStop.current(); }, [latestStop]); const latestDelete = useUpdatedRef(deleteMessage); const latestDeleteFunc = useCallback( (messageId) => { return latestDelete.current(messageId); }, [latestDelete] ); const latestSetMessages = useUpdatedRef(setMessages); const latestSetMessagesFunc = useCallback( (messages2) => { if (messages2.every((message) => message instanceof DeprecatedGqlMessage)) { return latestSetMessages.current(messages2); } return latestSetMessages.current(aguiToGQL(messages2)); }, [latestSetMessages] ); const latestRunChatCompletion = useUpdatedRef(runChatCompletion); const latestRunChatCompletionFunc = useAsyncCallback(() => __async(this, null, function* () { return yield latestRunChatCompletion.current(); }), [latestRunChatCompletion]); const reset = useCallback(() => { latestStopFunc(); setMessages([]); setRunId(null); setCoagentStatesWithRef({}); let initialAgentSession = null; if (agentLock) { initialAgentSession = { agentName: agentLock }; } setAgentSession(initialAgentSession); resetSuggestions(); }, [ latestStopFunc, setMessages, setThreadId, setCoagentStatesWithRef, setAgentSession, agentLock, resetSuggestions ]); const latestReset = useUpdatedRef(reset); const latestResetFunc = useCallback(() => { return latestReset.current(); }, [latestReset]); const interrupt = useLangGraphInterruptRender(); return { visibleMessages: messages, messages: gqlToAGUI(messages, actions, coAgentStateRenders), sendMessage: latestSendMessageFunc, appendMessage: latestAppendFunc, setMessages: latestSetMessagesFunc, reloadMessages: latestReloadFunc, stopGeneration: latestStopFunc, reset: latestResetFunc, deleteMessage: latestDeleteFunc, runChatCompletion: latestRunChatCompletionFunc, isLoading, mcpServers, setMcpServers, suggestions, setSuggestions, generateSuggestions: generateSuggestionsFunc, resetSuggestions, isLoadingSuggestions: isLoadingSuggestionsRef.current, interrupt }; } function useUpdatedRef(value) { const ref = useRef(value); useEffect(() => { ref.current = value; }, [value]); return ref; } function defaultSystemMessage(contextString, additionalInstructions) { return ` Please act as an efficient, competent, conscientious, and industrious professional assistant. Help 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. Always be polite and respectful, and prefer brevity over verbosity. The user has provided you with the following context: \`\`\` ${contextString} \`\`\` They have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information. Please assist them as best you can. You 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. If you would like to call a function, call it without saying anything else. In case of a function error: - If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments. - If the error's source is unclear or seems unrelated to your input, do not attempt further retries. ` + (additionalInstructions ? ` ${additionalInstructions}` : ""); } export { useCopilotChat, defaultSystemMessage }; //# sourceMappingURL=chunk-QHCLJODF.mjs.map