@copilotkit/react-core 0.37.0 → 0.38.0-beta.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 +187 -234
- package/CHANGELOG.md +12 -0
- package/dist/{chunk-HUKLBIUK.mjs → chunk-5CKW6KE7.mjs} +13 -22
- package/dist/chunk-5CKW6KE7.mjs.map +1 -0
- package/dist/{chunk-S5LWO5V3.mjs → chunk-7GPIOOXB.mjs} +2 -2
- package/dist/{chunk-LLU5URI5.mjs → chunk-DDHJCFFV.mjs} +18 -33
- package/dist/chunk-DDHJCFFV.mjs.map +1 -0
- package/dist/{chunk-SR4RW4CU.mjs → chunk-IQCLNCGL.mjs} +6 -6
- package/dist/chunk-IQCLNCGL.mjs.map +1 -0
- package/dist/{chunk-DY63PD22.mjs → chunk-K6EV2CNB.mjs} +4 -5
- package/dist/chunk-K6EV2CNB.mjs.map +1 -0
- package/dist/{chunk-NSUYO6TP.mjs → chunk-LZVHW3T3.mjs} +9 -9
- package/dist/chunk-LZVHW3T3.mjs.map +1 -0
- package/dist/{chunk-Z5FB4WBL.mjs → chunk-NY6QSOU7.mjs} +43 -40
- package/dist/chunk-NY6QSOU7.mjs.map +1 -0
- package/dist/chunk-PHMHNAYC.mjs +192 -0
- package/dist/chunk-PHMHNAYC.mjs.map +1 -0
- package/dist/{chunk-B244LK6F.mjs → chunk-QNJQKKD4.mjs} +2 -2
- package/dist/{chunk-4OIVQMEM.mjs → chunk-WU3I3G3G.mjs} +60 -42
- package/dist/chunk-WU3I3G3G.mjs.map +1 -0
- package/dist/chunk-YJLRG5U3.mjs +1 -0
- package/dist/{chunk-MNZXQ6UH.mjs → chunk-YM2JV2YQ.mjs} +2 -2
- package/dist/components/copilot-provider/copilotkit-props.d.ts +2 -2
- package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.js +18 -33
- package/dist/components/copilot-provider/copilotkit.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.mjs +2 -2
- package/dist/components/copilot-provider/index.js +18 -33
- package/dist/components/copilot-provider/index.js.map +1 -1
- package/dist/components/copilot-provider/index.mjs +2 -2
- package/dist/components/index.js +18 -33
- package/dist/components/index.js.map +1 -1
- package/dist/components/index.mjs +2 -2
- package/dist/context/copilot-context.d.ts +7 -18
- package/dist/context/copilot-context.js +3 -4
- package/dist/context/copilot-context.js.map +1 -1
- package/dist/context/copilot-context.mjs +1 -1
- package/dist/context/index.d.ts +1 -0
- package/dist/context/index.js +3 -4
- package/dist/context/index.js.map +1 -1
- package/dist/context/index.mjs +1 -1
- package/dist/hooks/index.d.ts +2 -1
- package/dist/hooks/index.js +140 -229
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +9 -10
- package/dist/hooks/use-chat.d.ts +25 -51
- package/dist/hooks/use-chat.js +109 -203
- package/dist/hooks/use-chat.js.map +1 -1
- package/dist/hooks/use-chat.mjs +1 -2
- package/dist/hooks/use-copilot-action.js +10 -11
- package/dist/hooks/use-copilot-action.js.map +1 -1
- package/dist/hooks/use-copilot-action.mjs +2 -2
- package/dist/hooks/use-copilot-chat.d.ts +1 -1
- package/dist/hooks/use-copilot-chat.js +123 -212
- package/dist/hooks/use-copilot-chat.js.map +1 -1
- package/dist/hooks/use-copilot-chat.mjs +4 -5
- package/dist/hooks/use-copilot-readable.js +3 -4
- package/dist/hooks/use-copilot-readable.js.map +1 -1
- package/dist/hooks/use-copilot-readable.mjs +2 -2
- package/dist/hooks/use-make-copilot-actionable.js +7 -8
- package/dist/hooks/use-make-copilot-actionable.js.map +1 -1
- package/dist/hooks/use-make-copilot-actionable.mjs +2 -2
- package/dist/hooks/use-make-copilot-document-readable.js +3 -4
- package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
- package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
- package/dist/hooks/use-make-copilot-readable.js +3 -4
- package/dist/hooks/use-make-copilot-readable.js.map +1 -1
- package/dist/hooks/use-make-copilot-readable.mjs +2 -2
- package/dist/index.d.ts +1 -3
- package/dist/index.js +239 -497
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +12 -31
- package/dist/lib/copilot-task.d.ts +1 -0
- package/dist/lib/copilot-task.js +34 -110
- package/dist/lib/copilot-task.js.map +1 -1
- package/dist/lib/copilot-task.mjs +3 -4
- package/dist/lib/index.d.ts +1 -0
- package/dist/lib/index.js +36 -110
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/index.mjs +3 -4
- package/dist/utils/extract.d.ts +1 -0
- package/dist/utils/extract.js +53 -109
- package/dist/utils/extract.js.map +1 -1
- package/dist/utils/extract.mjs +3 -4
- package/dist/utils/index.d.ts +1 -1
- package/dist/utils/index.js +56 -132
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/index.mjs +5 -13
- package/package.json +6 -5
- package/src/components/copilot-provider/copilotkit-props.tsx +2 -2
- package/src/components/copilot-provider/copilotkit.tsx +16 -37
- package/src/context/copilot-context.tsx +11 -30
- package/src/hooks/use-chat.ts +179 -208
- package/src/hooks/use-copilot-action.ts +7 -8
- package/src/hooks/use-copilot-chat.ts +9 -23
- package/src/hooks/use-make-copilot-actionable.ts +4 -4
- package/src/index.tsx +0 -1
- package/src/lib/copilot-task.ts +45 -42
- package/src/utils/extract.ts +64 -36
- package/src/utils/index.ts +0 -7
- package/dist/chunk-2EQGN5QK.mjs +0 -137
- package/dist/chunk-2EQGN5QK.mjs.map +0 -1
- package/dist/chunk-4OIVQMEM.mjs.map +0 -1
- package/dist/chunk-7GFKOIO7.mjs +0 -1
- package/dist/chunk-B2H3NC4E.mjs +0 -204
- package/dist/chunk-B2H3NC4E.mjs.map +0 -1
- package/dist/chunk-BABVSMJR.mjs +0 -1
- package/dist/chunk-BABVSMJR.mjs.map +0 -1
- package/dist/chunk-CYDWEPFL.mjs +0 -1
- package/dist/chunk-CYDWEPFL.mjs.map +0 -1
- package/dist/chunk-DY63PD22.mjs.map +0 -1
- package/dist/chunk-FRAKUJWH.mjs +0 -1
- package/dist/chunk-FRAKUJWH.mjs.map +0 -1
- package/dist/chunk-HUKLBIUK.mjs.map +0 -1
- package/dist/chunk-LLU5URI5.mjs.map +0 -1
- package/dist/chunk-MJKBCG4U.mjs +0 -91
- package/dist/chunk-MJKBCG4U.mjs.map +0 -1
- package/dist/chunk-NSUYO6TP.mjs.map +0 -1
- package/dist/chunk-SR4RW4CU.mjs.map +0 -1
- package/dist/chunk-Z5FB4WBL.mjs.map +0 -1
- package/dist/chunk-ZFS5SQUT.mjs +0 -31
- package/dist/chunk-ZFS5SQUT.mjs.map +0 -1
- package/dist/openai-assistants/hooks/index.d.ts +0 -2
- package/dist/openai-assistants/hooks/index.js +0 -277
- package/dist/openai-assistants/hooks/index.js.map +0 -1
- package/dist/openai-assistants/hooks/index.mjs +0 -18
- package/dist/openai-assistants/hooks/index.mjs.map +0 -1
- package/dist/openai-assistants/hooks/use-assistants.d.ts +0 -17
- package/dist/openai-assistants/hooks/use-assistants.js +0 -154
- package/dist/openai-assistants/hooks/use-assistants.js.map +0 -1
- package/dist/openai-assistants/hooks/use-assistants.mjs +0 -92
- package/dist/openai-assistants/hooks/use-assistants.mjs.map +0 -1
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.d.ts +0 -44
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.js +0 -277
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.js.map +0 -1
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs +0 -19
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs.map +0 -1
- package/dist/openai-assistants/index.d.ts +0 -3
- package/dist/openai-assistants/index.js +0 -279
- package/dist/openai-assistants/index.js.map +0 -1
- package/dist/openai-assistants/index.mjs +0 -22
- package/dist/openai-assistants/index.mjs.map +0 -1
- package/dist/openai-assistants/utils/index.d.ts +0 -1
- package/dist/openai-assistants/utils/index.js +0 -73
- package/dist/openai-assistants/utils/index.js.map +0 -1
- package/dist/openai-assistants/utils/index.mjs +0 -9
- package/dist/openai-assistants/utils/index.mjs.map +0 -1
- package/dist/openai-assistants/utils/process-message-stream.d.ts +0 -3
- package/dist/openai-assistants/utils/process-message-stream.js +0 -71
- package/dist/openai-assistants/utils/process-message-stream.js.map +0 -1
- package/dist/openai-assistants/utils/process-message-stream.mjs +0 -8
- package/dist/openai-assistants/utils/process-message-stream.mjs.map +0 -1
- package/dist/utils/fetch-chat-completion.d.ts +0 -36
- package/dist/utils/fetch-chat-completion.js +0 -141
- package/dist/utils/fetch-chat-completion.js.map +0 -1
- package/dist/utils/fetch-chat-completion.mjs +0 -12
- package/dist/utils/fetch-chat-completion.mjs.map +0 -1
- package/src/openai-assistants/hooks/index.ts +0 -9
- package/src/openai-assistants/hooks/use-assistants.ts +0 -112
- package/src/openai-assistants/hooks/use-copilot-chat-v2.ts +0 -189
- package/src/openai-assistants/index.ts +0 -2
- package/src/openai-assistants/utils/index.ts +0 -1
- package/src/openai-assistants/utils/process-message-stream.ts +0 -25
- package/src/utils/fetch-chat-completion.ts +0 -120
- /package/dist/{chunk-S5LWO5V3.mjs.map → chunk-7GPIOOXB.mjs.map} +0 -0
- /package/dist/{chunk-B244LK6F.mjs.map → chunk-QNJQKKD4.mjs.map} +0 -0
- /package/dist/{chunk-7GFKOIO7.mjs.map → chunk-YJLRG5U3.mjs.map} +0 -0
- /package/dist/{chunk-MNZXQ6UH.mjs.map → chunk-YM2JV2YQ.mjs.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/use-chat.ts"],"sourcesContent":["import { useRef, useState, useContext, useEffect } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport {\n Message,\n ToolDefinition,\n FunctionCallHandler,\n encodeResult,\n FunctionCall,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n} from \"@copilotkit/shared\";\n\nimport { nanoid } from \"nanoid\";\nimport { fetchAndDecodeChatCompletion } from \"../utils/fetch-chat-completion\";\nimport { CopilotApiConfig } from \"../context\";\nimport untruncateJson from \"untruncate-json\";\n\nexport type UseChatOptions = {\n /**\n * The API endpoint that accepts a `{ messages: Message[] }` object and returns\n * a stream of tokens of the AI chat response. Defaults to `/api/chat`.\n */\n api?: string;\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n /**\n * Callback function to be called when a function call is received.\n * If the function returns a `ChatRequest` object, the request will be sent\n * automatically to the API and will be used to update the chat.\n */\n onFunctionCall?: FunctionCallHandler;\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 /**\n * Function definitions to be sent to the API.\n */\n tools?: ToolDefinition[];\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: () => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n};\n\nexport type UseChatOptionsWithCopilotConfig = UseChatOptions & {\n copilotConfig: CopilotApiConfig;\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * A callback to get the latest system message.\n */\n makeSystemMessageCallback: () => Message;\n\n /**\n * Whether the API request is in progress\n */\n isLoading: boolean;\n\n /**\n * setState-powered method to update the isChatLoading value\n */\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n};\n\nexport function useChat(options: UseChatOptionsWithCopilotConfig): UseChatHelpers {\n const { messages, setMessages, makeSystemMessageCallback } = options;\n const abortControllerRef = useRef<AbortController>();\n const threadIdRef = useRef<string | null>(null);\n const runIdRef = useRef<string | null>(null);\n const publicApiKey = options.copilotConfig.publicApiKey;\n const headers = {\n ...(options.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const runChatCompletion = async (messages: Message[]): Promise<Message[]> => {\n options.setIsLoading(true);\n\n const newMessages: Message[] = [\n {\n id: nanoid(),\n createdAt: new Date(),\n content: \"\",\n role: \"assistant\",\n },\n ];\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setMessages([...messages, ...newMessages]);\n // add threadId and runId to the body if it exists\n const copilotConfigBody = options.copilotConfig.body || {};\n if (threadIdRef.current) {\n copilotConfigBody.threadId = threadIdRef.current;\n }\n if (runIdRef.current) {\n copilotConfigBody.runId = runIdRef.current;\n }\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(options.initialMessages || []), ...messages];\n const response = await fetchAndDecodeChatCompletion({\n copilotConfig: { ...options.copilotConfig, body: copilotConfigBody },\n messages: messagesWithContext,\n tools: options.tools,\n headers: headers,\n signal: abortController.signal,\n });\n\n if (response.headers.get(\"threadid\")) {\n threadIdRef.current = response.headers.get(\"threadid\");\n }\n\n if (response.headers.get(\"runid\")) {\n runIdRef.current = response.headers.get(\"runid\");\n }\n\n if (!response.events) {\n setMessages([\n ...messages,\n {\n id: nanoid(),\n createdAt: new Date(),\n content: response.statusText,\n role: \"assistant\",\n },\n ]);\n options.setIsLoading(false);\n throw new Error(\"Failed to fetch chat completion\");\n }\n\n const reader = response.events.getReader();\n\n // Whether to feed back the new messages to GPT\n let feedback = false;\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n let currentMessage = Object.assign({}, newMessages[newMessages.length - 1]);\n\n if (value.type === \"content\") {\n if (currentMessage.function_call || currentMessage.role === \"function\") {\n // Create a new message if the previous one is a function call or result\n currentMessage = {\n id: nanoid(),\n createdAt: new Date(),\n content: \"\",\n role: \"assistant\",\n };\n newMessages.push(currentMessage);\n }\n currentMessage.content += value.content;\n newMessages[newMessages.length - 1] = currentMessage;\n setMessages([...messages, ...newMessages]);\n } else if (value.type === \"result\") {\n // When we get a result message, it is already complete\n currentMessage = {\n id: nanoid(),\n role: \"function\",\n content: value.content,\n name: value.name,\n };\n newMessages.push(currentMessage);\n setMessages([...messages, ...newMessages]);\n\n // After receiving a result, feed back the new messages to GPT\n feedback = true;\n } else if (value.type === \"function\" || value.type === \"partial\") {\n // Create a new message if the previous one is not empty\n if (\n currentMessage.content != \"\" ||\n currentMessage.function_call ||\n currentMessage.role == \"function\"\n ) {\n currentMessage = {\n id: nanoid(),\n createdAt: new Date(),\n content: \"\",\n role: \"assistant\",\n };\n newMessages.push(currentMessage);\n }\n if (value.type === \"function\") {\n currentMessage.function_call = {\n name: value.name,\n arguments: JSON.stringify(value.arguments),\n scope: value.scope,\n };\n } else if (value.type === \"partial\") {\n let partialArguments: any = {};\n try {\n partialArguments = JSON.parse(untruncateJson(value.arguments));\n } catch (e) {}\n\n currentMessage.partialFunctionCall = {\n name: value.name,\n arguments: partialArguments,\n };\n }\n\n newMessages[newMessages.length - 1] = currentMessage;\n setMessages([...messages, ...newMessages]);\n\n if (value.type === \"function\") {\n // Execute the function call\n try {\n if (options.onFunctionCall && value.scope === \"client\") {\n const result = await options.onFunctionCall(\n messages,\n currentMessage.function_call as FunctionCall,\n );\n\n currentMessage = {\n id: nanoid(),\n role: \"function\",\n content: encodeResult(result),\n name: (currentMessage.function_call! as FunctionCall).name!,\n };\n newMessages.push(currentMessage);\n setMessages([...messages, ...newMessages]);\n\n // After a function call, feed back the new messages to GPT\n feedback = true;\n }\n } catch (error) {\n console.error(\"Failed to execute function call\", error);\n // TODO: Handle error\n // this should go to the message itself\n }\n }\n }\n }\n\n // If we want feedback, run the completion again and return the results\n if (feedback) {\n // wait for next tick to make sure all the react state updates\n // TODO: This is a hack, is there a more robust way to do this?\n // - tried using react-dom's flushSync, but it did not work\n await new Promise((resolve) => setTimeout(resolve, 10));\n\n return await runChatCompletion([...messages, ...newMessages]);\n }\n // otherwise, return the new messages\n else {\n return newMessages.slice();\n }\n } finally {\n options.setIsLoading(false);\n }\n };\n\n const runChatCompletionAndHandleFunctionCall = async (messages: Message[]): Promise<void> => {\n await runChatCompletion(messages);\n };\n\n const append = async (message: Message): Promise<void> => {\n if (options.isLoading) {\n return;\n }\n const newMessages = [...messages, message];\n setMessages(newMessages);\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const reload = async (): Promise<void> => {\n if (options.isLoading || messages.length === 0) {\n return;\n }\n let newMessages = [...messages];\n const lastMessage = messages[messages.length - 1];\n\n if (lastMessage.role === \"assistant\") {\n newMessages = newMessages.slice(0, -1);\n }\n setMessages(newMessages);\n\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const stop = (): void => {\n abortControllerRef.current?.abort();\n };\n\n return {\n append,\n reload,\n stop,\n };\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAS,cAA+C;AAExD;AAAA,EAIE;AAAA,EAEA;AAAA,OACK;AAEP,SAAS,cAAc;AAGvB,OAAO,oBAAoB;AA6FpB,SAAS,QAAQ,SAA0D;AAChF,QAAM,EAAE,UAAU,aAAa,0BAA0B,IAAI;AAC7D,QAAM,qBAAqB,OAAwB;AACnD,QAAM,cAAc,OAAsB,IAAI;AAC9C,QAAM,WAAW,OAAsB,IAAI;AAC3C,QAAM,eAAe,QAAQ,cAAc;AAC3C,QAAM,UAAU,kCACV,QAAQ,WAAW,CAAC,IACpB,eAAe,EAAE,CAAC,mCAAmC,GAAG,aAAa,IAAI,CAAC;AAGhF,QAAM,oBAAoB,CAAOA,cAA4C;AAC3E,YAAQ,aAAa,IAAI;AAEzB,UAAM,cAAyB;AAAA,MAC7B;AAAA,QACE,IAAI,OAAO;AAAA,QACX,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AO,uCAAuC,WAAW;AAAA,EAC3D;AAEA,QAAM,SAAS,MAA2B;AACxC,QAAI,QAAQ,aAAa,SAAS,WAAW,GAAG;AAC9C;AAAA,IACF;AACA,QAAI,cAAc,CAAC,GAAG,QAAQ;AAC9B,UAAM,cAAc,SAAS,SAAS,SAAS,CAAC;AAEhD,QAAI,YAAY,SAAS,aAAa;AACpC,oBAAc,YAAY,MAAM,GAAG,EAAE;AAAA,IACvC;AACA,gBAAY,WAAW;AAEvB,WAAO,uCAAuC,WAAW;AAAA,EAC3D;AAEA,QAAM,OAAO,MAAY;AAzU3B;AA0UI,6BAAmB,YAAnB,mBAA4B;AAAA,EAC9B;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["messages"]}
|
package/dist/chunk-BABVSMJR.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
//# sourceMappingURL=chunk-BABVSMJR.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/dist/chunk-CYDWEPFL.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
//# sourceMappingURL=chunk-CYDWEPFL.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/context/copilot-context.tsx"],"sourcesContent":["import {\n CopilotCloudConfig,\n FunctionCallHandler,\n Message,\n ToolDefinition,\n} from \"@copilotkit/shared\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: 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 /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\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 // chat\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n entryPoints: {},\n setEntryPoint: () => {},\n removeEntryPoint: () => {},\n\n chatComponentsCache: { current: {} },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n\n getChatCompletionFunctionDescriptions: () => returnAndThrowInDebug([]),\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n messages: [],\n setMessages: () => returnAndThrowInDebug([]),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\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 chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\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"],"mappings":";;;;;AAOA,OAAO,WAAW;AAgIlB,IAAM,sBAA4C;AAAA,EAChD,aAAa,CAAC;AAAA,EACd,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,kBAAkB,MAAM;AAAA,EAAC;AAAA,EAEzB,qBAAqB,EAAE,SAAS,CAAC,EAAE;AAAA,EACnC,kBAAkB,CAAC,WAA8B,eAC/C,sBAAsB,EAAE;AAAA,EAC1B,YAAY,MAAM;AAAA,EAClB,eAAe,MAAM;AAAA,EAAC;AAAA,EAEtB,uCAAuC,MAAM,sBAAsB,CAAC,CAAC;AAAA,EACrE,wBAAwB,MAAM,sBAAsB,MAAY;AAAA,EAAC,EAAC;AAAA,EAElE,UAAU,CAAC;AAAA,EACX,aAAa,MAAM,sBAAsB,CAAC,CAAC;AAAA,EAE3C,WAAW;AAAA,EACX,cAAc,MAAM,sBAAsB,KAAK;AAAA,EAE/C,kBAAkB;AAAA,EAClB,qBAAqB,MAAM,sBAAsB,EAAE;AAAA,EAEnD,qBAAqB,CAAC,eAAyB,sBAAsB,CAAC,CAAC;AAAA,EACvE,oBAAoB,MAAM,sBAAsB,EAAE;AAAA,EAClD,uBAAuB,MAAM;AAAA,EAAC;AAAA,EAE9B,kBAAkB,IAAK,MAAkC;AAAA,IACvD,IAAI,kBAA0B;AAC5B,YAAM,IAAI,MAAM,uEAAuE;AAAA,IACzF;AAAA,IACA,IAAI,oBAA4B;AAC9B,YAAM,IAAI,MAAM,uEAAuE;AAAA,IACzF;AAAA,IACA,IAAI,UAAkC;AACpC,aAAO,CAAC;AAAA,IACV;AAAA,IACA,IAAI,OAA4B;AAC9B,aAAO,CAAC;AAAA,IACV;AAAA,EACF,EAAG;AAAA,EAEH,6BAA6B,CAAC;AAAA,EAC9B,gCAAgC,MAAM;AAAA,EAAC;AAAA,EACvC,mCAAmC,MAAM;AAAA,EAAC;AAC5C;AAEO,IAAM,iBAAiB,MAAM,cAAoC,mBAAmB;AAEpF,SAAS,oBAA0C;AACxD,SAAO,MAAM,WAAW,cAAc;AACxC;AAEA,SAAS,sBAAyB,OAAa;AAC7C,QAAM,IAAI,MAAM,uEAAuE;AACvF,SAAO;AACT;","names":[]}
|
package/dist/chunk-FRAKUJWH.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
//# sourceMappingURL=chunk-FRAKUJWH.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/use-copilot-chat.ts"],"sourcesContent":["/**\n * A hook for accessing Copilot's chat API.\n *\n * `useCopilotChat` is a React hook that lets you directly interact with the\n * Copilot instance. Use to implement a fully custom UI (headless UI) or to\n * programmatically interact with the Copilot instance managed by the default\n * UI.\n *\n * <RequestExample>\n * ```jsx useCopilotChat Example\n * import { useCopilotChat }\n * from \"@copilotkit/react-core\";\n *\n * const { appendMessage } = useCopilotChat();\n * appendMessage({ content: \"Hello, world!\", role: \"user\", id: \"1\" });\n * ```\n * </RequestExample>\n *\n * useCopilotChat returns an object with the following properties:\n * - `visibleMessages`: An array of messages that are currently visible in the chat.\n * - `appendMessage`: A function to append a message to the chat.\n * - `setMessages`: A function to set the messages in the chat.\n * - `deleteMessage`: A function to delete a message from the chat.\n * - `reloadMessages`: A function to reload the messages from the API.\n * - `stopGeneration`: A function to stop the generation of the next message.\n * - `isLoading`: A boolean indicating if the chat is loading.\n *\n */\nimport { useMemo, useContext, useRef, useEffect, useCallback } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { Message, ToolDefinition } from \"@copilotkit/shared\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useChat } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\n\nexport interface UseCopilotChatOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n\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 /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n}\n\nexport interface UseCopilotChatReturn {\n visibleMessages: Message[];\n appendMessage: (message: Message) => Promise<void>;\n setMessages: (messages: Message[]) => void;\n deleteMessage: (messageId: string) => void;\n reloadMessages: () => Promise<void>;\n stopGeneration: () => void;\n isLoading: boolean;\n}\n\nexport function useCopilotChat({\n makeSystemMessage,\n ...options\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const {\n getContextString,\n getChatCompletionFunctionDescriptions,\n getFunctionCallHandler,\n copilotApiConfig,\n messages,\n setMessages,\n isLoading,\n setIsLoading,\n chatInstructions,\n } = useContext(CopilotContext);\n\n // We need to ensure that makeSystemMessageCallback always uses the latest\n // useCopilotReadable data.\n const latestGetContextString = useUpdatedRef(getContextString);\n const deleteMessage = useCallback(\n (messageId: string) => {\n setMessages((prev) => prev.filter((message) => message.id !== messageId));\n },\n [setMessages],\n );\n\n const makeSystemMessageCallback = useCallback(() => {\n const systemMessageMaker = makeSystemMessage || defaultSystemMessage;\n // this always gets the latest context string\n const contextString = latestGetContextString.current([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return {\n id: \"system\",\n content: systemMessageMaker(contextString, chatInstructions),\n role: \"system\",\n } as Message;\n }, [getContextString, makeSystemMessage, chatInstructions]);\n\n const functionDescriptions: ToolDefinition[] = useMemo(() => {\n return getChatCompletionFunctionDescriptions();\n }, [getChatCompletionFunctionDescriptions]);\n\n const { append, reload, stop } = useChat({\n ...options,\n copilotConfig: copilotApiConfig,\n id: options.id,\n initialMessages: options.initialMessages || [],\n tools: functionDescriptions,\n onFunctionCall: getFunctionCallHandler(),\n headers: { ...options.headers },\n body: {\n ...options.body,\n },\n messages,\n setMessages,\n makeSystemMessageCallback,\n isLoading,\n setIsLoading,\n });\n\n const visibleMessages = messages.filter(\n (message) =>\n message.role === \"user\" || message.role === \"assistant\" || message.role === \"function\",\n );\n\n return {\n visibleMessages,\n appendMessage: append,\n setMessages,\n reloadMessages: reload,\n stopGeneration: stop,\n deleteMessage,\n isLoading,\n };\n}\n\n// store `value` in a ref and update\n// it whenever it changes.\nfunction useUpdatedRef<T>(value: T) {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref;\n}\n\nexport function defaultSystemMessage(\n contextString: string,\n additionalInstructions?: string,\n): string {\n return (\n `\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` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,SAAS,SAAS,YAAY,QAAQ,WAAW,mBAAmB;AAsD7D,SAAS,eAAe,KAGJ,CAAC,GAAyB;AAHtB,eAC7B;AAAA;AAAA,EAnFF,IAkF+B,IAE1B,o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AAAA,IACf;AAAA,IACA,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB;AAAA,IACA;AAAA,EACF;AACF;AAIA,SAAS,cAAiB,OAAU;AAClC,QAAM,MAAM,OAAO,KAAK;AAExB,YAAU,MAAM;AACd,QAAI,UAAU;AAAA,EAChB,GAAG,CAAC,KAAK,CAAC;AAEV,SAAO;AACT;AAEO,SAAS,qBACd,eACA,wBACQ;AACR,SACE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAUG,yBAAyB;AAAA;AAAA,EAAO,2BAA2B;AAEhE;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["/**\n * Provides the Copilot context to its children.\n * \n * <img\n * referrerPolicy=\"no-referrer-when-downgrade\"\n * src=\"https://static.scarf.sh/a.png?x-pxid=a9b290bb-38f9-4518-ac3b-8f54fdbf43be\"\n * />\n * \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>\n * The backend can use OpenAI, or you can bring your own LLM. For examples of the\n * backend api implementation, see `examples/next-openai` or the [runtime\n * docs](https://docs.copilotkit.ai/getting-started/quickstart-runtime).\n * </Note>\n * \n * <RequestExample>\n * ```jsx CopilotKit Example\n * import { CopilotKit } from \"@copilotkit/react-core\";\n * \n * <CopilotKit \n * runtimeUrl=\"https://your.copilotkit.api\">\n * <YourApp/>\n * </CopilotKit>\n * ```\n * </RequestExample>\n * \n * ## Example usage\n * \n * ```jsx\n * <CopilotKit publicApiKey=\"the api key or self host (see below)\">\n * <App />\n * </CopilotKit>\n```\n */\nimport { 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 { CopilotChatSuggestionConfiguration, DocumentPointer } from \"../../types\";\n\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n Message,\n actionToChatCompletionFunction,\n} from \"@copilotkit/shared\";\n\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { ToolDefinition } from \"@copilotkit/shared\";\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 if (!props.runtimeUrl && !props.url && !props.publicApiKey) {\n throw new Error(\"Please provide either a url or a publicApiKey to the CopilotKit component.\");\n }\n\n const chatApiEndpoint = props.runtimeUrl || props.url || COPILOT_CLOUD_CHAT_URL;\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 const [messages, setMessages] = useState<Message[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\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 if (!props.publicApiKey) {\n if (props.cloudRestrictToTopic) {\n throw new Error(\n \"To use the cloudRestrictToTopic feature, please sign up at https://copilotkit.ai and provide a publicApiKey.\",\n );\n }\n }\n\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (props.publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: props.cloudRestrictToTopic ? true : false,\n validTopics: props.cloudRestrictToTopic?.validTopics || [],\n invalidTopics: props.cloudRestrictToTopic?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = {\n publicApiKey: props.publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n chatApiEndpointV2: `${props.url}/v2`,\n headers: props.headers || {},\n body: {\n ...props.body,\n ...props.backendOnlyProps,\n },\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n };\n\n const removeChatSuggestionConfiguration = (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\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 messages,\n setMessages,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\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":";;;;;;;;;;;;;;;;;;AAoCA,SAAc,aAAa,QAAQ,gBAAgB;AASnD;AAAA,EACE;AAAA,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ACA;AAAA,QACA;AAAA,MACF;AAAA,MAEC;AAAA;AAAA,EACH;AAEJ;AAEO,IAAM,kCAAkC,CAAC,QAAQ;AAExD,SAAS,qCAAqC,SAAkD;AAC9F,SAAO,QAAQ,IAAI,8BAA8B;AACnD;AAEA,SAAS,iCAAiC,SAAqD;AAC7F,SAAO,CAAO,cAAc,iBAAiB;AAC3C,QAAI,wBAA6D,CAAC;AAClE,aAASE,WAAU,SAAS;AAC1B,4BAAsBA,QAAO,IAAI,IAAIA;AAAA,IACvC;AAEA,UAAM,SAAS,sBAAsB,aAAa,QAAQ,EAAE;AAC5D,QAAI,QAAQ;AACV,UAAI,wBAA+C,CAAC;AACpD,UAAI,aAAa,WAAW;AAC1B,gCAAwB,KAAK,MAAM,aAAa,SAAS;AAAA,MAC3D;AACA,aAAO,MAAM,OAAO,QAAQ,qBAAqB;AAAA,IACnD;AAAA,EACF;AACF;","names":["_a","_b","action"]}
|
package/dist/chunk-MJKBCG4U.mjs
DELETED
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
__async,
|
|
3
|
-
__spreadValues
|
|
4
|
-
} from "./chunk-SKC7AJIV.mjs";
|
|
5
|
-
|
|
6
|
-
// src/utils/fetch-chat-completion.ts
|
|
7
|
-
import {
|
|
8
|
-
decodeChatCompletion,
|
|
9
|
-
parseChatCompletion,
|
|
10
|
-
decodeChatCompletionAsText,
|
|
11
|
-
EXCLUDE_FROM_FORWARD_PROPS_KEYS
|
|
12
|
-
} from "@copilotkit/shared";
|
|
13
|
-
function fetchChatCompletion(_0) {
|
|
14
|
-
return __async(this, arguments, function* ({
|
|
15
|
-
copilotConfig,
|
|
16
|
-
model,
|
|
17
|
-
messages,
|
|
18
|
-
tools,
|
|
19
|
-
temperature,
|
|
20
|
-
headers,
|
|
21
|
-
body,
|
|
22
|
-
signal,
|
|
23
|
-
toolChoice
|
|
24
|
-
}) {
|
|
25
|
-
temperature || (temperature = 0.5);
|
|
26
|
-
tools || (tools = []);
|
|
27
|
-
const cleanedMessages = messages.map((message) => {
|
|
28
|
-
const { content, role, name, function_call } = message;
|
|
29
|
-
return { content, role, name, function_call };
|
|
30
|
-
});
|
|
31
|
-
toolChoice || (toolChoice = "auto");
|
|
32
|
-
const response = yield fetch(copilotConfig.chatApiEndpoint, {
|
|
33
|
-
method: "POST",
|
|
34
|
-
headers: __spreadValues(__spreadValues({
|
|
35
|
-
"Content-Type": "application/json"
|
|
36
|
-
}, copilotConfig.headers), headers ? __spreadValues({}, headers) : {}),
|
|
37
|
-
body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
|
|
38
|
-
model,
|
|
39
|
-
messages: cleanedMessages,
|
|
40
|
-
stream: true
|
|
41
|
-
}, tools.length ? { tools } : {}), temperature ? { temperature } : {}), tools.length != 0 ? { tool_choice: toolChoice } : {}), copilotConfig.body), copilotConfig.backendOnlyProps), excludeBackendOnlyProps(copilotConfig)), body ? __spreadValues({}, body) : {}), copilotConfig.cloud ? { cloud: copilotConfig.cloud } : {})),
|
|
42
|
-
signal,
|
|
43
|
-
credentials: copilotConfig.credentials
|
|
44
|
-
});
|
|
45
|
-
return response;
|
|
46
|
-
});
|
|
47
|
-
}
|
|
48
|
-
function excludeBackendOnlyProps(copilotConfig) {
|
|
49
|
-
var _a;
|
|
50
|
-
const backendOnlyProps = (_a = copilotConfig.backendOnlyProps) != null ? _a : {};
|
|
51
|
-
if (Object.keys(backendOnlyProps).length > 0) {
|
|
52
|
-
return {
|
|
53
|
-
[EXCLUDE_FROM_FORWARD_PROPS_KEYS]: Object.keys(backendOnlyProps)
|
|
54
|
-
};
|
|
55
|
-
} else {
|
|
56
|
-
return {};
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
function fetchAndDecodeChatCompletion(params) {
|
|
60
|
-
return __async(this, null, function* () {
|
|
61
|
-
const response = yield fetchChatCompletion(params);
|
|
62
|
-
if (!response.ok || !response.body) {
|
|
63
|
-
response.events = null;
|
|
64
|
-
} else {
|
|
65
|
-
const events = yield decodeChatCompletion(parseChatCompletion(response.body));
|
|
66
|
-
response.events = events;
|
|
67
|
-
}
|
|
68
|
-
return response;
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
function fetchAndDecodeChatCompletionAsText(params) {
|
|
72
|
-
return __async(this, null, function* () {
|
|
73
|
-
const response = yield fetchChatCompletion(params);
|
|
74
|
-
if (!response.ok || !response.body) {
|
|
75
|
-
response.events = null;
|
|
76
|
-
} else {
|
|
77
|
-
const events = yield decodeChatCompletionAsText(
|
|
78
|
-
decodeChatCompletion(parseChatCompletion(response.body))
|
|
79
|
-
);
|
|
80
|
-
response.events = events;
|
|
81
|
-
}
|
|
82
|
-
return response;
|
|
83
|
-
});
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
export {
|
|
87
|
-
fetchChatCompletion,
|
|
88
|
-
fetchAndDecodeChatCompletion,
|
|
89
|
-
fetchAndDecodeChatCompletionAsText
|
|
90
|
-
};
|
|
91
|
-
//# sourceMappingURL=chunk-MJKBCG4U.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
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 toolChoice?: string | { type: \"function\"; function: { name: string } };\n}\n\nexport async function fetchChatCompletion({\n copilotConfig,\n model,\n messages,\n tools,\n temperature,\n headers,\n body,\n signal,\n toolChoice,\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 toolChoice ||= \"auto\";\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: toolChoice } : {}),\n ...copilotConfig.body,\n ...copilotConfig.backendOnlyProps,\n ...excludeBackendOnlyProps(copilotConfig),\n ...(body ? { ...body } : {}),\n ...(copilotConfig.cloud ? { cloud: copilotConfig.cloud } : {}),\n }),\n signal,\n credentials: copilotConfig.credentials,\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,EAIE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAgBP,SAAsB,oBAAoB,IAUO;AAAA,6CAVP;AAAA,IACxC;AAAA,IACA;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,gCAAe;AAEf,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,WAAW,IAAI,CAAC,IACpD,cAAc,OACd,cAAc,mBACd,wBAAwB,aAAa,IACpC,OAAO,mBAAK,QAAS,CAAC,IACtB,cAAc,QAAQ,EAAE,OAAO,cAAc,MAAM,IAAI,CAAC,EAC7D;AAAA,MACD;AAAA,MACA,aAAa,cAAc;AAAA,IAC7B,CAAC;AAED,WAAO;AAAA,EACT;AAAA;AAEA,SAAS,wBAAwB,eAAoB;AAzErD;AA0EE,QAAM,oBAAmB,mBAAc,qBAAd,YAAkC,CAAC;AAC5D,MAAI,OAAO,KAAK,gBAAgB,EAAE,SAAS,GAAG;AAC5C,WAAO;AAAA,MACL,CAAC,+BAA+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,MAAM,qBAAqB,oBAAoB,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,MAAM;AAAA,QACnB,qBAAqB,oBAAoB,SAAS,IAAI,CAAC;AAAA,MACzD;AACA,MAAC,SAAiB,SAAS;AAAA,IAC7B;AAEA,WAAO;AAAA,EACT;AAAA;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/use-copilot-action.ts"],"sourcesContent":["import { useRef, useContext, useEffect } from \"react\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { nanoid } from \"nanoid\";\nimport { Parameter } from \"@copilotkit/shared\";\n\n// We implement useCopilotAction dependency handling so that\n// the developer has the option to not provide any dependencies.\n// In this case, we assume they want to update the handler on each rerender.\n// To avoid getting stuck in an infinite loop, we update the handler directly,\n// skipping React state updates.\n// This is ok in this case, because the handler is not part of any UI that\n// needs to be updated.\n// useCallback, useMemo or other memoization techniques are not suitable here,\n// because they will cause a infinite rerender loop.\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { setEntryPoint, removeEntryPoint, entryPoints, chatComponentsCache } =\n useContext(CopilotContext);\n const idRef = useRef<string>(nanoid());\n\n // If the developer doesn't provide dependencies, we assume they want to\n // update handler and render function when the action object changes.\n // This ensures that any captured variables in the handler are up to date.\n if (dependencies === undefined) {\n if (entryPoints[idRef.current]) {\n entryPoints[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current[action.name] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n setEntryPoint(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current[action.name] = action.render;\n }\n return () => {\n // NOTE: For now, we don't remove the chatComponentsCache entry when the action is removed.\n // This is because we currently don't have access to the messages array in CopilotContext.\n removeEntryPoint(idRef.current);\n };\n }, [\n setEntryPoint,\n removeEntryPoint,\n action.description,\n action.name,\n // This should be faster than deep equality checking\n // In addition, all major JS engines guarantee the order of object keys\n JSON.stringify(action.parameters),\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n\n// Usage Example:\n// useCopilotAction({\n// name: \"myAction\",\n// parameters: [\n// { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n// { name: \"arg2\", type: \"number\" },\n// {\n// name: \"arg3\",\n// type: \"object\",\n// attributes: [\n// { name: \"nestedArg1\", type: \"boolean\" },\n// { name: \"xyz\", required: false },\n// ],\n// },\n// { name: \"arg4\", type: \"number[]\" },\n// ],\n// handler: ({ arg1, arg2, arg3, arg4 }) => {\n// const x = arg3.nestedArg1;\n// const z = arg3.xyz;\n// console.log(arg1, arg2, arg3);\n// },\n// });\n\n// useCopilotAction({\n// name: \"myAction\",\n// handler: () => {\n// console.log(\"No parameters provided.\");\n// },\n// });\n"],"mappings":";;;;;AAAA,SAAS,QAAQ,YAAY,iBAAiB;AAG9C,SAAS,cAAc;AAYhB,SAAS,iBACd,QACA,cACM;AACN,QAAM,EAAE,eAAe,kBAAkB,aAAa,oBAAoB,IACxE,WAAW,cAAc;AAC3B,QAAM,QAAQ,OAAe,OAAO,CAAC;AAKrC,MAAI,iBAAiB,QAAW;AAC9B,QAAI,YAAY,MAAM,OAAO,GAAG;AAC9B,kBAAY,MAAM,OAAO,EAAE,UAAU,OAAO;AAC5C,UAAI,OAAO,OAAO,WAAW,YAAY;AACvC,YAAI,oBAAoB,YAAY,MAAM;AACxC,8BAAoB,QAAQ,OAAO,IAAI,IAAI,OAAO;AAAA,QACpD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,YAAU,MAAM;AACd,kBAAc,MAAM,SAAS,MAAa;AAC1C,QAAI,oBAAoB,YAAY,QAAQ,OAAO,WAAW,QAAW;AACvE,0BAAoB,QAAQ,OAAO,IAAI,IAAI,OAAO;AAAA,IACpD;AACA,WAAO,MAAM;AAGX,uBAAiB,MAAM,OAAO;AAAA,IAChC;AAAA,EACF,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,OAAO;AAAA;AAAA;AAAA,IAGP,KAAK,UAAU,OAAO,UAAU;AAAA;AAAA,IAEhC,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA;AAAA,IAEpD,GAAI,gBAAgB,CAAC;AAAA,EACvB,CAAC;AACH;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/use-make-copilot-actionable.ts"],"sourcesContent":["import { useRef, useContext, useEffect, useMemo } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { AnnotatedFunction } from \"@copilotkit/shared\";\nimport { nanoid } from \"nanoid\";\nimport { annotatedFunctionToAction } from \"@copilotkit/shared\";\n\n/**\n * @deprecated Use the useCopilotAction function instead.\n */\nexport function useMakeCopilotActionable<ActionInput extends any[]>(\n annotatedFunction: AnnotatedFunction<ActionInput>,\n dependencies: any[],\n) {\n const idRef = useRef(nanoid()); // generate a unique id\n const { setEntryPoint, removeEntryPoint } = useContext(CopilotContext);\n\n const memoizedAnnotatedFunction: AnnotatedFunction<ActionInput> = useMemo(\n () => ({\n name: annotatedFunction.name,\n description: annotatedFunction.description,\n argumentAnnotations: annotatedFunction.argumentAnnotations,\n implementation: annotatedFunction.implementation,\n }),\n dependencies,\n );\n\n useEffect(() => {\n const action = annotatedFunctionToAction(memoizedAnnotatedFunction as AnnotatedFunction<any[]>);\n setEntryPoint(idRef.current, action);\n\n return () => {\n removeEntryPoint(idRef.current);\n };\n }, [memoizedAnnotatedFunction, setEntryPoint, removeEntryPoint]);\n}\n"],"mappings":";;;;;AAAA,SAAS,QAAQ,YAAY,WAAW,eAAe;AAGvD,SAAS,cAAc;AACvB,SAAS,iCAAiC;AAKnC,SAAS,yBACd,mBACA,cACA;AACA,QAAM,QAAQ,OAAO,OAAO,CAAC;AAC7B,QAAM,EAAE,eAAe,iBAAiB,IAAI,WAAW,cAAc;AAErE,QAAM,4BAA4D;AAAA,IAChE,OAAO;AAAA,MACL,MAAM,kBAAkB;AAAA,MACxB,aAAa,kBAAkB;AAAA,MAC/B,qBAAqB,kBAAkB;AAAA,MACvC,gBAAgB,kBAAkB;AAAA,IACpC;AAAA,IACA;AAAA,EACF;AAEA,YAAU,MAAM;AACd,UAAM,SAAS,0BAA0B,yBAAqD;AAC9F,kBAAc,MAAM,SAAS,MAAM;AAEnC,WAAO,MAAM;AACX,uBAAiB,MAAM,OAAO;AAAA,IAChC;AAAA,EACF,GAAG,CAAC,2BAA2B,eAAe,gBAAgB,CAAC;AACjE;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/copilot-task.ts"],"sourcesContent":["/**\n * Execute one-off tasks using Copilot intelligence.\n *\n * <img referrerPolicy=\"no-referrer-when-downgrade\" src=\"https://static.scarf.sh/a.png?x-pxid=a9b290bb-38f9-4518-ac3b-8f54fdbf43be\" />\n *\n * This class is used to execute one-off tasks, for example on button press. It\n * can use the context available via [useCopilotReadable](../useCopilotReadable)\n * and the actions provided by [useCopilotAction](../useCopilotAction), or\n * you can provide your own context and actions.\n *\n * <RequestExample>\n * ```jsx CopilotTask Example\n * import {\n * CopilotTask,\n * useCopilotContext\n * } from \"@copilotkit/react-core\";\n *\n * const task = new CopilotTask({\n * instructions: \"Set a random message\",\n * actions: [\n * {\n * name: \"setMessage\",\n * description: \"Set the message.\",\n * argumentAnnotations: [\n * {\n * name: \"message\",\n * type: \"string\",\n * description:\n * \"A message to display.\",\n * required: true,\n * },\n * ],\n *\n * implementation: async (message) => {\n * // ...\n * },\n * }\n * ]\n * });\n * const context = useCopilotContext();\n * await task.run(context);\n * ```\n * </RequestExample>\n *\n * In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.\n *\n * ```jsx\n * import {\n * CopilotTask,\n * useCopilotContext\n * } from \"@copilotkit/react-core\";\n *\n * const randomSlideTask = new CopilotTask({\n * instructions: \"Make a random slide\",\n * });\n *\n * const context = useCopilotContext();\n *\n * return (\n * <button onClick={() => randomSlideTask.run(context)}>\n * Make a random slide\n * </button>\n * );\n * ```\n *\n * Have a look at the [Presentation example](https://github.com/CopilotKit/CopilotKit/blob/main/CopilotKit/examples/next-openai/src/app/presentation/page.tsx)\n * for a more complete example.\n *\n * It's also possible to provide your own context and actions. In addition, you can specify to ignore\n * `useCopilotReadable` and `useCopilotAction`.\n *\n * ```jsx\n * import {\n * CopilotTask,\n * useCopilotContext\n * } from \"@copilotkit/react-core\";\n *\n * const standaloneTask = new CopilotTask({\n * instructions: \"Do something standalone\",\n * data: [...],\n * actions: [...],\n * includeCopilotReadable: false, // Don't use current context\n * includeCopilotActions: false, // Don't use current actions\n * });\n *\n * const context = useCopilotContext();\n *\n * standaloneTask.run(context);\n * ```\n */\n\nimport { FunctionCall, Message } from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { fetchAndDecodeChatCompletion } from \"../utils/fetch-chat-completion\";\n\nexport interface CopilotTaskConfig {\n /**\n * The instructions to be given to the assistant.\n */\n instructions: string;\n /**\n * An array of action definitions that can be called.\n */\n actions?: FrontendAction<any>[];\n /**\n * Whether to include the copilot readable context in the task.\n */\n includeCopilotReadable?: boolean;\n\n /**\n * Whether to include actions defined via useCopilotAction in the task.\n * @deprecated Use the `includeCopilotActions` property instead.\n */\n includeCopilotActionable?: boolean;\n\n /**\n * Whether to include actions defined via useCopilotAction in the task.\n */\n includeCopilotActions?: boolean;\n}\n\nexport class CopilotTask<T = any> {\n private instructions: string;\n private actions: FrontendAction<any>[];\n private includeCopilotReadable: boolean;\n private includeCopilotActions: boolean;\n\n constructor(config: CopilotTaskConfig) {\n this.instructions = config.instructions;\n this.actions = config.actions || [];\n this.includeCopilotReadable = config.includeCopilotReadable !== false;\n this.includeCopilotActions =\n config.includeCopilotActions !== false && config.includeCopilotActionable !== false;\n }\n\n /**\n * Run the task.\n * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.\n * @param data The data to use for the task.\n */\n async run(context: CopilotContextParams, data?: T): Promise<void> {\n const entryPoints = this.includeCopilotActions ? Object.assign({}, context.entryPoints) : {};\n\n // merge functions into entry points\n for (const fn of this.actions) {\n entryPoints[fn.name] = fn;\n }\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (this.includeCopilotReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage: Message = {\n id: \"system\",\n content: taskSystemMessage(contextString, this.instructions),\n role: \"system\",\n };\n\n const messages = [systemMessage];\n\n const response = await fetchAndDecodeChatCompletion({\n copilotConfig: context.copilotApiConfig,\n messages: messages,\n tools: context.getChatCompletionFunctionDescriptions(entryPoints),\n headers: context.copilotApiConfig.headers,\n body: context.copilotApiConfig.body,\n });\n\n if (!response.events) {\n throw new Error(\"Failed to execute task\");\n }\n\n const reader = response.events.getReader();\n let functionCalls: FunctionCall[] = [];\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (value.type === \"function\") {\n functionCalls.push({\n name: value.name,\n arguments: JSON.stringify(value.arguments),\n });\n break;\n }\n }\n\n if (!functionCalls.length) {\n throw new Error(\"No function call occurred\");\n }\n\n const functionCallHandler = context.getFunctionCallHandler(entryPoints);\n for (const functionCall of functionCalls) {\n await functionCallHandler(messages, functionCall);\n }\n }\n}\n\nfunction taskSystemMessage(contextString: string, instructions: 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.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call a function without saying anything else.\n\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n`;\n}\n"],"mappings":";;;;;;;;;;;AA2HO,IAAM,cAAN,MAA2B;AAAA,EAMhC,YAAY,QAA2B;AACrC,SAAK,eAAe,OAAO;AAC3B,SAAK,UAAU,OAAO,WAAW,CAAC;AAClC,SAAK,yBAAyB,OAAO,2BAA2B;AAChE,SAAK,wBACH,OAAO,0BAA0B,SAAS,OAAO,6BAA6B;AAAA,EAClF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOM,IAAI,SAA+B,MAAyB;AAAA;AAChE,YAAM,cAAc,KAAK,wBAAwB,OAAO,OAAO,CAAC,GAAG,QAAQ,WAAW,IAAI,CAAC;AAG3F,iBAAW,MAAM,KAAK,SAAS;AAC7B,oBAAY,GAAG,IAAI,IAAI;AAAA,MACzB;AAEA,UAAI,gBAAgB;AAEpB,UAAI,MAAM;A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AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA;AAAA;AAAA;AAGF;","names":[]}
|
package/dist/chunk-ZFS5SQUT.mjs
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
__async
|
|
3
|
-
} from "./chunk-SKC7AJIV.mjs";
|
|
4
|
-
|
|
5
|
-
// src/openai-assistants/utils/process-message-stream.ts
|
|
6
|
-
function processMessageStream(reader, processMessage) {
|
|
7
|
-
return __async(this, null, function* () {
|
|
8
|
-
const decoder = new TextDecoder();
|
|
9
|
-
let buffer = "";
|
|
10
|
-
while (true) {
|
|
11
|
-
const { done, value } = yield reader.read();
|
|
12
|
-
if (done) {
|
|
13
|
-
if (buffer.length > 0) {
|
|
14
|
-
processMessage(buffer);
|
|
15
|
-
}
|
|
16
|
-
break;
|
|
17
|
-
}
|
|
18
|
-
buffer += decoder.decode(value, { stream: true });
|
|
19
|
-
let endIndex;
|
|
20
|
-
while ((endIndex = buffer.indexOf("\n")) !== -1) {
|
|
21
|
-
processMessage(buffer.substring(0, endIndex).trim());
|
|
22
|
-
buffer = buffer.substring(endIndex + 1);
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
});
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export {
|
|
29
|
-
processMessageStream
|
|
30
|
-
};
|
|
31
|
-
//# sourceMappingURL=chunk-ZFS5SQUT.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/openai-assistants/utils/process-message-stream.ts"],"sourcesContent":["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"],"mappings":";;;;;AAAA,SAAsB,qBACpB,QACA,gBACA;AAAA;AACA,UAAM,UAAU,IAAI,YAAY;AAChC,QAAI,SAAS;AACb,WAAO,MAAM;AACX,YAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAE1C,UAAI,MAAM;AACR,YAAI,OAAO,SAAS,GAAG;AACrB,yBAAe,MAAM;AAAA,QACvB;AACA;AAAA,MACF;AAEA,gBAAU,QAAQ,OAAO,OAAO,EAAE,QAAQ,KAAK,CAAC;AAEhD,UAAI;AACJ,cAAQ,WAAW,OAAO,QAAQ,IAAI,OAAO,IAAI;AAC/C,uBAAe,OAAO,UAAU,GAAG,QAAQ,EAAE,KAAK,CAAC;AACnD,iBAAS,OAAO,UAAU,WAAW,CAAC;AAAA,MACxC;AAAA,IACF;AAAA,EACF;AAAA;","names":[]}
|
|
@@ -1,277 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __create = Object.create;
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
7
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
-
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
10
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
11
|
-
var __spreadValues = (a, b) => {
|
|
12
|
-
for (var prop in b || (b = {}))
|
|
13
|
-
if (__hasOwnProp.call(b, prop))
|
|
14
|
-
__defNormalProp(a, prop, b[prop]);
|
|
15
|
-
if (__getOwnPropSymbols)
|
|
16
|
-
for (var prop of __getOwnPropSymbols(b)) {
|
|
17
|
-
if (__propIsEnum.call(b, prop))
|
|
18
|
-
__defNormalProp(a, prop, b[prop]);
|
|
19
|
-
}
|
|
20
|
-
return a;
|
|
21
|
-
};
|
|
22
|
-
var __export = (target, all) => {
|
|
23
|
-
for (var name in all)
|
|
24
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
25
|
-
};
|
|
26
|
-
var __copyProps = (to, from, except, desc) => {
|
|
27
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
28
|
-
for (let key of __getOwnPropNames(from))
|
|
29
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
30
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
31
|
-
}
|
|
32
|
-
return to;
|
|
33
|
-
};
|
|
34
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
35
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
36
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
37
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
38
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
39
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
40
|
-
mod
|
|
41
|
-
));
|
|
42
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
43
|
-
var __async = (__this, __arguments, generator) => {
|
|
44
|
-
return new Promise((resolve, reject) => {
|
|
45
|
-
var fulfilled = (value) => {
|
|
46
|
-
try {
|
|
47
|
-
step(generator.next(value));
|
|
48
|
-
} catch (e) {
|
|
49
|
-
reject(e);
|
|
50
|
-
}
|
|
51
|
-
};
|
|
52
|
-
var rejected = (value) => {
|
|
53
|
-
try {
|
|
54
|
-
step(generator.throw(value));
|
|
55
|
-
} catch (e) {
|
|
56
|
-
reject(e);
|
|
57
|
-
}
|
|
58
|
-
};
|
|
59
|
-
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
|
|
60
|
-
step((generator = generator.apply(__this, __arguments)).next());
|
|
61
|
-
});
|
|
62
|
-
};
|
|
63
|
-
|
|
64
|
-
// src/openai-assistants/hooks/index.ts
|
|
65
|
-
var hooks_exports = {};
|
|
66
|
-
__export(hooks_exports, {
|
|
67
|
-
useCopilotChatV2: () => useCopilotChatV2
|
|
68
|
-
});
|
|
69
|
-
module.exports = __toCommonJS(hooks_exports);
|
|
70
|
-
|
|
71
|
-
// src/openai-assistants/hooks/use-copilot-chat-v2.ts
|
|
72
|
-
var import_react3 = require("react");
|
|
73
|
-
|
|
74
|
-
// src/openai-assistants/utils/process-message-stream.ts
|
|
75
|
-
function processMessageStream(reader, processMessage) {
|
|
76
|
-
return __async(this, null, function* () {
|
|
77
|
-
const decoder = new TextDecoder();
|
|
78
|
-
let buffer = "";
|
|
79
|
-
while (true) {
|
|
80
|
-
const { done, value } = yield reader.read();
|
|
81
|
-
if (done) {
|
|
82
|
-
if (buffer.length > 0) {
|
|
83
|
-
processMessage(buffer);
|
|
84
|
-
}
|
|
85
|
-
break;
|
|
86
|
-
}
|
|
87
|
-
buffer += decoder.decode(value, { stream: true });
|
|
88
|
-
let endIndex;
|
|
89
|
-
while ((endIndex = buffer.indexOf("\n")) !== -1) {
|
|
90
|
-
processMessage(buffer.substring(0, endIndex).trim());
|
|
91
|
-
buffer = buffer.substring(endIndex + 1);
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
// src/openai-assistants/hooks/use-copilot-chat-v2.ts
|
|
98
|
-
var import_shared2 = require("@copilotkit/shared");
|
|
99
|
-
|
|
100
|
-
// src/context/copilot-context.tsx
|
|
101
|
-
var import_react = __toESM(require("react"));
|
|
102
|
-
var emptyCopilotContext = {
|
|
103
|
-
entryPoints: {},
|
|
104
|
-
setEntryPoint: () => {
|
|
105
|
-
},
|
|
106
|
-
removeEntryPoint: () => {
|
|
107
|
-
},
|
|
108
|
-
chatComponentsCache: { current: {} },
|
|
109
|
-
getContextString: (documents, categories) => returnAndThrowInDebug(""),
|
|
110
|
-
addContext: () => "",
|
|
111
|
-
removeContext: () => {
|
|
112
|
-
},
|
|
113
|
-
getChatCompletionFunctionDescriptions: () => returnAndThrowInDebug([]),
|
|
114
|
-
getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
|
|
115
|
-
})),
|
|
116
|
-
messages: [],
|
|
117
|
-
setMessages: () => returnAndThrowInDebug([]),
|
|
118
|
-
isLoading: false,
|
|
119
|
-
setIsLoading: () => returnAndThrowInDebug(false),
|
|
120
|
-
chatInstructions: "",
|
|
121
|
-
setChatInstructions: () => returnAndThrowInDebug(""),
|
|
122
|
-
getDocumentsContext: (categories) => returnAndThrowInDebug([]),
|
|
123
|
-
addDocumentContext: () => returnAndThrowInDebug(""),
|
|
124
|
-
removeDocumentContext: () => {
|
|
125
|
-
},
|
|
126
|
-
copilotApiConfig: new class {
|
|
127
|
-
get chatApiEndpoint() {
|
|
128
|
-
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
|
|
129
|
-
}
|
|
130
|
-
get chatApiEndpointV2() {
|
|
131
|
-
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
|
|
132
|
-
}
|
|
133
|
-
get headers() {
|
|
134
|
-
return {};
|
|
135
|
-
}
|
|
136
|
-
get body() {
|
|
137
|
-
return {};
|
|
138
|
-
}
|
|
139
|
-
}(),
|
|
140
|
-
chatSuggestionConfiguration: {},
|
|
141
|
-
addChatSuggestionConfiguration: () => {
|
|
142
|
-
},
|
|
143
|
-
removeChatSuggestionConfiguration: () => {
|
|
144
|
-
}
|
|
145
|
-
};
|
|
146
|
-
var CopilotContext = import_react.default.createContext(emptyCopilotContext);
|
|
147
|
-
function returnAndThrowInDebug(value) {
|
|
148
|
-
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
|
|
149
|
-
return value;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
// src/components/copilot-provider/copilotkit.tsx
|
|
153
|
-
var import_react2 = require("react");
|
|
154
|
-
var import_shared = require("@copilotkit/shared");
|
|
155
|
-
var import_jsx_runtime = require("react/jsx-runtime");
|
|
156
|
-
var defaultCopilotContextCategories = ["global"];
|
|
157
|
-
|
|
158
|
-
// src/openai-assistants/hooks/use-copilot-chat-v2.ts
|
|
159
|
-
function useCopilotChatV2(options) {
|
|
160
|
-
const {
|
|
161
|
-
getContextString,
|
|
162
|
-
getChatCompletionFunctionDescriptions,
|
|
163
|
-
getFunctionCallHandler,
|
|
164
|
-
copilotApiConfig
|
|
165
|
-
} = (0, import_react3.useContext)(CopilotContext);
|
|
166
|
-
const [messages, setMessages] = (0, import_react3.useState)([]);
|
|
167
|
-
const [input, setInput] = (0, import_react3.useState)("");
|
|
168
|
-
const [threadId, setThreadId] = (0, import_react3.useState)(void 0);
|
|
169
|
-
const [status, setStatus] = (0, import_react3.useState)("awaiting_message");
|
|
170
|
-
const [error, setError] = (0, import_react3.useState)(void 0);
|
|
171
|
-
const systemMessage = (0, import_react3.useMemo)(() => {
|
|
172
|
-
const systemMessageMaker = options.makeSystemMessage || defaultSystemMessage;
|
|
173
|
-
const contextString = getContextString([], defaultCopilotContextCategories);
|
|
174
|
-
return {
|
|
175
|
-
id: "system",
|
|
176
|
-
content: systemMessageMaker(contextString),
|
|
177
|
-
role: "system"
|
|
178
|
-
};
|
|
179
|
-
}, [getContextString, options.makeSystemMessage]);
|
|
180
|
-
const handleInputChange = (e) => {
|
|
181
|
-
setInput(e.target.value);
|
|
182
|
-
};
|
|
183
|
-
const submitMessage = (e) => __async(this, null, function* () {
|
|
184
|
-
var _a, _b;
|
|
185
|
-
e.preventDefault();
|
|
186
|
-
if (input === "") {
|
|
187
|
-
return;
|
|
188
|
-
}
|
|
189
|
-
setStatus("in_progress");
|
|
190
|
-
setMessages((messages2) => [...messages2, { id: "", role: "user", content: input }]);
|
|
191
|
-
setInput("");
|
|
192
|
-
const apiUrl = copilotApiConfig.chatApiEndpointV2;
|
|
193
|
-
const functions = getChatCompletionFunctionDescriptions();
|
|
194
|
-
const result = yield fetch(apiUrl, {
|
|
195
|
-
method: "POST",
|
|
196
|
-
headers: __spreadValues(__spreadValues({
|
|
197
|
-
"Content-Type": "application/json"
|
|
198
|
-
}, copilotApiConfig.headers), options.headers),
|
|
199
|
-
body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues({
|
|
200
|
-
// always use user-provided threadId when available:
|
|
201
|
-
threadId: (_b = (_a = options.threadId) != null ? _a : threadId) != null ? _b : null,
|
|
202
|
-
message: input
|
|
203
|
-
}, functions.length > 0 && { functions }), copilotApiConfig.body), options.body))
|
|
204
|
-
});
|
|
205
|
-
if (result.body == null) {
|
|
206
|
-
throw new Error("The response body is empty.");
|
|
207
|
-
}
|
|
208
|
-
yield processMessageStream(result.body.getReader(), (message) => {
|
|
209
|
-
try {
|
|
210
|
-
const { type, value } = (0, import_shared2.parseStreamPart)(message);
|
|
211
|
-
switch (type) {
|
|
212
|
-
case "assistant_message": {
|
|
213
|
-
setMessages((messages2) => [
|
|
214
|
-
...messages2,
|
|
215
|
-
{
|
|
216
|
-
id: value.id,
|
|
217
|
-
role: value.role,
|
|
218
|
-
content: value.content[0].text.value
|
|
219
|
-
}
|
|
220
|
-
]);
|
|
221
|
-
break;
|
|
222
|
-
}
|
|
223
|
-
case "assistant_control_data": {
|
|
224
|
-
setThreadId(value.threadId);
|
|
225
|
-
setMessages((messages2) => {
|
|
226
|
-
const lastMessage = messages2[messages2.length - 1];
|
|
227
|
-
lastMessage.id = value.messageId;
|
|
228
|
-
return [...messages2.slice(0, messages2.length - 1), lastMessage];
|
|
229
|
-
});
|
|
230
|
-
break;
|
|
231
|
-
}
|
|
232
|
-
case "error": {
|
|
233
|
-
setError(value);
|
|
234
|
-
break;
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
} catch (error2) {
|
|
238
|
-
setError(error2);
|
|
239
|
-
}
|
|
240
|
-
});
|
|
241
|
-
setStatus("awaiting_message");
|
|
242
|
-
});
|
|
243
|
-
return {
|
|
244
|
-
messages,
|
|
245
|
-
input,
|
|
246
|
-
handleInputChange,
|
|
247
|
-
submitMessage,
|
|
248
|
-
status,
|
|
249
|
-
error
|
|
250
|
-
};
|
|
251
|
-
}
|
|
252
|
-
function defaultSystemMessage(contextString) {
|
|
253
|
-
return `
|
|
254
|
-
Please act as an efficient, competent, conscientious, and industrious professional assistant.
|
|
255
|
-
|
|
256
|
-
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.
|
|
257
|
-
Always be polite and respectful, and prefer brevity over verbosity.
|
|
258
|
-
|
|
259
|
-
The user has provided you with the following context:
|
|
260
|
-
\`\`\`
|
|
261
|
-
${contextString}
|
|
262
|
-
\`\`\`
|
|
263
|
-
|
|
264
|
-
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.
|
|
265
|
-
|
|
266
|
-
Please assist them as best you can.
|
|
267
|
-
|
|
268
|
-
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.
|
|
269
|
-
|
|
270
|
-
If you would like to call a function, call it without saying anything else.
|
|
271
|
-
`;
|
|
272
|
-
}
|
|
273
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
274
|
-
0 && (module.exports = {
|
|
275
|
-
useCopilotChatV2
|
|
276
|
-
});
|
|
277
|
-
//# sourceMappingURL=index.js.map
|