UNPKG

@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>

202 lines (200 loc) 6.74 kB
import { useCopilotChat } from "./chunk-S3XGAWBE.mjs"; import { useCopilotContext } from "./chunk-PTSWFERP.mjs"; import { useCopilotMessagesContext } from "./chunk-DCTJZ742.mjs"; import { useCopilotRuntimeClient } from "./chunk-BKTARDXX.mjs"; import { useAsyncCallback, useToast } from "./chunk-22ENANUU.mjs"; import { __async, __spreadProps, __spreadValues } from "./chunk-SKC7AJIV.mjs"; // src/hooks/use-coagent.ts import { useCallback, useEffect, useMemo, useRef } from "react"; import { parseJson } from "@copilotkit/shared"; function useCoAgent(options) { const generalContext = useCopilotContext(); const { availableAgents } = generalContext; const { addToast } = 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); addToast({ type: "warning", message }); } }, [availableAgents]); const messagesContext = useCopilotMessagesContext(); const context = __spreadValues(__spreadValues({}, generalContext), messagesContext); const { coagentStates, coagentStatesRef, setCoagentStatesWithRef, threadId, copilotApiConfig } = context; const { appendMessage, runChatCompletion } = useCopilotChat(); const runtimeClient = useCopilotRuntimeClient({ url: copilotApiConfig.chatApiEndpoint, publicApiKey: copilotApiConfig.publicApiKey, credentials: copilotApiConfig.credentials }); 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 }); 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 ]); const runAgentCallback = useAsyncCallback( (hint) => __async(this, null, function* () { yield runAgent(name, context, appendMessage, runChatCompletion, hint); }), [name, context, appendMessage, 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, appendMessage, 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 = context.messages.length - 1; i >= 0; i--) { const message = context.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 appendMessage(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 }) => { var _a; if (coagentStates[name]) { return coagentStates[name]; } else { return { name, state: isInternalStateManagementWithInitial(options) ? options.initialState : {}, configurable: (_a = options.configurable) != null ? _a : {}, running: false, active: false, threadId: void 0, nodeName: void 0, runId: void 0 }; } }; export { useCoAgent, startAgent, stopAgent, runAgent }; //# sourceMappingURL=chunk-TUEB3WSW.mjs.map