@copilotkit/react-core 0.25.0-function-calling-fixes.2 → 0.25.0-mme-cloud.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +216 -234
- package/CHANGELOG.md +3 -25
- package/dist/{chunk-BGB5G33N.mjs → chunk-4E2RCCQB.mjs} +2 -2
- package/dist/{chunk-AEUR5JBT.mjs → chunk-APVNN5QF.mjs} +3 -4
- package/dist/chunk-APVNN5QF.mjs.map +1 -0
- package/dist/{chunk-3WKJ25L3.mjs → chunk-CGT3AVYT.mjs} +3 -3
- package/dist/chunk-CGT3AVYT.mjs.map +1 -0
- package/dist/{chunk-KIKHLN4X.mjs → chunk-GH7QK2AZ.mjs} +3 -1
- package/dist/chunk-GH7QK2AZ.mjs.map +1 -0
- package/dist/{chunk-H3FQWB4B.mjs → chunk-KMTE4NLW.mjs} +19 -12
- package/dist/chunk-KMTE4NLW.mjs.map +1 -0
- package/dist/{chunk-KJQZ2VEU.mjs → chunk-M7JUS6OQ.mjs} +2 -2
- package/dist/{chunk-QGRMN7L3.mjs → chunk-O2GQ2XK7.mjs} +3 -3
- package/dist/{chunk-FCEPEM4B.mjs → chunk-PYBBWHNC.mjs} +3 -3
- package/dist/{chunk-GVLCTSXW.mjs → chunk-SPLPX72P.mjs} +11 -7
- package/dist/chunk-SPLPX72P.mjs.map +1 -0
- package/dist/{chunk-75RLNHDB.mjs → chunk-TEI34ZF5.mjs} +5 -5
- package/dist/chunk-TEI34ZF5.mjs.map +1 -0
- package/dist/{chunk-H6V2C2AN.mjs → chunk-YKHUBROO.mjs} +2 -2
- package/dist/components/copilot-provider/copilotkit-props.d.ts +12 -0
- package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.d.ts +0 -17
- package/dist/components/copilot-provider/copilotkit.js +19 -17
- package/dist/components/copilot-provider/copilotkit.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.mjs +8 -435
- package/dist/components/copilot-provider/copilotkit.mjs.map +1 -1
- package/dist/components/copilot-provider/index.js +19 -17
- package/dist/components/copilot-provider/index.js.map +1 -1
- package/dist/components/copilot-provider/index.mjs +9 -435
- package/dist/components/copilot-provider/index.mjs.map +1 -1
- package/dist/components/index.js +19 -17
- package/dist/components/index.js.map +1 -1
- package/dist/components/index.mjs +10 -435
- package/dist/components/index.mjs.map +1 -1
- package/dist/context/copilot-context.d.ts +15 -2
- package/dist/context/copilot-context.js +2 -0
- package/dist/context/copilot-context.js.map +1 -1
- package/dist/context/copilot-context.mjs +5 -64
- package/dist/context/copilot-context.mjs.map +1 -1
- package/dist/context/index.js +2 -0
- package/dist/context/index.js.map +1 -1
- package/dist/context/index.mjs +6 -64
- package/dist/context/index.mjs.map +1 -1
- package/dist/hooks/index.js +14 -14
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +23 -518
- package/dist/hooks/index.mjs.map +1 -1
- package/dist/hooks/use-chat.d.ts +8 -2
- package/dist/hooks/use-chat.js +3 -4
- package/dist/hooks/use-chat.js.map +1 -1
- package/dist/hooks/use-chat.mjs +4 -285
- package/dist/hooks/use-chat.mjs.map +1 -1
- package/dist/hooks/use-copilot-action.d.ts +1 -1
- package/dist/hooks/use-copilot-action.js +4 -9
- package/dist/hooks/use-copilot-action.js.map +1 -1
- package/dist/hooks/use-copilot-action.mjs +5 -107
- package/dist/hooks/use-copilot-action.mjs.map +1 -1
- package/dist/hooks/use-copilot-chat.js +12 -7
- package/dist/hooks/use-copilot-chat.js.map +1 -1
- package/dist/hooks/use-copilot-chat.mjs +12 -420
- package/dist/hooks/use-copilot-chat.mjs.map +1 -1
- package/dist/hooks/use-flat-category-store.mjs +4 -65
- package/dist/hooks/use-flat-category-store.mjs.map +1 -1
- package/dist/hooks/use-make-copilot-actionable.js +2 -0
- package/dist/hooks/use-make-copilot-actionable.js.map +1 -1
- package/dist/hooks/use-make-copilot-actionable.mjs +5 -88
- package/dist/hooks/use-make-copilot-actionable.mjs.map +1 -1
- package/dist/hooks/use-make-copilot-document-readable.js +2 -0
- package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
- package/dist/hooks/use-make-copilot-document-readable.mjs +5 -78
- package/dist/hooks/use-make-copilot-document-readable.mjs.map +1 -1
- package/dist/hooks/use-make-copilot-readable.js +2 -0
- package/dist/hooks/use-make-copilot-readable.js.map +1 -1
- package/dist/hooks/use-make-copilot-readable.mjs +5 -78
- package/dist/hooks/use-make-copilot-readable.mjs.map +1 -1
- package/dist/hooks/use-tree.mjs +4 -150
- package/dist/hooks/use-tree.mjs.map +1 -1
- package/dist/index.js +31 -31
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +48 -1103
- package/dist/index.mjs.map +1 -1
- package/dist/lib/copilot-task.js +2 -2
- package/dist/lib/copilot-task.js.map +1 -1
- package/dist/lib/copilot-task.mjs +10 -192
- package/dist/lib/copilot-task.mjs.map +1 -1
- package/dist/lib/index.js +2 -2
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/index.mjs +11 -192
- package/dist/lib/index.mjs.map +1 -1
- package/dist/openai-assistants/hooks/index.js +2 -0
- package/dist/openai-assistants/hooks/index.js.map +1 -1
- package/dist/openai-assistants/hooks/index.mjs +14 -228
- package/dist/openai-assistants/hooks/index.mjs.map +1 -1
- package/dist/openai-assistants/hooks/use-assistants.mjs +7 -45
- package/dist/openai-assistants/hooks/use-assistants.mjs.map +1 -1
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.js +2 -0
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.js.map +1 -1
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs +14 -228
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs.map +1 -1
- package/dist/openai-assistants/index.js +2 -0
- package/dist/openai-assistants/index.js.map +1 -1
- package/dist/openai-assistants/index.mjs +17 -228
- package/dist/openai-assistants/index.mjs.map +1 -1
- package/dist/openai-assistants/utils/index.mjs +5 -43
- package/dist/openai-assistants/utils/index.mjs.map +1 -1
- package/dist/openai-assistants/utils/process-message-stream.mjs +4 -43
- package/dist/openai-assistants/utils/process-message-stream.mjs.map +1 -1
- package/dist/types/index.mjs +1 -0
- package/dist/utils/fetch-chat-completion.js +2 -2
- package/dist/utils/fetch-chat-completion.js.map +1 -1
- package/dist/utils/fetch-chat-completion.mjs +5 -112
- package/dist/utils/fetch-chat-completion.mjs.map +1 -1
- package/package.json +4 -4
- package/src/components/copilot-provider/copilotkit-props.tsx +14 -0
- package/src/components/copilot-provider/copilotkit.tsx +21 -25
- package/src/context/copilot-context.tsx +19 -1
- package/src/hooks/use-chat.ts +9 -4
- package/src/hooks/use-copilot-action.ts +58 -10
- package/src/hooks/use-copilot-chat.ts +5 -1
- package/src/utils/fetch-chat-completion.ts +1 -0
- package/dist/chunk-3WKJ25L3.mjs.map +0 -1
- package/dist/chunk-75RLNHDB.mjs.map +0 -1
- package/dist/chunk-AEUR5JBT.mjs.map +0 -1
- package/dist/chunk-F2JIAPZQ.mjs +0 -14
- package/dist/chunk-F2JIAPZQ.mjs.map +0 -1
- package/dist/chunk-GVLCTSXW.mjs.map +0 -1
- package/dist/chunk-H3FQWB4B.mjs.map +0 -1
- package/dist/chunk-ISKBWE4O.mjs +0 -13
- package/dist/chunk-ISKBWE4O.mjs.map +0 -1
- package/dist/chunk-KIKHLN4X.mjs.map +0 -1
- package/dist/components/copilot-provider/standard-copilot-api-config.d.ts +0 -23
- package/dist/components/copilot-provider/standard-copilot-api-config.js +0 -38
- package/dist/components/copilot-provider/standard-copilot-api-config.js.map +0 -1
- package/dist/components/copilot-provider/standard-copilot-api-config.mjs +0 -13
- package/dist/components/copilot-provider/standard-copilot-api-config.mjs.map +0 -1
- package/dist/hooks/use-copilot-action-implementation.d.ts +0 -7
- package/dist/hooks/use-copilot-action-implementation.js +0 -140
- package/dist/hooks/use-copilot-action-implementation.js.map +0 -1
- package/dist/hooks/use-copilot-action-implementation.mjs +0 -106
- package/dist/hooks/use-copilot-action-implementation.mjs.map +0 -1
- package/src/components/copilot-provider/standard-copilot-api-config.tsx +0 -28
- package/src/hooks/use-copilot-action-implementation.ts +0 -60
- /package/dist/{chunk-BGB5G33N.mjs.map → chunk-4E2RCCQB.mjs.map} +0 -0
- /package/dist/{chunk-KJQZ2VEU.mjs.map → chunk-M7JUS6OQ.mjs.map} +0 -0
- /package/dist/{chunk-QGRMN7L3.mjs.map → chunk-O2GQ2XK7.mjs.map} +0 -0
- /package/dist/{chunk-FCEPEM4B.mjs.map → chunk-PYBBWHNC.mjs.map} +0 -0
- /package/dist/{chunk-H6V2C2AN.mjs.map → chunk-YKHUBROO.mjs.map} +0 -0
|
@@ -1,231 +1,17 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
return a;
|
|
16
|
-
};
|
|
17
|
-
var __async = (__this, __arguments, generator) => {
|
|
18
|
-
return new Promise((resolve, reject) => {
|
|
19
|
-
var fulfilled = (value) => {
|
|
20
|
-
try {
|
|
21
|
-
step(generator.next(value));
|
|
22
|
-
} catch (e) {
|
|
23
|
-
reject(e);
|
|
24
|
-
}
|
|
25
|
-
};
|
|
26
|
-
var rejected = (value) => {
|
|
27
|
-
try {
|
|
28
|
-
step(generator.throw(value));
|
|
29
|
-
} catch (e) {
|
|
30
|
-
reject(e);
|
|
31
|
-
}
|
|
32
|
-
};
|
|
33
|
-
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
|
|
34
|
-
step((generator = generator.apply(__this, __arguments)).next());
|
|
35
|
-
});
|
|
36
|
-
};
|
|
37
|
-
|
|
38
|
-
// src/openai-assistants/hooks/use-copilot-chat-v2.ts
|
|
39
|
-
import { useContext, useMemo, useState as useState2 } from "react";
|
|
40
|
-
|
|
41
|
-
// src/openai-assistants/utils/process-message-stream.ts
|
|
42
|
-
function processMessageStream(reader, processMessage) {
|
|
43
|
-
return __async(this, null, function* () {
|
|
44
|
-
const decoder = new TextDecoder();
|
|
45
|
-
let buffer = "";
|
|
46
|
-
while (true) {
|
|
47
|
-
const { done, value } = yield reader.read();
|
|
48
|
-
if (done) {
|
|
49
|
-
if (buffer.length > 0) {
|
|
50
|
-
processMessage(buffer);
|
|
51
|
-
}
|
|
52
|
-
break;
|
|
53
|
-
}
|
|
54
|
-
buffer += decoder.decode(value, { stream: true });
|
|
55
|
-
let endIndex;
|
|
56
|
-
while ((endIndex = buffer.indexOf("\n")) !== -1) {
|
|
57
|
-
processMessage(buffer.substring(0, endIndex).trim());
|
|
58
|
-
buffer = buffer.substring(endIndex + 1);
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
});
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
// src/openai-assistants/hooks/use-copilot-chat-v2.ts
|
|
65
|
-
import { parseStreamPart } from "@copilotkit/shared";
|
|
66
|
-
|
|
67
|
-
// src/context/copilot-context.tsx
|
|
68
|
-
import React from "react";
|
|
69
|
-
var emptyCopilotContext = {
|
|
70
|
-
entryPoints: {},
|
|
71
|
-
setEntryPoint: () => {
|
|
72
|
-
},
|
|
73
|
-
removeEntryPoint: () => {
|
|
74
|
-
},
|
|
75
|
-
getChatCompletionFunctionDescriptions: () => returnAndThrowInDebug([]),
|
|
76
|
-
getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
|
|
77
|
-
})),
|
|
78
|
-
chatComponentsCache: { current: {} },
|
|
79
|
-
getContextString: (documents, categories) => returnAndThrowInDebug(""),
|
|
80
|
-
addContext: () => "",
|
|
81
|
-
removeContext: () => {
|
|
82
|
-
},
|
|
83
|
-
getDocumentsContext: (categories) => returnAndThrowInDebug([]),
|
|
84
|
-
addDocumentContext: () => returnAndThrowInDebug(""),
|
|
85
|
-
removeDocumentContext: () => {
|
|
86
|
-
},
|
|
87
|
-
copilotApiConfig: new class {
|
|
88
|
-
get chatApiEndpoint() {
|
|
89
|
-
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
|
|
90
|
-
}
|
|
91
|
-
get chatApiEndpointV2() {
|
|
92
|
-
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
|
|
93
|
-
}
|
|
94
|
-
get headers() {
|
|
95
|
-
return {};
|
|
96
|
-
}
|
|
97
|
-
get body() {
|
|
98
|
-
return {};
|
|
99
|
-
}
|
|
100
|
-
}()
|
|
101
|
-
};
|
|
102
|
-
var CopilotContext = React.createContext(emptyCopilotContext);
|
|
103
|
-
function returnAndThrowInDebug(value) {
|
|
104
|
-
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
|
|
105
|
-
return value;
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
// src/components/copilot-provider/copilotkit.tsx
|
|
109
|
-
import { useCallback, useRef, useState } from "react";
|
|
110
|
-
import { actionToChatCompletionFunction } from "@copilotkit/shared";
|
|
111
|
-
import { jsx } from "react/jsx-runtime";
|
|
112
|
-
var defaultCopilotContextCategories = ["global"];
|
|
113
|
-
|
|
114
|
-
// src/openai-assistants/hooks/use-copilot-chat-v2.ts
|
|
115
|
-
function useCopilotChatV2(options) {
|
|
116
|
-
const {
|
|
117
|
-
getContextString,
|
|
118
|
-
getChatCompletionFunctionDescriptions,
|
|
119
|
-
getFunctionCallHandler,
|
|
120
|
-
copilotApiConfig
|
|
121
|
-
} = useContext(CopilotContext);
|
|
122
|
-
const [messages, setMessages] = useState2([]);
|
|
123
|
-
const [input, setInput] = useState2("");
|
|
124
|
-
const [threadId, setThreadId] = useState2(void 0);
|
|
125
|
-
const [status, setStatus] = useState2("awaiting_message");
|
|
126
|
-
const [error, setError] = useState2(void 0);
|
|
127
|
-
const systemMessage = useMemo(() => {
|
|
128
|
-
const systemMessageMaker = options.makeSystemMessage || defaultSystemMessage;
|
|
129
|
-
const contextString = getContextString([], defaultCopilotContextCategories);
|
|
130
|
-
return {
|
|
131
|
-
id: "system",
|
|
132
|
-
content: systemMessageMaker(contextString),
|
|
133
|
-
role: "system"
|
|
134
|
-
};
|
|
135
|
-
}, [getContextString, options.makeSystemMessage]);
|
|
136
|
-
const handleInputChange = (e) => {
|
|
137
|
-
setInput(e.target.value);
|
|
138
|
-
};
|
|
139
|
-
const submitMessage = (e) => __async(this, null, function* () {
|
|
140
|
-
var _a, _b;
|
|
141
|
-
e.preventDefault();
|
|
142
|
-
if (input === "") {
|
|
143
|
-
return;
|
|
144
|
-
}
|
|
145
|
-
setStatus("in_progress");
|
|
146
|
-
setMessages((messages2) => [...messages2, { id: "", role: "user", content: input }]);
|
|
147
|
-
setInput("");
|
|
148
|
-
const apiUrl = copilotApiConfig.chatApiEndpointV2;
|
|
149
|
-
const functions = getChatCompletionFunctionDescriptions();
|
|
150
|
-
const result = yield fetch(apiUrl, {
|
|
151
|
-
method: "POST",
|
|
152
|
-
headers: __spreadValues(__spreadValues({
|
|
153
|
-
"Content-Type": "application/json"
|
|
154
|
-
}, copilotApiConfig.headers), options.headers),
|
|
155
|
-
body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues({
|
|
156
|
-
// always use user-provided threadId when available:
|
|
157
|
-
threadId: (_b = (_a = options.threadId) != null ? _a : threadId) != null ? _b : null,
|
|
158
|
-
message: input
|
|
159
|
-
}, functions.length > 0 && { functions }), copilotApiConfig.body), options.body))
|
|
160
|
-
});
|
|
161
|
-
if (result.body == null) {
|
|
162
|
-
throw new Error("The response body is empty.");
|
|
163
|
-
}
|
|
164
|
-
yield processMessageStream(result.body.getReader(), (message) => {
|
|
165
|
-
try {
|
|
166
|
-
const { type, value } = parseStreamPart(message);
|
|
167
|
-
switch (type) {
|
|
168
|
-
case "assistant_message": {
|
|
169
|
-
setMessages((messages2) => [
|
|
170
|
-
...messages2,
|
|
171
|
-
{
|
|
172
|
-
id: value.id,
|
|
173
|
-
role: value.role,
|
|
174
|
-
content: value.content[0].text.value
|
|
175
|
-
}
|
|
176
|
-
]);
|
|
177
|
-
break;
|
|
178
|
-
}
|
|
179
|
-
case "assistant_control_data": {
|
|
180
|
-
setThreadId(value.threadId);
|
|
181
|
-
setMessages((messages2) => {
|
|
182
|
-
const lastMessage = messages2[messages2.length - 1];
|
|
183
|
-
lastMessage.id = value.messageId;
|
|
184
|
-
return [...messages2.slice(0, messages2.length - 1), lastMessage];
|
|
185
|
-
});
|
|
186
|
-
break;
|
|
187
|
-
}
|
|
188
|
-
case "error": {
|
|
189
|
-
setError(value);
|
|
190
|
-
break;
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
} catch (error2) {
|
|
194
|
-
setError(error2);
|
|
195
|
-
}
|
|
196
|
-
});
|
|
197
|
-
setStatus("awaiting_message");
|
|
198
|
-
});
|
|
199
|
-
return {
|
|
200
|
-
messages,
|
|
201
|
-
input,
|
|
202
|
-
handleInputChange,
|
|
203
|
-
submitMessage,
|
|
204
|
-
status,
|
|
205
|
-
error
|
|
206
|
-
};
|
|
207
|
-
}
|
|
208
|
-
function defaultSystemMessage(contextString) {
|
|
209
|
-
return `
|
|
210
|
-
Please act as an efficient, competent, conscientious, and industrious professional assistant.
|
|
211
|
-
|
|
212
|
-
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.
|
|
213
|
-
Always be polite and respectful, and prefer brevity over verbosity.
|
|
214
|
-
|
|
215
|
-
The user has provided you with the following context:
|
|
216
|
-
\`\`\`
|
|
217
|
-
${contextString}
|
|
218
|
-
\`\`\`
|
|
219
|
-
|
|
220
|
-
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.
|
|
221
|
-
|
|
222
|
-
Please assist them as best you can.
|
|
223
|
-
|
|
224
|
-
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.
|
|
225
|
-
|
|
226
|
-
If you would like to call a function, call it without saying anything else.
|
|
227
|
-
`;
|
|
228
|
-
}
|
|
1
|
+
import {
|
|
2
|
+
defaultSystemMessage,
|
|
3
|
+
useCopilotChatV2
|
|
4
|
+
} from "../../chunk-PYBBWHNC.mjs";
|
|
5
|
+
import "../../chunk-FRAKUJWH.mjs";
|
|
6
|
+
import "../../chunk-MZ5UN3BY.mjs";
|
|
7
|
+
import "../../chunk-VNRDQJXW.mjs";
|
|
8
|
+
import "../../chunk-JD7BAH7U.mjs";
|
|
9
|
+
import "../../chunk-SPCZTZCY.mjs";
|
|
10
|
+
import "../../chunk-KMTE4NLW.mjs";
|
|
11
|
+
import "../../chunk-YULKJPY3.mjs";
|
|
12
|
+
import "../../chunk-VUY2K2DI.mjs";
|
|
13
|
+
import "../../chunk-GH7QK2AZ.mjs";
|
|
14
|
+
import "../../chunk-MRXNTQOX.mjs";
|
|
229
15
|
export {
|
|
230
16
|
defaultSystemMessage,
|
|
231
17
|
useCopilotChatV2
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/openai-assistants/hooks/use-copilot-chat-v2.ts","../../../src/openai-assistants/utils/process-message-stream.ts","../../../src/context/copilot-context.tsx","../../../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["import { useContext, useMemo, useState } from \"react\";\nimport { processMessageStream } from \"../utils\";\nimport { Message, parseStreamPart } from \"@copilotkit/shared\";\nimport { CopilotContext } from \"../../context\";\nimport { defaultCopilotContextCategories } from \"../../components\";\n\nexport type AssistantStatus = \"in_progress\" | \"awaiting_message\";\n\nexport interface RequestForwardingOptions {\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n /**\n * Extra body object to be sent with the API request.\n * @example\n * Send a `sessionId` to the API along with the messages.\n * ```js\n * useChat({\n * body: {\n * sessionId: '123',\n * }\n * })\n * ```\n */\n body?: object;\n}\nexport interface UseCopilotChatOptionsV2 extends RequestForwardingOptions {\n makeSystemMessage?: (contextString: string) => string;\n threadId?: string | undefined;\n}\n\nexport interface UseCopilotChatV2Result {\n messages: Message[];\n input: string;\n handleInputChange: (e: any) => void;\n submitMessage: (e: any) => Promise<void>;\n status: AssistantStatus;\n error: unknown;\n}\n\nexport function useCopilotChatV2(options: UseCopilotChatOptionsV2): UseCopilotChatV2Result {\n const {\n getContextString,\n getChatCompletionFunctionDescriptions,\n getFunctionCallHandler,\n copilotApiConfig,\n } = useContext(CopilotContext);\n\n const [messages, setMessages] = useState<Message[]>([]);\n const [input, setInput] = useState(\"\");\n const [threadId, setThreadId] = useState<string | undefined>(undefined);\n const [status, setStatus] = useState<AssistantStatus>(\"awaiting_message\");\n const [error, setError] = useState<unknown | undefined>(undefined);\n\n const systemMessage: Message = useMemo(() => {\n const systemMessageMaker = options.makeSystemMessage || defaultSystemMessage;\n const contextString = getContextString([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return {\n id: \"system\",\n content: systemMessageMaker(contextString),\n role: \"system\",\n };\n }, [getContextString, options.makeSystemMessage]);\n\n const handleInputChange = (e: any) => {\n setInput(e.target.value);\n };\n\n const submitMessage = async (e: any) => {\n e.preventDefault();\n\n if (input === \"\") {\n return;\n }\n\n setStatus(\"in_progress\");\n\n setMessages((messages) => [...messages, { id: \"\", role: \"user\", content: input }]);\n\n setInput(\"\");\n\n const apiUrl = copilotApiConfig.chatApiEndpointV2;\n\n const functions = getChatCompletionFunctionDescriptions();\n\n const result = await fetch(apiUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...copilotApiConfig.headers,\n ...options.headers,\n },\n body: JSON.stringify({\n // always use user-provided threadId when available:\n threadId: options.threadId ?? threadId ?? null,\n message: input,\n ...(functions.length > 0 && { functions: functions }),\n ...copilotApiConfig.body,\n ...options.body,\n }),\n });\n\n if (result.body == null) {\n throw new Error(\"The response body is empty.\");\n }\n\n await processMessageStream(result.body.getReader(), (message: string) => {\n try {\n const { type, value } = parseStreamPart(message);\n\n switch (type) {\n case \"assistant_message\": {\n // append message:\n setMessages((messages) => [\n ...messages,\n {\n id: value.id,\n role: value.role,\n content: value.content[0].text.value,\n },\n ]);\n break;\n }\n\n case \"assistant_control_data\": {\n setThreadId(value.threadId);\n\n // set id of last message:\n setMessages((messages) => {\n const lastMessage = messages[messages.length - 1];\n lastMessage.id = value.messageId;\n return [...messages.slice(0, messages.length - 1), lastMessage];\n });\n\n break;\n }\n\n case \"error\": {\n setError(value);\n break;\n }\n }\n } catch (error) {\n setError(error);\n }\n });\n\n setStatus(\"awaiting_message\");\n };\n\n return {\n messages,\n input,\n handleInputChange,\n submitMessage,\n status,\n error,\n };\n}\n\nexport function defaultSystemMessage(contextString: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\n`;\n}\n","export async function processMessageStream(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n processMessage: (message: string) => void | Promise<void>,\n) {\n const decoder = new TextDecoder();\n let buffer = \"\";\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n if (buffer.length > 0) {\n processMessage(buffer);\n }\n break;\n }\n\n buffer += decoder.decode(value, { stream: true });\n\n let endIndex: number;\n while ((endIndex = buffer.indexOf(\"\\n\")) !== -1) {\n processMessage(buffer.substring(0, endIndex).trim());\n buffer = buffer.substring(endIndex + 1); // Remove the processed instruction + delimiter\n }\n }\n}\n","import { FunctionCallHandler, ToolDefinition } from \"@copilotkit/shared\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport React, { Ref } from \"react\";\nimport { TreeNodeId } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the chat API v2.\n */\n chatApiEndpointV2: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Additional body params to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'message': 'Hello, world!'\n * }\n * ```\n */\n body: Record<string, any>;\n\n /**\n * Backend only props that will be combined to body params to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n backendOnlyProps?: Record<string, any>;\n}\n\nexport type InChatRenderFunction = (props: ActionRenderProps<any>) => string | JSX.Element;\n\nexport interface CopilotContextParams {\n // function-calling\n entryPoints: Record<string, FrontendAction<any>>;\n setEntryPoint: (id: string, entryPoint: FrontendAction<any>) => void;\n removeEntryPoint: (id: string) => void;\n chatComponentsCache: React.RefObject<Record<string, InChatRenderFunction | string>>;\n getChatCompletionFunctionDescriptions: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => ToolDefinition[];\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n entryPoints: {},\n setEntryPoint: () => {},\n removeEntryPoint: () => {},\n getChatCompletionFunctionDescriptions: () => returnAndThrowInDebug([]),\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n chatComponentsCache: { current: {} },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n get chatApiEndpointV2(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n return React.useContext(CopilotContext);\n}\n\nfunction returnAndThrowInDebug<T>(value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n return value;\n}\n","import { Ref, useCallback, useRef, useState } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n InChatRenderFunction,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { DocumentPointer } from \"../../types\";\nimport { FunctionCallHandler, actionToChatCompletionFunction } from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { StandardCopilotApiConfig } from \"./standard-copilot-api-config\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { ToolDefinition } from \"@copilotkit/shared\";\n\n/**\n * The CopilotKit component.\n * This component provides the Copilot context to its children.\n * It can be configured either with a chat API endpoint or a CopilotApiConfig.\n *\n * NOTE: The backend can use OpenAI, or you can bring your own LLM.\n * For examples of the backend api implementation, see `examples/next-openai` usage (under `src/api/copilotkit`),\n * or read the documentation at https://docs.copilotkit.ai\n * In particular, Getting-Started > Quickstart-Backend: https://docs.copilotkit.ai/getting-started/quickstart-backend\n *\n * Example usage:\n * ```\n * <CopilotKit url=\"https://your.copilotkit.api\">\n * <App />\n * </CopilotKit>\n * ```\n *\n * or\n *\n * ```\n * const copilotApiConfig = new StandardCopilotApiConfig(\n * \"https://your.copilotkit.api/v1\",\n * \"https://your.copilotkit.api/v2\",\n * {},\n * {}\n * );\n *\n * // ...\n *\n * <CopilotKit chatApiConfig={copilotApiConfig}>\n * <App />\n * </CopilotKit>\n * ```\n *\n * @param props - The props for the component.\n * @returns The CopilotKit component.\n */\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n // Compute all the functions and properties that we need to pass\n // to the CopilotContext.\n\n const [entryPoints, setEntryPoints] = useState<Record<string, FrontendAction<any>>>({});\n const chatComponentsCache = useRef<Record<string, InChatRenderFunction | string>>({});\n const { addElement, removeElement, printTree } = useTree();\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n const setEntryPoint = useCallback((id: string, entryPoint: FrontendAction<any>) => {\n setEntryPoints((prevPoints) => {\n return {\n ...prevPoints,\n [id]: entryPoint,\n };\n });\n }, []);\n\n const removeEntryPoint = useCallback((id: string) => {\n setEntryPoints((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getChatCompletionFunctionDescriptions = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToChatCompletionFunctions(Object.values(customEntryPoints || entryPoints));\n },\n [entryPoints],\n );\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || entryPoints));\n },\n [entryPoints],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = new StandardCopilotApiConfig(\n props.url,\n `${props.url}/v2`,\n props.headers || {},\n {\n ...props.body,\n ...props.backendOnlyProps,\n },\n );\n\n return (\n <CopilotContext.Provider\n value={{\n entryPoints,\n chatComponentsCache,\n getChatCompletionFunctionDescriptions,\n getFunctionCallHandler,\n setEntryPoint,\n removeEntryPoint,\n getContextString,\n addContext,\n removeContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n }}\n >\n {children}\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToChatCompletionFunctions(actions: FrontendAction<any>[]): ToolDefinition[] {\n return actions.map(actionToChatCompletionFunction);\n}\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async (chatMessages, functionCall) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[functionCall.name || \"\"];\n if (action) {\n let functionCallArguments: Record<string, any>[] = [];\n if (functionCall.arguments) {\n functionCallArguments = JSON.parse(functionCall.arguments);\n }\n return await action.handler(functionCallArguments);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,SAAS,YAAAA,iBAAgB;;;ACA9C,SAAsB,qBACpB,QACA,gBACA;AAAA;AACA,UAAM,UAAU,IAAI,YAAY;AAChC,QAAI,SAAS;AACb,WAAO,MAAM;AACX,YAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAE1C,UAAI,MAAM;AACR,YAAI,OAAO,SAAS,GAAG;AACrB,yBAAe,MAAM;AAAA,QACvB;AACA;AAAA,MACF;AAEA,gBAAU,QAAQ,OAAO,OAAO,EAAE,QAAQ,KAAK,CAAC;AAEhD,UAAI;AACJ,cAAQ,WAAW,OAAO,QAAQ,IAAI,OAAO,IAAI;AAC/C,uBAAe,OAAO,UAAU,GAAG,QAAQ,EAAE,KAAK,CAAC;AACnD,iBAAS,OAAO,UAAU,WAAW,CAAC;AAAA,MACxC;AAAA,IACF;AAAA,EACF;AAAA;;;ADtBA,SAAkB,uBAAuB;;;AEAzC,OAAO,WAAoB;AAoF3B,IAAM,sBAA4C;AAAA,EAChD,aAAa,CAAC;AAAA,EACd,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,kBAAkB,MAAM;AAAA,EAAC;AAAA,EACzB,uCAAuC,MAAM,sBAAsB,CAAC,CAAC;AAAA,EACrE,wBAAwB,MAAM,sBAAsB,MAAY;AAAA,EAAC,EAAC;AAAA,EAClE,qBAAqB,EAAE,SAAS,CAAC,EAAE;AAAA,EACnC,kBAAkB,CAAC,WAA8B,e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,QAAQ,CAAC,EAAE,KAAK;AAAA,cACjC;AAAA,YACF,CAAC;AACD;AAAA,UACF;AAAA,UAEA,KAAK,0BAA0B;AAC7B,wBAAY,MAAM,QAAQ;AAG1B,wBAAY,CAACA,cAAa;AACxB,oBAAM,cAAcA,UAASA,UAAS,SAAS,CAAC;AAChD,0BAAY,KAAK,MAAM;AACvB,qBAAO,CAAC,GAAGA,UAAS,MAAM,GAAGA,UAAS,SAAS,CAAC,GAAG,WAAW;AAAA,YAChE,CAAC;AAED;AAAA,UACF;AAAA,UAEA,KAAK,SAAS;AACZ,qBAAS,KAAK;AACd;AAAA,UACF;AAAA,QACF;AAAA,MACF,SAASC,QAAP;AACA,iBAASA,MAAK;AAAA,MAChB;AAAA,IACF,CAAC;AAED,cAAU,kBAAkB;AAAA,EAC9B;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,qBAAqB,eAA+B;AAClE,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWF;","names":["useState","useState","messages","error"]}
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -114,6 +114,8 @@ var emptyCopilotContext = {
|
|
|
114
114
|
addContext: () => "",
|
|
115
115
|
removeContext: () => {
|
|
116
116
|
},
|
|
117
|
+
messages: [],
|
|
118
|
+
setMessages: () => returnAndThrowInDebug([]),
|
|
117
119
|
getDocumentsContext: (categories) => returnAndThrowInDebug([]),
|
|
118
120
|
addDocumentContext: () => returnAndThrowInDebug(""),
|
|
119
121
|
removeDocumentContext: () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/openai-assistants/index.ts","../../src/openai-assistants/hooks/use-copilot-chat-v2.ts","../../src/openai-assistants/utils/process-message-stream.ts","../../src/context/copilot-context.tsx","../../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["export * from \"./hooks\";\nexport * from \"./utils\";\n","import { useContext, useMemo, useState } from \"react\";\nimport { processMessageStream } from \"../utils\";\nimport { Message, parseStreamPart } from \"@copilotkit/shared\";\nimport { CopilotContext } from \"../../context\";\nimport { defaultCopilotContextCategories } from \"../../components\";\n\nexport type AssistantStatus = \"in_progress\" | \"awaiting_message\";\n\nexport interface RequestForwardingOptions {\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n /**\n * Extra body object to be sent with the API request.\n * @example\n * Send a `sessionId` to the API along with the messages.\n * ```js\n * useChat({\n * body: {\n * sessionId: '123',\n * }\n * })\n * ```\n */\n body?: object;\n}\nexport interface UseCopilotChatOptionsV2 extends RequestForwardingOptions {\n makeSystemMessage?: (contextString: string) => string;\n threadId?: string | undefined;\n}\n\nexport interface UseCopilotChatV2Result {\n messages: Message[];\n input: string;\n handleInputChange: (e: any) => void;\n submitMessage: (e: any) => Promise<void>;\n status: AssistantStatus;\n error: unknown;\n}\n\nexport function useCopilotChatV2(options: UseCopilotChatOptionsV2): UseCopilotChatV2Result {\n const {\n getContextString,\n getChatCompletionFunctionDescriptions,\n getFunctionCallHandler,\n copilotApiConfig,\n } = useContext(CopilotContext);\n\n const [messages, setMessages] = useState<Message[]>([]);\n const [input, setInput] = useState(\"\");\n const [threadId, setThreadId] = useState<string | undefined>(undefined);\n const [status, setStatus] = useState<AssistantStatus>(\"awaiting_message\");\n const [error, setError] = useState<unknown | undefined>(undefined);\n\n const systemMessage: Message = useMemo(() => {\n const systemMessageMaker = options.makeSystemMessage || defaultSystemMessage;\n const contextString = getContextString([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return {\n id: \"system\",\n content: systemMessageMaker(contextString),\n role: \"system\",\n };\n }, [getContextString, options.makeSystemMessage]);\n\n const handleInputChange = (e: any) => {\n setInput(e.target.value);\n };\n\n const submitMessage = async (e: any) => {\n e.preventDefault();\n\n if (input === \"\") {\n return;\n }\n\n setStatus(\"in_progress\");\n\n setMessages((messages) => [...messages, { id: \"\", role: \"user\", content: input }]);\n\n setInput(\"\");\n\n const apiUrl = copilotApiConfig.chatApiEndpointV2;\n\n const functions = getChatCompletionFunctionDescriptions();\n\n const result = await fetch(apiUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...copilotApiConfig.headers,\n ...options.headers,\n },\n body: JSON.stringify({\n // always use user-provided threadId when available:\n threadId: options.threadId ?? threadId ?? null,\n message: input,\n ...(functions.length > 0 && { functions: functions }),\n ...copilotApiConfig.body,\n ...options.body,\n }),\n });\n\n if (result.body == null) {\n throw new Error(\"The response body is empty.\");\n }\n\n await processMessageStream(result.body.getReader(), (message: string) => {\n try {\n const { type, value } = parseStreamPart(message);\n\n switch (type) {\n case \"assistant_message\": {\n // append message:\n setMessages((messages) => [\n ...messages,\n {\n id: value.id,\n role: value.role,\n content: value.content[0].text.value,\n },\n ]);\n break;\n }\n\n case \"assistant_control_data\": {\n setThreadId(value.threadId);\n\n // set id of last message:\n setMessages((messages) => {\n const lastMessage = messages[messages.length - 1];\n lastMessage.id = value.messageId;\n return [...messages.slice(0, messages.length - 1), lastMessage];\n });\n\n break;\n }\n\n case \"error\": {\n setError(value);\n break;\n }\n }\n } catch (error) {\n setError(error);\n }\n });\n\n setStatus(\"awaiting_message\");\n };\n\n return {\n messages,\n input,\n handleInputChange,\n submitMessage,\n status,\n error,\n };\n}\n\nexport function defaultSystemMessage(contextString: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\n`;\n}\n","export async function processMessageStream(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n processMessage: (message: string) => void | Promise<void>,\n) {\n const decoder = new TextDecoder();\n let buffer = \"\";\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n if (buffer.length > 0) {\n processMessage(buffer);\n }\n break;\n }\n\n buffer += decoder.decode(value, { stream: true });\n\n let endIndex: number;\n while ((endIndex = buffer.indexOf(\"\\n\")) !== -1) {\n processMessage(buffer.substring(0, endIndex).trim());\n buffer = buffer.substring(endIndex + 1); // Remove the processed instruction + delimiter\n }\n }\n}\n","import { FunctionCallHandler, ToolDefinition } from \"@copilotkit/shared\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport React, { Ref } from \"react\";\nimport { TreeNodeId } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the chat API v2.\n */\n chatApiEndpointV2: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Additional body params to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'message': 'Hello, world!'\n * }\n * ```\n */\n body: Record<string, any>;\n\n /**\n * Backend only props that will be combined to body params to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n backendOnlyProps?: Record<string, any>;\n}\n\nexport type InChatRenderFunction = (props: ActionRenderProps<any>) => string | JSX.Element;\n\nexport interface CopilotContextParams {\n // function-calling\n entryPoints: Record<string, FrontendAction<any>>;\n setEntryPoint: (id: string, entryPoint: FrontendAction<any>) => void;\n removeEntryPoint: (id: string) => void;\n chatComponentsCache: React.RefObject<Record<string, InChatRenderFunction | string>>;\n getChatCompletionFunctionDescriptions: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => ToolDefinition[];\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n entryPoints: {},\n setEntryPoint: () => {},\n removeEntryPoint: () => {},\n getChatCompletionFunctionDescriptions: () => returnAndThrowInDebug([]),\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n chatComponentsCache: { current: {} },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n get chatApiEndpointV2(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n return React.useContext(CopilotContext);\n}\n\nfunction returnAndThrowInDebug<T>(value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n return value;\n}\n","import { Ref, useCallback, useRef, useState } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n InChatRenderFunction,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { DocumentPointer } from \"../../types\";\nimport { FunctionCallHandler, actionToChatCompletionFunction } from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { StandardCopilotApiConfig } from \"./standard-copilot-api-config\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { ToolDefinition } from \"@copilotkit/shared\";\n\n/**\n * The CopilotKit component.\n * This component provides the Copilot context to its children.\n * It can be configured either with a chat API endpoint or a CopilotApiConfig.\n *\n * NOTE: The backend can use OpenAI, or you can bring your own LLM.\n * For examples of the backend api implementation, see `examples/next-openai` usage (under `src/api/copilotkit`),\n * or read the documentation at https://docs.copilotkit.ai\n * In particular, Getting-Started > Quickstart-Backend: https://docs.copilotkit.ai/getting-started/quickstart-backend\n *\n * Example usage:\n * ```\n * <CopilotKit url=\"https://your.copilotkit.api\">\n * <App />\n * </CopilotKit>\n * ```\n *\n * or\n *\n * ```\n * const copilotApiConfig = new StandardCopilotApiConfig(\n * \"https://your.copilotkit.api/v1\",\n * \"https://your.copilotkit.api/v2\",\n * {},\n * {}\n * );\n *\n * // ...\n *\n * <CopilotKit chatApiConfig={copilotApiConfig}>\n * <App />\n * </CopilotKit>\n * ```\n *\n * @param props - The props for the component.\n * @returns The CopilotKit component.\n */\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n // Compute all the functions and properties that we need to pass\n // to the CopilotContext.\n\n const [entryPoints, setEntryPoints] = useState<Record<string, FrontendAction<any>>>({});\n const chatComponentsCache = useRef<Record<string, InChatRenderFunction | string>>({});\n const { addElement, removeElement, printTree } = useTree();\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n const setEntryPoint = useCallback((id: string, entryPoint: FrontendAction<any>) => {\n setEntryPoints((prevPoints) => {\n return {\n ...prevPoints,\n [id]: entryPoint,\n };\n });\n }, []);\n\n const removeEntryPoint = useCallback((id: string) => {\n setEntryPoints((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getChatCompletionFunctionDescriptions = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToChatCompletionFunctions(Object.values(customEntryPoints || entryPoints));\n },\n [entryPoints],\n );\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || entryPoints));\n },\n [entryPoints],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = new StandardCopilotApiConfig(\n props.url,\n `${props.url}/v2`,\n props.headers || {},\n {\n ...props.body,\n ...props.backendOnlyProps,\n },\n );\n\n return (\n <CopilotContext.Provider\n value={{\n entryPoints,\n chatComponentsCache,\n getChatCompletionFunctionDescriptions,\n getFunctionCallHandler,\n setEntryPoint,\n removeEntryPoint,\n getContextString,\n addContext,\n removeContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n }}\n >\n {children}\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToChatCompletionFunctions(actions: FrontendAction<any>[]): ToolDefinition[] {\n return actions.map(actionToChatCompletionFunction);\n}\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async (chatMessages, functionCall) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[functionCall.name || \"\"];\n if (action) {\n let functionCallArguments: Record<string, any>[] = [];\n if (functionCall.arguments) {\n functionCallArguments = JSON.parse(functionCall.arguments);\n }\n return await action.handler(functionCallArguments);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAA8C;;;ACA9C,SAAsB,qBACpB,QACA,gBACA;AAAA;AACA,UAAM,UAAU,IAAI,YAAY;AAChC,QAAI,SAAS;AACb,WAAO,MAAM;AACX,YAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAE1C,UAAI,MAAM;AACR,YAAI,OAAO,SAAS,GAAG;AACrB,yBAAe,MAAM;AAAA,QACvB;AACA;AAAA,MACF;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AAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWF;","names":["import_react","import_shared","React","import_react","messages","error"]}
|
|
1
|
+
{"version":3,"sources":["../../src/openai-assistants/index.ts","../../src/openai-assistants/hooks/use-copilot-chat-v2.ts","../../src/openai-assistants/utils/process-message-stream.ts","../../src/context/copilot-context.tsx","../../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["export * from \"./hooks\";\nexport * from \"./utils\";\n","import { useContext, useMemo, useState } from \"react\";\nimport { processMessageStream } from \"../utils\";\nimport { Message, parseStreamPart } from \"@copilotkit/shared\";\nimport { CopilotContext } from \"../../context\";\nimport { defaultCopilotContextCategories } from \"../../components\";\n\nexport type AssistantStatus = \"in_progress\" | \"awaiting_message\";\n\nexport interface RequestForwardingOptions {\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n /**\n * Extra body object to be sent with the API request.\n * @example\n * Send a `sessionId` to the API along with the messages.\n * ```js\n * useChat({\n * body: {\n * sessionId: '123',\n * }\n * })\n * ```\n */\n body?: object;\n}\nexport interface UseCopilotChatOptionsV2 extends RequestForwardingOptions {\n makeSystemMessage?: (contextString: string) => string;\n threadId?: string | undefined;\n}\n\nexport interface UseCopilotChatV2Result {\n messages: Message[];\n input: string;\n handleInputChange: (e: any) => void;\n submitMessage: (e: any) => Promise<void>;\n status: AssistantStatus;\n error: unknown;\n}\n\nexport function useCopilotChatV2(options: UseCopilotChatOptionsV2): UseCopilotChatV2Result {\n const {\n getContextString,\n getChatCompletionFunctionDescriptions,\n getFunctionCallHandler,\n copilotApiConfig,\n } = useContext(CopilotContext);\n\n const [messages, setMessages] = useState<Message[]>([]);\n const [input, setInput] = useState(\"\");\n const [threadId, setThreadId] = useState<string | undefined>(undefined);\n const [status, setStatus] = useState<AssistantStatus>(\"awaiting_message\");\n const [error, setError] = useState<unknown | undefined>(undefined);\n\n const systemMessage: Message = useMemo(() => {\n const systemMessageMaker = options.makeSystemMessage || defaultSystemMessage;\n const contextString = getContextString([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return {\n id: \"system\",\n content: systemMessageMaker(contextString),\n role: \"system\",\n };\n }, [getContextString, options.makeSystemMessage]);\n\n const handleInputChange = (e: any) => {\n setInput(e.target.value);\n };\n\n const submitMessage = async (e: any) => {\n e.preventDefault();\n\n if (input === \"\") {\n return;\n }\n\n setStatus(\"in_progress\");\n\n setMessages((messages) => [...messages, { id: \"\", role: \"user\", content: input }]);\n\n setInput(\"\");\n\n const apiUrl = copilotApiConfig.chatApiEndpointV2;\n\n const functions = getChatCompletionFunctionDescriptions();\n\n const result = await fetch(apiUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...copilotApiConfig.headers,\n ...options.headers,\n },\n body: JSON.stringify({\n // always use user-provided threadId when available:\n threadId: options.threadId ?? threadId ?? null,\n message: input,\n ...(functions.length > 0 && { functions: functions }),\n ...copilotApiConfig.body,\n ...options.body,\n }),\n });\n\n if (result.body == null) {\n throw new Error(\"The response body is empty.\");\n }\n\n await processMessageStream(result.body.getReader(), (message: string) => {\n try {\n const { type, value } = parseStreamPart(message);\n\n switch (type) {\n case \"assistant_message\": {\n // append message:\n setMessages((messages) => [\n ...messages,\n {\n id: value.id,\n role: value.role,\n content: value.content[0].text.value,\n },\n ]);\n break;\n }\n\n case \"assistant_control_data\": {\n setThreadId(value.threadId);\n\n // set id of last message:\n setMessages((messages) => {\n const lastMessage = messages[messages.length - 1];\n lastMessage.id = value.messageId;\n return [...messages.slice(0, messages.length - 1), lastMessage];\n });\n\n break;\n }\n\n case \"error\": {\n setError(value);\n break;\n }\n }\n } catch (error) {\n setError(error);\n }\n });\n\n setStatus(\"awaiting_message\");\n };\n\n return {\n messages,\n input,\n handleInputChange,\n submitMessage,\n status,\n error,\n };\n}\n\nexport function defaultSystemMessage(contextString: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\n`;\n}\n","export async function processMessageStream(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n processMessage: (message: string) => void | Promise<void>,\n) {\n const decoder = new TextDecoder();\n let buffer = \"\";\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n if (buffer.length > 0) {\n processMessage(buffer);\n }\n break;\n }\n\n buffer += decoder.decode(value, { stream: true });\n\n let endIndex: number;\n while ((endIndex = buffer.indexOf(\"\\n\")) !== -1) {\n processMessage(buffer.substring(0, endIndex).trim());\n buffer = buffer.substring(endIndex + 1); // Remove the processed instruction + delimiter\n }\n }\n}\n","import { FunctionCallHandler, Message, ToolDefinition } from \"@copilotkit/shared\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport React, { Ref } from \"react\";\nimport { TreeNodeId } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\n\nexport interface CopilotCloudConfig {\n apiKey: string;\n restrictToTopic?: {\n validTopics: string[];\n invalidTopics?: string[];\n };\n}\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the chat API v2.\n */\n chatApiEndpointV2: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Additional body params to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'message': 'Hello, world!'\n * }\n * ```\n */\n body: Record<string, any>;\n\n /**\n * Backend only props that will be combined to body params to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n backendOnlyProps?: Record<string, any>;\n}\n\nexport type InChatRenderFunction = (props: ActionRenderProps<any>) => string | JSX.Element;\n\nexport interface CopilotContextParams {\n // function-calling\n entryPoints: Record<string, FrontendAction<any>>;\n setEntryPoint: (id: string, entryPoint: FrontendAction<any>) => void;\n removeEntryPoint: (id: string) => void;\n chatComponentsCache: React.RefObject<Record<string, InChatRenderFunction | string>>;\n getChatCompletionFunctionDescriptions: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => ToolDefinition[];\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n entryPoints: {},\n setEntryPoint: () => {},\n removeEntryPoint: () => {},\n getChatCompletionFunctionDescriptions: () => returnAndThrowInDebug([]),\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n chatComponentsCache: { current: {} },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n messages: [],\n setMessages: () => returnAndThrowInDebug([]),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n get chatApiEndpointV2(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n return React.useContext(CopilotContext);\n}\n\nfunction returnAndThrowInDebug<T>(value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n return value;\n}\n","import { Ref, useCallback, useRef, useState } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n InChatRenderFunction,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { DocumentPointer } from \"../../types\";\nimport { FunctionCallHandler, Message, actionToChatCompletionFunction } from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { ToolDefinition } from \"@copilotkit/shared\";\n\n/**\n * The CopilotKit component.\n * This component provides the Copilot context to its children.\n * It can be configured either with a chat API endpoint or a CopilotApiConfig.\n *\n * NOTE: The backend can use OpenAI, or you can bring your own LLM.\n * For examples of the backend api implementation, see `examples/next-openai` usage (under `src/api/copilotkit`),\n * or read the documentation at https://docs.copilotkit.ai\n * In particular, Getting-Started > Quickstart-Backend: https://docs.copilotkit.ai/getting-started/quickstart-backend\n *\n * Example usage:\n * ```\n * <CopilotKit url=\"https://your.copilotkit.api\">\n * <App />\n * </CopilotKit>\n * ```\n *\n * @param props - The props for the component.\n * @returns The CopilotKit component.\n */\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n // Compute all the functions and properties that we need to pass\n // to the CopilotContext.\n\n const [entryPoints, setEntryPoints] = useState<Record<string, FrontendAction<any>>>({});\n const chatComponentsCache = useRef<Record<string, InChatRenderFunction | string>>({});\n const { addElement, removeElement, printTree } = useTree();\n const [messages, setMessages] = useState<Message[]>([]);\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n const setEntryPoint = useCallback((id: string, entryPoint: FrontendAction<any>) => {\n setEntryPoints((prevPoints) => {\n return {\n ...prevPoints,\n [id]: entryPoint,\n };\n });\n }, []);\n\n const removeEntryPoint = useCallback((id: string) => {\n setEntryPoints((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getChatCompletionFunctionDescriptions = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToChatCompletionFunctions(Object.values(customEntryPoints || entryPoints));\n },\n [entryPoints],\n );\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || entryPoints));\n },\n [entryPoints],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n if (!props.apiKey) {\n if (props.cloudRestrictToTopic) {\n throw new Error(\n \"To use the cloudRestrictToTopic feature, please sign up at https://copilotkit.ai and provide an apiKey.\",\n );\n }\n }\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = {\n ...(props.apiKey\n ? { cloud: { apiKey: props.apiKey, restrictToTopic: props.cloudRestrictToTopic } }\n : {}),\n chatApiEndpoint: props.url,\n chatApiEndpointV2: `${props.url}/v2`,\n headers: props.headers || {},\n body: {\n ...props.body,\n ...props.backendOnlyProps,\n },\n };\n\n return (\n <CopilotContext.Provider\n value={{\n entryPoints,\n chatComponentsCache,\n getChatCompletionFunctionDescriptions,\n getFunctionCallHandler,\n setEntryPoint,\n removeEntryPoint,\n getContextString,\n addContext,\n removeContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n messages,\n setMessages,\n }}\n >\n {children}\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToChatCompletionFunctions(actions: FrontendAction<any>[]): ToolDefinition[] {\n return actions.map(actionToChatCompletionFunction);\n}\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async (chatMessages, functionCall) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[functionCall.name || \"\"];\n if (action) {\n let functionCallArguments: Record<string, any>[] = [];\n if (functionCall.arguments) {\n functionCallArguments = JSON.parse(functionCall.arguments);\n }\n return await action.handler(functionCallArguments);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAA8C;;;ACA9C,SAAsB,qBACpB,QACA,gBACA;AAAA;AACA,UAAM,UAAU,IAAI,YAAY;AAChC,QAAI,SAAS;AACb,WAAO,MAAM;AACX,YAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAE1C,UAAI,MAAM;AACR,YAAI,OAAO,SAAS,GAAG;AACrB,yBAAe,MAAM;AAAA,QACvB;AACA;AAAA,MACF;AAEA,gBAAU,QAAQ,OAAO,OAAO,EAAE,QAAQ,KAAK,CAAC;AAEhD,UAAI;AACJ,cAAQ,WAAW,OAAO,QAAQ,IAAI,OAAO,IAAI;AAC/C,uBAAe,OAAO,UAAU,GAAG,QAAQ,EAAE,KAAK,CAAC;AACnD,iBAAS,OAAO,UAAU,WAAW,CAAC;AAAA,MACxC;AAAA,IACF;AAAA,EACF;AAAA;;;ADtBA,IAAAC,iBAAyC;;;AEAzC,mBAA2B;AAoG3B,IAAM,sBAA4C;AAAA,EAChD,aAAa,CAAC;AAAA,EACd,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,kBAAkB,MAAM;AAAA,EAAC;AAAA,EACzB,uCAAuC,MAAM,sBAAsB,CAAC,CAAC;AAAA,EACrE,wBAAwB,MAAM,sBAAsB,MAAY;AAAA,EAAC,EAAC;AAAA,EAClE,qBAAqB,EAAE,SAAS,CAAC,EAAE;AAAA,EACnC,kBAAkB,CAAC,WAA8B,eAC/C,sBAAsB,EAAE;AAAA,EAC1B,YAAY,MAAM;AAAA,EAClB,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,UAAU,CAAC;AAAA,EACX,aAAa,MA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ACF;AAAA,UAEA,KAAK,0BAA0B;AAC7B,wBAAY,MAAM,QAAQ;AAG1B,wBAAY,CAACA,cAAa;AACxB,oBAAM,cAAcA,UAASA,UAAS,SAAS,CAAC;AAChD,0BAAY,KAAK,MAAM;AACvB,qBAAO,CAAC,GAAGA,UAAS,MAAM,GAAGA,UAAS,SAAS,CAAC,GAAG,WAAW;AAAA,YAChE,CAAC;AAED;AAAA,UACF;AAAA,UAEA,KAAK,SAAS;AACZ,qBAAS,KAAK;AACd;AAAA,UACF;AAAA,QACF;AAAA,MACF,SAASC,QAAP;AACA,iBAASA,MAAK;AAAA,MAChB;AAAA,IACF,CAAC;AAED,cAAU,kBAAkB;AAAA,EAC9B;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,qBAAqB,eAA+B;AAClE,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAWF;","names":["import_react","import_shared","React","import_react","messages","error"]}
|
|
@@ -1,231 +1,20 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
return new Promise((resolve, reject) => {
|
|
19
|
-
var fulfilled = (value) => {
|
|
20
|
-
try {
|
|
21
|
-
step(generator.next(value));
|
|
22
|
-
} catch (e) {
|
|
23
|
-
reject(e);
|
|
24
|
-
}
|
|
25
|
-
};
|
|
26
|
-
var rejected = (value) => {
|
|
27
|
-
try {
|
|
28
|
-
step(generator.throw(value));
|
|
29
|
-
} catch (e) {
|
|
30
|
-
reject(e);
|
|
31
|
-
}
|
|
32
|
-
};
|
|
33
|
-
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
|
|
34
|
-
step((generator = generator.apply(__this, __arguments)).next());
|
|
35
|
-
});
|
|
36
|
-
};
|
|
37
|
-
|
|
38
|
-
// src/openai-assistants/hooks/use-copilot-chat-v2.ts
|
|
39
|
-
import { useContext, useMemo, useState as useState2 } from "react";
|
|
40
|
-
|
|
41
|
-
// src/openai-assistants/utils/process-message-stream.ts
|
|
42
|
-
function processMessageStream(reader, processMessage) {
|
|
43
|
-
return __async(this, null, function* () {
|
|
44
|
-
const decoder = new TextDecoder();
|
|
45
|
-
let buffer = "";
|
|
46
|
-
while (true) {
|
|
47
|
-
const { done, value } = yield reader.read();
|
|
48
|
-
if (done) {
|
|
49
|
-
if (buffer.length > 0) {
|
|
50
|
-
processMessage(buffer);
|
|
51
|
-
}
|
|
52
|
-
break;
|
|
53
|
-
}
|
|
54
|
-
buffer += decoder.decode(value, { stream: true });
|
|
55
|
-
let endIndex;
|
|
56
|
-
while ((endIndex = buffer.indexOf("\n")) !== -1) {
|
|
57
|
-
processMessage(buffer.substring(0, endIndex).trim());
|
|
58
|
-
buffer = buffer.substring(endIndex + 1);
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
});
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
// src/openai-assistants/hooks/use-copilot-chat-v2.ts
|
|
65
|
-
import { parseStreamPart } from "@copilotkit/shared";
|
|
66
|
-
|
|
67
|
-
// src/context/copilot-context.tsx
|
|
68
|
-
import React from "react";
|
|
69
|
-
var emptyCopilotContext = {
|
|
70
|
-
entryPoints: {},
|
|
71
|
-
setEntryPoint: () => {
|
|
72
|
-
},
|
|
73
|
-
removeEntryPoint: () => {
|
|
74
|
-
},
|
|
75
|
-
getChatCompletionFunctionDescriptions: () => returnAndThrowInDebug([]),
|
|
76
|
-
getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
|
|
77
|
-
})),
|
|
78
|
-
chatComponentsCache: { current: {} },
|
|
79
|
-
getContextString: (documents, categories) => returnAndThrowInDebug(""),
|
|
80
|
-
addContext: () => "",
|
|
81
|
-
removeContext: () => {
|
|
82
|
-
},
|
|
83
|
-
getDocumentsContext: (categories) => returnAndThrowInDebug([]),
|
|
84
|
-
addDocumentContext: () => returnAndThrowInDebug(""),
|
|
85
|
-
removeDocumentContext: () => {
|
|
86
|
-
},
|
|
87
|
-
copilotApiConfig: new class {
|
|
88
|
-
get chatApiEndpoint() {
|
|
89
|
-
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
|
|
90
|
-
}
|
|
91
|
-
get chatApiEndpointV2() {
|
|
92
|
-
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
|
|
93
|
-
}
|
|
94
|
-
get headers() {
|
|
95
|
-
return {};
|
|
96
|
-
}
|
|
97
|
-
get body() {
|
|
98
|
-
return {};
|
|
99
|
-
}
|
|
100
|
-
}()
|
|
101
|
-
};
|
|
102
|
-
var CopilotContext = React.createContext(emptyCopilotContext);
|
|
103
|
-
function returnAndThrowInDebug(value) {
|
|
104
|
-
throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
|
|
105
|
-
return value;
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
// src/components/copilot-provider/copilotkit.tsx
|
|
109
|
-
import { useCallback, useRef, useState } from "react";
|
|
110
|
-
import { actionToChatCompletionFunction } from "@copilotkit/shared";
|
|
111
|
-
import { jsx } from "react/jsx-runtime";
|
|
112
|
-
var defaultCopilotContextCategories = ["global"];
|
|
113
|
-
|
|
114
|
-
// src/openai-assistants/hooks/use-copilot-chat-v2.ts
|
|
115
|
-
function useCopilotChatV2(options) {
|
|
116
|
-
const {
|
|
117
|
-
getContextString,
|
|
118
|
-
getChatCompletionFunctionDescriptions,
|
|
119
|
-
getFunctionCallHandler,
|
|
120
|
-
copilotApiConfig
|
|
121
|
-
} = useContext(CopilotContext);
|
|
122
|
-
const [messages, setMessages] = useState2([]);
|
|
123
|
-
const [input, setInput] = useState2("");
|
|
124
|
-
const [threadId, setThreadId] = useState2(void 0);
|
|
125
|
-
const [status, setStatus] = useState2("awaiting_message");
|
|
126
|
-
const [error, setError] = useState2(void 0);
|
|
127
|
-
const systemMessage = useMemo(() => {
|
|
128
|
-
const systemMessageMaker = options.makeSystemMessage || defaultSystemMessage;
|
|
129
|
-
const contextString = getContextString([], defaultCopilotContextCategories);
|
|
130
|
-
return {
|
|
131
|
-
id: "system",
|
|
132
|
-
content: systemMessageMaker(contextString),
|
|
133
|
-
role: "system"
|
|
134
|
-
};
|
|
135
|
-
}, [getContextString, options.makeSystemMessage]);
|
|
136
|
-
const handleInputChange = (e) => {
|
|
137
|
-
setInput(e.target.value);
|
|
138
|
-
};
|
|
139
|
-
const submitMessage = (e) => __async(this, null, function* () {
|
|
140
|
-
var _a, _b;
|
|
141
|
-
e.preventDefault();
|
|
142
|
-
if (input === "") {
|
|
143
|
-
return;
|
|
144
|
-
}
|
|
145
|
-
setStatus("in_progress");
|
|
146
|
-
setMessages((messages2) => [...messages2, { id: "", role: "user", content: input }]);
|
|
147
|
-
setInput("");
|
|
148
|
-
const apiUrl = copilotApiConfig.chatApiEndpointV2;
|
|
149
|
-
const functions = getChatCompletionFunctionDescriptions();
|
|
150
|
-
const result = yield fetch(apiUrl, {
|
|
151
|
-
method: "POST",
|
|
152
|
-
headers: __spreadValues(__spreadValues({
|
|
153
|
-
"Content-Type": "application/json"
|
|
154
|
-
}, copilotApiConfig.headers), options.headers),
|
|
155
|
-
body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues({
|
|
156
|
-
// always use user-provided threadId when available:
|
|
157
|
-
threadId: (_b = (_a = options.threadId) != null ? _a : threadId) != null ? _b : null,
|
|
158
|
-
message: input
|
|
159
|
-
}, functions.length > 0 && { functions }), copilotApiConfig.body), options.body))
|
|
160
|
-
});
|
|
161
|
-
if (result.body == null) {
|
|
162
|
-
throw new Error("The response body is empty.");
|
|
163
|
-
}
|
|
164
|
-
yield processMessageStream(result.body.getReader(), (message) => {
|
|
165
|
-
try {
|
|
166
|
-
const { type, value } = parseStreamPart(message);
|
|
167
|
-
switch (type) {
|
|
168
|
-
case "assistant_message": {
|
|
169
|
-
setMessages((messages2) => [
|
|
170
|
-
...messages2,
|
|
171
|
-
{
|
|
172
|
-
id: value.id,
|
|
173
|
-
role: value.role,
|
|
174
|
-
content: value.content[0].text.value
|
|
175
|
-
}
|
|
176
|
-
]);
|
|
177
|
-
break;
|
|
178
|
-
}
|
|
179
|
-
case "assistant_control_data": {
|
|
180
|
-
setThreadId(value.threadId);
|
|
181
|
-
setMessages((messages2) => {
|
|
182
|
-
const lastMessage = messages2[messages2.length - 1];
|
|
183
|
-
lastMessage.id = value.messageId;
|
|
184
|
-
return [...messages2.slice(0, messages2.length - 1), lastMessage];
|
|
185
|
-
});
|
|
186
|
-
break;
|
|
187
|
-
}
|
|
188
|
-
case "error": {
|
|
189
|
-
setError(value);
|
|
190
|
-
break;
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
} catch (error2) {
|
|
194
|
-
setError(error2);
|
|
195
|
-
}
|
|
196
|
-
});
|
|
197
|
-
setStatus("awaiting_message");
|
|
198
|
-
});
|
|
199
|
-
return {
|
|
200
|
-
messages,
|
|
201
|
-
input,
|
|
202
|
-
handleInputChange,
|
|
203
|
-
submitMessage,
|
|
204
|
-
status,
|
|
205
|
-
error
|
|
206
|
-
};
|
|
207
|
-
}
|
|
208
|
-
function defaultSystemMessage(contextString) {
|
|
209
|
-
return `
|
|
210
|
-
Please act as an efficient, competent, conscientious, and industrious professional assistant.
|
|
211
|
-
|
|
212
|
-
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.
|
|
213
|
-
Always be polite and respectful, and prefer brevity over verbosity.
|
|
214
|
-
|
|
215
|
-
The user has provided you with the following context:
|
|
216
|
-
\`\`\`
|
|
217
|
-
${contextString}
|
|
218
|
-
\`\`\`
|
|
219
|
-
|
|
220
|
-
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.
|
|
221
|
-
|
|
222
|
-
Please assist them as best you can.
|
|
223
|
-
|
|
224
|
-
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.
|
|
225
|
-
|
|
226
|
-
If you would like to call a function, call it without saying anything else.
|
|
227
|
-
`;
|
|
228
|
-
}
|
|
1
|
+
import "../chunk-7GFKOIO7.mjs";
|
|
2
|
+
import "../chunk-BABVSMJR.mjs";
|
|
3
|
+
import {
|
|
4
|
+
useCopilotChatV2
|
|
5
|
+
} from "../chunk-PYBBWHNC.mjs";
|
|
6
|
+
import "../chunk-FRAKUJWH.mjs";
|
|
7
|
+
import {
|
|
8
|
+
processMessageStream
|
|
9
|
+
} from "../chunk-MZ5UN3BY.mjs";
|
|
10
|
+
import "../chunk-VNRDQJXW.mjs";
|
|
11
|
+
import "../chunk-JD7BAH7U.mjs";
|
|
12
|
+
import "../chunk-SPCZTZCY.mjs";
|
|
13
|
+
import "../chunk-KMTE4NLW.mjs";
|
|
14
|
+
import "../chunk-YULKJPY3.mjs";
|
|
15
|
+
import "../chunk-VUY2K2DI.mjs";
|
|
16
|
+
import "../chunk-GH7QK2AZ.mjs";
|
|
17
|
+
import "../chunk-MRXNTQOX.mjs";
|
|
229
18
|
export {
|
|
230
19
|
processMessageStream,
|
|
231
20
|
useCopilotChatV2
|