@copilotkit/react-core 0.19.0 → 0.20.0-demofixes.2

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.
Files changed (125) hide show
  1. package/.turbo/turbo-build.log +215 -197
  2. package/CHANGELOG.md +33 -0
  3. package/dist/{chunk-VP2EU4US.mjs → chunk-4LKP4DMT.mjs} +3 -3
  4. package/dist/{chunk-4CFJ6A6A.mjs → chunk-4OWTRVNI.mjs} +6 -2
  5. package/dist/chunk-4OWTRVNI.mjs.map +1 -0
  6. package/dist/{chunk-IQEWY7P4.mjs → chunk-ABXVFQLN.mjs} +46 -29
  7. package/dist/chunk-ABXVFQLN.mjs.map +1 -0
  8. package/dist/{chunk-YOXWT7I6.mjs → chunk-CPEUPJQJ.mjs} +2 -2
  9. package/dist/{chunk-UAKLDQMP.mjs → chunk-JIKWSWIX.mjs} +4 -4
  10. package/dist/chunk-JIKWSWIX.mjs.map +1 -0
  11. package/dist/{chunk-DGUVNY3V.mjs → chunk-K2LVBFRY.mjs} +2 -2
  12. package/dist/{chunk-GBZZPQ5X.mjs → chunk-KAZJPE2I.mjs} +14 -8
  13. package/dist/chunk-KAZJPE2I.mjs.map +1 -0
  14. package/dist/{chunk-5GS7FQPW.mjs → chunk-KZNQLITJ.mjs} +5 -5
  15. package/dist/chunk-KZNQLITJ.mjs.map +1 -0
  16. package/dist/chunk-LUGEI4YQ.mjs +1 -0
  17. package/dist/chunk-LUGEI4YQ.mjs.map +1 -0
  18. package/dist/chunk-TZPIY754.mjs +102 -0
  19. package/dist/chunk-TZPIY754.mjs.map +1 -0
  20. package/dist/{chunk-IQH5AQQC.mjs → chunk-XBLCD24W.mjs} +2 -2
  21. package/dist/components/copilot-provider/copilotkit.js +12 -6
  22. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  23. package/dist/components/copilot-provider/copilotkit.mjs +439 -8
  24. package/dist/components/copilot-provider/copilotkit.mjs.map +1 -1
  25. package/dist/components/copilot-provider/index.js +12 -6
  26. package/dist/components/copilot-provider/index.js.map +1 -1
  27. package/dist/components/copilot-provider/index.mjs +439 -9
  28. package/dist/components/copilot-provider/index.mjs.map +1 -1
  29. package/dist/components/copilot-provider/standard-copilot-api-config.mjs +9 -4
  30. package/dist/components/copilot-provider/standard-copilot-api-config.mjs.map +1 -1
  31. package/dist/components/index.js +12 -6
  32. package/dist/components/index.js.map +1 -1
  33. package/dist/components/index.mjs +439 -10
  34. package/dist/components/index.mjs.map +1 -1
  35. package/dist/context/copilot-context.d.ts +5 -4
  36. package/dist/context/copilot-context.js +7 -2
  37. package/dist/context/copilot-context.js.map +1 -1
  38. package/dist/context/copilot-context.mjs +65 -5
  39. package/dist/context/copilot-context.mjs.map +1 -1
  40. package/dist/context/index.d.ts +1 -1
  41. package/dist/context/index.js +7 -2
  42. package/dist/context/index.js.map +1 -1
  43. package/dist/context/index.mjs +65 -6
  44. package/dist/context/index.mjs.map +1 -1
  45. package/dist/hooks/index.js +47 -29
  46. package/dist/hooks/index.js.map +1 -1
  47. package/dist/hooks/index.mjs +392 -21
  48. package/dist/hooks/index.mjs.map +1 -1
  49. package/dist/hooks/use-chat.d.ts +2 -2
  50. package/dist/hooks/use-chat.js +46 -28
  51. package/dist/hooks/use-chat.js.map +1 -1
  52. package/dist/hooks/use-chat.mjs +204 -4
  53. package/dist/hooks/use-chat.mjs.map +1 -1
  54. package/dist/hooks/use-copilot-chat.js +47 -29
  55. package/dist/hooks/use-copilot-chat.js.map +1 -1
  56. package/dist/hooks/use-copilot-chat.mjs +340 -13
  57. package/dist/hooks/use-copilot-chat.mjs.map +1 -1
  58. package/dist/hooks/use-flat-category-store.mjs +65 -4
  59. package/dist/hooks/use-flat-category-store.mjs.map +1 -1
  60. package/dist/hooks/use-make-copilot-actionable.js.map +1 -1
  61. package/dist/hooks/use-make-copilot-actionable.mjs +85 -5
  62. package/dist/hooks/use-make-copilot-actionable.mjs.map +1 -1
  63. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  64. package/dist/hooks/use-make-copilot-document-readable.mjs +77 -5
  65. package/dist/hooks/use-make-copilot-document-readable.mjs.map +1 -1
  66. package/dist/hooks/use-make-copilot-readable.js.map +1 -1
  67. package/dist/hooks/use-make-copilot-readable.mjs +77 -5
  68. package/dist/hooks/use-make-copilot-readable.mjs.map +1 -1
  69. package/dist/hooks/use-tree.mjs +150 -4
  70. package/dist/hooks/use-tree.mjs.map +1 -1
  71. package/dist/index.d.ts +2 -1
  72. package/dist/index.js +154 -35
  73. package/dist/index.js.map +1 -1
  74. package/dist/index.mjs +981 -41
  75. package/dist/index.mjs.map +1 -1
  76. package/dist/lib/copilot-task.d.ts +34 -0
  77. package/dist/lib/copilot-task.js +206 -0
  78. package/dist/lib/copilot-task.js.map +1 -0
  79. package/dist/lib/copilot-task.mjs +188 -0
  80. package/dist/lib/copilot-task.mjs.map +1 -0
  81. package/dist/lib/index.d.ts +6 -0
  82. package/dist/lib/index.js +206 -0
  83. package/dist/lib/index.js.map +1 -0
  84. package/dist/lib/index.mjs +188 -0
  85. package/dist/lib/index.mjs.map +1 -0
  86. package/dist/openai-assistants/hooks/index.js.map +1 -1
  87. package/dist/openai-assistants/hooks/index.mjs +228 -14
  88. package/dist/openai-assistants/hooks/index.mjs.map +1 -1
  89. package/dist/openai-assistants/hooks/use-assistants.mjs +45 -7
  90. package/dist/openai-assistants/hooks/use-assistants.mjs.map +1 -1
  91. package/dist/openai-assistants/hooks/use-copilot-chat-v2.js.map +1 -1
  92. package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs +228 -14
  93. package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs.map +1 -1
  94. package/dist/openai-assistants/index.js.map +1 -1
  95. package/dist/openai-assistants/index.mjs +228 -17
  96. package/dist/openai-assistants/index.mjs.map +1 -1
  97. package/dist/openai-assistants/utils/index.mjs +43 -5
  98. package/dist/openai-assistants/utils/index.mjs.map +1 -1
  99. package/dist/openai-assistants/utils/process-message-stream.mjs +43 -4
  100. package/dist/openai-assistants/utils/process-message-stream.mjs.map +1 -1
  101. package/dist/types/index.mjs +0 -1
  102. package/dist/utils/fetch-chat-completion.d.ts +3 -3
  103. package/dist/utils/fetch-chat-completion.js +3 -3
  104. package/dist/utils/fetch-chat-completion.js.map +1 -1
  105. package/dist/utils/fetch-chat-completion.mjs +99 -5
  106. package/dist/utils/fetch-chat-completion.mjs.map +1 -1
  107. package/package.json +4 -4
  108. package/src/components/copilot-provider/copilotkit.tsx +17 -8
  109. package/src/context/copilot-context.tsx +11 -3
  110. package/src/context/index.ts +1 -1
  111. package/src/hooks/use-chat.ts +52 -30
  112. package/src/hooks/use-copilot-chat.ts +3 -3
  113. package/src/index.tsx +1 -0
  114. package/src/lib/copilot-task.ts +131 -0
  115. package/src/lib/index.ts +1 -0
  116. package/src/utils/fetch-chat-completion.ts +6 -6
  117. package/dist/chunk-4CFJ6A6A.mjs.map +0 -1
  118. package/dist/chunk-5GS7FQPW.mjs.map +0 -1
  119. package/dist/chunk-GBZZPQ5X.mjs.map +0 -1
  120. package/dist/chunk-IQEWY7P4.mjs.map +0 -1
  121. package/dist/chunk-UAKLDQMP.mjs.map +0 -1
  122. /package/dist/{chunk-VP2EU4US.mjs.map → chunk-4LKP4DMT.mjs.map} +0 -0
  123. /package/dist/{chunk-YOXWT7I6.mjs.map → chunk-CPEUPJQJ.mjs.map} +0 -0
  124. /package/dist/{chunk-DGUVNY3V.mjs.map → chunk-K2LVBFRY.mjs.map} +0 -0
  125. /package/dist/{chunk-IQH5AQQC.mjs.map → chunk-XBLCD24W.mjs.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/index.ts","../../src/hooks/use-copilot-chat.ts","../../src/context/copilot-context.tsx","../../src/hooks/use-chat.ts","../../src/utils/fetch-chat-completion.ts","../../src/components/copilot-provider/copilotkit.tsx","../../src/hooks/use-make-copilot-actionable.ts","../../src/hooks/use-make-copilot-readable.ts","../../src/hooks/use-make-copilot-document-readable.ts"],"sourcesContent":["export { useCopilotChat } from \"./use-copilot-chat\";\nexport type { UseCopilotChatOptions } from \"./use-copilot-chat\";\nexport type { UseCopilotChatReturn } from \"./use-copilot-chat\";\n\nexport { useMakeCopilotActionable } from \"./use-make-copilot-actionable\";\nexport { useMakeCopilotReadable } from \"./use-make-copilot-readable\";\nexport { useMakeCopilotDocumentReadable } from \"./use-make-copilot-document-readable\";\nexport { type UseChatHelpers } from \"./use-chat\";\n","import { useMemo, useContext } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { Message, Function } from \"@copilotkit/shared\";\nimport { SystemMessageFunction } from \"../types\";\nimport { UseChatOptions, useChat } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\n\nexport interface UseCopilotChatOptions extends UseChatOptions {\n makeSystemMessage?: SystemMessageFunction;\n additionalInstructions?: string;\n}\n\nexport interface UseCopilotChatReturn {\n visibleMessages: Message[];\n append: (message: Message) => Promise<void>;\n reload: () => Promise<void>;\n stop: () => void;\n isLoading: boolean;\n input: string;\n setInput: React.Dispatch<React.SetStateAction<string>>;\n}\n\nexport function useCopilotChat({\n makeSystemMessage,\n additionalInstructions,\n ...options\n}: UseCopilotChatOptions): UseCopilotChatReturn {\n const {\n getContextString,\n getChatCompletionFunctionDescriptions,\n getFunctionCallHandler,\n copilotApiConfig,\n } = useContext(CopilotContext);\n\n const systemMessage: Message = useMemo(() => {\n const systemMessageMaker = makeSystemMessage || defaultSystemMessage;\n const contextString = getContextString([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return {\n id: \"system\",\n content: systemMessageMaker(contextString, additionalInstructions),\n role: \"system\",\n };\n }, [getContextString, makeSystemMessage]);\n\n const functionDescriptions: Function[] = useMemo(() => {\n return getChatCompletionFunctionDescriptions();\n }, [getChatCompletionFunctionDescriptions]);\n\n const { messages, append, reload, stop, isLoading, input, setInput } = useChat({\n ...options,\n copilotConfig: copilotApiConfig,\n id: options.id,\n initialMessages: [systemMessage].concat(options.initialMessages || []),\n functions: functionDescriptions,\n onFunctionCall: getFunctionCallHandler(),\n headers: { ...options.headers },\n body: {\n ...options.body,\n },\n });\n\n const visibleMessages = messages.filter(\n (message) => message.role === \"user\" || message.role === \"assistant\",\n );\n\n return {\n visibleMessages,\n append,\n reload,\n stop,\n isLoading,\n input,\n setInput,\n };\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","\"use client\";\n\nimport { FunctionCallHandler, AnnotatedFunction, Function } from \"@copilotkit/shared\";\nimport React 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\nexport interface CopilotContextParams {\n // function-calling\n entryPoints: Record<string, AnnotatedFunction<any[]>>;\n setEntryPoint: (id: string, entryPoint: AnnotatedFunction<any[]>) => void;\n removeEntryPoint: (id: string) => void;\n getChatCompletionFunctionDescriptions: () => Function[];\n getFunctionCallHandler: () => 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\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\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 { useRef, useState } from \"react\";\nimport { Message, Function, FunctionCallHandler, FunctionCall } from \"@copilotkit/shared\";\nimport { nanoid } from \"nanoid\";\nimport { fetchAndDecodeChatCompletion } from \"../utils/fetch-chat-completion\";\nimport { CopilotApiConfig } from \"../context\";\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 functions?: Function[];\n};\n\nexport type UseChatHelpers = {\n /** Current messages in the chat */\n messages: Message[];\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 /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport type UseChatOptionsWithCopilotConfig = UseChatOptions & {\n copilotConfig: CopilotApiConfig;\n};\n\nexport function useChat(options: UseChatOptionsWithCopilotConfig): UseChatHelpers {\n const [messages, setMessages] = useState<Message[]>([]);\n const [input, setInput] = useState(\"\");\n const [isLoading, setIsLoading] = useState(false);\n const abortControllerRef = useRef<AbortController>();\n\n const runChatCompletion = async (messages: Message[]): Promise<Message> => {\n setIsLoading(true);\n const assistantMessage: Message = {\n id: nanoid(),\n createdAt: new Date(),\n content: \"\",\n role: \"assistant\",\n };\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setMessages([...messages, { ...assistantMessage }]);\n\n const messagesWithContext = [...(options.initialMessages || []), ...messages];\n const response = await fetchAndDecodeChatCompletion({\n copilotConfig: options.copilotConfig,\n messages: messagesWithContext,\n functions: options.functions,\n headers: options.headers,\n signal: abortController.signal,\n });\n\n if (!response.events) {\n throw new Error(\"Failed to fetch chat completion\");\n }\n\n const reader = response.events.getReader();\n\n while (true) {\n try {\n const { done, value } = await reader.read();\n\n if (done) {\n setIsLoading(false);\n return { ...assistantMessage };\n }\n\n if (value.type === \"content\") {\n assistantMessage.content += value.content;\n setMessages([...messages, { ...assistantMessage }]);\n } else if (value.type === \"function\") {\n assistantMessage.function_call = {\n name: value.name,\n arguments: JSON.stringify(value.arguments),\n };\n setMessages([...messages, { ...assistantMessage }]);\n // quit early if we get a function call\n setIsLoading(false);\n return { ...assistantMessage };\n }\n } catch (error) {\n setIsLoading(false);\n throw error;\n }\n }\n };\n\n const runChatCompletionAndHandleFunctionCall = async (messages: Message[]): Promise<void> => {\n const message = await runChatCompletion(messages);\n if (message.function_call && options.onFunctionCall) {\n await options.onFunctionCall(messages, message.function_call as FunctionCall);\n }\n };\n\n const append = async (message: Message): Promise<void> => {\n if (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 (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 messages,\n append,\n reload,\n stop,\n isLoading,\n input,\n setInput,\n };\n}\n","import {\n Message,\n Function,\n ChatCompletionEvent,\n decodeChatCompletion,\n parseChatCompletion,\n decodeChatCompletionAsText,\n} from \"@copilotkit/shared\";\nimport { CopilotApiConfig } from \"../context\";\n\nexport interface FetchChatCompletionParams {\n copilotConfig: CopilotApiConfig;\n model?: string;\n messages: Message[];\n functions?: Function[];\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 functions,\n temperature,\n headers,\n body,\n signal,\n}: FetchChatCompletionParams): Promise<Response> {\n temperature ||= 0.5;\n functions ||= [];\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 ...(functions.length ? { functions } : {}),\n ...(temperature ? { temperature } : {}),\n ...(functions.length != 0 ? { function_call: \"auto\" } : {}),\n ...copilotConfig.body,\n ...(body ? { ...body } : {}),\n }),\n signal,\n });\n\n return response;\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 return { ...response, events: null };\n }\n const events = await decodeChatCompletion(parseChatCompletion(response.body));\n return { ...response, events };\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 return { ...response, events: null };\n }\n const events = await decodeChatCompletionAsText(\n decodeChatCompletion(parseChatCompletion(response.body)),\n );\n return { ...response, events };\n}\n","\"use client\";\n\nimport { Function } from \"@copilotkit/shared\";\nimport { useCallback, useState } from \"react\";\nimport { CopilotContext, CopilotApiConfig } from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { DocumentPointer } from \"../../types\";\nimport {\n FunctionCallHandler,\n AnnotatedFunction,\n annotatedFunctionToChatCompletionFunction,\n} from \"@copilotkit/shared\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { StandardCopilotApiConfig } from \"./standard-copilot-api-config\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\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, AnnotatedFunction<any[]>>>({});\n\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: AnnotatedFunction<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 return entryPointsToChatCompletionFunctions(Object.values(entryPoints));\n }, [entryPoints]);\n\n const getFunctionCallHandler = useCallback(() => {\n return entryPointsToFunctionCallHandler(Object.values(entryPoints));\n }, [entryPoints]);\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 props.body || {},\n );\n\n return (\n <CopilotContext.Provider\n value={{\n entryPoints,\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 entryPointsToFunctionCallHandler(\n entryPoints: AnnotatedFunction<any[]>[],\n): FunctionCallHandler {\n return async (chatMessages, functionCall) => {\n let entrypointsByFunctionName: Record<string, AnnotatedFunction<any[]>> = {};\n for (let entryPoint of entryPoints) {\n entrypointsByFunctionName[entryPoint.name] = entryPoint;\n }\n\n const entryPointFunction = entrypointsByFunctionName[functionCall.name || \"\"];\n if (entryPointFunction) {\n let functionCallArguments: Record<string, any>[] = [];\n if (functionCall.arguments) {\n functionCallArguments = JSON.parse(functionCall.arguments);\n }\n\n const paramsInCorrectOrder: any[] = [];\n for (let arg of entryPointFunction.argumentAnnotations) {\n paramsInCorrectOrder.push(\n functionCallArguments[arg.name as keyof typeof functionCallArguments],\n );\n }\n\n await entryPointFunction.implementation(...paramsInCorrectOrder);\n\n // commented out becasue for now we don't want to return anything\n // const result = await entryPointFunction.implementation(\n // ...parsedFunctionCallArguments\n // );\n // const functionResponse: ChatRequest = {\n // messages: [\n // ...chatMessages,\n // {\n // id: nanoid(),\n // name: functionCall.name,\n // role: 'function' as const,\n // content: JSON.stringify(result),\n // },\n // ],\n // };\n\n // return functionResponse;\n }\n };\n}\n\nfunction entryPointsToChatCompletionFunctions(entryPoints: AnnotatedFunction<any[]>[]): Function[] {\n return entryPoints.map(annotatedFunctionToChatCompletionFunction);\n}\n","\"use client\";\n\nimport { useRef, useContext, useEffect, useMemo } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { AnnotatedFunction } from \"@copilotkit/shared\";\nimport { nanoid } from \"nanoid\";\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 setEntryPoint(idRef.current, memoizedAnnotatedFunction as AnnotatedFunction<any[]>);\n\n return () => {\n removeEntryPoint(idRef.current);\n };\n }, [memoizedAnnotatedFunction, setEntryPoint, removeEntryPoint]);\n}\n","\"use client\";\n\nimport { useContext, useEffect, useRef } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\n\n/**\n * Adds the given information to the Copilot context to make it readable by Copilot.\n * @param information - The information to be added to the Copilot context.\n * @param parentId - The ID of the parent context, if any.\n * @param categories - An array of categories to control which context are visible where. Particularly useful with CopilotTextarea (see `useMakeAutosuggestionFunction`)\n * @returns The ID of the added context.\n */\nexport function useMakeCopilotReadable(\n information: string,\n parentId?: string,\n categories?: string[],\n): string | undefined {\n const { addContext, removeContext } = useContext(CopilotContext);\n const idRef = useRef<string>();\n\n useEffect(() => {\n const id = addContext(information, parentId, categories);\n idRef.current = id;\n\n return () => {\n removeContext(id);\n };\n }, [information, parentId, addContext, removeContext]);\n\n return idRef.current;\n}\n","\"use client\";\n\nimport { useContext, useEffect, useRef } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { DocumentPointer } from \"../types\";\n\n/**\n * Makes a document readable by Copilot.\n * @param document The document to make readable.\n * @param categories The categories to associate with the document.\n * @param dependencies The dependencies to use for the effect.\n * @returns The id of the document.\n */\nexport function useMakeCopilotDocumentReadable(\n document: DocumentPointer,\n categories?: string[],\n dependencies: any[] = [],\n): string | undefined {\n const { addDocumentContext, removeDocumentContext } = useContext(CopilotContext);\n const idRef = useRef<string>();\n\n useEffect(() => {\n const id = addDocumentContext(document, categories);\n idRef.current = id;\n\n return () => {\n removeDocumentContext(id);\n };\n }, [addDocumentContext, removeDocumentContext, ...dependencies]);\n\n return idRef.current;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAAoC;;;ACGpC,mBAAkB;AAiElB,IAAM,sBAA4C;AAAA,EAChD,aAAa,CAAC;AAAA,EACd,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,kBAAkB,MAAM;AAAA,EAAC;AAAA,EACzB,uCAAuC,MAAM,sBAAsB,CAAC,CAAC;AAAA,EACrE,wBAAwB,MAAM,sBAAsB,MAAY;AAAA,EAAC,EAAC;AAAA,EAElE,kBAAkB,CAAC,WAA8B,eAC/C,sBAAsB,EAAE;AAAA,EAC1B,YAAY,MAAM;AAAA,EAClB,eAAe,MAAM;AAAA,EAAC;AAAA,EAEtB,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;AACL;AAEO,IAAM,iBAAiB,aAAAC,QAAM,cAAoC,mBAAmB;AAE3F,SAAS,sBAAyB,OAAa;AAC7C,QAAM,IAAI,MAAM,uEAAuE;AACvF,SAAO;AACT;;;ACzGA,IAAAC,gBAAiC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AAC;AAC7B,QAAM,EAAE,eAAe,iBAAiB,QAAI,0BAAW,cAAc;AAErE,QAAM,gCAA4D;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,+BAAU,MAAM;AACd,kBAAc,MAAM,SAAS,yBAAqD;AAElF,WAAO,MAAM;AACX,uBAAiB,MAAM,OAAO;AAAA,IAChC;AAAA,EACF,GAAG,CAAC,2BAA2B,eAAe,gBAAgB,CAAC;AACjE;;;AC7BA,IAAAC,gBAA8C;AAUvC,SAAS,uBACd,aACA,UACA,YACoB;AACpB,QAAM,EAAE,YAAY,cAAc,QAAI,0BAAW,cAAc;AAC/D,QAAM,YAAQ,sBAAe;AAE7B,+BAAU,MAAM;AACd,UAAM,KAAK,WAAW,aAAa,UAAU,UAAU;AACvD,UAAM,UAAU;AAEhB,WAAO,MAAM;AACX,oBAAc,EAAE;AAAA,IAClB;AAAA,EACF,GAAG,CAAC,aAAa,UAAU,YAAY,aAAa,CAAC;AAErD,SAAO,MAAM;AACf;;;AC5BA,IAAAC,gBAA8C;AAWvC,SAAS,+BACd,UACA,YACA,eAAsB,CAAC,GACH;AACpB,QAAM,EAAE,oBAAoB,sBAAsB,QAAI,0BAAW,cAAc;AAC/E,QAAM,YAAQ,sBAAe;AAE7B,+BAAU,MAAM;AACd,UAAM,KAAK,mBAAmB,UAAU,UAAU;AAClD,UAAM,UAAU;AAEhB,WAAO,MAAM;AACX,4BAAsB,EAAE;AAAA,IAC1B;AAAA,EACF,GAAG,CAAC,oBAAoB,uBAAuB,GAAG,YAAY,CAAC;AAE/D,SAAO,MAAM;AACf;","names":["import_react","React","import_react","messages","import_react","import_shared","import_react","import_nanoid","import_react","import_react"]}
1
+ {"version":3,"sources":["../../src/hooks/index.ts","../../src/hooks/use-copilot-chat.ts","../../src/context/copilot-context.tsx","../../src/hooks/use-chat.ts","../../src/utils/fetch-chat-completion.ts","../../src/components/copilot-provider/copilotkit.tsx","../../src/hooks/use-make-copilot-actionable.ts","../../src/hooks/use-make-copilot-readable.ts","../../src/hooks/use-make-copilot-document-readable.ts"],"sourcesContent":["export { useCopilotChat } from \"./use-copilot-chat\";\nexport type { UseCopilotChatOptions } from \"./use-copilot-chat\";\nexport type { UseCopilotChatReturn } from \"./use-copilot-chat\";\n\nexport { useMakeCopilotActionable } from \"./use-make-copilot-actionable\";\nexport { useMakeCopilotReadable } from \"./use-make-copilot-readable\";\nexport { useMakeCopilotDocumentReadable } from \"./use-make-copilot-document-readable\";\nexport { type UseChatHelpers } from \"./use-chat\";\n","import { useMemo, useContext } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { Message, ToolDefinition } from \"@copilotkit/shared\";\nimport { SystemMessageFunction } from \"../types\";\nimport { UseChatOptions, useChat } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\n\nexport interface UseCopilotChatOptions extends UseChatOptions {\n makeSystemMessage?: SystemMessageFunction;\n additionalInstructions?: string;\n}\n\nexport interface UseCopilotChatReturn {\n visibleMessages: Message[];\n append: (message: Message) => Promise<void>;\n reload: () => Promise<void>;\n stop: () => void;\n isLoading: boolean;\n input: string;\n setInput: React.Dispatch<React.SetStateAction<string>>;\n}\n\nexport function useCopilotChat({\n makeSystemMessage,\n additionalInstructions,\n ...options\n}: UseCopilotChatOptions): UseCopilotChatReturn {\n const {\n getContextString,\n getChatCompletionFunctionDescriptions,\n getFunctionCallHandler,\n copilotApiConfig,\n } = useContext(CopilotContext);\n\n const systemMessage: Message = useMemo(() => {\n const systemMessageMaker = makeSystemMessage || defaultSystemMessage;\n const contextString = getContextString([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return {\n id: \"system\",\n content: systemMessageMaker(contextString, additionalInstructions),\n role: \"system\",\n };\n }, [getContextString, makeSystemMessage]);\n\n const functionDescriptions: ToolDefinition[] = useMemo(() => {\n return getChatCompletionFunctionDescriptions();\n }, [getChatCompletionFunctionDescriptions]);\n\n const { messages, append, reload, stop, isLoading, input, setInput } = useChat({\n ...options,\n copilotConfig: copilotApiConfig,\n id: options.id,\n initialMessages: [systemMessage].concat(options.initialMessages || []),\n tools: functionDescriptions,\n onFunctionCall: getFunctionCallHandler(),\n headers: { ...options.headers },\n body: {\n ...options.body,\n },\n });\n\n const visibleMessages = messages.filter(\n (message) => message.role === \"user\" || message.role === \"assistant\",\n );\n\n return {\n visibleMessages,\n append,\n reload,\n stop,\n isLoading,\n input,\n setInput,\n };\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","\"use client\";\n\nimport { FunctionCallHandler, AnnotatedFunction, ToolDefinition } from \"@copilotkit/shared\";\nimport React 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\nexport interface CopilotContextParams {\n // function-calling\n entryPoints: Record<string, AnnotatedFunction<any[]>>;\n setEntryPoint: (id: string, entryPoint: AnnotatedFunction<any[]>) => void;\n removeEntryPoint: (id: string) => void;\n getChatCompletionFunctionDescriptions: (\n customEntryPoints?: Record<string, AnnotatedFunction<any[]>>,\n ) => ToolDefinition[];\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, AnnotatedFunction<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\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 { useRef, useState } from \"react\";\nimport { Message, ToolDefinition, FunctionCallHandler } from \"@copilotkit/shared\";\nimport { nanoid } from \"nanoid\";\nimport { fetchAndDecodeChatCompletion } from \"../utils/fetch-chat-completion\";\nimport { CopilotApiConfig } from \"../context\";\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 /** Current messages in the chat */\n messages: Message[];\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 /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport type UseChatOptionsWithCopilotConfig = UseChatOptions & {\n copilotConfig: CopilotApiConfig;\n};\n\nexport function useChat(options: UseChatOptionsWithCopilotConfig): UseChatHelpers {\n const [messages, setMessages] = useState<Message[]>([]);\n const [input, setInput] = useState(\"\");\n const [isLoading, setIsLoading] = useState(false);\n const abortControllerRef = useRef<AbortController>();\n\n const runChatCompletion = async (messages: Message[]): Promise<Message[]> => {\n 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\n const messagesWithContext = [...(options.initialMessages || []), ...messages];\n const response = await fetchAndDecodeChatCompletion({\n copilotConfig: options.copilotConfig,\n messages: messagesWithContext,\n tools: options.tools,\n headers: options.headers,\n signal: abortController.signal,\n });\n\n if (!response.events) {\n throw new Error(\"Failed to fetch chat completion\");\n }\n\n const reader = response.events.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n return newMessages.slice();\n }\n\n let currentMessage = Object.assign({}, newMessages[newMessages.length - 1]);\n\n if (value.type === \"content\") {\n if (currentMessage.function_call) {\n // Create a new message if the previous one is a function call\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 === \"function\") {\n // Create a new message if the previous one is not empty\n if (currentMessage.content != \"\" || currentMessage.function_call) {\n currentMessage = {\n id: nanoid(),\n createdAt: new Date(),\n content: \"\",\n role: \"assistant\",\n };\n newMessages.push(currentMessage);\n }\n currentMessage.function_call = {\n name: value.name,\n arguments: JSON.stringify(value.arguments),\n };\n\n newMessages[newMessages.length - 1] = currentMessage;\n setMessages([...messages, ...newMessages]);\n\n // Execute the function call\n await options.onFunctionCall?.(messages, currentMessage.function_call);\n }\n }\n } finally {\n 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 (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 (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 messages,\n append,\n reload,\n stop,\n isLoading,\n input,\n setInput,\n };\n}\n","import {\n Message,\n ToolDefinition,\n ChatCompletionEvent,\n decodeChatCompletion,\n parseChatCompletion,\n decodeChatCompletionAsText,\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 ...(body ? { ...body } : {}),\n }),\n signal,\n });\n\n return response;\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 return { ...response, events: null };\n }\n const events = await decodeChatCompletion(parseChatCompletion(response.body));\n return { ...response, events };\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 return { ...response, events: null };\n }\n const events = await decodeChatCompletionAsText(\n decodeChatCompletion(parseChatCompletion(response.body)),\n );\n return { ...response, events };\n}\n","\"use client\";\n\nimport { FunctionDefinition } from \"@copilotkit/shared\";\nimport { useCallback, useState } from \"react\";\nimport { CopilotContext, CopilotApiConfig } from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { DocumentPointer } from \"../../types\";\nimport {\n FunctionCallHandler,\n AnnotatedFunction,\n annotatedFunctionToChatCompletionFunction,\n} from \"@copilotkit/shared\";\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, AnnotatedFunction<any[]>>>({});\n\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: AnnotatedFunction<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, AnnotatedFunction<any[]>>) => {\n return entryPointsToChatCompletionFunctions(Object.values(customEntryPoints || entryPoints));\n },\n [entryPoints],\n );\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, AnnotatedFunction<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 props.body || {},\n );\n\n return (\n <CopilotContext.Provider\n value={{\n entryPoints,\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 entryPointsToFunctionCallHandler(\n entryPoints: AnnotatedFunction<any[]>[],\n): FunctionCallHandler {\n return async (chatMessages, functionCall) => {\n let entrypointsByFunctionName: Record<string, AnnotatedFunction<any[]>> = {};\n for (let entryPoint of entryPoints) {\n entrypointsByFunctionName[entryPoint.name] = entryPoint;\n }\n\n const entryPointFunction = entrypointsByFunctionName[functionCall.name || \"\"];\n if (entryPointFunction) {\n let functionCallArguments: Record<string, any>[] = [];\n if (functionCall.arguments) {\n functionCallArguments = JSON.parse(functionCall.arguments);\n }\n\n const paramsInCorrectOrder: any[] = [];\n for (let arg of entryPointFunction.argumentAnnotations) {\n paramsInCorrectOrder.push(\n functionCallArguments[arg.name as keyof typeof functionCallArguments],\n );\n }\n\n await entryPointFunction.implementation(...paramsInCorrectOrder);\n\n // commented out becasue for now we don't want to return anything\n // const result = await entryPointFunction.implementation(\n // ...parsedFunctionCallArguments\n // );\n // const functionResponse: ChatRequest = {\n // messages: [\n // ...chatMessages,\n // {\n // id: nanoid(),\n // name: functionCall.name,\n // role: 'function' as const,\n // content: JSON.stringify(result),\n // },\n // ],\n // };\n\n // return functionResponse;\n }\n };\n}\n\nfunction entryPointsToChatCompletionFunctions(\n entryPoints: AnnotatedFunction<any[]>[],\n): ToolDefinition[] {\n return entryPoints.map(annotatedFunctionToChatCompletionFunction);\n}\n","\"use client\";\n\nimport { useRef, useContext, useEffect, useMemo } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { AnnotatedFunction } from \"@copilotkit/shared\";\nimport { nanoid } from \"nanoid\";\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 setEntryPoint(idRef.current, memoizedAnnotatedFunction as AnnotatedFunction<any[]>);\n\n return () => {\n removeEntryPoint(idRef.current);\n };\n }, [memoizedAnnotatedFunction, setEntryPoint, removeEntryPoint]);\n}\n","\"use client\";\n\nimport { useContext, useEffect, useRef } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\n\n/**\n * Adds the given information to the Copilot context to make it readable by Copilot.\n * @param information - The information to be added to the Copilot context.\n * @param parentId - The ID of the parent context, if any.\n * @param categories - An array of categories to control which context are visible where. Particularly useful with CopilotTextarea (see `useMakeAutosuggestionFunction`)\n * @returns The ID of the added context.\n */\nexport function useMakeCopilotReadable(\n information: string,\n parentId?: string,\n categories?: string[],\n): string | undefined {\n const { addContext, removeContext } = useContext(CopilotContext);\n const idRef = useRef<string>();\n\n useEffect(() => {\n const id = addContext(information, parentId, categories);\n idRef.current = id;\n\n return () => {\n removeContext(id);\n };\n }, [information, parentId, addContext, removeContext]);\n\n return idRef.current;\n}\n","\"use client\";\n\nimport { useContext, useEffect, useRef } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { DocumentPointer } from \"../types\";\n\n/**\n * Makes a document readable by Copilot.\n * @param document The document to make readable.\n * @param categories The categories to associate with the document.\n * @param dependencies The dependencies to use for the effect.\n * @returns The id of the document.\n */\nexport function useMakeCopilotDocumentReadable(\n document: DocumentPointer,\n categories?: string[],\n dependencies: any[] = [],\n): string | undefined {\n const { addDocumentContext, removeDocumentContext } = useContext(CopilotContext);\n const idRef = useRef<string>();\n\n useEffect(() => {\n const id = addDocumentContext(document, categories);\n idRef.current = id;\n\n return () => {\n removeDocumentContext(id);\n };\n }, [addDocumentContext, removeDocumentContext, ...dependencies]);\n\n return idRef.current;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAAoC;;;ACGpC,mBAAkB;AAqElB,IAAM,sBAA4C;AAAA,EAChD,aAAa,CAAC;AAAA,EACd,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,kBAAkB,MAAM;AAAA,EAAC;AAAA,EACzB,uCAAuC,MAAM,sBAAs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AAI,0BAAW,cAAc;AAErE,QAAM,gCAA4D;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,+BAAU,MAAM;AACd,kBAAc,MAAM,SAAS,yBAAqD;AAElF,WAAO,MAAM;AACX,uBAAiB,MAAM,OAAO;AAAA,IAChC;AAAA,EACF,GAAG,CAAC,2BAA2B,eAAe,gBAAgB,CAAC;AACjE;;;AC7BA,IAAAC,gBAA8C;AAUvC,SAAS,uBACd,aACA,UACA,YACoB;AACpB,QAAM,EAAE,YAAY,cAAc,QAAI,0BAAW,cAAc;AAC/D,QAAM,YAAQ,sBAAe;AAE7B,+BAAU,MAAM;AACd,UAAM,KAAK,WAAW,aAAa,UAAU,UAAU;AACvD,UAAM,UAAU;AAEhB,WAAO,MAAM;AACX,oBAAc,EAAE;AAAA,IAClB;AAAA,EACF,GAAG,CAAC,aAAa,UAAU,YAAY,aAAa,CAAC;AAErD,SAAO,MAAM;AACf;;;AC5BA,IAAAC,gBAA8C;AAWvC,SAAS,+BACd,UACA,YACA,eAAsB,CAAC,GACH;AACpB,QAAM,EAAE,oBAAoB,sBAAsB,QAAI,0BAAW,cAAc;AAC/E,QAAM,YAAQ,sBAAe;AAE7B,+BAAU,MAAM;AACd,UAAM,KAAK,mBAAmB,UAAU,UAAU;AAClD,UAAM,UAAU;AAEhB,WAAO,MAAM;AACX,4BAAsB,EAAE;AAAA,IAC1B;AAAA,EACF,GAAG,CAAC,oBAAoB,uBAAuB,GAAG,YAAY,CAAC;AAE/D,SAAO,MAAM;AACf;","names":["import_react","React","import_react","messages","import_react","import_shared","import_react","import_nanoid","import_react","import_react"]}
@@ -1,26 +1,397 @@
1
- import "../chunk-5UGLWBZJ.mjs";
2
- import {
3
- useMakeCopilotActionable
4
- } from "../chunk-DGUVNY3V.mjs";
5
- import {
6
- useMakeCopilotDocumentReadable
7
- } from "../chunk-IQH5AQQC.mjs";
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __objRest = (source, exclude) => {
21
+ var target = {};
22
+ for (var prop in source)
23
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
+ target[prop] = source[prop];
25
+ if (source != null && __getOwnPropSymbols)
26
+ for (var prop of __getOwnPropSymbols(source)) {
27
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
+ target[prop] = source[prop];
29
+ }
30
+ return target;
31
+ };
32
+ var __async = (__this, __arguments, generator) => {
33
+ return new Promise((resolve, reject) => {
34
+ var fulfilled = (value) => {
35
+ try {
36
+ step(generator.next(value));
37
+ } catch (e) {
38
+ reject(e);
39
+ }
40
+ };
41
+ var rejected = (value) => {
42
+ try {
43
+ step(generator.throw(value));
44
+ } catch (e) {
45
+ reject(e);
46
+ }
47
+ };
48
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
49
+ step((generator = generator.apply(__this, __arguments)).next());
50
+ });
51
+ };
52
+
53
+ // src/hooks/use-copilot-chat.ts
54
+ import { useMemo, useContext } from "react";
55
+
56
+ // src/context/copilot-context.tsx
57
+ import React from "react";
58
+ var emptyCopilotContext = {
59
+ entryPoints: {},
60
+ setEntryPoint: () => {
61
+ },
62
+ removeEntryPoint: () => {
63
+ },
64
+ getChatCompletionFunctionDescriptions: () => returnAndThrowInDebug([]),
65
+ getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
66
+ })),
67
+ getContextString: (documents, categories) => returnAndThrowInDebug(""),
68
+ addContext: () => "",
69
+ removeContext: () => {
70
+ },
71
+ getDocumentsContext: (categories) => returnAndThrowInDebug([]),
72
+ addDocumentContext: () => returnAndThrowInDebug(""),
73
+ removeDocumentContext: () => {
74
+ },
75
+ copilotApiConfig: new class {
76
+ get chatApiEndpoint() {
77
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
78
+ }
79
+ get chatApiEndpointV2() {
80
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
81
+ }
82
+ get headers() {
83
+ return {};
84
+ }
85
+ get body() {
86
+ return {};
87
+ }
88
+ }()
89
+ };
90
+ var CopilotContext = React.createContext(emptyCopilotContext);
91
+ function returnAndThrowInDebug(value) {
92
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
93
+ return value;
94
+ }
95
+
96
+ // src/hooks/use-chat.ts
97
+ import { useRef, useState } from "react";
98
+ import { nanoid } from "nanoid";
99
+
100
+ // src/utils/fetch-chat-completion.ts
8
101
  import {
9
- useMakeCopilotReadable
10
- } from "../chunk-YOXWT7I6.mjs";
102
+ decodeChatCompletion,
103
+ parseChatCompletion,
104
+ decodeChatCompletionAsText
105
+ } from "@copilotkit/shared";
106
+ function fetchChatCompletion(_0) {
107
+ return __async(this, arguments, function* ({
108
+ copilotConfig,
109
+ model,
110
+ messages,
111
+ tools,
112
+ temperature,
113
+ headers,
114
+ body,
115
+ signal
116
+ }) {
117
+ temperature || (temperature = 0.5);
118
+ tools || (tools = []);
119
+ const cleanedMessages = messages.map((message) => {
120
+ const { content, role, name, function_call } = message;
121
+ return { content, role, name, function_call };
122
+ });
123
+ const response = yield fetch(copilotConfig.chatApiEndpoint, {
124
+ method: "POST",
125
+ headers: __spreadValues(__spreadValues({
126
+ "Content-Type": "application/json"
127
+ }, copilotConfig.headers), headers ? __spreadValues({}, headers) : {}),
128
+ body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
129
+ model,
130
+ messages: cleanedMessages,
131
+ stream: true
132
+ }, tools.length ? { tools } : {}), temperature ? { temperature } : {}), tools.length != 0 ? { tool_choice: "auto" } : {}), copilotConfig.body), body ? __spreadValues({}, body) : {})),
133
+ signal
134
+ });
135
+ return response;
136
+ });
137
+ }
138
+ function fetchAndDecodeChatCompletion(params) {
139
+ return __async(this, null, function* () {
140
+ const response = yield fetchChatCompletion(params);
141
+ if (!response.ok || !response.body) {
142
+ return __spreadProps(__spreadValues({}, response), { events: null });
143
+ }
144
+ const events = yield decodeChatCompletion(parseChatCompletion(response.body));
145
+ return __spreadProps(__spreadValues({}, response), { events });
146
+ });
147
+ }
148
+
149
+ // src/hooks/use-chat.ts
150
+ function useChat(options) {
151
+ const [messages, setMessages] = useState([]);
152
+ const [input, setInput] = useState("");
153
+ const [isLoading, setIsLoading] = useState(false);
154
+ const abortControllerRef = useRef();
155
+ const runChatCompletion = (messages2) => __async(this, null, function* () {
156
+ var _a;
157
+ setIsLoading(true);
158
+ const newMessages = [
159
+ {
160
+ id: nanoid(),
161
+ createdAt: /* @__PURE__ */ new Date(),
162
+ content: "",
163
+ role: "assistant"
164
+ }
165
+ ];
166
+ const abortController = new AbortController();
167
+ abortControllerRef.current = abortController;
168
+ setMessages([...messages2, ...newMessages]);
169
+ const messagesWithContext = [...options.initialMessages || [], ...messages2];
170
+ const response = yield fetchAndDecodeChatCompletion({
171
+ copilotConfig: options.copilotConfig,
172
+ messages: messagesWithContext,
173
+ tools: options.tools,
174
+ headers: options.headers,
175
+ signal: abortController.signal
176
+ });
177
+ if (!response.events) {
178
+ throw new Error("Failed to fetch chat completion");
179
+ }
180
+ const reader = response.events.getReader();
181
+ try {
182
+ while (true) {
183
+ const { done, value } = yield reader.read();
184
+ if (done) {
185
+ return newMessages.slice();
186
+ }
187
+ let currentMessage = Object.assign({}, newMessages[newMessages.length - 1]);
188
+ if (value.type === "content") {
189
+ if (currentMessage.function_call) {
190
+ currentMessage = {
191
+ id: nanoid(),
192
+ createdAt: /* @__PURE__ */ new Date(),
193
+ content: "",
194
+ role: "assistant"
195
+ };
196
+ newMessages.push(currentMessage);
197
+ }
198
+ currentMessage.content += value.content;
199
+ newMessages[newMessages.length - 1] = currentMessage;
200
+ setMessages([...messages2, ...newMessages]);
201
+ } else if (value.type === "function") {
202
+ if (currentMessage.content != "" || currentMessage.function_call) {
203
+ currentMessage = {
204
+ id: nanoid(),
205
+ createdAt: /* @__PURE__ */ new Date(),
206
+ content: "",
207
+ role: "assistant"
208
+ };
209
+ newMessages.push(currentMessage);
210
+ }
211
+ currentMessage.function_call = {
212
+ name: value.name,
213
+ arguments: JSON.stringify(value.arguments)
214
+ };
215
+ newMessages[newMessages.length - 1] = currentMessage;
216
+ setMessages([...messages2, ...newMessages]);
217
+ yield (_a = options.onFunctionCall) == null ? void 0 : _a.call(options, messages2, currentMessage.function_call);
218
+ }
219
+ }
220
+ } finally {
221
+ setIsLoading(false);
222
+ }
223
+ });
224
+ const runChatCompletionAndHandleFunctionCall = (messages2) => __async(this, null, function* () {
225
+ yield runChatCompletion(messages2);
226
+ });
227
+ const append = (message) => __async(this, null, function* () {
228
+ if (isLoading) {
229
+ return;
230
+ }
231
+ const newMessages = [...messages, message];
232
+ setMessages(newMessages);
233
+ return runChatCompletionAndHandleFunctionCall(newMessages);
234
+ });
235
+ const reload = () => __async(this, null, function* () {
236
+ if (isLoading || messages.length === 0) {
237
+ return;
238
+ }
239
+ let newMessages = [...messages];
240
+ const lastMessage = messages[messages.length - 1];
241
+ if (lastMessage.role === "assistant") {
242
+ newMessages = newMessages.slice(0, -1);
243
+ }
244
+ setMessages(newMessages);
245
+ return runChatCompletionAndHandleFunctionCall(newMessages);
246
+ });
247
+ const stop = () => {
248
+ var _a;
249
+ (_a = abortControllerRef.current) == null ? void 0 : _a.abort();
250
+ };
251
+ return {
252
+ messages,
253
+ append,
254
+ reload,
255
+ stop,
256
+ isLoading,
257
+ input,
258
+ setInput
259
+ };
260
+ }
261
+
262
+ // src/components/copilot-provider/copilotkit.tsx
263
+ import { useCallback, useState as useState2 } from "react";
11
264
  import {
12
- useCopilotChat
13
- } from "../chunk-5GS7FQPW.mjs";
14
- import "../chunk-JD7BAH7U.mjs";
15
- import "../chunk-SPCZTZCY.mjs";
16
- import "../chunk-GBZZPQ5X.mjs";
17
- import "../chunk-F2JIAPZQ.mjs";
18
- import "../chunk-VUY2K2DI.mjs";
19
- import "../chunk-4CFJ6A6A.mjs";
20
- import "../chunk-IQEWY7P4.mjs";
21
- import "../chunk-UAKLDQMP.mjs";
22
- import "../chunk-YULKJPY3.mjs";
23
- import "../chunk-MRXNTQOX.mjs";
265
+ annotatedFunctionToChatCompletionFunction
266
+ } from "@copilotkit/shared";
267
+ import { jsx } from "react/jsx-runtime";
268
+ var defaultCopilotContextCategories = ["global"];
269
+
270
+ // src/hooks/use-copilot-chat.ts
271
+ function useCopilotChat(_a) {
272
+ var _b = _a, {
273
+ makeSystemMessage,
274
+ additionalInstructions
275
+ } = _b, options = __objRest(_b, [
276
+ "makeSystemMessage",
277
+ "additionalInstructions"
278
+ ]);
279
+ const {
280
+ getContextString,
281
+ getChatCompletionFunctionDescriptions,
282
+ getFunctionCallHandler,
283
+ copilotApiConfig
284
+ } = useContext(CopilotContext);
285
+ const systemMessage = useMemo(() => {
286
+ const systemMessageMaker = makeSystemMessage || defaultSystemMessage;
287
+ const contextString = getContextString([], defaultCopilotContextCategories);
288
+ return {
289
+ id: "system",
290
+ content: systemMessageMaker(contextString, additionalInstructions),
291
+ role: "system"
292
+ };
293
+ }, [getContextString, makeSystemMessage]);
294
+ const functionDescriptions = useMemo(() => {
295
+ return getChatCompletionFunctionDescriptions();
296
+ }, [getChatCompletionFunctionDescriptions]);
297
+ const { messages, append, reload, stop, isLoading, input, setInput } = useChat(__spreadProps(__spreadValues({}, options), {
298
+ copilotConfig: copilotApiConfig,
299
+ id: options.id,
300
+ initialMessages: [systemMessage].concat(options.initialMessages || []),
301
+ tools: functionDescriptions,
302
+ onFunctionCall: getFunctionCallHandler(),
303
+ headers: __spreadValues({}, options.headers),
304
+ body: __spreadValues({}, options.body)
305
+ }));
306
+ const visibleMessages = messages.filter(
307
+ (message) => message.role === "user" || message.role === "assistant"
308
+ );
309
+ return {
310
+ visibleMessages,
311
+ append,
312
+ reload,
313
+ stop,
314
+ isLoading,
315
+ input,
316
+ setInput
317
+ };
318
+ }
319
+ function defaultSystemMessage(contextString, additionalInstructions) {
320
+ return `
321
+ Please act as an efficient, competent, conscientious, and industrious professional assistant.
322
+
323
+ 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.
324
+ Always be polite and respectful, and prefer brevity over verbosity.
325
+
326
+ The user has provided you with the following context:
327
+ \`\`\`
328
+ ${contextString}
329
+ \`\`\`
330
+
331
+ 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.
332
+
333
+ Please assist them as best you can.
334
+
335
+ 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.
336
+
337
+ If you would like to call a function, call it without saying anything else.
338
+ ` + (additionalInstructions ? `
339
+
340
+ ${additionalInstructions}` : "");
341
+ }
342
+
343
+ // src/hooks/use-make-copilot-actionable.ts
344
+ import { useRef as useRef2, useContext as useContext2, useEffect, useMemo as useMemo2 } from "react";
345
+ import { nanoid as nanoid2 } from "nanoid";
346
+ function useMakeCopilotActionable(annotatedFunction, dependencies) {
347
+ const idRef = useRef2(nanoid2());
348
+ const { setEntryPoint, removeEntryPoint } = useContext2(CopilotContext);
349
+ const memoizedAnnotatedFunction = useMemo2(
350
+ () => ({
351
+ name: annotatedFunction.name,
352
+ description: annotatedFunction.description,
353
+ argumentAnnotations: annotatedFunction.argumentAnnotations,
354
+ implementation: annotatedFunction.implementation
355
+ }),
356
+ dependencies
357
+ );
358
+ useEffect(() => {
359
+ setEntryPoint(idRef.current, memoizedAnnotatedFunction);
360
+ return () => {
361
+ removeEntryPoint(idRef.current);
362
+ };
363
+ }, [memoizedAnnotatedFunction, setEntryPoint, removeEntryPoint]);
364
+ }
365
+
366
+ // src/hooks/use-make-copilot-readable.ts
367
+ import { useContext as useContext3, useEffect as useEffect2, useRef as useRef3 } from "react";
368
+ function useMakeCopilotReadable(information, parentId, categories) {
369
+ const { addContext, removeContext } = useContext3(CopilotContext);
370
+ const idRef = useRef3();
371
+ useEffect2(() => {
372
+ const id = addContext(information, parentId, categories);
373
+ idRef.current = id;
374
+ return () => {
375
+ removeContext(id);
376
+ };
377
+ }, [information, parentId, addContext, removeContext]);
378
+ return idRef.current;
379
+ }
380
+
381
+ // src/hooks/use-make-copilot-document-readable.ts
382
+ import { useContext as useContext4, useEffect as useEffect3, useRef as useRef4 } from "react";
383
+ function useMakeCopilotDocumentReadable(document, categories, dependencies = []) {
384
+ const { addDocumentContext, removeDocumentContext } = useContext4(CopilotContext);
385
+ const idRef = useRef4();
386
+ useEffect3(() => {
387
+ const id = addDocumentContext(document, categories);
388
+ idRef.current = id;
389
+ return () => {
390
+ removeDocumentContext(id);
391
+ };
392
+ }, [addDocumentContext, removeDocumentContext, ...dependencies]);
393
+ return idRef.current;
394
+ }
24
395
  export {
25
396
  useCopilotChat,
26
397
  useMakeCopilotActionable,