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;" />

239 lines (237 loc) • 8.03 kB
import { useCopilotChat } from "./chunk-QHCLJODF.mjs"; import { useMessagesTap } from "./chunk-C6IANC2R.mjs"; import { useCopilotRuntimeClient } from "./chunk-6ESSSQ7Q.mjs"; import { useAsyncCallback } from "./chunk-N4WEHORG.mjs"; import { useToast } from "./chunk-EFL5OBKN.mjs"; import { useCopilotContext } from "./chunk-EUX2P2E7.mjs"; import { __async, __spreadProps, __spreadValues } from "./chunk-SKC7AJIV.mjs"; // src/hooks/use-coagent.ts import { useCallback, useEffect, useMemo, useRef } from "react"; import { parseJson, CopilotKitAgentDiscoveryError } from "@copilotkit/shared"; function useCoAgent(options) { const context = useCopilotContext(); const { availableAgents, onError } = context; const { setBannerError } = useToast(); const lastLoadedThreadId = useRef(); const lastLoadedState = useRef(); const { name } = options; useEffect(() => { if ((availableAgents == null ? void 0 : availableAgents.length) && !availableAgents.some((a) => a.name === name)) { const message = `(useCoAgent): Agent "${name}" not found. Make sure the agent exists and is properly configured.`; console.warn(message); const agentError = new CopilotKitAgentDiscoveryError({ agentName: name, availableAgents: availableAgents.map((a) => ({ name: a.name, id: a.id })) }); setBannerError(agentError); } }, [availableAgents]); const { getMessagesFromTap } = useMessagesTap(); const { coagentStates, coagentStatesRef, setCoagentStatesWithRef, threadId, copilotApiConfig } = context; const { sendMessage, runChatCompletion } = useCopilotChat(); const headers = __spreadValues({}, copilotApiConfig.headers || {}); const runtimeClient = useCopilotRuntimeClient({ url: copilotApiConfig.chatApiEndpoint, publicApiKey: copilotApiConfig.publicApiKey, headers, credentials: copilotApiConfig.credentials, showDevConsole: context.showDevConsole, onError }); const setState = useCallback( (newState) => { let coagentState = getCoagentState({ coagentStates, name, options }); const updatedState = typeof newState === "function" ? newState(coagentState.state) : newState; setCoagentStatesWithRef(__spreadProps(__spreadValues({}, coagentStatesRef.current), { [name]: __spreadProps(__spreadValues({}, coagentState), { state: updatedState }) })); }, [coagentStates, name] ); useEffect(() => { const fetchAgentState = () => __async(this, null, function* () { var _a, _b, _c, _d; if (!threadId || threadId === lastLoadedThreadId.current) return; const result = yield runtimeClient.loadAgentState({ threadId, agentName: name }); if (result.error) { return; } const newState = (_b = (_a = result.data) == null ? void 0 : _a.loadAgentState) == null ? void 0 : _b.state; if (newState === lastLoadedState.current) return; if (((_d = (_c = result.data) == null ? void 0 : _c.loadAgentState) == null ? void 0 : _d.threadExists) && newState && newState != "{}") { lastLoadedState.current = newState; lastLoadedThreadId.current = threadId; const fetchedState = parseJson(newState, {}); isExternalStateManagement(options) ? options.setState(fetchedState) : setState(fetchedState); } }); void fetchAgentState(); }, [threadId]); useEffect(() => { if (isExternalStateManagement(options)) { setState(options.state); } else if (coagentStates[name] === void 0) { setState(options.initialState === void 0 ? {} : options.initialState); } }, [ isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0, // reset initialstate on reset coagentStates[name] === void 0 ]); useEffect(() => { const newConfig = options.config ? options.config : options.configurable ? { configurable: options.configurable } : void 0; if (newConfig === void 0) return; setCoagentStatesWithRef((prev) => { var _a; const existing = (_a = prev[name]) != null ? _a : { name, state: isInternalStateManagementWithInitial(options) ? options.initialState : {}, config: {}, running: false, active: false, threadId: void 0, nodeName: void 0, runId: void 0 }; if (JSON.stringify(existing.config) === JSON.stringify(newConfig)) { return prev; } return __spreadProps(__spreadValues({}, prev), { [name]: __spreadProps(__spreadValues({}, existing), { config: newConfig }) }); }); }, [JSON.stringify(options.config), JSON.stringify(options.configurable)]); const runAgentCallback = useAsyncCallback( (hint) => __async(this, null, function* () { yield runAgent(name, context, getMessagesFromTap(), sendMessage, runChatCompletion, hint); }), [name, context, sendMessage, runChatCompletion] ); return useMemo(() => { const coagentState = getCoagentState({ coagentStates, name, options }); return { name, nodeName: coagentState.nodeName, threadId: coagentState.threadId, running: coagentState.running, state: coagentState.state, setState: isExternalStateManagement(options) ? options.setState : setState, start: () => startAgent(name, context), stop: () => stopAgent(name, context), run: runAgentCallback }; }, [name, coagentStates, options, setState, runAgentCallback]); } function startAgent(name, context) { const { setAgentSession } = context; setAgentSession({ agentName: name }); } function stopAgent(name, context) { const { agentSession, setAgentSession } = context; if (agentSession && agentSession.agentName === name) { setAgentSession(null); context.setCoagentStates((prevAgentStates) => { return __spreadProps(__spreadValues({}, prevAgentStates), { [name]: __spreadProps(__spreadValues({}, prevAgentStates[name]), { running: false, active: false, threadId: void 0, nodeName: void 0, runId: void 0 }) }); }); } else { console.warn(`No agent session found for ${name}`); } } function runAgent(name, context, messages, sendMessage, runChatCompletion, hint) { return __async(this, null, function* () { var _a, _b; const { agentSession, setAgentSession } = context; if (!agentSession || agentSession.agentName !== name) { setAgentSession({ agentName: name }); } let previousState = null; for (let i = messages.length - 1; i >= 0; i--) { const message = messages[i]; if (message.isAgentStateMessage() && message.agentName === name) { previousState = message.state; } } let state = ((_b = (_a = context.coagentStatesRef.current) == null ? void 0 : _a[name]) == null ? void 0 : _b.state) || {}; if (hint) { const hintMessage = hint({ previousState, currentState: state }); if (hintMessage) { yield sendMessage(hintMessage); } else { yield runChatCompletion(); } } else { yield runChatCompletion(); } }); } var isExternalStateManagement = (options) => { return "state" in options && "setState" in options; }; var isInternalStateManagementWithInitial = (options) => { return "initialState" in options; }; var getCoagentState = ({ coagentStates, name, options }) => { if (coagentStates[name]) { return coagentStates[name]; } else { return { name, state: isInternalStateManagementWithInitial(options) ? options.initialState : {}, config: options.config ? options.config : options.configurable ? { configurable: options.configurable } : {}, running: false, active: false, threadId: void 0, nodeName: void 0, runId: void 0 }; } }; export { useCoAgent, startAgent, stopAgent, runAgent }; //# sourceMappingURL=chunk-QV5SBF2S.mjs.map