@copilotkit/react-core 0.17.0-alpha.4 → 0.17.0-alpha.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +101 -105
- package/CHANGELOG.md +6 -0
- package/dist/components/copilot-provider/copilot-provider-props.mjs +1 -2
- package/dist/components/copilot-provider/copilot-provider-props.mjs.map +1 -1
- package/dist/components/copilot-provider/copilot-provider.mjs +468 -7
- package/dist/components/copilot-provider/copilot-provider.mjs.map +1 -1
- package/dist/components/copilot-provider/index.mjs +467 -8
- package/dist/components/copilot-provider/index.mjs.map +1 -1
- package/dist/components/copilot-provider/standard-copilot-api-config.mjs +12 -3
- package/dist/components/copilot-provider/standard-copilot-api-config.mjs.map +1 -1
- package/dist/components/index.mjs +467 -9
- package/dist/components/index.mjs.map +1 -1
- package/dist/context/copilot-context.mjs +70 -3
- package/dist/context/copilot-context.mjs.map +1 -1
- package/dist/context/index.mjs +69 -4
- package/dist/context/index.mjs.map +1 -1
- package/dist/hooks/index.mjs +646 -17
- package/dist/hooks/index.mjs.map +1 -1
- package/dist/hooks/use-chat.mjs +452 -5
- package/dist/hooks/use-chat.mjs.map +1 -1
- package/dist/hooks/use-copilot-chat.mjs +591 -13
- package/dist/hooks/use-copilot-chat.mjs.map +1 -1
- package/dist/hooks/use-flat-category-store.mjs +68 -3
- package/dist/hooks/use-flat-category-store.mjs.map +1 -1
- package/dist/hooks/use-make-copilot-actionable.mjs +95 -4
- package/dist/hooks/use-make-copilot-actionable.mjs.map +1 -1
- package/dist/hooks/use-make-copilot-document-readable.mjs +87 -4
- package/dist/hooks/use-make-copilot-document-readable.mjs.map +1 -1
- package/dist/hooks/use-make-copilot-readable.mjs +87 -4
- package/dist/hooks/use-make-copilot-readable.mjs.map +1 -1
- package/dist/hooks/use-tree.mjs +153 -3
- package/dist/hooks/use-tree.mjs.map +1 -1
- package/dist/index.mjs +1194 -26
- package/dist/index.mjs.map +1 -1
- package/dist/openai/chat-completion-client.mjs +353 -4
- package/dist/openai/chat-completion-client.mjs.map +1 -1
- package/dist/openai/chat-completion-stream.mjs +217 -4
- package/dist/openai/chat-completion-stream.mjs.map +1 -1
- package/dist/openai/chat-completion-transport.mjs +179 -3
- package/dist/openai/chat-completion-transport.mjs.map +1 -1
- package/dist/openai/index.mjs +217 -5
- package/dist/openai/index.mjs.map +1 -1
- package/dist/openai-assistants/hooks/index.mjs +235 -14
- package/dist/openai-assistants/hooks/index.mjs.map +1 -1
- package/dist/openai-assistants/hooks/use-assistants.mjs +52 -8
- package/dist/openai-assistants/hooks/use-assistants.mjs.map +1 -1
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs +236 -13
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs.map +1 -1
- package/dist/openai-assistants/index.mjs +236 -15
- package/dist/openai-assistants/index.mjs.map +1 -1
- package/dist/openai-assistants/utils/index.mjs +46 -4
- package/dist/openai-assistants/utils/index.mjs.map +1 -1
- package/dist/openai-assistants/utils/process-message-stream.mjs +46 -3
- package/dist/openai-assistants/utils/process-message-stream.mjs.map +1 -1
- package/dist/types/annotated-function.mjs +0 -2
- package/dist/types/annotated-function.mjs.map +1 -1
- package/dist/types/base.mjs +0 -2
- package/dist/types/base.mjs.map +1 -1
- package/dist/types/document-pointer.mjs +0 -2
- package/dist/types/document-pointer.mjs.map +1 -1
- package/dist/types/index.mjs +0 -2
- package/dist/types/index.mjs.map +1 -1
- package/dist/types/message.mjs +0 -2
- package/dist/types/message.mjs.map +1 -1
- package/dist/utils/utils.mjs +0 -2
- package/dist/utils/utils.mjs.map +1 -1
- package/dist/utils/utils.test.mjs +0 -1
- package/dist/utils/utils.test.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-56GURLWX.mjs +0 -165
- package/dist/chunk-56GURLWX.mjs.map +0 -1
- package/dist/chunk-5UGLWBZJ.mjs +0 -3
- package/dist/chunk-5UGLWBZJ.mjs.map +0 -1
- package/dist/chunk-6A4PCNMZ.mjs +0 -48
- package/dist/chunk-6A4PCNMZ.mjs.map +0 -1
- package/dist/chunk-6SOQYBNX.mjs +0 -44
- package/dist/chunk-6SOQYBNX.mjs.map +0 -1
- package/dist/chunk-7GFKOIO7.mjs +0 -3
- package/dist/chunk-7GFKOIO7.mjs.map +0 -1
- package/dist/chunk-7P4OYNP3.mjs +0 -19
- package/dist/chunk-7P4OYNP3.mjs.map +0 -1
- package/dist/chunk-BABVSMJR.mjs +0 -3
- package/dist/chunk-BABVSMJR.mjs.map +0 -1
- package/dist/chunk-EFZPSZWO.mjs +0 -3
- package/dist/chunk-EFZPSZWO.mjs.map +0 -1
- package/dist/chunk-ELXZFAYR.mjs +0 -77
- package/dist/chunk-ELXZFAYR.mjs.map +0 -1
- package/dist/chunk-F2JIAPZQ.mjs +0 -13
- package/dist/chunk-F2JIAPZQ.mjs.map +0 -1
- package/dist/chunk-FP4EXCGS.mjs +0 -27
- package/dist/chunk-FP4EXCGS.mjs.map +0 -1
- package/dist/chunk-FRAKUJWH.mjs +0 -3
- package/dist/chunk-FRAKUJWH.mjs.map +0 -1
- package/dist/chunk-HW5IH6PV.mjs +0 -19
- package/dist/chunk-HW5IH6PV.mjs.map +0 -1
- package/dist/chunk-JD7BAH7U.mjs +0 -3
- package/dist/chunk-JD7BAH7U.mjs.map +0 -1
- package/dist/chunk-LV3MQPZL.mjs +0 -125
- package/dist/chunk-LV3MQPZL.mjs.map +0 -1
- package/dist/chunk-MRXNTQOX.mjs +0 -55
- package/dist/chunk-MRXNTQOX.mjs.map +0 -1
- package/dist/chunk-MZ5UN3BY.mjs +0 -28
- package/dist/chunk-MZ5UN3BY.mjs.map +0 -1
- package/dist/chunk-PUFR5OAI.mjs +0 -3
- package/dist/chunk-PUFR5OAI.mjs.map +0 -1
- package/dist/chunk-SPCZTZCY.mjs +0 -3
- package/dist/chunk-SPCZTZCY.mjs.map +0 -1
- package/dist/chunk-TKXPMMND.mjs +0 -177
- package/dist/chunk-TKXPMMND.mjs.map +0 -1
- package/dist/chunk-VK25FIML.mjs +0 -144
- package/dist/chunk-VK25FIML.mjs.map +0 -1
- package/dist/chunk-VNRDQJXW.mjs +0 -3
- package/dist/chunk-VNRDQJXW.mjs.map +0 -1
- package/dist/chunk-VUY2K2DI.mjs +0 -135
- package/dist/chunk-VUY2K2DI.mjs.map +0 -1
- package/dist/chunk-WMXA2TIX.mjs +0 -102
- package/dist/chunk-WMXA2TIX.mjs.map +0 -1
- package/dist/chunk-YULKJPY3.mjs +0 -70
- package/dist/chunk-YULKJPY3.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,27 +1,1195 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
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/components/copilot-provider/copilot-provider.tsx
|
|
54
|
+
import { useCallback as useCallback3, useState } 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(
|
|
78
|
+
"Remember to wrap your app in a `<CopilotProvider> {...} </CopilotProvider>` !!!"
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
get chatApiEndpointV2() {
|
|
82
|
+
throw new Error(
|
|
83
|
+
"Remember to wrap your app in a `<CopilotProvider> {...} </CopilotProvider>` !!!"
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
get headers() {
|
|
87
|
+
return {};
|
|
88
|
+
}
|
|
89
|
+
get body() {
|
|
90
|
+
return {};
|
|
91
|
+
}
|
|
92
|
+
}()
|
|
93
|
+
};
|
|
94
|
+
var CopilotContext = React.createContext(emptyCopilotContext);
|
|
95
|
+
function returnAndThrowInDebug(value) {
|
|
96
|
+
throw new Error(
|
|
97
|
+
"Remember to wrap your app in a `<CopilotProvider> {...} </CopilotProvider>` !!!"
|
|
98
|
+
);
|
|
99
|
+
return value;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// src/hooks/use-tree.ts
|
|
103
|
+
import { nanoid } from "nanoid";
|
|
104
|
+
import { useCallback, useReducer } from "react";
|
|
105
|
+
var removeNode = (nodes, id) => {
|
|
106
|
+
return nodes.reduce((result, node) => {
|
|
107
|
+
if (node.id !== id) {
|
|
108
|
+
const newNode = __spreadProps(__spreadValues({}, node), { children: removeNode(node.children, id) });
|
|
109
|
+
result.push(newNode);
|
|
110
|
+
}
|
|
111
|
+
return result;
|
|
112
|
+
}, []);
|
|
113
|
+
};
|
|
114
|
+
var addNode = (nodes, newNode, parentId) => {
|
|
115
|
+
if (!parentId) {
|
|
116
|
+
return [...nodes, newNode];
|
|
117
|
+
}
|
|
118
|
+
return nodes.map((node) => {
|
|
119
|
+
if (node.id === parentId) {
|
|
120
|
+
return __spreadProps(__spreadValues({}, node), { children: [...node.children, newNode] });
|
|
121
|
+
} else if (node.children.length) {
|
|
122
|
+
return __spreadProps(__spreadValues({}, node), { children: addNode(node.children, newNode, parentId) });
|
|
123
|
+
}
|
|
124
|
+
return node;
|
|
125
|
+
});
|
|
126
|
+
};
|
|
127
|
+
var treeIndentationRepresentation = (index, indentLevel) => {
|
|
128
|
+
if (indentLevel === 0) {
|
|
129
|
+
return (index + 1).toString();
|
|
130
|
+
} else if (indentLevel === 1) {
|
|
131
|
+
return String.fromCharCode(65 + index);
|
|
132
|
+
} else if (indentLevel === 2) {
|
|
133
|
+
return String.fromCharCode(97 + index);
|
|
134
|
+
} else {
|
|
135
|
+
return "-";
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
var printNode = (node, prefix = "", indentLevel = 0) => {
|
|
139
|
+
const indent = " ".repeat(3).repeat(indentLevel);
|
|
140
|
+
const prefixPlusIndentLength = prefix.length + indent.length;
|
|
141
|
+
const subsequentLinesPrefix = " ".repeat(prefixPlusIndentLength);
|
|
142
|
+
const valueLines = node.value.split("\n");
|
|
143
|
+
const outputFirstLine = `${indent}${prefix}${valueLines[0]}`;
|
|
144
|
+
const outputSubsequentLines = valueLines.slice(1).map((line) => `${subsequentLinesPrefix}${line}`).join("\n");
|
|
145
|
+
let output = `${outputFirstLine}
|
|
146
|
+
`;
|
|
147
|
+
if (outputSubsequentLines) {
|
|
148
|
+
output += `${outputSubsequentLines}
|
|
149
|
+
`;
|
|
150
|
+
}
|
|
151
|
+
const childPrePrefix = " ".repeat(prefix.length);
|
|
152
|
+
node.children.forEach(
|
|
153
|
+
(child, index) => output += printNode(
|
|
154
|
+
child,
|
|
155
|
+
`${childPrePrefix}${treeIndentationRepresentation(index, indentLevel + 1)}. `,
|
|
156
|
+
indentLevel + 1
|
|
157
|
+
)
|
|
158
|
+
);
|
|
159
|
+
return output;
|
|
160
|
+
};
|
|
161
|
+
function treeReducer(state, action) {
|
|
162
|
+
switch (action.type) {
|
|
163
|
+
case "ADD_NODE": {
|
|
164
|
+
const { value, parentId, id: newNodeId } = action;
|
|
165
|
+
const newNode = {
|
|
166
|
+
id: newNodeId,
|
|
167
|
+
value,
|
|
168
|
+
children: [],
|
|
169
|
+
categories: new Set(action.categories)
|
|
170
|
+
};
|
|
171
|
+
try {
|
|
172
|
+
return addNode(state, newNode, parentId);
|
|
173
|
+
} catch (error) {
|
|
174
|
+
console.error(`Error while adding node with id ${newNodeId}: ${error}`);
|
|
175
|
+
return state;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
case "REMOVE_NODE":
|
|
179
|
+
return removeNode(state, action.id);
|
|
180
|
+
default:
|
|
181
|
+
return state;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
var useTree = () => {
|
|
185
|
+
const [tree, dispatch] = useReducer(treeReducer, []);
|
|
186
|
+
const addElement = useCallback(
|
|
187
|
+
(value, categories, parentId) => {
|
|
188
|
+
const newNodeId = nanoid();
|
|
189
|
+
dispatch({
|
|
190
|
+
type: "ADD_NODE",
|
|
191
|
+
value,
|
|
192
|
+
parentId,
|
|
193
|
+
id: newNodeId,
|
|
194
|
+
categories
|
|
195
|
+
});
|
|
196
|
+
return newNodeId;
|
|
197
|
+
},
|
|
198
|
+
[]
|
|
199
|
+
);
|
|
200
|
+
const removeElement = useCallback((id) => {
|
|
201
|
+
dispatch({ type: "REMOVE_NODE", id });
|
|
202
|
+
}, []);
|
|
203
|
+
const printTree = useCallback(
|
|
204
|
+
(categories) => {
|
|
205
|
+
const categoriesSet = new Set(categories);
|
|
206
|
+
let output = "";
|
|
207
|
+
tree.forEach((node, index) => {
|
|
208
|
+
if (!setsHaveIntersection(categoriesSet, node.categories)) {
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
if (index !== 0) {
|
|
212
|
+
output += "\n";
|
|
213
|
+
}
|
|
214
|
+
output += printNode(node, `${treeIndentationRepresentation(index, 0)}. `);
|
|
215
|
+
});
|
|
216
|
+
return output;
|
|
217
|
+
},
|
|
218
|
+
[tree]
|
|
219
|
+
);
|
|
220
|
+
return { tree, addElement, printTree, removeElement };
|
|
221
|
+
};
|
|
222
|
+
var use_tree_default = useTree;
|
|
223
|
+
function setsHaveIntersection(setA, setB) {
|
|
224
|
+
const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
|
|
225
|
+
for (let item of smallerSet) {
|
|
226
|
+
if (largerSet.has(item)) {
|
|
227
|
+
return true;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return false;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// src/hooks/use-flat-category-store.ts
|
|
234
|
+
import { nanoid as nanoid2 } from "nanoid";
|
|
235
|
+
import { useCallback as useCallback2, useReducer as useReducer2 } from "react";
|
|
236
|
+
var useFlatCategoryStore = () => {
|
|
237
|
+
const [elements, dispatch] = useReducer2(flatCategoryStoreReducer, /* @__PURE__ */ new Map());
|
|
238
|
+
const addElement = useCallback2((value, categories) => {
|
|
239
|
+
const newId = nanoid2();
|
|
240
|
+
dispatch({
|
|
241
|
+
type: "ADD_ELEMENT",
|
|
242
|
+
value,
|
|
243
|
+
id: newId,
|
|
244
|
+
categories
|
|
245
|
+
});
|
|
246
|
+
return newId;
|
|
247
|
+
}, []);
|
|
248
|
+
const removeElement = useCallback2((id) => {
|
|
249
|
+
dispatch({ type: "REMOVE_ELEMENT", id });
|
|
250
|
+
}, []);
|
|
251
|
+
const allElements = useCallback2(
|
|
252
|
+
(categories) => {
|
|
253
|
+
const categoriesSet = new Set(categories);
|
|
254
|
+
const result = [];
|
|
255
|
+
elements.forEach((element) => {
|
|
256
|
+
if (setsHaveIntersection2(categoriesSet, element.categories)) {
|
|
257
|
+
result.push(element.value);
|
|
258
|
+
}
|
|
259
|
+
});
|
|
260
|
+
return result;
|
|
261
|
+
},
|
|
262
|
+
[elements]
|
|
263
|
+
);
|
|
264
|
+
return { addElement, removeElement, allElements };
|
|
265
|
+
};
|
|
266
|
+
var use_flat_category_store_default = useFlatCategoryStore;
|
|
267
|
+
function flatCategoryStoreReducer(state, action) {
|
|
268
|
+
switch (action.type) {
|
|
269
|
+
case "ADD_ELEMENT": {
|
|
270
|
+
const { value, id, categories } = action;
|
|
271
|
+
const newElement = {
|
|
272
|
+
id,
|
|
273
|
+
value,
|
|
274
|
+
categories: new Set(categories)
|
|
275
|
+
};
|
|
276
|
+
const newState = new Map(state);
|
|
277
|
+
newState.set(id, newElement);
|
|
278
|
+
return newState;
|
|
279
|
+
}
|
|
280
|
+
case "REMOVE_ELEMENT": {
|
|
281
|
+
const newState = new Map(state);
|
|
282
|
+
newState.delete(action.id);
|
|
283
|
+
return newState;
|
|
284
|
+
}
|
|
285
|
+
default:
|
|
286
|
+
return state;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
function setsHaveIntersection2(setA, setB) {
|
|
290
|
+
const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
|
|
291
|
+
for (let item of smallerSet) {
|
|
292
|
+
if (largerSet.has(item)) {
|
|
293
|
+
return true;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return false;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// src/components/copilot-provider/standard-copilot-api-config.tsx
|
|
300
|
+
var StandardCopilotApiConfig = class {
|
|
301
|
+
constructor(chatApiEndpoint, chatApiEndpointV2, headers, body) {
|
|
302
|
+
this.chatApiEndpoint = chatApiEndpoint;
|
|
303
|
+
this.chatApiEndpointV2 = chatApiEndpointV2;
|
|
304
|
+
this.headers = headers;
|
|
305
|
+
this.body = body;
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
// src/components/copilot-provider/copilot-provider.tsx
|
|
310
|
+
import { jsx } from "react/jsx-runtime";
|
|
311
|
+
function CopilotProvider(_a) {
|
|
312
|
+
var _b = _a, { children } = _b, props = __objRest(_b, ["children"]);
|
|
313
|
+
const [entryPoints, setEntryPoints] = useState({});
|
|
314
|
+
const { addElement, removeElement, printTree } = use_tree_default();
|
|
315
|
+
const {
|
|
316
|
+
addElement: addDocument,
|
|
317
|
+
removeElement: removeDocument,
|
|
318
|
+
allElements: allDocuments
|
|
319
|
+
} = use_flat_category_store_default();
|
|
320
|
+
const setEntryPoint = useCallback3((id, entryPoint) => {
|
|
321
|
+
setEntryPoints((prevPoints) => {
|
|
322
|
+
return __spreadProps(__spreadValues({}, prevPoints), {
|
|
323
|
+
[id]: entryPoint
|
|
324
|
+
});
|
|
325
|
+
});
|
|
326
|
+
}, []);
|
|
327
|
+
const removeEntryPoint = useCallback3((id) => {
|
|
328
|
+
setEntryPoints((prevPoints) => {
|
|
329
|
+
const newPoints = __spreadValues({}, prevPoints);
|
|
330
|
+
delete newPoints[id];
|
|
331
|
+
return newPoints;
|
|
332
|
+
});
|
|
333
|
+
}, []);
|
|
334
|
+
const getContextString = useCallback3(
|
|
335
|
+
(documents, categories) => {
|
|
336
|
+
const documentsString = documents.map((document) => {
|
|
337
|
+
return `${document.name} (${document.sourceApplication}):
|
|
338
|
+
${document.getContents()}`;
|
|
339
|
+
}).join("\n\n");
|
|
340
|
+
const nonDocumentStrings = printTree(categories);
|
|
341
|
+
return `${documentsString}
|
|
342
|
+
|
|
343
|
+
${nonDocumentStrings}`;
|
|
344
|
+
},
|
|
345
|
+
[printTree]
|
|
346
|
+
);
|
|
347
|
+
const addContext = useCallback3(
|
|
348
|
+
(context, parentId, categories = defaultCopilotContextCategories) => {
|
|
349
|
+
return addElement(context, categories, parentId);
|
|
350
|
+
},
|
|
351
|
+
[addElement]
|
|
352
|
+
);
|
|
353
|
+
const removeContext = useCallback3(
|
|
354
|
+
(id) => {
|
|
355
|
+
removeElement(id);
|
|
356
|
+
},
|
|
357
|
+
[removeElement]
|
|
358
|
+
);
|
|
359
|
+
const getChatCompletionFunctionDescriptions = useCallback3(() => {
|
|
360
|
+
return entryPointsToChatCompletionFunctions(Object.values(entryPoints));
|
|
361
|
+
}, [entryPoints]);
|
|
362
|
+
const getFunctionCallHandler = useCallback3(() => {
|
|
363
|
+
return entryPointsToFunctionCallHandler(Object.values(entryPoints));
|
|
364
|
+
}, [entryPoints]);
|
|
365
|
+
const getDocumentsContext = useCallback3(
|
|
366
|
+
(categories) => {
|
|
367
|
+
return allDocuments(categories);
|
|
368
|
+
},
|
|
369
|
+
[allDocuments]
|
|
370
|
+
);
|
|
371
|
+
const addDocumentContext = useCallback3(
|
|
372
|
+
(documentPointer, categories = defaultCopilotContextCategories) => {
|
|
373
|
+
return addDocument(documentPointer, categories);
|
|
374
|
+
},
|
|
375
|
+
[addDocument]
|
|
376
|
+
);
|
|
377
|
+
const removeDocumentContext = useCallback3(
|
|
378
|
+
(documentId) => {
|
|
379
|
+
removeDocument(documentId);
|
|
380
|
+
},
|
|
381
|
+
[removeDocument]
|
|
382
|
+
);
|
|
383
|
+
let copilotApiConfig;
|
|
384
|
+
if ("chatApiEndpoint" in props) {
|
|
385
|
+
copilotApiConfig = new StandardCopilotApiConfig(
|
|
386
|
+
props.chatApiEndpoint,
|
|
387
|
+
props.chatApiEndpointV2 || `${props.chatApiEndpoint}/v2`,
|
|
388
|
+
{},
|
|
389
|
+
{}
|
|
390
|
+
);
|
|
391
|
+
} else {
|
|
392
|
+
copilotApiConfig = props.chatApiConfig;
|
|
393
|
+
}
|
|
394
|
+
return /* @__PURE__ */ jsx(
|
|
395
|
+
CopilotContext.Provider,
|
|
396
|
+
{
|
|
397
|
+
value: {
|
|
398
|
+
entryPoints,
|
|
399
|
+
getChatCompletionFunctionDescriptions,
|
|
400
|
+
getFunctionCallHandler,
|
|
401
|
+
setEntryPoint,
|
|
402
|
+
removeEntryPoint,
|
|
403
|
+
getContextString,
|
|
404
|
+
addContext,
|
|
405
|
+
removeContext,
|
|
406
|
+
getDocumentsContext,
|
|
407
|
+
addDocumentContext,
|
|
408
|
+
removeDocumentContext,
|
|
409
|
+
copilotApiConfig
|
|
410
|
+
},
|
|
411
|
+
children
|
|
412
|
+
}
|
|
413
|
+
);
|
|
414
|
+
}
|
|
415
|
+
var defaultCopilotContextCategories = ["global"];
|
|
416
|
+
function entryPointsToFunctionCallHandler(entryPoints) {
|
|
417
|
+
return (chatMessages, functionCall) => __async(this, null, function* () {
|
|
418
|
+
let entrypointsByFunctionName = {};
|
|
419
|
+
for (let entryPoint of entryPoints) {
|
|
420
|
+
entrypointsByFunctionName[entryPoint.name] = entryPoint;
|
|
421
|
+
}
|
|
422
|
+
const entryPointFunction = entrypointsByFunctionName[functionCall.name || ""];
|
|
423
|
+
if (entryPointFunction) {
|
|
424
|
+
let functionCallArguments = [];
|
|
425
|
+
if (functionCall.arguments) {
|
|
426
|
+
functionCallArguments = JSON.parse(functionCall.arguments);
|
|
427
|
+
}
|
|
428
|
+
const paramsInCorrectOrder = [];
|
|
429
|
+
for (let arg of entryPointFunction.argumentAnnotations) {
|
|
430
|
+
paramsInCorrectOrder.push(
|
|
431
|
+
functionCallArguments[arg.name]
|
|
432
|
+
);
|
|
433
|
+
}
|
|
434
|
+
yield entryPointFunction.implementation(...paramsInCorrectOrder);
|
|
435
|
+
}
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
function entryPointsToChatCompletionFunctions(entryPoints) {
|
|
439
|
+
return entryPoints.map(annotatedFunctionToChatCompletionFunction);
|
|
440
|
+
}
|
|
441
|
+
function annotatedFunctionToChatCompletionFunction(annotatedFunction) {
|
|
442
|
+
let parameters = {};
|
|
443
|
+
for (let arg of annotatedFunction.argumentAnnotations) {
|
|
444
|
+
let _a = arg, { name, required } = _a, forwardedArgs = __objRest(_a, ["name", "required"]);
|
|
445
|
+
parameters[arg.name] = forwardedArgs;
|
|
446
|
+
}
|
|
447
|
+
let requiredParameterNames = [];
|
|
448
|
+
for (let arg of annotatedFunction.argumentAnnotations) {
|
|
449
|
+
if (arg.required) {
|
|
450
|
+
requiredParameterNames.push(arg.name);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
let chatCompletionFunction = {
|
|
454
|
+
name: annotatedFunction.name,
|
|
455
|
+
description: annotatedFunction.description,
|
|
456
|
+
parameters: {
|
|
457
|
+
type: "object",
|
|
458
|
+
properties: parameters,
|
|
459
|
+
required: requiredParameterNames
|
|
460
|
+
}
|
|
461
|
+
};
|
|
462
|
+
return chatCompletionFunction;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// src/hooks/use-copilot-chat.ts
|
|
466
|
+
import { useMemo, useContext } from "react";
|
|
467
|
+
|
|
468
|
+
// src/hooks/use-chat.ts
|
|
469
|
+
import { useState as useState2 } from "react";
|
|
470
|
+
import { nanoid as nanoid3 } from "nanoid";
|
|
471
|
+
|
|
472
|
+
// src/openai/chat-completion-client.ts
|
|
473
|
+
import EventEmitter2 from "eventemitter3";
|
|
474
|
+
|
|
475
|
+
// src/openai/chat-completion-transport.ts
|
|
476
|
+
import EventEmitter from "eventemitter3";
|
|
477
|
+
var DEFAULT_MODEL = "gpt-4-1106-preview";
|
|
478
|
+
var ChatCompletionTransport = class extends EventEmitter {
|
|
479
|
+
constructor(params) {
|
|
480
|
+
super();
|
|
481
|
+
this.buffer = new Uint8Array();
|
|
482
|
+
this.bodyReader = null;
|
|
483
|
+
}
|
|
484
|
+
cleanup() {
|
|
485
|
+
return __async(this, null, function* () {
|
|
486
|
+
if (this.bodyReader) {
|
|
487
|
+
try {
|
|
488
|
+
yield this.bodyReader.cancel();
|
|
489
|
+
} catch (error) {
|
|
490
|
+
console.warn("Failed to cancel body reader:", error);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
this.bodyReader = null;
|
|
494
|
+
this.buffer = new Uint8Array();
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
fetch(_0) {
|
|
498
|
+
return __async(this, arguments, function* ({
|
|
499
|
+
copilotConfig,
|
|
500
|
+
model,
|
|
501
|
+
messages,
|
|
502
|
+
functions,
|
|
503
|
+
temperature,
|
|
504
|
+
headers,
|
|
505
|
+
body,
|
|
506
|
+
signal
|
|
507
|
+
}) {
|
|
508
|
+
yield this.cleanup();
|
|
509
|
+
temperature || (temperature = 0.5);
|
|
510
|
+
functions || (functions = []);
|
|
511
|
+
model || (model = DEFAULT_MODEL);
|
|
512
|
+
const cleanedMessages = messages.map((message) => {
|
|
513
|
+
const { content, role, name, function_call } = message;
|
|
514
|
+
return { content, role, name, function_call };
|
|
515
|
+
});
|
|
516
|
+
try {
|
|
517
|
+
const response = yield fetch(copilotConfig.chatApiEndpoint, {
|
|
518
|
+
method: "POST",
|
|
519
|
+
headers: __spreadValues(__spreadValues({
|
|
520
|
+
"Content-Type": "application/json"
|
|
521
|
+
}, copilotConfig.headers), headers ? __spreadValues({}, headers) : {}),
|
|
522
|
+
body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
|
|
523
|
+
model,
|
|
524
|
+
messages: cleanedMessages,
|
|
525
|
+
stream: true
|
|
526
|
+
}, functions.length ? { functions } : {}), temperature ? { temperature } : {}), functions.length != 0 ? { function_call: "auto" } : {}), copilotConfig.body), body ? __spreadValues({}, body) : {})),
|
|
527
|
+
signal
|
|
528
|
+
});
|
|
529
|
+
if (!response.ok) {
|
|
530
|
+
try {
|
|
531
|
+
const errorText = yield response.text();
|
|
532
|
+
yield this.cleanup();
|
|
533
|
+
const msg = `Error ${response.status}: ${errorText}`;
|
|
534
|
+
this.emit("error", new Error(msg));
|
|
535
|
+
} catch (_error) {
|
|
536
|
+
yield this.cleanup();
|
|
537
|
+
const msg = `Error ${response.status}: ${response.statusText}`;
|
|
538
|
+
this.emit("error", new Error(msg));
|
|
539
|
+
}
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
if (response.body == null) {
|
|
543
|
+
yield this.cleanup();
|
|
544
|
+
const msg = "Response body is null";
|
|
545
|
+
this.emit("error", new Error(msg));
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
this.bodyReader = response.body.getReader();
|
|
549
|
+
yield this.streamBody();
|
|
550
|
+
} catch (error) {
|
|
551
|
+
yield this.cleanup();
|
|
552
|
+
this.emit("error", error);
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
streamBody() {
|
|
558
|
+
return __async(this, null, function* () {
|
|
559
|
+
while (true) {
|
|
560
|
+
try {
|
|
561
|
+
const { done, value } = yield this.bodyReader.read();
|
|
562
|
+
if (done) {
|
|
563
|
+
yield this.cleanup();
|
|
564
|
+
this.emit("end");
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
567
|
+
const shouldContinue = yield this.processData(value);
|
|
568
|
+
if (!shouldContinue) {
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
} catch (error) {
|
|
572
|
+
yield this.cleanup();
|
|
573
|
+
this.emit("error", error);
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
processData(data) {
|
|
580
|
+
return __async(this, null, function* () {
|
|
581
|
+
const newBuffer = new Uint8Array(this.buffer.length + data.length);
|
|
582
|
+
newBuffer.set(this.buffer);
|
|
583
|
+
newBuffer.set(data, this.buffer.length);
|
|
584
|
+
this.buffer = newBuffer;
|
|
585
|
+
const dataString = new TextDecoder("utf-8").decode(this.buffer);
|
|
586
|
+
let lines = dataString.split("\n").filter((line) => line.trim() !== "");
|
|
587
|
+
if (!dataString.endsWith("\n")) {
|
|
588
|
+
const lastLine = lines.pop() || "";
|
|
589
|
+
const remainingBytes = new TextEncoder().encode(lastLine);
|
|
590
|
+
this.buffer = new Uint8Array(remainingBytes);
|
|
591
|
+
} else {
|
|
592
|
+
this.buffer = new Uint8Array();
|
|
593
|
+
}
|
|
594
|
+
for (const line of lines) {
|
|
595
|
+
const cleanedLine = line.replace(/^data: /, "");
|
|
596
|
+
if (cleanedLine === "[DONE]") {
|
|
597
|
+
yield this.cleanup();
|
|
598
|
+
this.emit("end");
|
|
599
|
+
return false;
|
|
600
|
+
}
|
|
601
|
+
let json;
|
|
602
|
+
try {
|
|
603
|
+
json = JSON.parse(cleanedLine);
|
|
604
|
+
} catch (error) {
|
|
605
|
+
console.error("Failed to parse JSON:", error);
|
|
606
|
+
continue;
|
|
607
|
+
}
|
|
608
|
+
this.emit("data", json);
|
|
609
|
+
}
|
|
610
|
+
return true;
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
};
|
|
614
|
+
|
|
615
|
+
// src/openai/chat-completion-client.ts
|
|
616
|
+
var DEFAULT_MAX_TOKENS = 8192;
|
|
617
|
+
var ChatCompletionClient = class extends EventEmitter2 {
|
|
618
|
+
constructor(params) {
|
|
619
|
+
super();
|
|
620
|
+
this.chatCompletionTransport = null;
|
|
621
|
+
this.mode = null;
|
|
622
|
+
this.functionCallName = "";
|
|
623
|
+
this.functionCallArguments = "";
|
|
624
|
+
this.onData = (data) => {
|
|
625
|
+
if (this.mode === "function" && !data.choices[0].delta.function_call) {
|
|
626
|
+
const success = this.tryFlushFunctionCall();
|
|
627
|
+
if (!success) {
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
this.mode = data.choices[0].delta.function_call ? "function" : "message";
|
|
632
|
+
if (this.mode === "message") {
|
|
633
|
+
if (data.choices[0].delta.content) {
|
|
634
|
+
this.emit("content", data.choices[0].delta.content);
|
|
635
|
+
}
|
|
636
|
+
return;
|
|
637
|
+
} else if (this.mode === "function") {
|
|
638
|
+
if (data.choices[0].delta.function_call.name) {
|
|
639
|
+
this.functionCallName = data.choices[0].delta.function_call.name;
|
|
640
|
+
}
|
|
641
|
+
if (data.choices[0].delta.function_call.arguments) {
|
|
642
|
+
this.functionCallArguments += data.choices[0].delta.function_call.arguments;
|
|
643
|
+
}
|
|
644
|
+
this.emit("partial", this.functionCallName, this.functionCallArguments);
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
};
|
|
648
|
+
this.onError = (error) => {
|
|
649
|
+
this.emit("error", error);
|
|
650
|
+
this.cleanup();
|
|
651
|
+
};
|
|
652
|
+
this.onEnd = () => {
|
|
653
|
+
if (this.mode === "function") {
|
|
654
|
+
const success = this.tryFlushFunctionCall();
|
|
655
|
+
if (!success) {
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
this.emit("end");
|
|
660
|
+
this.cleanup();
|
|
661
|
+
};
|
|
662
|
+
}
|
|
663
|
+
fetch(params) {
|
|
664
|
+
return __async(this, null, function* () {
|
|
665
|
+
params = __spreadValues({}, params);
|
|
666
|
+
if (params.model && params.model in maxTokensByModel) {
|
|
667
|
+
params.maxTokens || (params.maxTokens = maxTokensByModel[params.model]);
|
|
668
|
+
} else {
|
|
669
|
+
params.maxTokens || (params.maxTokens = DEFAULT_MAX_TOKENS);
|
|
670
|
+
}
|
|
671
|
+
params.functions || (params.functions = []);
|
|
672
|
+
params.messages = this.buildPrompt(params);
|
|
673
|
+
return yield this.runPrompt(params);
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
buildPrompt(params) {
|
|
677
|
+
let maxTokens = params.maxTokens;
|
|
678
|
+
const messages = params.messages;
|
|
679
|
+
const functions = params.functions;
|
|
680
|
+
const functionsNumTokens = countFunctionsTokens(functions);
|
|
681
|
+
if (functionsNumTokens > maxTokens) {
|
|
682
|
+
throw new Error(`Too many tokens in function calls: ${functionsNumTokens} > ${maxTokens}`);
|
|
683
|
+
}
|
|
684
|
+
maxTokens -= functionsNumTokens;
|
|
685
|
+
for (const message of messages) {
|
|
686
|
+
if (message.role === "system") {
|
|
687
|
+
const numTokens = this.countTokens(message);
|
|
688
|
+
maxTokens -= numTokens;
|
|
689
|
+
if (maxTokens < 0) {
|
|
690
|
+
throw new Error("Not enough tokens for system message.");
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
const result = [];
|
|
695
|
+
let cutoff = false;
|
|
696
|
+
const reversedMessages = [...messages].reverse();
|
|
697
|
+
for (const message of reversedMessages) {
|
|
698
|
+
if (message.role === "system") {
|
|
699
|
+
result.unshift(message);
|
|
700
|
+
continue;
|
|
701
|
+
} else if (cutoff) {
|
|
702
|
+
continue;
|
|
703
|
+
}
|
|
704
|
+
let numTokens = this.countTokens(message);
|
|
705
|
+
if (maxTokens < numTokens) {
|
|
706
|
+
cutoff = true;
|
|
707
|
+
continue;
|
|
708
|
+
}
|
|
709
|
+
result.unshift(message);
|
|
710
|
+
maxTokens -= numTokens;
|
|
711
|
+
}
|
|
712
|
+
return result;
|
|
713
|
+
}
|
|
714
|
+
runPrompt(params) {
|
|
715
|
+
return __async(this, null, function* () {
|
|
716
|
+
this.chatCompletionTransport = new ChatCompletionTransport({});
|
|
717
|
+
this.chatCompletionTransport.on("data", this.onData);
|
|
718
|
+
this.chatCompletionTransport.on("error", this.onError);
|
|
719
|
+
this.chatCompletionTransport.on("end", this.onEnd);
|
|
720
|
+
yield this.chatCompletionTransport.fetch(params);
|
|
721
|
+
});
|
|
722
|
+
}
|
|
723
|
+
tryFlushFunctionCall() {
|
|
724
|
+
let args = null;
|
|
725
|
+
try {
|
|
726
|
+
args = JSON.parse(this.functionCallArguments);
|
|
727
|
+
} catch (error) {
|
|
728
|
+
this.emit("error", error);
|
|
729
|
+
this.cleanup();
|
|
730
|
+
return false;
|
|
731
|
+
}
|
|
732
|
+
this.emit("function", {
|
|
733
|
+
name: this.functionCallName,
|
|
734
|
+
arguments: args
|
|
735
|
+
});
|
|
736
|
+
this.mode = null;
|
|
737
|
+
this.functionCallName = "";
|
|
738
|
+
this.functionCallArguments = "";
|
|
739
|
+
return true;
|
|
740
|
+
}
|
|
741
|
+
cleanup() {
|
|
742
|
+
if (this.chatCompletionTransport) {
|
|
743
|
+
this.chatCompletionTransport.off("data", this.onData);
|
|
744
|
+
this.chatCompletionTransport.off("error", this.onError);
|
|
745
|
+
this.chatCompletionTransport.off("end", this.onEnd);
|
|
746
|
+
}
|
|
747
|
+
this.chatCompletionTransport = null;
|
|
748
|
+
this.mode = null;
|
|
749
|
+
this.functionCallName = "";
|
|
750
|
+
this.functionCallArguments = "";
|
|
751
|
+
}
|
|
752
|
+
countTokens(message) {
|
|
753
|
+
if (message.content) {
|
|
754
|
+
return estimateTokens(message.content);
|
|
755
|
+
} else if (message.function_call) {
|
|
756
|
+
return estimateTokens(JSON.stringify(message.function_call));
|
|
757
|
+
}
|
|
758
|
+
return 0;
|
|
759
|
+
}
|
|
760
|
+
};
|
|
761
|
+
var maxTokensByModel = {
|
|
762
|
+
"gpt-3.5-turbo": 4097,
|
|
763
|
+
"gpt-3.5-turbo-16k": 16385,
|
|
764
|
+
"gpt-4": 8192,
|
|
765
|
+
"gpt-4-1106-preview": 8192,
|
|
766
|
+
"gpt-4-32k": 32768,
|
|
767
|
+
"gpt-3.5-turbo-0301": 4097,
|
|
768
|
+
"gpt-4-0314": 8192,
|
|
769
|
+
"gpt-4-32k-0314": 32768,
|
|
770
|
+
"gpt-3.5-turbo-0613": 4097,
|
|
771
|
+
"gpt-4-0613": 8192,
|
|
772
|
+
"gpt-4-32k-0613": 32768,
|
|
773
|
+
"gpt-3.5-turbo-16k-0613": 16385
|
|
774
|
+
};
|
|
775
|
+
function estimateTokens(text) {
|
|
776
|
+
return text.length / 3;
|
|
777
|
+
}
|
|
778
|
+
function countFunctionsTokens(functions) {
|
|
779
|
+
if (functions.length === 0) {
|
|
780
|
+
return 0;
|
|
781
|
+
}
|
|
782
|
+
const json = JSON.stringify(functions);
|
|
783
|
+
return estimateTokens(json);
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
// src/hooks/use-chat.ts
|
|
787
|
+
function useChat(options) {
|
|
788
|
+
const [messages, setMessages] = useState2([]);
|
|
789
|
+
const [input, setInput] = useState2("");
|
|
790
|
+
const [isLoading, setIsLoading] = useState2(false);
|
|
791
|
+
const runChatCompletion = (messages2) => __async(this, null, function* () {
|
|
792
|
+
return new Promise((resolve, reject) => {
|
|
793
|
+
setIsLoading(true);
|
|
794
|
+
const assistantMessage = {
|
|
795
|
+
id: nanoid3(),
|
|
796
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
797
|
+
content: "",
|
|
798
|
+
role: "assistant"
|
|
799
|
+
};
|
|
800
|
+
setMessages([...messages2, __spreadValues({}, assistantMessage)]);
|
|
801
|
+
const messagesWithContext = [...options.initialMessages || [], ...messages2];
|
|
802
|
+
const client = new ChatCompletionClient({});
|
|
803
|
+
const cleanup = () => {
|
|
804
|
+
client.off("content");
|
|
805
|
+
client.off("end");
|
|
806
|
+
client.off("error");
|
|
807
|
+
client.off("function");
|
|
808
|
+
};
|
|
809
|
+
client.on("content", (content) => {
|
|
810
|
+
assistantMessage.content += content;
|
|
811
|
+
setMessages([...messages2, __spreadValues({}, assistantMessage)]);
|
|
812
|
+
});
|
|
813
|
+
client.on("end", () => {
|
|
814
|
+
setIsLoading(false);
|
|
815
|
+
cleanup();
|
|
816
|
+
resolve(__spreadValues({}, assistantMessage));
|
|
817
|
+
});
|
|
818
|
+
client.on("error", (error) => {
|
|
819
|
+
setIsLoading(false);
|
|
820
|
+
cleanup();
|
|
821
|
+
reject(error);
|
|
822
|
+
});
|
|
823
|
+
client.on("function", (functionCall) => __async(this, null, function* () {
|
|
824
|
+
assistantMessage.function_call = {
|
|
825
|
+
name: functionCall.name,
|
|
826
|
+
arguments: JSON.stringify(functionCall.arguments)
|
|
827
|
+
};
|
|
828
|
+
setMessages([...messages2, __spreadValues({}, assistantMessage)]);
|
|
829
|
+
setIsLoading(false);
|
|
830
|
+
cleanup();
|
|
831
|
+
resolve(__spreadValues({}, assistantMessage));
|
|
832
|
+
}));
|
|
833
|
+
client.fetch({
|
|
834
|
+
copilotConfig: options.copilotConfig,
|
|
835
|
+
messages: messagesWithContext,
|
|
836
|
+
functions: options.functions,
|
|
837
|
+
headers: options.headers
|
|
838
|
+
});
|
|
839
|
+
});
|
|
840
|
+
});
|
|
841
|
+
const runChatCompletionAndHandleFunctionCall = (messages2) => __async(this, null, function* () {
|
|
842
|
+
const message = yield runChatCompletion(messages2);
|
|
843
|
+
if (message.function_call && options.onFunctionCall) {
|
|
844
|
+
yield options.onFunctionCall(messages2, message.function_call);
|
|
845
|
+
}
|
|
846
|
+
});
|
|
847
|
+
const append = (message) => __async(this, null, function* () {
|
|
848
|
+
if (isLoading) {
|
|
849
|
+
return;
|
|
850
|
+
}
|
|
851
|
+
const newMessages = [...messages, message];
|
|
852
|
+
setMessages(newMessages);
|
|
853
|
+
return runChatCompletionAndHandleFunctionCall(newMessages);
|
|
854
|
+
});
|
|
855
|
+
const reload = () => __async(this, null, function* () {
|
|
856
|
+
if (isLoading || messages.length === 0) {
|
|
857
|
+
return;
|
|
858
|
+
}
|
|
859
|
+
let newMessages = [...messages];
|
|
860
|
+
const lastMessage = messages[messages.length - 1];
|
|
861
|
+
if (lastMessage.role === "assistant") {
|
|
862
|
+
newMessages = newMessages.slice(0, -1);
|
|
863
|
+
}
|
|
864
|
+
setMessages(newMessages);
|
|
865
|
+
return runChatCompletionAndHandleFunctionCall(newMessages);
|
|
866
|
+
});
|
|
867
|
+
const stop = () => {
|
|
868
|
+
throw new Error("Not implemented");
|
|
869
|
+
};
|
|
870
|
+
return {
|
|
871
|
+
messages,
|
|
872
|
+
append,
|
|
873
|
+
reload,
|
|
874
|
+
stop,
|
|
875
|
+
isLoading,
|
|
876
|
+
input,
|
|
877
|
+
setInput
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
// src/hooks/use-copilot-chat.ts
|
|
882
|
+
function useCopilotChat(_a) {
|
|
883
|
+
var _b = _a, {
|
|
884
|
+
makeSystemMessage
|
|
885
|
+
} = _b, options = __objRest(_b, [
|
|
886
|
+
"makeSystemMessage"
|
|
887
|
+
]);
|
|
888
|
+
const {
|
|
889
|
+
getContextString,
|
|
890
|
+
getChatCompletionFunctionDescriptions,
|
|
891
|
+
getFunctionCallHandler,
|
|
892
|
+
copilotApiConfig
|
|
893
|
+
} = useContext(CopilotContext);
|
|
894
|
+
const systemMessage = useMemo(() => {
|
|
895
|
+
const systemMessageMaker = makeSystemMessage || defaultSystemMessage;
|
|
896
|
+
const contextString = getContextString([], defaultCopilotContextCategories);
|
|
897
|
+
return {
|
|
898
|
+
id: "system",
|
|
899
|
+
content: systemMessageMaker(contextString),
|
|
900
|
+
role: "system"
|
|
901
|
+
};
|
|
902
|
+
}, [getContextString, makeSystemMessage]);
|
|
903
|
+
const functionDescriptions = useMemo(() => {
|
|
904
|
+
return getChatCompletionFunctionDescriptions();
|
|
905
|
+
}, [getChatCompletionFunctionDescriptions]);
|
|
906
|
+
const { messages, append, reload, stop, isLoading, input, setInput } = useChat(__spreadProps(__spreadValues({}, options), {
|
|
907
|
+
copilotConfig: copilotApiConfig,
|
|
908
|
+
id: options.id,
|
|
909
|
+
initialMessages: [systemMessage].concat(options.initialMessages || []),
|
|
910
|
+
functions: functionDescriptions,
|
|
911
|
+
onFunctionCall: getFunctionCallHandler(),
|
|
912
|
+
headers: __spreadValues({}, options.headers),
|
|
913
|
+
body: __spreadValues({}, options.body)
|
|
914
|
+
}));
|
|
915
|
+
const visibleMessages = messages.filter(
|
|
916
|
+
(message) => message.role === "user" || message.role === "assistant"
|
|
917
|
+
);
|
|
918
|
+
return {
|
|
919
|
+
visibleMessages,
|
|
920
|
+
append,
|
|
921
|
+
reload,
|
|
922
|
+
stop,
|
|
923
|
+
isLoading,
|
|
924
|
+
input,
|
|
925
|
+
setInput
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
function defaultSystemMessage(contextString) {
|
|
929
|
+
return `
|
|
930
|
+
Please act as an efficient, competent, conscientious, and industrious professional assistant.
|
|
931
|
+
|
|
932
|
+
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.
|
|
933
|
+
Always be polite and respectful, and prefer brevity over verbosity.
|
|
934
|
+
|
|
935
|
+
The user has provided you with the following context:
|
|
936
|
+
\`\`\`
|
|
937
|
+
${contextString}
|
|
938
|
+
\`\`\`
|
|
939
|
+
|
|
940
|
+
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.
|
|
941
|
+
|
|
942
|
+
Please assist them as best you can.
|
|
943
|
+
|
|
944
|
+
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.
|
|
945
|
+
|
|
946
|
+
If you would like to call a function, call it without saying anything else.
|
|
947
|
+
`;
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
// src/hooks/use-make-copilot-actionable.ts
|
|
951
|
+
import { useRef, useContext as useContext2, useEffect, useMemo as useMemo2 } from "react";
|
|
952
|
+
import { nanoid as nanoid4 } from "nanoid";
|
|
953
|
+
function useMakeCopilotActionable(annotatedFunction, dependencies) {
|
|
954
|
+
const idRef = useRef(nanoid4());
|
|
955
|
+
const { setEntryPoint, removeEntryPoint } = useContext2(CopilotContext);
|
|
956
|
+
const memoizedAnnotatedFunction = useMemo2(
|
|
957
|
+
() => ({
|
|
958
|
+
name: annotatedFunction.name,
|
|
959
|
+
description: annotatedFunction.description,
|
|
960
|
+
argumentAnnotations: annotatedFunction.argumentAnnotations,
|
|
961
|
+
implementation: annotatedFunction.implementation
|
|
962
|
+
}),
|
|
963
|
+
dependencies
|
|
964
|
+
);
|
|
965
|
+
useEffect(() => {
|
|
966
|
+
setEntryPoint(idRef.current, memoizedAnnotatedFunction);
|
|
967
|
+
return () => {
|
|
968
|
+
removeEntryPoint(idRef.current);
|
|
969
|
+
};
|
|
970
|
+
}, [memoizedAnnotatedFunction, setEntryPoint, removeEntryPoint]);
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
// src/hooks/use-make-copilot-readable.ts
|
|
974
|
+
import { useContext as useContext3, useEffect as useEffect2, useRef as useRef2 } from "react";
|
|
975
|
+
function useMakeCopilotReadable(information, parentId, categories) {
|
|
976
|
+
const { addContext, removeContext } = useContext3(CopilotContext);
|
|
977
|
+
const idRef = useRef2();
|
|
978
|
+
useEffect2(() => {
|
|
979
|
+
const id = addContext(information, parentId, categories);
|
|
980
|
+
idRef.current = id;
|
|
981
|
+
return () => {
|
|
982
|
+
removeContext(id);
|
|
983
|
+
};
|
|
984
|
+
}, [information, parentId, addContext, removeContext]);
|
|
985
|
+
return idRef.current;
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
// src/hooks/use-make-copilot-document-readable.ts
|
|
989
|
+
import { useContext as useContext4, useEffect as useEffect3, useRef as useRef3 } from "react";
|
|
990
|
+
function useMakeCopilotDocumentReadable(document, categories, dependencies = []) {
|
|
991
|
+
const { addDocumentContext, removeDocumentContext } = useContext4(CopilotContext);
|
|
992
|
+
const idRef = useRef3();
|
|
993
|
+
useEffect3(() => {
|
|
994
|
+
const id = addDocumentContext(document, categories);
|
|
995
|
+
idRef.current = id;
|
|
996
|
+
return () => {
|
|
997
|
+
removeDocumentContext(id);
|
|
998
|
+
};
|
|
999
|
+
}, [addDocumentContext, removeDocumentContext, ...dependencies]);
|
|
1000
|
+
return idRef.current;
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
// src/openai-assistants/hooks/use-copilot-chat-v2.ts
|
|
1004
|
+
import { useContext as useContext5, useMemo as useMemo3, useState as useState3 } from "react";
|
|
1005
|
+
|
|
1006
|
+
// src/openai-assistants/utils/process-message-stream.ts
|
|
1007
|
+
function processMessageStream(reader, processMessage) {
|
|
1008
|
+
return __async(this, null, function* () {
|
|
1009
|
+
const decoder = new TextDecoder();
|
|
1010
|
+
let buffer = "";
|
|
1011
|
+
while (true) {
|
|
1012
|
+
const { done, value } = yield reader.read();
|
|
1013
|
+
if (done) {
|
|
1014
|
+
if (buffer.length > 0) {
|
|
1015
|
+
processMessage(buffer);
|
|
1016
|
+
}
|
|
1017
|
+
break;
|
|
1018
|
+
}
|
|
1019
|
+
buffer += decoder.decode(value, { stream: true });
|
|
1020
|
+
let endIndex;
|
|
1021
|
+
while ((endIndex = buffer.indexOf("\n")) !== -1) {
|
|
1022
|
+
processMessage(buffer.substring(0, endIndex).trim());
|
|
1023
|
+
buffer = buffer.substring(endIndex + 1);
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
});
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
// src/openai-assistants/hooks/use-copilot-chat-v2.ts
|
|
1030
|
+
import { parseStreamPart } from "@copilotkit/shared";
|
|
1031
|
+
function useCopilotChatV2(options) {
|
|
1032
|
+
const {
|
|
1033
|
+
getContextString,
|
|
1034
|
+
getChatCompletionFunctionDescriptions,
|
|
1035
|
+
getFunctionCallHandler,
|
|
1036
|
+
copilotApiConfig
|
|
1037
|
+
} = useContext5(CopilotContext);
|
|
1038
|
+
const [messages, setMessages] = useState3([]);
|
|
1039
|
+
const [input, setInput] = useState3("");
|
|
1040
|
+
const [threadId, setThreadId] = useState3(void 0);
|
|
1041
|
+
const [status, setStatus] = useState3("awaiting_message");
|
|
1042
|
+
const [error, setError] = useState3(void 0);
|
|
1043
|
+
const systemMessage = useMemo3(() => {
|
|
1044
|
+
const systemMessageMaker = options.makeSystemMessage || defaultSystemMessage2;
|
|
1045
|
+
const contextString = getContextString([], defaultCopilotContextCategories);
|
|
1046
|
+
return {
|
|
1047
|
+
id: "system",
|
|
1048
|
+
content: systemMessageMaker(contextString),
|
|
1049
|
+
role: "system"
|
|
1050
|
+
};
|
|
1051
|
+
}, [getContextString, options.makeSystemMessage]);
|
|
1052
|
+
const handleInputChange = (e) => {
|
|
1053
|
+
setInput(e.target.value);
|
|
1054
|
+
};
|
|
1055
|
+
const submitMessage = (e) => __async(this, null, function* () {
|
|
1056
|
+
var _a, _b;
|
|
1057
|
+
e.preventDefault();
|
|
1058
|
+
if (input === "") {
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
1061
|
+
setStatus("in_progress");
|
|
1062
|
+
setMessages((messages2) => [...messages2, { id: "", role: "user", content: input }]);
|
|
1063
|
+
setInput("");
|
|
1064
|
+
const apiUrl = copilotApiConfig.chatApiEndpointV2;
|
|
1065
|
+
const functions = getChatCompletionFunctionDescriptions();
|
|
1066
|
+
const result = yield fetch(apiUrl, {
|
|
1067
|
+
method: "POST",
|
|
1068
|
+
headers: __spreadValues(__spreadValues({
|
|
1069
|
+
"Content-Type": "application/json"
|
|
1070
|
+
}, copilotApiConfig.headers), options.headers),
|
|
1071
|
+
body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues({
|
|
1072
|
+
// always use user-provided threadId when available:
|
|
1073
|
+
threadId: (_b = (_a = options.threadId) != null ? _a : threadId) != null ? _b : null,
|
|
1074
|
+
message: input
|
|
1075
|
+
}, functions.length > 0 && { functions }), copilotApiConfig.body), options.body))
|
|
1076
|
+
});
|
|
1077
|
+
if (result.body == null) {
|
|
1078
|
+
throw new Error("The response body is empty.");
|
|
1079
|
+
}
|
|
1080
|
+
yield processMessageStream(result.body.getReader(), (message) => {
|
|
1081
|
+
try {
|
|
1082
|
+
const { type, value } = parseStreamPart(message);
|
|
1083
|
+
switch (type) {
|
|
1084
|
+
case "assistant_message": {
|
|
1085
|
+
setMessages((messages2) => [
|
|
1086
|
+
...messages2,
|
|
1087
|
+
{
|
|
1088
|
+
id: value.id,
|
|
1089
|
+
role: value.role,
|
|
1090
|
+
content: value.content[0].text.value
|
|
1091
|
+
}
|
|
1092
|
+
]);
|
|
1093
|
+
break;
|
|
1094
|
+
}
|
|
1095
|
+
case "assistant_control_data": {
|
|
1096
|
+
setThreadId(value.threadId);
|
|
1097
|
+
setMessages((messages2) => {
|
|
1098
|
+
const lastMessage = messages2[messages2.length - 1];
|
|
1099
|
+
lastMessage.id = value.messageId;
|
|
1100
|
+
return [...messages2.slice(0, messages2.length - 1), lastMessage];
|
|
1101
|
+
});
|
|
1102
|
+
break;
|
|
1103
|
+
}
|
|
1104
|
+
case "error": {
|
|
1105
|
+
setError(value);
|
|
1106
|
+
break;
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
} catch (error2) {
|
|
1110
|
+
setError(error2);
|
|
1111
|
+
}
|
|
1112
|
+
});
|
|
1113
|
+
setStatus("awaiting_message");
|
|
1114
|
+
});
|
|
1115
|
+
return {
|
|
1116
|
+
messages,
|
|
1117
|
+
input,
|
|
1118
|
+
handleInputChange,
|
|
1119
|
+
submitMessage,
|
|
1120
|
+
status,
|
|
1121
|
+
error
|
|
1122
|
+
};
|
|
1123
|
+
}
|
|
1124
|
+
function defaultSystemMessage2(contextString) {
|
|
1125
|
+
return `
|
|
1126
|
+
Please act as an efficient, competent, conscientious, and industrious professional assistant.
|
|
1127
|
+
|
|
1128
|
+
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.
|
|
1129
|
+
Always be polite and respectful, and prefer brevity over verbosity.
|
|
1130
|
+
|
|
1131
|
+
The user has provided you with the following context:
|
|
1132
|
+
\`\`\`
|
|
1133
|
+
${contextString}
|
|
1134
|
+
\`\`\`
|
|
1135
|
+
|
|
1136
|
+
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.
|
|
1137
|
+
|
|
1138
|
+
Please assist them as best you can.
|
|
1139
|
+
|
|
1140
|
+
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.
|
|
1141
|
+
|
|
1142
|
+
If you would like to call a function, call it without saying anything else.
|
|
1143
|
+
`;
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
// src/openai/chat-completion-stream.ts
|
|
1147
|
+
var ChatCompletionStream = class {
|
|
1148
|
+
constructor(params) {
|
|
1149
|
+
this.url = params.url;
|
|
1150
|
+
}
|
|
1151
|
+
fetch(params) {
|
|
1152
|
+
return __async(this, null, function* () {
|
|
1153
|
+
params = __spreadValues({}, params);
|
|
1154
|
+
params.functions = void 0;
|
|
1155
|
+
const transport = new ChatCompletionTransport({});
|
|
1156
|
+
const cleanup = () => {
|
|
1157
|
+
transport.off("data");
|
|
1158
|
+
transport.off("end");
|
|
1159
|
+
transport.off("error");
|
|
1160
|
+
};
|
|
1161
|
+
const stream = new ReadableStream({
|
|
1162
|
+
start: (controller) => {
|
|
1163
|
+
transport.on("data", (data) => {
|
|
1164
|
+
if (data.choices[0].delta.content) {
|
|
1165
|
+
controller.enqueue(data.choices[0].delta.content);
|
|
1166
|
+
}
|
|
1167
|
+
});
|
|
1168
|
+
transport.on("error", (error) => {
|
|
1169
|
+
controller.error(error);
|
|
1170
|
+
cleanup();
|
|
1171
|
+
});
|
|
1172
|
+
transport.on("end", () => {
|
|
1173
|
+
controller.close();
|
|
1174
|
+
cleanup();
|
|
1175
|
+
});
|
|
1176
|
+
}
|
|
1177
|
+
});
|
|
1178
|
+
transport.fetch(params);
|
|
1179
|
+
return stream;
|
|
1180
|
+
});
|
|
1181
|
+
}
|
|
1182
|
+
};
|
|
1183
|
+
export {
|
|
1184
|
+
ChatCompletionStream,
|
|
1185
|
+
CopilotContext,
|
|
1186
|
+
CopilotProvider,
|
|
1187
|
+
defaultCopilotContextCategories,
|
|
1188
|
+
processMessageStream,
|
|
1189
|
+
useCopilotChat,
|
|
1190
|
+
useCopilotChatV2,
|
|
1191
|
+
useMakeCopilotActionable,
|
|
1192
|
+
useMakeCopilotDocumentReadable,
|
|
1193
|
+
useMakeCopilotReadable
|
|
1194
|
+
};
|
|
27
1195
|
//# sourceMappingURL=index.mjs.map
|