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>

541 lines (529 loc) 17.6 kB
import { CopilotErrorBoundary } from "./chunk-534J55RX.mjs"; import { shouldShowDevConsole } from "./chunk-MLAS4QUR.mjs"; import { CopilotMessages } from "./chunk-37LXOL6B.mjs"; import { use_flat_category_store_default } from "./chunk-5FHSUKQL.mjs"; import { use_tree_default } from "./chunk-6U3UH3KO.mjs"; import { CopilotContext } from "./chunk-PTSWFERP.mjs"; import { useCopilotRuntimeClient } from "./chunk-BKTARDXX.mjs"; import { ToastProvider } from "./chunk-22ENANUU.mjs"; import { __async, __objRest, __restKey, __spreadProps, __spreadValues } from "./chunk-SKC7AJIV.mjs"; // src/utils/extract.ts import { actionParametersToJsonSchema } from "@copilotkit/shared"; import { Role, TextMessage, convertGqlOutputToMessages, CopilotRequestType } from "@copilotkit/runtime-client-gql"; // src/components/copilot-provider/copilotkit.tsx import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { flushSync } from "react-dom"; import { COPILOT_CLOUD_CHAT_URL, COPILOT_CLOUD_PUBLIC_API_KEY_HEADER, randomUUID, ConfigurationError, MissingPublicApiKeyError } from "@copilotkit/shared"; import { jsx } from "react/jsx-runtime"; function CopilotKit(_a) { var _b = _a, { children } = _b, props = __objRest(_b, ["children"]); const showDevConsole = props.showDevConsole === void 0 ? "auto" : props.showDevConsole; const enabled = shouldShowDevConsole(showDevConsole); return /* @__PURE__ */ jsx(ToastProvider, { enabled, children: /* @__PURE__ */ jsx(CopilotErrorBoundary, { publicApiKey: props.publicApiKey, showUsageBanner: enabled, children: /* @__PURE__ */ jsx(CopilotKitInternal, __spreadProps(__spreadValues({}, props), { children })) }) }); } function CopilotKitInternal(cpkProps) { const _a = cpkProps, { children } = _a, props = __objRest(_a, ["children"]); validateProps(cpkProps); const chatApiEndpoint = props.runtimeUrl || COPILOT_CLOUD_CHAT_URL; const [actions, setActions] = useState({}); const [coAgentStateRenders, setCoAgentStateRenders] = useState({}); const chatComponentsCache = useRef({ actions: {}, coAgentStateRenders: {} }); const { addElement, removeElement, printTree } = use_tree_default(); const [isLoading, setIsLoading] = useState(false); const [chatInstructions, setChatInstructions] = useState(""); const [authStates, setAuthStates] = useState({}); const [extensions, setExtensions] = useState({}); const [additionalInstructions, setAdditionalInstructions] = useState([]); const { addElement: addDocument, removeElement: removeDocument, allElements: allDocuments } = use_flat_category_store_default(); const setAction = useCallback((id, action) => { setActions((prevPoints) => { return __spreadProps(__spreadValues({}, prevPoints), { [id]: action }); }); }, []); const removeAction = useCallback((id) => { setActions((prevPoints) => { const newPoints = __spreadValues({}, prevPoints); delete newPoints[id]; return newPoints; }); }, []); const setCoAgentStateRender = useCallback((id, stateRender) => { setCoAgentStateRenders((prevPoints) => { return __spreadProps(__spreadValues({}, prevPoints), { [id]: stateRender }); }); }, []); const removeCoAgentStateRender = useCallback((id) => { setCoAgentStateRenders((prevPoints) => { const newPoints = __spreadValues({}, prevPoints); delete newPoints[id]; return newPoints; }); }, []); const getContextString = useCallback( (documents, categories) => { const documentsString = documents.map((document) => { return `${document.name} (${document.sourceApplication}): ${document.getContents()}`; }).join("\n\n"); const nonDocumentStrings = printTree(categories); return `${documentsString} ${nonDocumentStrings}`; }, [printTree] ); const addContext = useCallback( (context, parentId, categories = defaultCopilotContextCategories) => { return addElement(context, categories, parentId); }, [addElement] ); const removeContext = useCallback( (id) => { removeElement(id); }, [removeElement] ); const getFunctionCallHandler = useCallback( (customEntryPoints) => { return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions)); }, [actions] ); const getDocumentsContext = useCallback( (categories) => { return allDocuments(categories); }, [allDocuments] ); const addDocumentContext = useCallback( (documentPointer, categories = defaultCopilotContextCategories) => { return addDocument(documentPointer, categories); }, [addDocument] ); const removeDocumentContext = useCallback( (documentId) => { removeDocument(documentId); }, [removeDocument] ); const copilotApiConfig = useMemo(() => { var _a2, _b; let cloud = void 0; if (props.publicApiKey) { cloud = { guardrails: { input: { restrictToTopic: { enabled: Boolean(props.guardrails_c), validTopics: ((_a2 = props.guardrails_c) == null ? void 0 : _a2.validTopics) || [], invalidTopics: ((_b = props.guardrails_c) == null ? void 0 : _b.invalidTopics) || [] } } } }; } return __spreadProps(__spreadValues({ publicApiKey: props.publicApiKey }, cloud ? { cloud } : {}), { chatApiEndpoint, headers: props.headers || {}, properties: props.properties || {}, transcribeAudioUrl: props.transcribeAudioUrl, textToSpeechUrl: props.textToSpeechUrl, credentials: props.credentials }); }, [ props.publicApiKey, props.headers, props.properties, props.transcribeAudioUrl, props.textToSpeechUrl, props.credentials, props.cloudRestrictToTopic ]); const headers = useMemo(() => { const authHeaders = Object.values(authStates || {}).reduce((acc, state) => { if (state.status === "authenticated" && state.authHeaders) { return __spreadValues(__spreadValues({}, acc), Object.entries(state.authHeaders).reduce( (headers2, [key, value]) => __spreadProps(__spreadValues({}, headers2), { [key.startsWith("X-Custom-") ? key : `X-Custom-${key}`]: value }), {} )); } return acc; }, {}); return __spreadValues(__spreadValues(__spreadValues({}, copilotApiConfig.headers || {}), copilotApiConfig.publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey } : {}), authHeaders); }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]); const runtimeClient = useCopilotRuntimeClient({ url: copilotApiConfig.chatApiEndpoint, publicApiKey: copilotApiConfig.publicApiKey, headers, credentials: copilotApiConfig.credentials }); const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState({}); const addChatSuggestionConfiguration = (id, suggestion) => { setChatSuggestionConfiguration((prev) => __spreadProps(__spreadValues({}, prev), { [id]: suggestion })); }; const removeChatSuggestionConfiguration = (id) => { setChatSuggestionConfiguration((prev) => { const _a2 = prev, { [id]: _ } = _a2, rest = __objRest(_a2, [__restKey(id)]); return rest; }); }; const [availableAgents, setAvailableAgents] = useState([]); const [coagentStates, setCoagentStates] = useState({}); const coagentStatesRef = useRef({}); const setCoagentStatesWithRef = useCallback( (value) => { const newValue = typeof value === "function" ? value(coagentStatesRef.current) : value; coagentStatesRef.current = newValue; setCoagentStates((prev) => { return newValue; }); }, [] ); const hasLoadedAgents = useRef(false); useEffect(() => { if (hasLoadedAgents.current) return; const fetchData = () => __async(this, null, function* () { var _a2; const result = yield runtimeClient.availableAgents(); if ((_a2 = result.data) == null ? void 0 : _a2.availableAgents) { setAvailableAgents(result.data.availableAgents.agents); } hasLoadedAgents.current = true; }); void fetchData(); }, []); let initialAgentSession = null; if (props.agent) { initialAgentSession = { agentName: props.agent }; } const [agentSession, setAgentSession] = useState(initialAgentSession); useEffect(() => { if (props.agent) { setAgentSession({ agentName: props.agent }); } else { setAgentSession(null); } }, [props.agent]); const [internalThreadId, setInternalThreadId] = useState(props.threadId || randomUUID()); const setThreadId = useCallback( (value) => { if (props.threadId) { throw new Error("Cannot call setThreadId() when threadId is provided via props."); } setInternalThreadId(value); }, [props.threadId] ); useEffect(() => { if (props.threadId !== void 0) { setInternalThreadId(props.threadId); } }, [props.threadId]); const [runId, setRunId] = useState(null); const chatAbortControllerRef = useRef(null); const showDevConsole = props.showDevConsole === void 0 ? "auto" : props.showDevConsole; const [langGraphInterruptAction, _setLangGraphInterruptAction] = useState(null); const setLangGraphInterruptAction = useCallback((action) => { _setLangGraphInterruptAction((prev) => { if (prev == null) return action; if (action == null) return null; let event = prev.event; if (action.event) { event = __spreadValues(__spreadValues({}, prev.event), action.event); } return __spreadProps(__spreadValues(__spreadValues({}, prev), action), { event }); }); }, []); const removeLangGraphInterruptAction = useCallback(() => { setLangGraphInterruptAction(null); }, []); return /* @__PURE__ */ jsx( CopilotContext.Provider, { value: { actions, chatComponentsCache, getFunctionCallHandler, setAction, removeAction, coAgentStateRenders, setCoAgentStateRender, removeCoAgentStateRender, getContextString, addContext, removeContext, getDocumentsContext, addDocumentContext, removeDocumentContext, copilotApiConfig, isLoading, setIsLoading, chatSuggestionConfiguration, addChatSuggestionConfiguration, removeChatSuggestionConfiguration, chatInstructions, setChatInstructions, additionalInstructions, setAdditionalInstructions, showDevConsole, coagentStates, setCoagentStates, coagentStatesRef, setCoagentStatesWithRef, agentSession, setAgentSession, runtimeClient, forwardedParameters: props.forwardedParameters || {}, agentLock: props.agent || null, threadId: internalThreadId, setThreadId, runId, setRunId, chatAbortControllerRef, availableAgents, authConfig_c: props.authConfig_c, authStates_c: authStates, setAuthStates_c: setAuthStates, extensions, setExtensions, langGraphInterruptAction, setLangGraphInterruptAction, removeLangGraphInterruptAction }, children: /* @__PURE__ */ jsx(CopilotMessages, { children }) } ); } var defaultCopilotContextCategories = ["global"]; function entryPointsToFunctionCallHandler(actions) { return (_0) => __async(this, [_0], function* ({ name, args }) { let actionsByFunctionName = {}; for (let action2 of actions) { actionsByFunctionName[action2.name] = action2; } const action = actionsByFunctionName[name]; let result = void 0; if (action) { yield new Promise((resolve, reject) => { flushSync(() => __async(this, null, function* () { var _a; try { result = yield (_a = action.handler) == null ? void 0 : _a.call(action, args); resolve(); } catch (error) { reject(error); } })); }); yield new Promise((resolve) => setTimeout(resolve, 20)); } return result; }); } function formatFeatureName(featureName) { return featureName.replace(/_c$/, "").split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(" "); } function validateProps(props) { const cloudFeatures = Object.keys(props).filter((key) => key.endsWith("_c")); if (!props.runtimeUrl && !props.publicApiKey) { throw new ConfigurationError("Missing required prop: 'runtimeUrl' or 'publicApiKey'"); } if (cloudFeatures.length > 0 && !props.publicApiKey) { throw new MissingPublicApiKeyError( `Missing required prop: 'publicApiKey' to use cloud features: ${cloudFeatures.map(formatFeatureName).join(", ")}` ); } } // src/utils/extract.ts import { convertMessagesToGqlInput, filterAgentStateMessages } from "@copilotkit/runtime-client-gql"; function extract(_0) { return __async(this, arguments, function* ({ context, instructions, parameters, include, data, abortSignal, stream, requestType = CopilotRequestType.Task, forwardedParameters }) { var _a, _b; const { messages } = context; const action = { name: "extract", description: instructions, parameters, handler: (args) => { } }; const includeReadable = (_a = include == null ? void 0 : include.readable) != null ? _a : false; const includeMessages = (_b = include == null ? void 0 : include.messages) != null ? _b : false; let contextString = ""; if (data) { contextString = (typeof data === "string" ? data : JSON.stringify(data)) + "\n\n"; } if (includeReadable) { contextString += context.getContextString([], defaultCopilotContextCategories); } const systemMessage = new TextMessage({ content: makeSystemMessage(contextString, instructions), role: Role.System }); const instructionsMessage = new TextMessage({ content: makeInstructionsMessage(instructions), role: Role.User }); const response = context.runtimeClient.asStream( context.runtimeClient.generateCopilotResponse({ data: { frontend: { actions: [ { name: action.name, description: action.description || "", jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])) } ], url: window.location.href }, messages: convertMessagesToGqlInput( includeMessages ? [systemMessage, instructionsMessage, ...filterAgentStateMessages(messages)] : [systemMessage, instructionsMessage] ), metadata: { requestType }, forwardedParameters: __spreadProps(__spreadValues({}, forwardedParameters != null ? forwardedParameters : {}), { toolChoice: "function", toolChoiceFunctionName: action.name }) }, properties: context.copilotApiConfig.properties, signal: abortSignal }) ); const reader = response.getReader(); let isInitial = true; let actionExecutionMessage = void 0; while (true) { const { done, value } = yield reader.read(); if (done) { break; } if (abortSignal == null ? void 0 : abortSignal.aborted) { throw new Error("Aborted"); } actionExecutionMessage = convertGqlOutputToMessages( value.generateCopilotResponse.messages ).find((msg) => msg.isActionExecutionMessage()); if (!actionExecutionMessage) { continue; } stream == null ? void 0 : stream({ status: isInitial ? "initial" : "inProgress", args: actionExecutionMessage.arguments }); isInitial = false; } if (!actionExecutionMessage) { throw new Error("extract() failed: No function call occurred"); } stream == null ? void 0 : stream({ status: "complete", args: actionExecutionMessage.arguments }); return actionExecutionMessage.arguments; }); } function makeInstructionsMessage(instructions) { return ` The user has given you the following task to complete: \`\`\` ${instructions} \`\`\` Any additional messages provided are for providing context only and should not be used to ask questions or engage in conversation. `; } function makeSystemMessage(contextString, instructions) { 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 a function called extract you MUST call to initiate actions on their behalf. Please assist them as best you can. This is not a conversation, so please do not ask questions. Just call the function without saying anything else. `; } export { extract, CopilotKit, CopilotKitInternal, defaultCopilotContextCategories }; //# sourceMappingURL=chunk-OKBPP25E.mjs.map