@copilotkit/react-core 0.25.0-function-calling-fixes.2 → 0.25.0-mme-cloud.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +216 -234
- package/CHANGELOG.md +3 -25
- package/dist/{chunk-BGB5G33N.mjs → chunk-4E2RCCQB.mjs} +2 -2
- package/dist/{chunk-AEUR5JBT.mjs → chunk-APVNN5QF.mjs} +3 -4
- package/dist/chunk-APVNN5QF.mjs.map +1 -0
- package/dist/{chunk-3WKJ25L3.mjs → chunk-CGT3AVYT.mjs} +3 -3
- package/dist/chunk-CGT3AVYT.mjs.map +1 -0
- package/dist/{chunk-KIKHLN4X.mjs → chunk-GH7QK2AZ.mjs} +3 -1
- package/dist/chunk-GH7QK2AZ.mjs.map +1 -0
- package/dist/{chunk-H3FQWB4B.mjs → chunk-KMTE4NLW.mjs} +19 -12
- package/dist/chunk-KMTE4NLW.mjs.map +1 -0
- package/dist/{chunk-KJQZ2VEU.mjs → chunk-M7JUS6OQ.mjs} +2 -2
- package/dist/{chunk-QGRMN7L3.mjs → chunk-O2GQ2XK7.mjs} +3 -3
- package/dist/{chunk-FCEPEM4B.mjs → chunk-PYBBWHNC.mjs} +3 -3
- package/dist/{chunk-GVLCTSXW.mjs → chunk-SPLPX72P.mjs} +11 -7
- package/dist/chunk-SPLPX72P.mjs.map +1 -0
- package/dist/{chunk-75RLNHDB.mjs → chunk-TEI34ZF5.mjs} +5 -5
- package/dist/chunk-TEI34ZF5.mjs.map +1 -0
- package/dist/{chunk-H6V2C2AN.mjs → chunk-YKHUBROO.mjs} +2 -2
- package/dist/components/copilot-provider/copilotkit-props.d.ts +12 -0
- package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.d.ts +0 -17
- package/dist/components/copilot-provider/copilotkit.js +19 -17
- package/dist/components/copilot-provider/copilotkit.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.mjs +8 -435
- package/dist/components/copilot-provider/copilotkit.mjs.map +1 -1
- package/dist/components/copilot-provider/index.js +19 -17
- package/dist/components/copilot-provider/index.js.map +1 -1
- package/dist/components/copilot-provider/index.mjs +9 -435
- package/dist/components/copilot-provider/index.mjs.map +1 -1
- package/dist/components/index.js +19 -17
- package/dist/components/index.js.map +1 -1
- package/dist/components/index.mjs +10 -435
- package/dist/components/index.mjs.map +1 -1
- package/dist/context/copilot-context.d.ts +15 -2
- package/dist/context/copilot-context.js +2 -0
- package/dist/context/copilot-context.js.map +1 -1
- package/dist/context/copilot-context.mjs +5 -64
- package/dist/context/copilot-context.mjs.map +1 -1
- package/dist/context/index.js +2 -0
- package/dist/context/index.js.map +1 -1
- package/dist/context/index.mjs +6 -64
- package/dist/context/index.mjs.map +1 -1
- package/dist/hooks/index.js +14 -14
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +23 -518
- package/dist/hooks/index.mjs.map +1 -1
- package/dist/hooks/use-chat.d.ts +8 -2
- package/dist/hooks/use-chat.js +3 -4
- package/dist/hooks/use-chat.js.map +1 -1
- package/dist/hooks/use-chat.mjs +4 -285
- package/dist/hooks/use-chat.mjs.map +1 -1
- package/dist/hooks/use-copilot-action.d.ts +1 -1
- package/dist/hooks/use-copilot-action.js +4 -9
- package/dist/hooks/use-copilot-action.js.map +1 -1
- package/dist/hooks/use-copilot-action.mjs +5 -107
- package/dist/hooks/use-copilot-action.mjs.map +1 -1
- package/dist/hooks/use-copilot-chat.js +12 -7
- package/dist/hooks/use-copilot-chat.js.map +1 -1
- package/dist/hooks/use-copilot-chat.mjs +12 -420
- package/dist/hooks/use-copilot-chat.mjs.map +1 -1
- package/dist/hooks/use-flat-category-store.mjs +4 -65
- package/dist/hooks/use-flat-category-store.mjs.map +1 -1
- package/dist/hooks/use-make-copilot-actionable.js +2 -0
- package/dist/hooks/use-make-copilot-actionable.js.map +1 -1
- package/dist/hooks/use-make-copilot-actionable.mjs +5 -88
- package/dist/hooks/use-make-copilot-actionable.mjs.map +1 -1
- package/dist/hooks/use-make-copilot-document-readable.js +2 -0
- package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
- package/dist/hooks/use-make-copilot-document-readable.mjs +5 -78
- package/dist/hooks/use-make-copilot-document-readable.mjs.map +1 -1
- package/dist/hooks/use-make-copilot-readable.js +2 -0
- package/dist/hooks/use-make-copilot-readable.js.map +1 -1
- package/dist/hooks/use-make-copilot-readable.mjs +5 -78
- package/dist/hooks/use-make-copilot-readable.mjs.map +1 -1
- package/dist/hooks/use-tree.mjs +4 -150
- package/dist/hooks/use-tree.mjs.map +1 -1
- package/dist/index.js +31 -31
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +48 -1103
- package/dist/index.mjs.map +1 -1
- package/dist/lib/copilot-task.js +2 -2
- package/dist/lib/copilot-task.js.map +1 -1
- package/dist/lib/copilot-task.mjs +10 -192
- package/dist/lib/copilot-task.mjs.map +1 -1
- package/dist/lib/index.js +2 -2
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/index.mjs +11 -192
- package/dist/lib/index.mjs.map +1 -1
- package/dist/openai-assistants/hooks/index.js +2 -0
- package/dist/openai-assistants/hooks/index.js.map +1 -1
- package/dist/openai-assistants/hooks/index.mjs +14 -228
- package/dist/openai-assistants/hooks/index.mjs.map +1 -1
- package/dist/openai-assistants/hooks/use-assistants.mjs +7 -45
- package/dist/openai-assistants/hooks/use-assistants.mjs.map +1 -1
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.js +2 -0
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.js.map +1 -1
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs +14 -228
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs.map +1 -1
- package/dist/openai-assistants/index.js +2 -0
- package/dist/openai-assistants/index.js.map +1 -1
- package/dist/openai-assistants/index.mjs +17 -228
- package/dist/openai-assistants/index.mjs.map +1 -1
- package/dist/openai-assistants/utils/index.mjs +5 -43
- package/dist/openai-assistants/utils/index.mjs.map +1 -1
- package/dist/openai-assistants/utils/process-message-stream.mjs +4 -43
- package/dist/openai-assistants/utils/process-message-stream.mjs.map +1 -1
- package/dist/types/index.mjs +1 -0
- package/dist/utils/fetch-chat-completion.js +2 -2
- package/dist/utils/fetch-chat-completion.js.map +1 -1
- package/dist/utils/fetch-chat-completion.mjs +5 -112
- package/dist/utils/fetch-chat-completion.mjs.map +1 -1
- package/package.json +4 -4
- package/src/components/copilot-provider/copilotkit-props.tsx +14 -0
- package/src/components/copilot-provider/copilotkit.tsx +21 -25
- package/src/context/copilot-context.tsx +19 -1
- package/src/hooks/use-chat.ts +9 -4
- package/src/hooks/use-copilot-action.ts +58 -10
- package/src/hooks/use-copilot-chat.ts +5 -1
- package/src/utils/fetch-chat-completion.ts +1 -0
- package/dist/chunk-3WKJ25L3.mjs.map +0 -1
- package/dist/chunk-75RLNHDB.mjs.map +0 -1
- package/dist/chunk-AEUR5JBT.mjs.map +0 -1
- package/dist/chunk-F2JIAPZQ.mjs +0 -14
- package/dist/chunk-F2JIAPZQ.mjs.map +0 -1
- package/dist/chunk-GVLCTSXW.mjs.map +0 -1
- package/dist/chunk-H3FQWB4B.mjs.map +0 -1
- package/dist/chunk-ISKBWE4O.mjs +0 -13
- package/dist/chunk-ISKBWE4O.mjs.map +0 -1
- package/dist/chunk-KIKHLN4X.mjs.map +0 -1
- package/dist/components/copilot-provider/standard-copilot-api-config.d.ts +0 -23
- package/dist/components/copilot-provider/standard-copilot-api-config.js +0 -38
- package/dist/components/copilot-provider/standard-copilot-api-config.js.map +0 -1
- package/dist/components/copilot-provider/standard-copilot-api-config.mjs +0 -13
- package/dist/components/copilot-provider/standard-copilot-api-config.mjs.map +0 -1
- package/dist/hooks/use-copilot-action-implementation.d.ts +0 -7
- package/dist/hooks/use-copilot-action-implementation.js +0 -140
- package/dist/hooks/use-copilot-action-implementation.js.map +0 -1
- package/dist/hooks/use-copilot-action-implementation.mjs +0 -106
- package/dist/hooks/use-copilot-action-implementation.mjs.map +0 -1
- package/src/components/copilot-provider/standard-copilot-api-config.tsx +0 -28
- package/src/hooks/use-copilot-action-implementation.ts +0 -60
- /package/dist/{chunk-BGB5G33N.mjs.map → chunk-4E2RCCQB.mjs.map} +0 -0
- /package/dist/{chunk-KJQZ2VEU.mjs.map → chunk-M7JUS6OQ.mjs.map} +0 -0
- /package/dist/{chunk-QGRMN7L3.mjs.map → chunk-O2GQ2XK7.mjs.map} +0 -0
- /package/dist/{chunk-FCEPEM4B.mjs.map → chunk-PYBBWHNC.mjs.map} +0 -0
- /package/dist/{chunk-H6V2C2AN.mjs.map → chunk-YKHUBROO.mjs.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/openai-assistants/hooks/use-copilot-chat-v2.ts","../../src/openai-assistants/utils/process-message-stream.ts","../../src/context/copilot-context.tsx","../../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["import { useContext, useMemo, useState } from \"react\";\nimport { processMessageStream } from \"../utils\";\nimport { Message, parseStreamPart } from \"@copilotkit/shared\";\nimport { CopilotContext } from \"../../context\";\nimport { defaultCopilotContextCategories } from \"../../components\";\n\nexport type AssistantStatus = \"in_progress\" | \"awaiting_message\";\n\nexport interface RequestForwardingOptions {\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n /**\n * Extra body object to be sent with the API request.\n * @example\n * Send a `sessionId` to the API along with the messages.\n * ```js\n * useChat({\n * body: {\n * sessionId: '123',\n * }\n * })\n * ```\n */\n body?: object;\n}\nexport interface UseCopilotChatOptionsV2 extends RequestForwardingOptions {\n makeSystemMessage?: (contextString: string) => string;\n threadId?: string | undefined;\n}\n\nexport interface UseCopilotChatV2Result {\n messages: Message[];\n input: string;\n handleInputChange: (e: any) => void;\n submitMessage: (e: any) => Promise<void>;\n status: AssistantStatus;\n error: unknown;\n}\n\nexport function useCopilotChatV2(options: UseCopilotChatOptionsV2): UseCopilotChatV2Result {\n const {\n getContextString,\n getChatCompletionFunctionDescriptions,\n getFunctionCallHandler,\n copilotApiConfig,\n } = useContext(CopilotContext);\n\n const [messages, setMessages] = useState<Message[]>([]);\n const [input, setInput] = useState(\"\");\n const [threadId, setThreadId] = useState<string | undefined>(undefined);\n const [status, setStatus] = useState<AssistantStatus>(\"awaiting_message\");\n const [error, setError] = useState<unknown | undefined>(undefined);\n\n const systemMessage: Message = useMemo(() => {\n const systemMessageMaker = options.makeSystemMessage || defaultSystemMessage;\n const contextString = getContextString([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return {\n id: \"system\",\n content: systemMessageMaker(contextString),\n role: \"system\",\n };\n }, [getContextString, options.makeSystemMessage]);\n\n const handleInputChange = (e: any) => {\n setInput(e.target.value);\n };\n\n const submitMessage = async (e: any) => {\n e.preventDefault();\n\n if (input === \"\") {\n return;\n }\n\n setStatus(\"in_progress\");\n\n setMessages((messages) => [...messages, { id: \"\", role: \"user\", content: input }]);\n\n setInput(\"\");\n\n const apiUrl = copilotApiConfig.chatApiEndpointV2;\n\n const functions = getChatCompletionFunctionDescriptions();\n\n const result = await fetch(apiUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...copilotApiConfig.headers,\n ...options.headers,\n },\n body: JSON.stringify({\n // always use user-provided threadId when available:\n threadId: options.threadId ?? threadId ?? null,\n message: input,\n ...(functions.length > 0 && { functions: functions }),\n ...copilotApiConfig.body,\n ...options.body,\n }),\n });\n\n if (result.body == null) {\n throw new Error(\"The response body is empty.\");\n }\n\n await processMessageStream(result.body.getReader(), (message: string) => {\n try {\n const { type, value } = parseStreamPart(message);\n\n switch (type) {\n case \"assistant_message\": {\n // append message:\n setMessages((messages) => [\n ...messages,\n {\n id: value.id,\n role: value.role,\n content: value.content[0].text.value,\n },\n ]);\n break;\n }\n\n case \"assistant_control_data\": {\n setThreadId(value.threadId);\n\n // set id of last message:\n setMessages((messages) => {\n const lastMessage = messages[messages.length - 1];\n lastMessage.id = value.messageId;\n return [...messages.slice(0, messages.length - 1), lastMessage];\n });\n\n break;\n }\n\n case \"error\": {\n setError(value);\n break;\n }\n }\n } catch (error) {\n setError(error);\n }\n });\n\n setStatus(\"awaiting_message\");\n };\n\n return {\n messages,\n input,\n handleInputChange,\n submitMessage,\n status,\n error,\n };\n}\n\nexport function defaultSystemMessage(contextString: string): string {\n return `\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.\n`;\n}\n","export async function processMessageStream(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n processMessage: (message: string) => void | Promise<void>,\n) {\n const decoder = new TextDecoder();\n let buffer = \"\";\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n if (buffer.length > 0) {\n processMessage(buffer);\n }\n break;\n }\n\n buffer += decoder.decode(value, { stream: true });\n\n let endIndex: number;\n while ((endIndex = buffer.indexOf(\"\\n\")) !== -1) {\n processMessage(buffer.substring(0, endIndex).trim());\n buffer = buffer.substring(endIndex + 1); // Remove the processed instruction + delimiter\n }\n }\n}\n","import { FunctionCallHandler, ToolDefinition } from \"@copilotkit/shared\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport React, { Ref } from \"react\";\nimport { TreeNodeId } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the chat API v2.\n */\n chatApiEndpointV2: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Additional body params to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'message': 'Hello, world!'\n * }\n * ```\n */\n body: Record<string, any>;\n\n /**\n * Backend only props that will be combined to body params to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n backendOnlyProps?: Record<string, any>;\n}\n\nexport type InChatRenderFunction = (props: ActionRenderProps<any>) => string | JSX.Element;\n\nexport interface CopilotContextParams {\n // function-calling\n entryPoints: Record<string, FrontendAction<any>>;\n setEntryPoint: (id: string, entryPoint: FrontendAction<any>) => void;\n removeEntryPoint: (id: string) => void;\n chatComponentsCache: React.RefObject<Record<string, InChatRenderFunction | string>>;\n getChatCompletionFunctionDescriptions: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => ToolDefinition[];\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n entryPoints: {},\n setEntryPoint: () => {},\n removeEntryPoint: () => {},\n getChatCompletionFunctionDescriptions: () => returnAndThrowInDebug([]),\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n chatComponentsCache: { current: {} },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n get chatApiEndpointV2(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n return React.useContext(CopilotContext);\n}\n\nfunction returnAndThrowInDebug<T>(value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n return value;\n}\n","import { Ref, useCallback, useRef, useState } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n InChatRenderFunction,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { DocumentPointer } from \"../../types\";\nimport { FunctionCallHandler, actionToChatCompletionFunction } from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { StandardCopilotApiConfig } from \"./standard-copilot-api-config\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { ToolDefinition } from \"@copilotkit/shared\";\n\n/**\n * The CopilotKit component.\n * This component provides the Copilot context to its children.\n * It can be configured either with a chat API endpoint or a CopilotApiConfig.\n *\n * NOTE: The backend can use OpenAI, or you can bring your own LLM.\n * For examples of the backend api implementation, see `examples/next-openai` usage (under `src/api/copilotkit`),\n * or read the documentation at https://docs.copilotkit.ai\n * In particular, Getting-Started > Quickstart-Backend: https://docs.copilotkit.ai/getting-started/quickstart-backend\n *\n * Example usage:\n * ```\n * <CopilotKit url=\"https://your.copilotkit.api\">\n * <App />\n * </CopilotKit>\n * ```\n *\n * or\n *\n * ```\n * const copilotApiConfig = new StandardCopilotApiConfig(\n * \"https://your.copilotkit.api/v1\",\n * \"https://your.copilotkit.api/v2\",\n * {},\n * {}\n * );\n *\n * // ...\n *\n * <CopilotKit chatApiConfig={copilotApiConfig}>\n * <App />\n * </CopilotKit>\n * ```\n *\n * @param props - The props for the component.\n * @returns The CopilotKit component.\n */\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n // Compute all the functions and properties that we need to pass\n // to the CopilotContext.\n\n const [entryPoints, setEntryPoints] = useState<Record<string, FrontendAction<any>>>({});\n const chatComponentsCache = useRef<Record<string, InChatRenderFunction | string>>({});\n const { addElement, removeElement, printTree } = useTree();\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n const setEntryPoint = useCallback((id: string, entryPoint: FrontendAction<any>) => {\n setEntryPoints((prevPoints) => {\n return {\n ...prevPoints,\n [id]: entryPoint,\n };\n });\n }, []);\n\n const removeEntryPoint = useCallback((id: string) => {\n setEntryPoints((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getChatCompletionFunctionDescriptions = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToChatCompletionFunctions(Object.values(customEntryPoints || entryPoints));\n },\n [entryPoints],\n );\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || entryPoints));\n },\n [entryPoints],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = new StandardCopilotApiConfig(\n props.url,\n `${props.url}/v2`,\n props.headers || {},\n {\n ...props.body,\n ...props.backendOnlyProps,\n },\n );\n\n return (\n <CopilotContext.Provider\n value={{\n entryPoints,\n chatComponentsCache,\n getChatCompletionFunctionDescriptions,\n getFunctionCallHandler,\n setEntryPoint,\n removeEntryPoint,\n getContextString,\n addContext,\n removeContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n }}\n >\n {children}\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToChatCompletionFunctions(actions: FrontendAction<any>[]): ToolDefinition[] {\n return actions.map(actionToChatCompletionFunction);\n}\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async (chatMessages, functionCall) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[functionCall.name || \"\"];\n if (action) {\n let functionCallArguments: Record<string, any>[] = [];\n if (functionCall.arguments) {\n functionCallArguments = JSON.parse(functionCall.arguments);\n }\n return await action.handler(functionCallArguments);\n }\n };\n}\n"],"mappings":"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","names":["useState","useState","messages","error"]}
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -1,46 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
} catch (e) {
|
|
7
|
-
reject(e);
|
|
8
|
-
}
|
|
9
|
-
};
|
|
10
|
-
var rejected = (value) => {
|
|
11
|
-
try {
|
|
12
|
-
step(generator.throw(value));
|
|
13
|
-
} catch (e) {
|
|
14
|
-
reject(e);
|
|
15
|
-
}
|
|
16
|
-
};
|
|
17
|
-
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
|
|
18
|
-
step((generator = generator.apply(__this, __arguments)).next());
|
|
19
|
-
});
|
|
20
|
-
};
|
|
21
|
-
|
|
22
|
-
// src/openai-assistants/utils/process-message-stream.ts
|
|
23
|
-
function processMessageStream(reader, processMessage) {
|
|
24
|
-
return __async(this, null, function* () {
|
|
25
|
-
const decoder = new TextDecoder();
|
|
26
|
-
let buffer = "";
|
|
27
|
-
while (true) {
|
|
28
|
-
const { done, value } = yield reader.read();
|
|
29
|
-
if (done) {
|
|
30
|
-
if (buffer.length > 0) {
|
|
31
|
-
processMessage(buffer);
|
|
32
|
-
}
|
|
33
|
-
break;
|
|
34
|
-
}
|
|
35
|
-
buffer += decoder.decode(value, { stream: true });
|
|
36
|
-
let endIndex;
|
|
37
|
-
while ((endIndex = buffer.indexOf("\n")) !== -1) {
|
|
38
|
-
processMessage(buffer.substring(0, endIndex).trim());
|
|
39
|
-
buffer = buffer.substring(endIndex + 1);
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
});
|
|
43
|
-
}
|
|
1
|
+
import "../../chunk-FRAKUJWH.mjs";
|
|
2
|
+
import {
|
|
3
|
+
processMessageStream
|
|
4
|
+
} from "../../chunk-MZ5UN3BY.mjs";
|
|
5
|
+
import "../../chunk-MRXNTQOX.mjs";
|
|
44
6
|
export {
|
|
45
7
|
processMessageStream
|
|
46
8
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -1,46 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
step(generator.next(value));
|
|
6
|
-
} catch (e) {
|
|
7
|
-
reject(e);
|
|
8
|
-
}
|
|
9
|
-
};
|
|
10
|
-
var rejected = (value) => {
|
|
11
|
-
try {
|
|
12
|
-
step(generator.throw(value));
|
|
13
|
-
} catch (e) {
|
|
14
|
-
reject(e);
|
|
15
|
-
}
|
|
16
|
-
};
|
|
17
|
-
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
|
|
18
|
-
step((generator = generator.apply(__this, __arguments)).next());
|
|
19
|
-
});
|
|
20
|
-
};
|
|
21
|
-
|
|
22
|
-
// src/openai-assistants/utils/process-message-stream.ts
|
|
23
|
-
function processMessageStream(reader, processMessage) {
|
|
24
|
-
return __async(this, null, function* () {
|
|
25
|
-
const decoder = new TextDecoder();
|
|
26
|
-
let buffer = "";
|
|
27
|
-
while (true) {
|
|
28
|
-
const { done, value } = yield reader.read();
|
|
29
|
-
if (done) {
|
|
30
|
-
if (buffer.length > 0) {
|
|
31
|
-
processMessage(buffer);
|
|
32
|
-
}
|
|
33
|
-
break;
|
|
34
|
-
}
|
|
35
|
-
buffer += decoder.decode(value, { stream: true });
|
|
36
|
-
let endIndex;
|
|
37
|
-
while ((endIndex = buffer.indexOf("\n")) !== -1) {
|
|
38
|
-
processMessage(buffer.substring(0, endIndex).trim());
|
|
39
|
-
buffer = buffer.substring(endIndex + 1);
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
});
|
|
43
|
-
}
|
|
1
|
+
import {
|
|
2
|
+
processMessageStream
|
|
3
|
+
} from "../../chunk-MZ5UN3BY.mjs";
|
|
4
|
+
import "../../chunk-MRXNTQOX.mjs";
|
|
44
5
|
export {
|
|
45
6
|
processMessageStream
|
|
46
7
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/dist/types/index.mjs
CHANGED
|
@@ -82,11 +82,11 @@ function fetchChatCompletion(_0) {
|
|
|
82
82
|
headers: __spreadValues(__spreadValues({
|
|
83
83
|
"Content-Type": "application/json"
|
|
84
84
|
}, copilotConfig.headers), headers ? __spreadValues({}, headers) : {}),
|
|
85
|
-
body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
|
|
85
|
+
body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
|
|
86
86
|
model,
|
|
87
87
|
messages: cleanedMessages,
|
|
88
88
|
stream: true
|
|
89
|
-
}, tools.length ? { tools } : {}), temperature ? { temperature } : {}), tools.length != 0 ? { tool_choice: "auto" } : {}), copilotConfig.body), copilotConfig.backendOnlyProps), excludeBackendOnlyProps(copilotConfig)), body ? __spreadValues({}, body) : {})),
|
|
89
|
+
}, tools.length ? { tools } : {}), temperature ? { temperature } : {}), tools.length != 0 ? { tool_choice: "auto" } : {}), copilotConfig.body), copilotConfig.backendOnlyProps), excludeBackendOnlyProps(copilotConfig)), body ? __spreadValues({}, body) : {}), copilotConfig.cloud ? { cloud: copilotConfig.cloud } : {})),
|
|
90
90
|
signal
|
|
91
91
|
});
|
|
92
92
|
return response;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/fetch-chat-completion.ts"],"sourcesContent":["import {\n Message,\n ToolDefinition,\n ChatCompletionEvent,\n decodeChatCompletion,\n parseChatCompletion,\n decodeChatCompletionAsText,\n EXCLUDE_FROM_FORWARD_PROPS_KEYS,\n} from \"@copilotkit/shared\";\nimport { CopilotApiConfig } from \"../context\";\n\nexport interface FetchChatCompletionParams {\n copilotConfig: CopilotApiConfig;\n model?: string;\n messages: Message[];\n tools?: ToolDefinition[];\n temperature?: number;\n maxTokens?: number;\n headers?: Record<string, string> | Headers;\n body?: object;\n signal?: AbortSignal;\n}\n\nexport async function fetchChatCompletion({\n copilotConfig,\n model,\n messages,\n tools,\n temperature,\n headers,\n body,\n signal,\n}: FetchChatCompletionParams): Promise<Response> {\n temperature ||= 0.5;\n tools ||= [];\n\n // clean up any extra properties from messages\n const cleanedMessages = messages.map((message) => {\n const { content, role, name, function_call } = message;\n return { content, role, name, function_call };\n });\n\n const response = await fetch(copilotConfig.chatApiEndpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...copilotConfig.headers,\n ...(headers ? { ...headers } : {}),\n },\n body: JSON.stringify({\n model,\n messages: cleanedMessages,\n stream: true,\n ...(tools.length ? { tools } : {}),\n ...(temperature ? { temperature } : {}),\n ...(tools.length != 0 ? { tool_choice: \"auto\" } : {}),\n ...copilotConfig.body,\n ...copilotConfig.backendOnlyProps,\n ...excludeBackendOnlyProps(copilotConfig),\n ...(body ? { ...body } : {}),\n }),\n signal,\n });\n\n return response;\n}\n\nfunction excludeBackendOnlyProps(copilotConfig: any) {\n const backendOnlyProps = copilotConfig.backendOnlyProps ?? {};\n if (Object.keys(backendOnlyProps).length > 0) {\n return {\n [EXCLUDE_FROM_FORWARD_PROPS_KEYS]: Object.keys(backendOnlyProps),\n };\n } else {\n return {};\n }\n}\n\nexport interface DecodedChatCompletionResponse extends Response {\n events: ReadableStream<ChatCompletionEvent> | null;\n}\n\nexport async function fetchAndDecodeChatCompletion(\n params: FetchChatCompletionParams,\n): Promise<DecodedChatCompletionResponse> {\n const response = await fetchChatCompletion(params);\n if (!response.ok || !response.body) {\n (response as any).events = null;\n } else {\n const events = await decodeChatCompletion(parseChatCompletion(response.body));\n (response as any).events = events;\n }\n return response as any;\n}\n\nexport interface DecodedChatCompletionResponseAsText extends Response {\n events: ReadableStream<string> | null;\n}\n\nexport async function fetchAndDecodeChatCompletionAsText(\n params: FetchChatCompletionParams,\n): Promise<DecodedChatCompletionResponseAsText> {\n const response = await fetchChatCompletion(params);\n if (!response.ok || !response.body) {\n (response as any).events = null;\n } else {\n const events = await decodeChatCompletionAsText(\n decodeChatCompletion(parseChatCompletion(response.body)),\n );\n (response as any).events = events;\n }\n\n return response as any;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAQO;AAeP,SAAsB,oBAAoB,IASO;AAAA,6CATP;AAAA,IACxC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAAiD;AAC/C,kCAAgB;AAChB,sBAAU,CAAC;AAGX,UAAM,kBAAkB,SAAS,IAAI,CAAC,YAAY;AAChD,YAAM,EAAE,SAAS,MAAM,MAAM,cAAc,IAAI;AAC/C,aAAO,EAAE,SAAS,MAAM,MAAM,cAAc;AAAA,IAC9C,CAAC;AAED,UAAM,WAAW,MAAM,MAAM,cAAc,iBAAiB;AAAA,MAC1D,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,SACb,cAAc,UACb,UAAU,mBAAK,WAAY,CAAC;AAAA,MAElC,MAAM,KAAK,UAAU;AAAA,QACnB;AAAA,QACA,UAAU;AAAA,QACV,QAAQ;AAAA,SACJ,MAAM,SAAS,EAAE,MAAM,IAAI,CAAC,IAC5B,cAAc,EAAE,YAAY,IAAI,CAAC,IACjC,MAAM,UAAU,IAAI,EAAE,aAAa,OAAO,IAAI,CAAC,IAChD,cAAc,OACd,cAAc,mBACd,wBAAwB,aAAa,IACpC,OAAO,mBAAK,QAAS,CAAC,
|
|
1
|
+
{"version":3,"sources":["../../src/utils/fetch-chat-completion.ts"],"sourcesContent":["import {\n Message,\n ToolDefinition,\n ChatCompletionEvent,\n decodeChatCompletion,\n parseChatCompletion,\n decodeChatCompletionAsText,\n EXCLUDE_FROM_FORWARD_PROPS_KEYS,\n} from \"@copilotkit/shared\";\nimport { CopilotApiConfig } from \"../context\";\n\nexport interface FetchChatCompletionParams {\n copilotConfig: CopilotApiConfig;\n model?: string;\n messages: Message[];\n tools?: ToolDefinition[];\n temperature?: number;\n maxTokens?: number;\n headers?: Record<string, string> | Headers;\n body?: object;\n signal?: AbortSignal;\n}\n\nexport async function fetchChatCompletion({\n copilotConfig,\n model,\n messages,\n tools,\n temperature,\n headers,\n body,\n signal,\n}: FetchChatCompletionParams): Promise<Response> {\n temperature ||= 0.5;\n tools ||= [];\n\n // clean up any extra properties from messages\n const cleanedMessages = messages.map((message) => {\n const { content, role, name, function_call } = message;\n return { content, role, name, function_call };\n });\n\n const response = await fetch(copilotConfig.chatApiEndpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...copilotConfig.headers,\n ...(headers ? { ...headers } : {}),\n },\n body: JSON.stringify({\n model,\n messages: cleanedMessages,\n stream: true,\n ...(tools.length ? { tools } : {}),\n ...(temperature ? { temperature } : {}),\n ...(tools.length != 0 ? { tool_choice: \"auto\" } : {}),\n ...copilotConfig.body,\n ...copilotConfig.backendOnlyProps,\n ...excludeBackendOnlyProps(copilotConfig),\n ...(body ? { ...body } : {}),\n ...(copilotConfig.cloud ? { cloud: copilotConfig.cloud } : {}),\n }),\n signal,\n });\n\n return response;\n}\n\nfunction excludeBackendOnlyProps(copilotConfig: any) {\n const backendOnlyProps = copilotConfig.backendOnlyProps ?? {};\n if (Object.keys(backendOnlyProps).length > 0) {\n return {\n [EXCLUDE_FROM_FORWARD_PROPS_KEYS]: Object.keys(backendOnlyProps),\n };\n } else {\n return {};\n }\n}\n\nexport interface DecodedChatCompletionResponse extends Response {\n events: ReadableStream<ChatCompletionEvent> | null;\n}\n\nexport async function fetchAndDecodeChatCompletion(\n params: FetchChatCompletionParams,\n): Promise<DecodedChatCompletionResponse> {\n const response = await fetchChatCompletion(params);\n if (!response.ok || !response.body) {\n (response as any).events = null;\n } else {\n const events = await decodeChatCompletion(parseChatCompletion(response.body));\n (response as any).events = events;\n }\n return response as any;\n}\n\nexport interface DecodedChatCompletionResponseAsText extends Response {\n events: ReadableStream<string> | null;\n}\n\nexport async function fetchAndDecodeChatCompletionAsText(\n params: FetchChatCompletionParams,\n): Promise<DecodedChatCompletionResponseAsText> {\n const response = await fetchChatCompletion(params);\n if (!response.ok || !response.body) {\n (response as any).events = null;\n } else {\n const events = await decodeChatCompletionAsText(\n decodeChatCompletion(parseChatCompletion(response.body)),\n );\n (response as any).events = events;\n }\n\n return response as any;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAQO;AAeP,SAAsB,oBAAoB,IASO;AAAA,6CATP;AAAA,IACxC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAAiD;AAC/C,kCAAgB;AAChB,sBAAU,CAAC;AAGX,UAAM,kBAAkB,SAAS,IAAI,CAAC,YAAY;AAChD,YAAM,EAAE,SAAS,MAAM,MAAM,cAAc,IAAI;AAC/C,aAAO,EAAE,SAAS,MAAM,MAAM,cAAc;AAAA,IAC9C,CAAC;AAED,UAAM,WAAW,MAAM,MAAM,cAAc,iBAAiB;AAAA,MAC1D,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,SACb,cAAc,UACb,UAAU,mBAAK,WAAY,CAAC;AAAA,MAElC,MAAM,KAAK,UAAU;AAAA,QACnB;AAAA,QACA,UAAU;AAAA,QACV,QAAQ;AAAA,SACJ,MAAM,SAAS,EAAE,MAAM,IAAI,CAAC,IAC5B,cAAc,EAAE,YAAY,IAAI,CAAC,IACjC,MAAM,UAAU,IAAI,EAAE,aAAa,OAAO,IAAI,CAAC,IAChD,cAAc,OACd,cAAc,mBACd,wBAAwB,aAAa,IACpC,OAAO,mBAAK,QAAS,CAAC,IACtB,cAAc,QAAQ,EAAE,OAAO,cAAc,MAAM,IAAI,CAAC,EAC7D;AAAA,MACD;AAAA,IACF,CAAC;AAED,WAAO;AAAA,EACT;AAAA;AAEA,SAAS,wBAAwB,eAAoB;AApErD;AAqEE,QAAM,oBAAmB,mBAAc,qBAAd,YAAkC,CAAC;AAC5D,MAAI,OAAO,KAAK,gBAAgB,EAAE,SAAS,GAAG;AAC5C,WAAO;AAAA,MACL,CAAC,6CAA+B,GAAG,OAAO,KAAK,gBAAgB;AAAA,IACjE;AAAA,EACF,OAAO;AACL,WAAO,CAAC;AAAA,EACV;AACF;AAMA,SAAsB,6BACpB,QACwC;AAAA;AACxC,UAAM,WAAW,MAAM,oBAAoB,MAAM;AACjD,QAAI,CAAC,SAAS,MAAM,CAAC,SAAS,MAAM;AAClC,MAAC,SAAiB,SAAS;AAAA,IAC7B,OAAO;AACL,YAAM,SAAS,UAAM,wCAAqB,mCAAoB,SAAS,IAAI,CAAC;AAC5E,MAAC,SAAiB,SAAS;AAAA,IAC7B;AACA,WAAO;AAAA,EACT;AAAA;AAMA,SAAsB,mCACpB,QAC8C;AAAA;AAC9C,UAAM,WAAW,MAAM,oBAAoB,MAAM;AACjD,QAAI,CAAC,SAAS,MAAM,CAAC,SAAS,MAAM;AAClC,MAAC,SAAiB,SAAS;AAAA,IAC7B,OAAO;AACL,YAAM,SAAS,UAAM;AAAA,YACnB,wCAAqB,mCAAoB,SAAS,IAAI,CAAC;AAAA,MACzD;AACA,MAAC,SAAiB,SAAS;AAAA,IAC7B;AAEA,WAAO;AAAA,EACT;AAAA;","names":[]}
|
|
@@ -1,116 +1,9 @@
|
|
|
1
|
-
var __defProp = Object.defineProperty;
|
|
2
|
-
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
3
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
4
|
-
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
5
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
6
|
-
var __spreadValues = (a, b) => {
|
|
7
|
-
for (var prop in b || (b = {}))
|
|
8
|
-
if (__hasOwnProp.call(b, prop))
|
|
9
|
-
__defNormalProp(a, prop, b[prop]);
|
|
10
|
-
if (__getOwnPropSymbols)
|
|
11
|
-
for (var prop of __getOwnPropSymbols(b)) {
|
|
12
|
-
if (__propIsEnum.call(b, prop))
|
|
13
|
-
__defNormalProp(a, prop, b[prop]);
|
|
14
|
-
}
|
|
15
|
-
return a;
|
|
16
|
-
};
|
|
17
|
-
var __async = (__this, __arguments, generator) => {
|
|
18
|
-
return new Promise((resolve, reject) => {
|
|
19
|
-
var fulfilled = (value) => {
|
|
20
|
-
try {
|
|
21
|
-
step(generator.next(value));
|
|
22
|
-
} catch (e) {
|
|
23
|
-
reject(e);
|
|
24
|
-
}
|
|
25
|
-
};
|
|
26
|
-
var rejected = (value) => {
|
|
27
|
-
try {
|
|
28
|
-
step(generator.throw(value));
|
|
29
|
-
} catch (e) {
|
|
30
|
-
reject(e);
|
|
31
|
-
}
|
|
32
|
-
};
|
|
33
|
-
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
|
|
34
|
-
step((generator = generator.apply(__this, __arguments)).next());
|
|
35
|
-
});
|
|
36
|
-
};
|
|
37
|
-
|
|
38
|
-
// src/utils/fetch-chat-completion.ts
|
|
39
1
|
import {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
function fetchChatCompletion(_0) {
|
|
46
|
-
return __async(this, arguments, function* ({
|
|
47
|
-
copilotConfig,
|
|
48
|
-
model,
|
|
49
|
-
messages,
|
|
50
|
-
tools,
|
|
51
|
-
temperature,
|
|
52
|
-
headers,
|
|
53
|
-
body,
|
|
54
|
-
signal
|
|
55
|
-
}) {
|
|
56
|
-
temperature || (temperature = 0.5);
|
|
57
|
-
tools || (tools = []);
|
|
58
|
-
const cleanedMessages = messages.map((message) => {
|
|
59
|
-
const { content, role, name, function_call } = message;
|
|
60
|
-
return { content, role, name, function_call };
|
|
61
|
-
});
|
|
62
|
-
const response = yield fetch(copilotConfig.chatApiEndpoint, {
|
|
63
|
-
method: "POST",
|
|
64
|
-
headers: __spreadValues(__spreadValues({
|
|
65
|
-
"Content-Type": "application/json"
|
|
66
|
-
}, copilotConfig.headers), headers ? __spreadValues({}, headers) : {}),
|
|
67
|
-
body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
|
|
68
|
-
model,
|
|
69
|
-
messages: cleanedMessages,
|
|
70
|
-
stream: true
|
|
71
|
-
}, tools.length ? { tools } : {}), temperature ? { temperature } : {}), tools.length != 0 ? { tool_choice: "auto" } : {}), copilotConfig.body), copilotConfig.backendOnlyProps), excludeBackendOnlyProps(copilotConfig)), body ? __spreadValues({}, body) : {})),
|
|
72
|
-
signal
|
|
73
|
-
});
|
|
74
|
-
return response;
|
|
75
|
-
});
|
|
76
|
-
}
|
|
77
|
-
function excludeBackendOnlyProps(copilotConfig) {
|
|
78
|
-
var _a;
|
|
79
|
-
const backendOnlyProps = (_a = copilotConfig.backendOnlyProps) != null ? _a : {};
|
|
80
|
-
if (Object.keys(backendOnlyProps).length > 0) {
|
|
81
|
-
return {
|
|
82
|
-
[EXCLUDE_FROM_FORWARD_PROPS_KEYS]: Object.keys(backendOnlyProps)
|
|
83
|
-
};
|
|
84
|
-
} else {
|
|
85
|
-
return {};
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
function fetchAndDecodeChatCompletion(params) {
|
|
89
|
-
return __async(this, null, function* () {
|
|
90
|
-
const response = yield fetchChatCompletion(params);
|
|
91
|
-
if (!response.ok || !response.body) {
|
|
92
|
-
response.events = null;
|
|
93
|
-
} else {
|
|
94
|
-
const events = yield decodeChatCompletion(parseChatCompletion(response.body));
|
|
95
|
-
response.events = events;
|
|
96
|
-
}
|
|
97
|
-
return response;
|
|
98
|
-
});
|
|
99
|
-
}
|
|
100
|
-
function fetchAndDecodeChatCompletionAsText(params) {
|
|
101
|
-
return __async(this, null, function* () {
|
|
102
|
-
const response = yield fetchChatCompletion(params);
|
|
103
|
-
if (!response.ok || !response.body) {
|
|
104
|
-
response.events = null;
|
|
105
|
-
} else {
|
|
106
|
-
const events = yield decodeChatCompletionAsText(
|
|
107
|
-
decodeChatCompletion(parseChatCompletion(response.body))
|
|
108
|
-
);
|
|
109
|
-
response.events = events;
|
|
110
|
-
}
|
|
111
|
-
return response;
|
|
112
|
-
});
|
|
113
|
-
}
|
|
2
|
+
fetchAndDecodeChatCompletion,
|
|
3
|
+
fetchAndDecodeChatCompletionAsText,
|
|
4
|
+
fetchChatCompletion
|
|
5
|
+
} from "../chunk-CGT3AVYT.mjs";
|
|
6
|
+
import "../chunk-MRXNTQOX.mjs";
|
|
114
7
|
export {
|
|
115
8
|
fetchAndDecodeChatCompletion,
|
|
116
9
|
fetchAndDecodeChatCompletionAsText,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/package.json
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public"
|
|
6
6
|
},
|
|
7
|
-
"version": "0.25.0-
|
|
7
|
+
"version": "0.25.0-mme-cloud.0",
|
|
8
8
|
"sideEffects": false,
|
|
9
9
|
"main": "./dist/index.js",
|
|
10
10
|
"module": "./dist/index.mjs",
|
|
@@ -29,13 +29,13 @@
|
|
|
29
29
|
"ts-jest": "^29.1.1",
|
|
30
30
|
"tsup": "^6.7.0",
|
|
31
31
|
"typescript": "^5.2.3",
|
|
32
|
-
"eslint-config-custom": "0.10.0-
|
|
33
|
-
"tsconfig": "0.14.0-
|
|
32
|
+
"eslint-config-custom": "0.10.0-mme-cloud.0",
|
|
33
|
+
"tsconfig": "0.14.0-mme-cloud.0"
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
36
|
"nanoid": "^4.0.2",
|
|
37
37
|
"untruncate-json": "^0.0.1",
|
|
38
|
-
"@copilotkit/shared": "0.9.0-
|
|
38
|
+
"@copilotkit/shared": "0.9.0-mme-cloud.0"
|
|
39
39
|
},
|
|
40
40
|
"scripts": {
|
|
41
41
|
"build": "tsup --clean",
|
|
@@ -5,6 +5,20 @@ import { ReactNode } from "react";
|
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
export interface CopilotKitProps {
|
|
8
|
+
/**
|
|
9
|
+
* The api key for Copilot Cloud.
|
|
10
|
+
*/
|
|
11
|
+
apiKey?: string;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Cloud feature: Restrict to a specific topic.
|
|
15
|
+
*/
|
|
16
|
+
cloudRestrictToTopic?: {
|
|
17
|
+
enabled?: boolean;
|
|
18
|
+
validTopics: string[];
|
|
19
|
+
invalidTopics?: string[];
|
|
20
|
+
};
|
|
21
|
+
|
|
8
22
|
/**
|
|
9
23
|
* The endpoint for the chat API.
|
|
10
24
|
*/
|
|
@@ -6,10 +6,9 @@ import {
|
|
|
6
6
|
} from "../../context/copilot-context";
|
|
7
7
|
import useTree from "../../hooks/use-tree";
|
|
8
8
|
import { DocumentPointer } from "../../types";
|
|
9
|
-
import { FunctionCallHandler, actionToChatCompletionFunction } from "@copilotkit/shared";
|
|
9
|
+
import { FunctionCallHandler, Message, actionToChatCompletionFunction } from "@copilotkit/shared";
|
|
10
10
|
import { FrontendAction } from "../../types/frontend-action";
|
|
11
11
|
import useFlatCategoryStore from "../../hooks/use-flat-category-store";
|
|
12
|
-
import { StandardCopilotApiConfig } from "./standard-copilot-api-config";
|
|
13
12
|
import { CopilotKitProps } from "./copilotkit-props";
|
|
14
13
|
import { ToolDefinition } from "@copilotkit/shared";
|
|
15
14
|
|
|
@@ -30,23 +29,6 @@ import { ToolDefinition } from "@copilotkit/shared";
|
|
|
30
29
|
* </CopilotKit>
|
|
31
30
|
* ```
|
|
32
31
|
*
|
|
33
|
-
* or
|
|
34
|
-
*
|
|
35
|
-
* ```
|
|
36
|
-
* const copilotApiConfig = new StandardCopilotApiConfig(
|
|
37
|
-
* "https://your.copilotkit.api/v1",
|
|
38
|
-
* "https://your.copilotkit.api/v2",
|
|
39
|
-
* {},
|
|
40
|
-
* {}
|
|
41
|
-
* );
|
|
42
|
-
*
|
|
43
|
-
* // ...
|
|
44
|
-
*
|
|
45
|
-
* <CopilotKit chatApiConfig={copilotApiConfig}>
|
|
46
|
-
* <App />
|
|
47
|
-
* </CopilotKit>
|
|
48
|
-
* ```
|
|
49
|
-
*
|
|
50
32
|
* @param props - The props for the component.
|
|
51
33
|
* @returns The CopilotKit component.
|
|
52
34
|
*/
|
|
@@ -57,6 +39,7 @@ export function CopilotKit({ children, ...props }: CopilotKitProps) {
|
|
|
57
39
|
const [entryPoints, setEntryPoints] = useState<Record<string, FrontendAction<any>>>({});
|
|
58
40
|
const chatComponentsCache = useRef<Record<string, InChatRenderFunction | string>>({});
|
|
59
41
|
const { addElement, removeElement, printTree } = useTree();
|
|
42
|
+
const [messages, setMessages] = useState<Message[]>([]);
|
|
60
43
|
|
|
61
44
|
const {
|
|
62
45
|
addElement: addDocument,
|
|
@@ -149,16 +132,27 @@ export function CopilotKit({ children, ...props }: CopilotKitProps) {
|
|
|
149
132
|
[removeDocument],
|
|
150
133
|
);
|
|
151
134
|
|
|
135
|
+
if (!props.apiKey) {
|
|
136
|
+
if (props.cloudRestrictToTopic) {
|
|
137
|
+
throw new Error(
|
|
138
|
+
"To use the cloudRestrictToTopic feature, please sign up at https://copilotkit.ai and provide an apiKey.",
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
152
143
|
// get the appropriate CopilotApiConfig from the props
|
|
153
|
-
const copilotApiConfig: CopilotApiConfig =
|
|
154
|
-
props.
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
144
|
+
const copilotApiConfig: CopilotApiConfig = {
|
|
145
|
+
...(props.apiKey
|
|
146
|
+
? { cloud: { apiKey: props.apiKey, restrictToTopic: props.cloudRestrictToTopic } }
|
|
147
|
+
: {}),
|
|
148
|
+
chatApiEndpoint: props.url,
|
|
149
|
+
chatApiEndpointV2: `${props.url}/v2`,
|
|
150
|
+
headers: props.headers || {},
|
|
151
|
+
body: {
|
|
158
152
|
...props.body,
|
|
159
153
|
...props.backendOnlyProps,
|
|
160
154
|
},
|
|
161
|
-
|
|
155
|
+
};
|
|
162
156
|
|
|
163
157
|
return (
|
|
164
158
|
<CopilotContext.Provider
|
|
@@ -176,6 +170,8 @@ export function CopilotKit({ children, ...props }: CopilotKitProps) {
|
|
|
176
170
|
addDocumentContext,
|
|
177
171
|
removeDocumentContext,
|
|
178
172
|
copilotApiConfig: copilotApiConfig,
|
|
173
|
+
messages,
|
|
174
|
+
setMessages,
|
|
179
175
|
}}
|
|
180
176
|
>
|
|
181
177
|
{children}
|
|
@@ -1,13 +1,26 @@
|
|
|
1
|
-
import { FunctionCallHandler, ToolDefinition } from "@copilotkit/shared";
|
|
1
|
+
import { FunctionCallHandler, Message, ToolDefinition } from "@copilotkit/shared";
|
|
2
2
|
import { ActionRenderProps, FrontendAction } from "../types/frontend-action";
|
|
3
3
|
import React, { Ref } from "react";
|
|
4
4
|
import { TreeNodeId } from "../hooks/use-tree";
|
|
5
5
|
import { DocumentPointer } from "../types";
|
|
6
6
|
|
|
7
|
+
export interface CopilotCloudConfig {
|
|
8
|
+
apiKey: string;
|
|
9
|
+
restrictToTopic?: {
|
|
10
|
+
validTopics: string[];
|
|
11
|
+
invalidTopics?: string[];
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
|
|
7
15
|
/**
|
|
8
16
|
* Interface for the configuration of the Copilot API.
|
|
9
17
|
*/
|
|
10
18
|
export interface CopilotApiConfig {
|
|
19
|
+
/**
|
|
20
|
+
* The configuration for Copilot Cloud.
|
|
21
|
+
*/
|
|
22
|
+
cloud?: CopilotCloudConfig;
|
|
23
|
+
|
|
11
24
|
/**
|
|
12
25
|
* The endpoint for the chat API.
|
|
13
26
|
*/
|
|
@@ -70,6 +83,9 @@ export interface CopilotContextParams {
|
|
|
70
83
|
customEntryPoints?: Record<string, FrontendAction<any>>,
|
|
71
84
|
) => FunctionCallHandler;
|
|
72
85
|
|
|
86
|
+
messages: Message[];
|
|
87
|
+
setMessages: React.Dispatch<React.SetStateAction<Message[]>>;
|
|
88
|
+
|
|
73
89
|
// text context
|
|
74
90
|
addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;
|
|
75
91
|
removeContext: (id: TreeNodeId) => void;
|
|
@@ -95,6 +111,8 @@ const emptyCopilotContext: CopilotContextParams = {
|
|
|
95
111
|
returnAndThrowInDebug(""),
|
|
96
112
|
addContext: () => "",
|
|
97
113
|
removeContext: () => {},
|
|
114
|
+
messages: [],
|
|
115
|
+
setMessages: () => returnAndThrowInDebug([]),
|
|
98
116
|
|
|
99
117
|
getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),
|
|
100
118
|
addDocumentContext: () => returnAndThrowInDebug(""),
|
package/src/hooks/use-chat.ts
CHANGED
|
@@ -58,8 +58,6 @@ export type UseChatOptions = {
|
|
|
58
58
|
};
|
|
59
59
|
|
|
60
60
|
export type UseChatHelpers = {
|
|
61
|
-
/** Current messages in the chat */
|
|
62
|
-
messages: Message[];
|
|
63
61
|
/**
|
|
64
62
|
* Append a user message to the chat list. This triggers the API call to fetch
|
|
65
63
|
* the assistant's response.
|
|
@@ -86,10 +84,18 @@ export type UseChatHelpers = {
|
|
|
86
84
|
|
|
87
85
|
export type UseChatOptionsWithCopilotConfig = UseChatOptions & {
|
|
88
86
|
copilotConfig: CopilotApiConfig;
|
|
87
|
+
/**
|
|
88
|
+
* The current list of messages in the chat.
|
|
89
|
+
*/
|
|
90
|
+
messages: Message[];
|
|
91
|
+
/**
|
|
92
|
+
* The setState-powered method to update the chat messages.
|
|
93
|
+
*/
|
|
94
|
+
setMessages: React.Dispatch<React.SetStateAction<Message[]>>;
|
|
89
95
|
};
|
|
90
96
|
|
|
91
97
|
export function useChat(options: UseChatOptionsWithCopilotConfig): UseChatHelpers {
|
|
92
|
-
const
|
|
98
|
+
const { messages, setMessages } = options;
|
|
93
99
|
const [input, setInput] = useState("");
|
|
94
100
|
const [isLoading, setIsLoading] = useState(false);
|
|
95
101
|
const abortControllerRef = useRef<AbortController>();
|
|
@@ -296,7 +302,6 @@ export function useChat(options: UseChatOptionsWithCopilotConfig): UseChatHelper
|
|
|
296
302
|
};
|
|
297
303
|
|
|
298
304
|
return {
|
|
299
|
-
messages,
|
|
300
305
|
append,
|
|
301
306
|
reload,
|
|
302
307
|
stop,
|
|
@@ -1,13 +1,63 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { useRef, useContext, useEffect } from "react";
|
|
2
2
|
import { FrontendAction } from "../types/frontend-action";
|
|
3
|
-
import {
|
|
3
|
+
import { CopilotContext } from "../context/copilot-context";
|
|
4
|
+
import { nanoid } from "nanoid";
|
|
5
|
+
import { Parameter } from "@copilotkit/shared";
|
|
6
|
+
|
|
7
|
+
// We implement useCopilotActionImplementation dependency handling so that
|
|
8
|
+
// the developer has the option to not provide any dependencies.
|
|
9
|
+
// In this case, we assume they want to update the handler on each rerender.
|
|
10
|
+
// To avoid getting stuck in an infinite loop, we update the handler directly,
|
|
11
|
+
// skipping React state updates.
|
|
12
|
+
// This is ok in this case, because the handler is not part of any UI that
|
|
13
|
+
// needs to be updated.
|
|
14
|
+
// useCallback, useMemo or other memoization techniques are not suitable here,
|
|
15
|
+
// because they will cause a infinite rerender loop.
|
|
16
|
+
export function useCopilotAction<const T extends Parameter[] | [] = []>(
|
|
17
|
+
action: FrontendAction<T>,
|
|
18
|
+
dependencies?: any[],
|
|
19
|
+
): void {
|
|
20
|
+
const { setEntryPoint, removeEntryPoint, entryPoints, chatComponentsCache } =
|
|
21
|
+
useContext(CopilotContext);
|
|
22
|
+
const idRef = useRef<string>(nanoid());
|
|
4
23
|
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
24
|
+
// If the developer doesn't provide dependencies, we assume they want to
|
|
25
|
+
// update handler and render function when the action object changes.
|
|
26
|
+
// This ensures that any captured variables in the handler are up to date.
|
|
27
|
+
if (dependencies === undefined) {
|
|
28
|
+
if (entryPoints[idRef.current]) {
|
|
29
|
+
entryPoints[idRef.current].handler = action.handler;
|
|
30
|
+
if (typeof action.render === "function") {
|
|
31
|
+
if (chatComponentsCache.current !== null) {
|
|
32
|
+
chatComponentsCache.current[action.name] = action.render;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
useEffect(() => {
|
|
39
|
+
setEntryPoint(idRef.current, action);
|
|
40
|
+
if (chatComponentsCache.current !== null && action.render !== undefined) {
|
|
41
|
+
chatComponentsCache.current[action.name] = action.render;
|
|
42
|
+
}
|
|
43
|
+
return () => {
|
|
44
|
+
// NOTE: For now, we don't remove the chatComponentsCache entry when the action is removed.
|
|
45
|
+
// This is because we currently don't have access to the messages array in CopilotContext.
|
|
46
|
+
removeEntryPoint(idRef.current);
|
|
47
|
+
};
|
|
48
|
+
}, [
|
|
49
|
+
setEntryPoint,
|
|
50
|
+
removeEntryPoint,
|
|
51
|
+
action.description,
|
|
52
|
+
action.name,
|
|
53
|
+
// This should be faster than deep equality checking
|
|
54
|
+
// In addition, all major JS engines guarantee the order of object keys
|
|
55
|
+
JSON.stringify(action.parameters),
|
|
56
|
+
// include render only if it's a string
|
|
57
|
+
typeof action.render === "string" ? action.render : undefined,
|
|
58
|
+
// dependencies set by the developer
|
|
59
|
+
...(dependencies || []),
|
|
60
|
+
]);
|
|
11
61
|
}
|
|
12
62
|
|
|
13
63
|
// Usage Example:
|
|
@@ -39,5 +89,3 @@ export function useCopilotAction<const T extends Parameter[] | [] = []>(action:
|
|
|
39
89
|
// console.log("No parameters provided.");
|
|
40
90
|
// },
|
|
41
91
|
// });
|
|
42
|
-
|
|
43
|
-
// https://community.openai.com/t/function-call-complex-arrays-as-parameters/295648/3
|