@copilotkit/react-core 0.18.0-alpha.1 → 0.18.0-alpha.3

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 (158) hide show
  1. package/.turbo/turbo-build.log +184 -122
  2. package/CHANGELOG.md +25 -1
  3. package/dist/{chunk-6A4PCNMZ.mjs → chunk-4CFJ6A6A.mjs} +4 -10
  4. package/dist/chunk-4CFJ6A6A.mjs.map +1 -0
  5. package/dist/{chunk-FY7XNRJP.mjs → chunk-5GS7FQPW.mjs} +4 -4
  6. package/dist/chunk-5GS7FQPW.mjs.map +1 -0
  7. package/dist/{chunk-FP4EXCGS.mjs → chunk-DGUVNY3V.mjs} +2 -2
  8. package/dist/chunk-DGUVNY3V.mjs.map +1 -0
  9. package/dist/{chunk-D4NQCVHE.mjs → chunk-GBZZPQ5X.mjs} +11 -38
  10. package/dist/chunk-GBZZPQ5X.mjs.map +1 -0
  11. package/dist/chunk-IQEWY7P4.mjs +102 -0
  12. package/dist/chunk-IQEWY7P4.mjs.map +1 -0
  13. package/dist/{chunk-7P4OYNP3.mjs → chunk-IQH5AQQC.mjs} +2 -2
  14. package/dist/chunk-UAKLDQMP.mjs +61 -0
  15. package/dist/chunk-UAKLDQMP.mjs.map +1 -0
  16. package/dist/{chunk-P34OLW2N.mjs → chunk-VP2EU4US.mjs} +3 -3
  17. package/dist/{chunk-HW5IH6PV.mjs → chunk-YOXWT7I6.mjs} +2 -2
  18. package/dist/components/copilot-provider/copilotkit-props.d.ts +39 -0
  19. package/dist/components/copilot-provider/copilotkit-props.js +4 -0
  20. package/dist/components/copilot-provider/copilotkit-props.mjs +3 -0
  21. package/dist/components/copilot-provider/{copilot-provider.d.ts → copilotkit.d.ts} +9 -15
  22. package/dist/components/copilot-provider/copilotkit.js +426 -0
  23. package/dist/components/copilot-provider/copilotkit.js.map +1 -0
  24. package/dist/components/copilot-provider/copilotkit.mjs +8 -0
  25. package/dist/components/copilot-provider/index.d.ts +2 -8
  26. package/dist/components/copilot-provider/index.js +426 -0
  27. package/dist/components/copilot-provider/index.js.map +1 -0
  28. package/dist/components/copilot-provider/index.mjs +2 -2
  29. package/dist/components/copilot-provider/standard-copilot-api-config.d.ts +2 -4
  30. package/dist/components/copilot-provider/standard-copilot-api-config.js +15 -0
  31. package/dist/components/copilot-provider/standard-copilot-api-config.js.map +1 -0
  32. package/dist/components/index.d.ts +2 -8
  33. package/dist/components/index.js +426 -0
  34. package/dist/components/index.js.map +1 -0
  35. package/dist/components/index.mjs +2 -2
  36. package/dist/context/copilot-context.d.ts +3 -5
  37. package/dist/context/copilot-context.js +47 -0
  38. package/dist/context/copilot-context.js.map +1 -0
  39. package/dist/context/copilot-context.mjs +1 -1
  40. package/dist/context/index.d.ts +2 -4
  41. package/dist/context/index.js +47 -0
  42. package/dist/context/index.js.map +1 -0
  43. package/dist/context/index.mjs +1 -1
  44. package/dist/hooks/index.d.ts +2 -4
  45. package/dist/hooks/index.js +358 -0
  46. package/dist/hooks/index.js.map +1 -0
  47. package/dist/hooks/index.mjs +8 -9
  48. package/dist/hooks/use-chat.d.ts +2 -4
  49. package/dist/hooks/use-chat.js +186 -0
  50. package/dist/hooks/use-chat.js.map +1 -0
  51. package/dist/hooks/use-chat.mjs +2 -3
  52. package/dist/hooks/use-copilot-chat.d.ts +2 -4
  53. package/dist/hooks/use-copilot-chat.js +313 -0
  54. package/dist/hooks/use-copilot-chat.js.map +1 -0
  55. package/dist/hooks/use-copilot-chat.mjs +5 -6
  56. package/dist/hooks/use-flat-category-store.js +72 -0
  57. package/dist/hooks/use-flat-category-store.js.map +1 -0
  58. package/dist/hooks/use-make-copilot-actionable.d.ts +1 -1
  59. package/dist/hooks/use-make-copilot-actionable.js +67 -0
  60. package/dist/hooks/use-make-copilot-actionable.js.map +1 -0
  61. package/dist/hooks/use-make-copilot-actionable.mjs +2 -2
  62. package/dist/hooks/use-make-copilot-document-readable.js +61 -0
  63. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -0
  64. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  65. package/dist/hooks/use-make-copilot-readable.js +61 -0
  66. package/dist/hooks/use-make-copilot-readable.js.map +1 -0
  67. package/dist/hooks/use-make-copilot-readable.mjs +2 -2
  68. package/dist/hooks/use-tree.js +155 -0
  69. package/dist/hooks/use-tree.js.map +1 -0
  70. package/dist/index.d.ts +4 -9
  71. package/dist/index.js +838 -0
  72. package/dist/index.js.map +1 -0
  73. package/dist/index.mjs +10 -13
  74. package/dist/openai-assistants/hooks/index.js +225 -0
  75. package/dist/openai-assistants/hooks/index.js.map +1 -0
  76. package/dist/openai-assistants/hooks/index.mjs +3 -3
  77. package/dist/openai-assistants/hooks/use-assistants.js +129 -0
  78. package/dist/openai-assistants/hooks/use-assistants.js.map +1 -0
  79. package/dist/openai-assistants/hooks/use-copilot-chat-v2.js +226 -0
  80. package/dist/openai-assistants/hooks/use-copilot-chat-v2.js.map +1 -0
  81. package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs +3 -3
  82. package/dist/openai-assistants/index.js +226 -0
  83. package/dist/openai-assistants/index.js.map +1 -0
  84. package/dist/openai-assistants/index.mjs +3 -3
  85. package/dist/openai-assistants/utils/index.js +49 -0
  86. package/dist/openai-assistants/utils/index.js.map +1 -0
  87. package/dist/openai-assistants/utils/process-message-stream.js +49 -0
  88. package/dist/openai-assistants/utils/process-message-stream.js.map +1 -0
  89. package/dist/types/document-pointer.js +4 -0
  90. package/dist/types/index.d.ts +0 -2
  91. package/dist/types/index.js +4 -0
  92. package/dist/types/system-message.js +4 -0
  93. package/dist/utils/fetch-chat-completion.d.ts +28 -0
  94. package/dist/utils/fetch-chat-completion.js +103 -0
  95. package/dist/utils/fetch-chat-completion.js.map +1 -0
  96. package/dist/utils/fetch-chat-completion.mjs +4 -0
  97. package/dist/utils/utils.js +4 -0
  98. package/dist/utils/utils.test.js +10 -0
  99. package/dist/utils/utils.test.js.map +1 -0
  100. package/package.json +10 -10
  101. package/src/components/copilot-provider/copilotkit-props.tsx +42 -0
  102. package/src/components/copilot-provider/{copilot-provider.tsx → copilotkit.tsx} +22 -57
  103. package/src/components/copilot-provider/index.ts +2 -6
  104. package/src/context/copilot-context.tsx +5 -13
  105. package/src/hooks/use-chat.ts +54 -72
  106. package/src/hooks/use-copilot-chat.ts +4 -4
  107. package/src/hooks/use-make-copilot-actionable.ts +1 -1
  108. package/src/index.tsx +6 -1
  109. package/src/types/index.ts +0 -3
  110. package/src/utils/fetch-chat-completion.ts +95 -0
  111. package/tsup.config.ts +1 -2
  112. package/dist/chunk-6A4PCNMZ.mjs.map +0 -1
  113. package/dist/chunk-6SOQYBNX.mjs +0 -44
  114. package/dist/chunk-6SOQYBNX.mjs.map +0 -1
  115. package/dist/chunk-D4NQCVHE.mjs.map +0 -1
  116. package/dist/chunk-FP4EXCGS.mjs.map +0 -1
  117. package/dist/chunk-FY7XNRJP.mjs.map +0 -1
  118. package/dist/chunk-LMZN4NSM.mjs +0 -113
  119. package/dist/chunk-LMZN4NSM.mjs.map +0 -1
  120. package/dist/chunk-PUFR5OAI.mjs +0 -3
  121. package/dist/chunk-TKXPMMND.mjs +0 -177
  122. package/dist/chunk-TKXPMMND.mjs.map +0 -1
  123. package/dist/chunk-VK25FIML.mjs +0 -144
  124. package/dist/chunk-VK25FIML.mjs.map +0 -1
  125. package/dist/components/copilot-provider/copilot-provider-props.d.ts +0 -50
  126. package/dist/components/copilot-provider/copilot-provider-props.mjs +0 -3
  127. package/dist/components/copilot-provider/copilot-provider.mjs +0 -8
  128. package/dist/openai/chat-completion-client.d.ts +0 -52
  129. package/dist/openai/chat-completion-client.mjs +0 -5
  130. package/dist/openai/chat-completion-stream.d.ts +0 -21
  131. package/dist/openai/chat-completion-stream.mjs +0 -5
  132. package/dist/openai/chat-completion-transport.d.ts +0 -38
  133. package/dist/openai/chat-completion-transport.mjs +0 -4
  134. package/dist/openai/index.d.ts +0 -10
  135. package/dist/openai/index.mjs +0 -6
  136. package/dist/types/annotated-function.d.ts +0 -24
  137. package/dist/types/annotated-function.mjs +0 -3
  138. package/dist/types/base.d.ts +0 -56
  139. package/dist/types/base.mjs +0 -3
  140. package/dist/types/base.mjs.map +0 -1
  141. package/src/components/copilot-provider/copilot-provider-props.tsx +0 -50
  142. package/src/openai/chat-completion-client.ts +0 -229
  143. package/src/openai/chat-completion-stream.ts +0 -54
  144. package/src/openai/chat-completion-transport.ts +0 -186
  145. package/src/openai/index.tsx +0 -5
  146. package/src/types/annotated-function.ts +0 -27
  147. package/src/types/base.ts +0 -61
  148. /package/dist/{chunk-7P4OYNP3.mjs.map → chunk-IQH5AQQC.mjs.map} +0 -0
  149. /package/dist/{chunk-P34OLW2N.mjs.map → chunk-VP2EU4US.mjs.map} +0 -0
  150. /package/dist/{chunk-HW5IH6PV.mjs.map → chunk-YOXWT7I6.mjs.map} +0 -0
  151. /package/dist/{chunk-PUFR5OAI.mjs.map → components/copilot-provider/copilotkit-props.js.map} +0 -0
  152. /package/dist/components/copilot-provider/{copilot-provider-props.mjs.map → copilotkit-props.mjs.map} +0 -0
  153. /package/dist/components/copilot-provider/{copilot-provider.mjs.map → copilotkit.mjs.map} +0 -0
  154. /package/dist/{openai/chat-completion-client.mjs.map → types/document-pointer.js.map} +0 -0
  155. /package/dist/{openai/chat-completion-stream.mjs.map → types/index.js.map} +0 -0
  156. /package/dist/{openai/chat-completion-transport.mjs.map → types/system-message.js.map} +0 -0
  157. /package/dist/{openai/index.mjs.map → utils/fetch-chat-completion.mjs.map} +0 -0
  158. /package/dist/{types/annotated-function.mjs.map → utils/utils.js.map} +0 -0
package/dist/index.js ADDED
@@ -0,0 +1,838 @@
1
+ 'use strict';
2
+
3
+ var React = require('react');
4
+ var nanoid = require('nanoid');
5
+ var shared = require('@copilotkit/shared');
6
+ var jsxRuntime = require('react/jsx-runtime');
7
+
8
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
+
10
+ var React__default = /*#__PURE__*/_interopDefault(React);
11
+
12
+ var __defProp = Object.defineProperty;
13
+ var __defProps = Object.defineProperties;
14
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
15
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
16
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
17
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
18
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
19
+ var __spreadValues = (a, b) => {
20
+ for (var prop in b || (b = {}))
21
+ if (__hasOwnProp.call(b, prop))
22
+ __defNormalProp(a, prop, b[prop]);
23
+ if (__getOwnPropSymbols)
24
+ for (var prop of __getOwnPropSymbols(b)) {
25
+ if (__propIsEnum.call(b, prop))
26
+ __defNormalProp(a, prop, b[prop]);
27
+ }
28
+ return a;
29
+ };
30
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
31
+ var __objRest = (source, exclude) => {
32
+ var target = {};
33
+ for (var prop in source)
34
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
35
+ target[prop] = source[prop];
36
+ if (source != null && __getOwnPropSymbols)
37
+ for (var prop of __getOwnPropSymbols(source)) {
38
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
39
+ target[prop] = source[prop];
40
+ }
41
+ return target;
42
+ };
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
+ var emptyCopilotContext = {
64
+ entryPoints: {},
65
+ setEntryPoint: () => {
66
+ },
67
+ removeEntryPoint: () => {
68
+ },
69
+ getChatCompletionFunctionDescriptions: () => returnAndThrowInDebug(),
70
+ getFunctionCallHandler: () => returnAndThrowInDebug(),
71
+ getContextString: (documents, categories) => returnAndThrowInDebug(),
72
+ addContext: () => "",
73
+ removeContext: () => {
74
+ },
75
+ getDocumentsContext: (categories) => returnAndThrowInDebug(),
76
+ addDocumentContext: () => returnAndThrowInDebug(),
77
+ removeDocumentContext: () => {
78
+ },
79
+ copilotApiConfig: new class {
80
+ get chatApiEndpoint() {
81
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
82
+ }
83
+ get chatApiEndpointV2() {
84
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
85
+ }
86
+ get headers() {
87
+ return {};
88
+ }
89
+ get body() {
90
+ return {};
91
+ }
92
+ }()
93
+ };
94
+ var CopilotContext = React__default.default.createContext(emptyCopilotContext);
95
+ function returnAndThrowInDebug(value) {
96
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
97
+ }
98
+ var removeNode = (nodes, id) => {
99
+ return nodes.reduce((result, node) => {
100
+ if (node.id !== id) {
101
+ const newNode = __spreadProps(__spreadValues({}, node), { children: removeNode(node.children, id) });
102
+ result.push(newNode);
103
+ }
104
+ return result;
105
+ }, []);
106
+ };
107
+ var addNode = (nodes, newNode, parentId) => {
108
+ if (!parentId) {
109
+ return [...nodes, newNode];
110
+ }
111
+ return nodes.map((node) => {
112
+ if (node.id === parentId) {
113
+ return __spreadProps(__spreadValues({}, node), { children: [...node.children, newNode] });
114
+ } else if (node.children.length) {
115
+ return __spreadProps(__spreadValues({}, node), { children: addNode(node.children, newNode, parentId) });
116
+ }
117
+ return node;
118
+ });
119
+ };
120
+ var treeIndentationRepresentation = (index, indentLevel) => {
121
+ if (indentLevel === 0) {
122
+ return (index + 1).toString();
123
+ } else if (indentLevel === 1) {
124
+ return String.fromCharCode(65 + index);
125
+ } else if (indentLevel === 2) {
126
+ return String.fromCharCode(97 + index);
127
+ } else {
128
+ return "-";
129
+ }
130
+ };
131
+ var printNode = (node, prefix = "", indentLevel = 0) => {
132
+ const indent = " ".repeat(3).repeat(indentLevel);
133
+ const prefixPlusIndentLength = prefix.length + indent.length;
134
+ const subsequentLinesPrefix = " ".repeat(prefixPlusIndentLength);
135
+ const valueLines = node.value.split("\n");
136
+ const outputFirstLine = `${indent}${prefix}${valueLines[0]}`;
137
+ const outputSubsequentLines = valueLines.slice(1).map((line) => `${subsequentLinesPrefix}${line}`).join("\n");
138
+ let output = `${outputFirstLine}
139
+ `;
140
+ if (outputSubsequentLines) {
141
+ output += `${outputSubsequentLines}
142
+ `;
143
+ }
144
+ const childPrePrefix = " ".repeat(prefix.length);
145
+ node.children.forEach(
146
+ (child, index) => output += printNode(
147
+ child,
148
+ `${childPrePrefix}${treeIndentationRepresentation(index, indentLevel + 1)}. `,
149
+ indentLevel + 1
150
+ )
151
+ );
152
+ return output;
153
+ };
154
+ function treeReducer(state, action) {
155
+ switch (action.type) {
156
+ case "ADD_NODE": {
157
+ const { value, parentId, id: newNodeId } = action;
158
+ const newNode = {
159
+ id: newNodeId,
160
+ value,
161
+ children: [],
162
+ categories: new Set(action.categories)
163
+ };
164
+ try {
165
+ return addNode(state, newNode, parentId);
166
+ } catch (error) {
167
+ console.error(`Error while adding node with id ${newNodeId}: ${error}`);
168
+ return state;
169
+ }
170
+ }
171
+ case "REMOVE_NODE":
172
+ return removeNode(state, action.id);
173
+ default:
174
+ return state;
175
+ }
176
+ }
177
+ var useTree = () => {
178
+ const [tree, dispatch] = React.useReducer(treeReducer, []);
179
+ const addElement = React.useCallback(
180
+ (value, categories, parentId) => {
181
+ const newNodeId = nanoid.nanoid();
182
+ dispatch({
183
+ type: "ADD_NODE",
184
+ value,
185
+ parentId,
186
+ id: newNodeId,
187
+ categories
188
+ });
189
+ return newNodeId;
190
+ },
191
+ []
192
+ );
193
+ const removeElement = React.useCallback((id) => {
194
+ dispatch({ type: "REMOVE_NODE", id });
195
+ }, []);
196
+ const printTree = React.useCallback(
197
+ (categories) => {
198
+ const categoriesSet = new Set(categories);
199
+ let output = "";
200
+ tree.forEach((node, index) => {
201
+ if (!setsHaveIntersection(categoriesSet, node.categories)) {
202
+ return;
203
+ }
204
+ if (index !== 0) {
205
+ output += "\n";
206
+ }
207
+ output += printNode(node, `${treeIndentationRepresentation(index, 0)}. `);
208
+ });
209
+ return output;
210
+ },
211
+ [tree]
212
+ );
213
+ return { tree, addElement, printTree, removeElement };
214
+ };
215
+ var use_tree_default = useTree;
216
+ function setsHaveIntersection(setA, setB) {
217
+ const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
218
+ for (let item of smallerSet) {
219
+ if (largerSet.has(item)) {
220
+ return true;
221
+ }
222
+ }
223
+ return false;
224
+ }
225
+ var useFlatCategoryStore = () => {
226
+ const [elements, dispatch] = React.useReducer(flatCategoryStoreReducer, /* @__PURE__ */ new Map());
227
+ const addElement = React.useCallback((value, categories) => {
228
+ const newId = nanoid.nanoid();
229
+ dispatch({
230
+ type: "ADD_ELEMENT",
231
+ value,
232
+ id: newId,
233
+ categories
234
+ });
235
+ return newId;
236
+ }, []);
237
+ const removeElement = React.useCallback((id) => {
238
+ dispatch({ type: "REMOVE_ELEMENT", id });
239
+ }, []);
240
+ const allElements = React.useCallback(
241
+ (categories) => {
242
+ const categoriesSet = new Set(categories);
243
+ const result = [];
244
+ elements.forEach((element) => {
245
+ if (setsHaveIntersection2(categoriesSet, element.categories)) {
246
+ result.push(element.value);
247
+ }
248
+ });
249
+ return result;
250
+ },
251
+ [elements]
252
+ );
253
+ return { addElement, removeElement, allElements };
254
+ };
255
+ var use_flat_category_store_default = useFlatCategoryStore;
256
+ function flatCategoryStoreReducer(state, action) {
257
+ switch (action.type) {
258
+ case "ADD_ELEMENT": {
259
+ const { value, id, categories } = action;
260
+ const newElement = {
261
+ id,
262
+ value,
263
+ categories: new Set(categories)
264
+ };
265
+ const newState = new Map(state);
266
+ newState.set(id, newElement);
267
+ return newState;
268
+ }
269
+ case "REMOVE_ELEMENT": {
270
+ const newState = new Map(state);
271
+ newState.delete(action.id);
272
+ return newState;
273
+ }
274
+ default:
275
+ return state;
276
+ }
277
+ }
278
+ function setsHaveIntersection2(setA, setB) {
279
+ const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
280
+ for (let item of smallerSet) {
281
+ if (largerSet.has(item)) {
282
+ return true;
283
+ }
284
+ }
285
+ return false;
286
+ }
287
+
288
+ // src/components/copilot-provider/standard-copilot-api-config.tsx
289
+ var StandardCopilotApiConfig = class {
290
+ constructor(chatApiEndpoint, chatApiEndpointV2, headers, body) {
291
+ this.chatApiEndpoint = chatApiEndpoint;
292
+ this.chatApiEndpointV2 = chatApiEndpointV2;
293
+ this.headers = headers;
294
+ this.body = body;
295
+ }
296
+ };
297
+ function CopilotKit(_a) {
298
+ var _b = _a, { children } = _b, props = __objRest(_b, ["children"]);
299
+ const [entryPoints, setEntryPoints] = React.useState({});
300
+ const { addElement, removeElement, printTree } = use_tree_default();
301
+ const {
302
+ addElement: addDocument,
303
+ removeElement: removeDocument,
304
+ allElements: allDocuments
305
+ } = use_flat_category_store_default();
306
+ const setEntryPoint = React.useCallback((id, entryPoint) => {
307
+ setEntryPoints((prevPoints) => {
308
+ return __spreadProps(__spreadValues({}, prevPoints), {
309
+ [id]: entryPoint
310
+ });
311
+ });
312
+ }, []);
313
+ const removeEntryPoint = React.useCallback((id) => {
314
+ setEntryPoints((prevPoints) => {
315
+ const newPoints = __spreadValues({}, prevPoints);
316
+ delete newPoints[id];
317
+ return newPoints;
318
+ });
319
+ }, []);
320
+ const getContextString = React.useCallback(
321
+ (documents, categories) => {
322
+ const documentsString = documents.map((document) => {
323
+ return `${document.name} (${document.sourceApplication}):
324
+ ${document.getContents()}`;
325
+ }).join("\n\n");
326
+ const nonDocumentStrings = printTree(categories);
327
+ return `${documentsString}
328
+
329
+ ${nonDocumentStrings}`;
330
+ },
331
+ [printTree]
332
+ );
333
+ const addContext = React.useCallback(
334
+ (context, parentId, categories = defaultCopilotContextCategories) => {
335
+ return addElement(context, categories, parentId);
336
+ },
337
+ [addElement]
338
+ );
339
+ const removeContext = React.useCallback(
340
+ (id) => {
341
+ removeElement(id);
342
+ },
343
+ [removeElement]
344
+ );
345
+ const getChatCompletionFunctionDescriptions = React.useCallback(() => {
346
+ return entryPointsToChatCompletionFunctions(Object.values(entryPoints));
347
+ }, [entryPoints]);
348
+ const getFunctionCallHandler = React.useCallback(() => {
349
+ return entryPointsToFunctionCallHandler(Object.values(entryPoints));
350
+ }, [entryPoints]);
351
+ const getDocumentsContext = React.useCallback(
352
+ (categories) => {
353
+ return allDocuments(categories);
354
+ },
355
+ [allDocuments]
356
+ );
357
+ const addDocumentContext = React.useCallback(
358
+ (documentPointer, categories = defaultCopilotContextCategories) => {
359
+ return addDocument(documentPointer, categories);
360
+ },
361
+ [addDocument]
362
+ );
363
+ const removeDocumentContext = React.useCallback(
364
+ (documentId) => {
365
+ removeDocument(documentId);
366
+ },
367
+ [removeDocument]
368
+ );
369
+ const copilotApiConfig = new StandardCopilotApiConfig(
370
+ props.url,
371
+ `${props.url}/v2`,
372
+ props.headers || {},
373
+ props.body || {}
374
+ );
375
+ return /* @__PURE__ */ jsxRuntime.jsx(
376
+ CopilotContext.Provider,
377
+ {
378
+ value: {
379
+ entryPoints,
380
+ getChatCompletionFunctionDescriptions,
381
+ getFunctionCallHandler,
382
+ setEntryPoint,
383
+ removeEntryPoint,
384
+ getContextString,
385
+ addContext,
386
+ removeContext,
387
+ getDocumentsContext,
388
+ addDocumentContext,
389
+ removeDocumentContext,
390
+ copilotApiConfig
391
+ },
392
+ children
393
+ }
394
+ );
395
+ }
396
+ var defaultCopilotContextCategories = ["global"];
397
+ function entryPointsToFunctionCallHandler(entryPoints) {
398
+ return (chatMessages, functionCall) => __async(this, null, function* () {
399
+ let entrypointsByFunctionName = {};
400
+ for (let entryPoint of entryPoints) {
401
+ entrypointsByFunctionName[entryPoint.name] = entryPoint;
402
+ }
403
+ const entryPointFunction = entrypointsByFunctionName[functionCall.name || ""];
404
+ if (entryPointFunction) {
405
+ let functionCallArguments = [];
406
+ if (functionCall.arguments) {
407
+ functionCallArguments = JSON.parse(functionCall.arguments);
408
+ }
409
+ const paramsInCorrectOrder = [];
410
+ for (let arg of entryPointFunction.argumentAnnotations) {
411
+ paramsInCorrectOrder.push(
412
+ functionCallArguments[arg.name]
413
+ );
414
+ }
415
+ yield entryPointFunction.implementation(...paramsInCorrectOrder);
416
+ }
417
+ });
418
+ }
419
+ function entryPointsToChatCompletionFunctions(entryPoints) {
420
+ return entryPoints.map(shared.annotatedFunctionToChatCompletionFunction);
421
+ }
422
+ function fetchChatCompletion(_0) {
423
+ return __async(this, arguments, function* ({
424
+ copilotConfig,
425
+ model,
426
+ messages,
427
+ functions,
428
+ temperature,
429
+ headers,
430
+ body,
431
+ signal
432
+ }) {
433
+ temperature || (temperature = 0.5);
434
+ functions || (functions = []);
435
+ const cleanedMessages = messages.map((message) => {
436
+ const { content, role, name, function_call } = message;
437
+ return { content, role, name, function_call };
438
+ });
439
+ const response = yield fetch(copilotConfig.chatApiEndpoint, {
440
+ method: "POST",
441
+ headers: __spreadValues(__spreadValues({
442
+ "Content-Type": "application/json"
443
+ }, copilotConfig.headers), headers ? __spreadValues({}, headers) : {}),
444
+ body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
445
+ model,
446
+ messages: cleanedMessages,
447
+ stream: true
448
+ }, functions.length ? { functions } : {}), temperature ? { temperature } : {}), functions.length != 0 ? { function_call: "auto" } : {}), copilotConfig.body), body ? __spreadValues({}, body) : {})),
449
+ signal
450
+ });
451
+ return response;
452
+ });
453
+ }
454
+ function fetchAndDecodeChatCompletion(params) {
455
+ return __async(this, null, function* () {
456
+ const response = yield fetchChatCompletion(params);
457
+ if (!response.ok || !response.body) {
458
+ return __spreadProps(__spreadValues({}, response), { events: null });
459
+ }
460
+ const events = yield shared.decodeChatCompletion(shared.parseChatCompletion(response.body));
461
+ return __spreadProps(__spreadValues({}, response), { events });
462
+ });
463
+ }
464
+ function fetchAndDecodeChatCompletionAsText(params) {
465
+ return __async(this, null, function* () {
466
+ const response = yield fetchChatCompletion(params);
467
+ if (!response.ok || !response.body) {
468
+ return __spreadProps(__spreadValues({}, response), { events: null });
469
+ }
470
+ const events = yield shared.decodeChatCompletionAsText(
471
+ shared.decodeChatCompletion(shared.parseChatCompletion(response.body))
472
+ );
473
+ return __spreadProps(__spreadValues({}, response), { events });
474
+ });
475
+ }
476
+
477
+ // src/hooks/use-chat.ts
478
+ function useChat(options) {
479
+ const [messages, setMessages] = React.useState([]);
480
+ const [input, setInput] = React.useState("");
481
+ const [isLoading, setIsLoading] = React.useState(false);
482
+ const abortControllerRef = React.useRef();
483
+ const runChatCompletion = (messages2) => __async(this, null, function* () {
484
+ setIsLoading(true);
485
+ const assistantMessage = {
486
+ id: nanoid.nanoid(),
487
+ createdAt: /* @__PURE__ */ new Date(),
488
+ content: "",
489
+ role: "assistant"
490
+ };
491
+ const abortController = new AbortController();
492
+ abortControllerRef.current = abortController;
493
+ setMessages([...messages2, __spreadValues({}, assistantMessage)]);
494
+ const messagesWithContext = [...options.initialMessages || [], ...messages2];
495
+ const response = yield fetchAndDecodeChatCompletion({
496
+ copilotConfig: options.copilotConfig,
497
+ messages: messagesWithContext,
498
+ functions: options.functions,
499
+ headers: options.headers,
500
+ signal: abortController.signal
501
+ });
502
+ if (!response.events) {
503
+ throw new Error("Failed to fetch chat completion");
504
+ }
505
+ const reader = response.events.getReader();
506
+ while (true) {
507
+ try {
508
+ const { done, value } = yield reader.read();
509
+ if (done) {
510
+ setIsLoading(false);
511
+ return __spreadValues({}, assistantMessage);
512
+ }
513
+ if (value.type === "content") {
514
+ assistantMessage.content += value.content;
515
+ setMessages([...messages2, __spreadValues({}, assistantMessage)]);
516
+ } else if (value.type === "function") {
517
+ assistantMessage.function_call = {
518
+ name: value.name,
519
+ arguments: JSON.stringify(value.arguments)
520
+ };
521
+ setMessages([...messages2, __spreadValues({}, assistantMessage)]);
522
+ setIsLoading(false);
523
+ return __spreadValues({}, assistantMessage);
524
+ }
525
+ } catch (error) {
526
+ setIsLoading(false);
527
+ throw error;
528
+ }
529
+ }
530
+ });
531
+ const runChatCompletionAndHandleFunctionCall = (messages2) => __async(this, null, function* () {
532
+ const message = yield runChatCompletion(messages2);
533
+ if (message.function_call && options.onFunctionCall) {
534
+ yield options.onFunctionCall(messages2, message.function_call);
535
+ }
536
+ });
537
+ const append = (message) => __async(this, null, function* () {
538
+ if (isLoading) {
539
+ return;
540
+ }
541
+ const newMessages = [...messages, message];
542
+ setMessages(newMessages);
543
+ return runChatCompletionAndHandleFunctionCall(newMessages);
544
+ });
545
+ const reload = () => __async(this, null, function* () {
546
+ if (isLoading || messages.length === 0) {
547
+ return;
548
+ }
549
+ let newMessages = [...messages];
550
+ const lastMessage = messages[messages.length - 1];
551
+ if (lastMessage.role === "assistant") {
552
+ newMessages = newMessages.slice(0, -1);
553
+ }
554
+ setMessages(newMessages);
555
+ return runChatCompletionAndHandleFunctionCall(newMessages);
556
+ });
557
+ const stop = () => {
558
+ var _a;
559
+ (_a = abortControllerRef.current) == null ? void 0 : _a.abort();
560
+ };
561
+ return {
562
+ messages,
563
+ append,
564
+ reload,
565
+ stop,
566
+ isLoading,
567
+ input,
568
+ setInput
569
+ };
570
+ }
571
+
572
+ // src/hooks/use-copilot-chat.ts
573
+ function useCopilotChat(_a) {
574
+ var _b = _a, {
575
+ makeSystemMessage,
576
+ additionalInstructions
577
+ } = _b, options = __objRest(_b, [
578
+ "makeSystemMessage",
579
+ "additionalInstructions"
580
+ ]);
581
+ const {
582
+ getContextString,
583
+ getChatCompletionFunctionDescriptions,
584
+ getFunctionCallHandler,
585
+ copilotApiConfig
586
+ } = React.useContext(CopilotContext);
587
+ const systemMessage = React.useMemo(() => {
588
+ const systemMessageMaker = makeSystemMessage || defaultSystemMessage;
589
+ const contextString = getContextString([], defaultCopilotContextCategories);
590
+ return {
591
+ id: "system",
592
+ content: systemMessageMaker(contextString, additionalInstructions),
593
+ role: "system"
594
+ };
595
+ }, [getContextString, makeSystemMessage]);
596
+ const functionDescriptions = React.useMemo(() => {
597
+ return getChatCompletionFunctionDescriptions();
598
+ }, [getChatCompletionFunctionDescriptions]);
599
+ const { messages, append, reload, stop, isLoading, input, setInput } = useChat(__spreadProps(__spreadValues({}, options), {
600
+ copilotConfig: copilotApiConfig,
601
+ id: options.id,
602
+ initialMessages: [systemMessage].concat(options.initialMessages || []),
603
+ functions: functionDescriptions,
604
+ onFunctionCall: getFunctionCallHandler(),
605
+ headers: __spreadValues({}, options.headers),
606
+ body: __spreadValues({}, options.body)
607
+ }));
608
+ const visibleMessages = messages.filter(
609
+ (message) => message.role === "user" || message.role === "assistant"
610
+ );
611
+ return {
612
+ visibleMessages,
613
+ append,
614
+ reload,
615
+ stop,
616
+ isLoading,
617
+ input,
618
+ setInput
619
+ };
620
+ }
621
+ function defaultSystemMessage(contextString, additionalInstructions) {
622
+ return `
623
+ Please act as an efficient, competent, conscientious, and industrious professional assistant.
624
+
625
+ 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.
626
+ Always be polite and respectful, and prefer brevity over verbosity.
627
+
628
+ The user has provided you with the following context:
629
+ \`\`\`
630
+ ${contextString}
631
+ \`\`\`
632
+
633
+ 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.
634
+
635
+ Please assist them as best you can.
636
+
637
+ 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.
638
+
639
+ If you would like to call a function, call it without saying anything else.
640
+ ` + (additionalInstructions ? `
641
+
642
+ ${additionalInstructions}` : "");
643
+ }
644
+ function useMakeCopilotActionable(annotatedFunction, dependencies) {
645
+ const idRef = React.useRef(nanoid.nanoid());
646
+ const { setEntryPoint, removeEntryPoint } = React.useContext(CopilotContext);
647
+ const memoizedAnnotatedFunction = React.useMemo(
648
+ () => ({
649
+ name: annotatedFunction.name,
650
+ description: annotatedFunction.description,
651
+ argumentAnnotations: annotatedFunction.argumentAnnotations,
652
+ implementation: annotatedFunction.implementation
653
+ }),
654
+ dependencies
655
+ );
656
+ React.useEffect(() => {
657
+ setEntryPoint(idRef.current, memoizedAnnotatedFunction);
658
+ return () => {
659
+ removeEntryPoint(idRef.current);
660
+ };
661
+ }, [memoizedAnnotatedFunction, setEntryPoint, removeEntryPoint]);
662
+ }
663
+ function useMakeCopilotReadable(information, parentId, categories) {
664
+ const { addContext, removeContext } = React.useContext(CopilotContext);
665
+ const idRef = React.useRef();
666
+ React.useEffect(() => {
667
+ const id = addContext(information, parentId, categories);
668
+ idRef.current = id;
669
+ return () => {
670
+ removeContext(id);
671
+ };
672
+ }, [information, parentId, addContext, removeContext]);
673
+ return idRef.current;
674
+ }
675
+ function useMakeCopilotDocumentReadable(document, categories, dependencies = []) {
676
+ const { addDocumentContext, removeDocumentContext } = React.useContext(CopilotContext);
677
+ const idRef = React.useRef();
678
+ React.useEffect(() => {
679
+ const id = addDocumentContext(document, categories);
680
+ idRef.current = id;
681
+ return () => {
682
+ removeDocumentContext(id);
683
+ };
684
+ }, [addDocumentContext, removeDocumentContext, ...dependencies]);
685
+ return idRef.current;
686
+ }
687
+
688
+ // src/openai-assistants/utils/process-message-stream.ts
689
+ function processMessageStream(reader, processMessage) {
690
+ return __async(this, null, function* () {
691
+ const decoder = new TextDecoder();
692
+ let buffer = "";
693
+ while (true) {
694
+ const { done, value } = yield reader.read();
695
+ if (done) {
696
+ if (buffer.length > 0) {
697
+ processMessage(buffer);
698
+ }
699
+ break;
700
+ }
701
+ buffer += decoder.decode(value, { stream: true });
702
+ let endIndex;
703
+ while ((endIndex = buffer.indexOf("\n")) !== -1) {
704
+ processMessage(buffer.substring(0, endIndex).trim());
705
+ buffer = buffer.substring(endIndex + 1);
706
+ }
707
+ }
708
+ });
709
+ }
710
+ function useCopilotChatV2(options) {
711
+ const {
712
+ getContextString,
713
+ getChatCompletionFunctionDescriptions,
714
+ getFunctionCallHandler,
715
+ copilotApiConfig
716
+ } = React.useContext(CopilotContext);
717
+ const [messages, setMessages] = React.useState([]);
718
+ const [input, setInput] = React.useState("");
719
+ const [threadId, setThreadId] = React.useState(void 0);
720
+ const [status, setStatus] = React.useState("awaiting_message");
721
+ const [error, setError] = React.useState(void 0);
722
+ React.useMemo(() => {
723
+ const systemMessageMaker = options.makeSystemMessage || defaultSystemMessage2;
724
+ const contextString = getContextString([], defaultCopilotContextCategories);
725
+ return {
726
+ id: "system",
727
+ content: systemMessageMaker(contextString),
728
+ role: "system"
729
+ };
730
+ }, [getContextString, options.makeSystemMessage]);
731
+ const handleInputChange = (e) => {
732
+ setInput(e.target.value);
733
+ };
734
+ const submitMessage = (e) => __async(this, null, function* () {
735
+ var _a, _b;
736
+ e.preventDefault();
737
+ if (input === "") {
738
+ return;
739
+ }
740
+ setStatus("in_progress");
741
+ setMessages((messages2) => [...messages2, { id: "", role: "user", content: input }]);
742
+ setInput("");
743
+ const apiUrl = copilotApiConfig.chatApiEndpointV2;
744
+ const functions = getChatCompletionFunctionDescriptions();
745
+ const result = yield fetch(apiUrl, {
746
+ method: "POST",
747
+ headers: __spreadValues(__spreadValues({
748
+ "Content-Type": "application/json"
749
+ }, copilotApiConfig.headers), options.headers),
750
+ body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues({
751
+ // always use user-provided threadId when available:
752
+ threadId: (_b = (_a = options.threadId) != null ? _a : threadId) != null ? _b : null,
753
+ message: input
754
+ }, functions.length > 0 && { functions }), copilotApiConfig.body), options.body))
755
+ });
756
+ if (result.body == null) {
757
+ throw new Error("The response body is empty.");
758
+ }
759
+ yield processMessageStream(result.body.getReader(), (message) => {
760
+ try {
761
+ const { type, value } = shared.parseStreamPart(message);
762
+ switch (type) {
763
+ case "assistant_message": {
764
+ setMessages((messages2) => [
765
+ ...messages2,
766
+ {
767
+ id: value.id,
768
+ role: value.role,
769
+ content: value.content[0].text.value
770
+ }
771
+ ]);
772
+ break;
773
+ }
774
+ case "assistant_control_data": {
775
+ setThreadId(value.threadId);
776
+ setMessages((messages2) => {
777
+ const lastMessage = messages2[messages2.length - 1];
778
+ lastMessage.id = value.messageId;
779
+ return [...messages2.slice(0, messages2.length - 1), lastMessage];
780
+ });
781
+ break;
782
+ }
783
+ case "error": {
784
+ setError(value);
785
+ break;
786
+ }
787
+ }
788
+ } catch (error2) {
789
+ setError(error2);
790
+ }
791
+ });
792
+ setStatus("awaiting_message");
793
+ });
794
+ return {
795
+ messages,
796
+ input,
797
+ handleInputChange,
798
+ submitMessage,
799
+ status,
800
+ error
801
+ };
802
+ }
803
+ function defaultSystemMessage2(contextString) {
804
+ return `
805
+ Please act as an efficient, competent, conscientious, and industrious professional assistant.
806
+
807
+ 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.
808
+ Always be polite and respectful, and prefer brevity over verbosity.
809
+
810
+ The user has provided you with the following context:
811
+ \`\`\`
812
+ ${contextString}
813
+ \`\`\`
814
+
815
+ 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.
816
+
817
+ Please assist them as best you can.
818
+
819
+ 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.
820
+
821
+ If you would like to call a function, call it without saying anything else.
822
+ `;
823
+ }
824
+
825
+ exports.CopilotContext = CopilotContext;
826
+ exports.CopilotKit = CopilotKit;
827
+ exports.defaultCopilotContextCategories = defaultCopilotContextCategories;
828
+ exports.fetchAndDecodeChatCompletion = fetchAndDecodeChatCompletion;
829
+ exports.fetchAndDecodeChatCompletionAsText = fetchAndDecodeChatCompletionAsText;
830
+ exports.fetchChatCompletion = fetchChatCompletion;
831
+ exports.processMessageStream = processMessageStream;
832
+ exports.useCopilotChat = useCopilotChat;
833
+ exports.useCopilotChatV2 = useCopilotChatV2;
834
+ exports.useMakeCopilotActionable = useMakeCopilotActionable;
835
+ exports.useMakeCopilotDocumentReadable = useMakeCopilotDocumentReadable;
836
+ exports.useMakeCopilotReadable = useMakeCopilotReadable;
837
+ //# sourceMappingURL=out.js.map
838
+ //# sourceMappingURL=index.js.map