@copilotkit/react-core 0.37.0 → 0.38.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +187 -234
- package/CHANGELOG.md +12 -0
- package/dist/{chunk-HUKLBIUK.mjs → chunk-5CKW6KE7.mjs} +13 -22
- package/dist/chunk-5CKW6KE7.mjs.map +1 -0
- package/dist/{chunk-S5LWO5V3.mjs → chunk-7GPIOOXB.mjs} +2 -2
- package/dist/{chunk-LLU5URI5.mjs → chunk-DDHJCFFV.mjs} +18 -33
- package/dist/chunk-DDHJCFFV.mjs.map +1 -0
- package/dist/{chunk-SR4RW4CU.mjs → chunk-IQCLNCGL.mjs} +6 -6
- package/dist/chunk-IQCLNCGL.mjs.map +1 -0
- package/dist/{chunk-DY63PD22.mjs → chunk-K6EV2CNB.mjs} +4 -5
- package/dist/chunk-K6EV2CNB.mjs.map +1 -0
- package/dist/{chunk-NSUYO6TP.mjs → chunk-LZVHW3T3.mjs} +9 -9
- package/dist/chunk-LZVHW3T3.mjs.map +1 -0
- package/dist/{chunk-Z5FB4WBL.mjs → chunk-NY6QSOU7.mjs} +43 -40
- package/dist/chunk-NY6QSOU7.mjs.map +1 -0
- package/dist/chunk-PHMHNAYC.mjs +192 -0
- package/dist/chunk-PHMHNAYC.mjs.map +1 -0
- package/dist/{chunk-B244LK6F.mjs → chunk-QNJQKKD4.mjs} +2 -2
- package/dist/{chunk-4OIVQMEM.mjs → chunk-WU3I3G3G.mjs} +60 -42
- package/dist/chunk-WU3I3G3G.mjs.map +1 -0
- package/dist/chunk-YJLRG5U3.mjs +1 -0
- package/dist/{chunk-MNZXQ6UH.mjs → chunk-YM2JV2YQ.mjs} +2 -2
- package/dist/components/copilot-provider/copilotkit-props.d.ts +2 -2
- package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.js +18 -33
- package/dist/components/copilot-provider/copilotkit.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.mjs +2 -2
- package/dist/components/copilot-provider/index.js +18 -33
- package/dist/components/copilot-provider/index.js.map +1 -1
- package/dist/components/copilot-provider/index.mjs +2 -2
- package/dist/components/index.js +18 -33
- package/dist/components/index.js.map +1 -1
- package/dist/components/index.mjs +2 -2
- package/dist/context/copilot-context.d.ts +7 -18
- package/dist/context/copilot-context.js +3 -4
- package/dist/context/copilot-context.js.map +1 -1
- package/dist/context/copilot-context.mjs +1 -1
- package/dist/context/index.d.ts +1 -0
- package/dist/context/index.js +3 -4
- package/dist/context/index.js.map +1 -1
- package/dist/context/index.mjs +1 -1
- package/dist/hooks/index.d.ts +2 -1
- package/dist/hooks/index.js +140 -229
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +9 -10
- package/dist/hooks/use-chat.d.ts +25 -51
- package/dist/hooks/use-chat.js +109 -203
- package/dist/hooks/use-chat.js.map +1 -1
- package/dist/hooks/use-chat.mjs +1 -2
- package/dist/hooks/use-copilot-action.js +10 -11
- package/dist/hooks/use-copilot-action.js.map +1 -1
- package/dist/hooks/use-copilot-action.mjs +2 -2
- package/dist/hooks/use-copilot-chat.d.ts +1 -1
- package/dist/hooks/use-copilot-chat.js +123 -212
- package/dist/hooks/use-copilot-chat.js.map +1 -1
- package/dist/hooks/use-copilot-chat.mjs +4 -5
- package/dist/hooks/use-copilot-readable.js +3 -4
- package/dist/hooks/use-copilot-readable.js.map +1 -1
- package/dist/hooks/use-copilot-readable.mjs +2 -2
- package/dist/hooks/use-make-copilot-actionable.js +7 -8
- package/dist/hooks/use-make-copilot-actionable.js.map +1 -1
- package/dist/hooks/use-make-copilot-actionable.mjs +2 -2
- package/dist/hooks/use-make-copilot-document-readable.js +3 -4
- package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
- package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
- package/dist/hooks/use-make-copilot-readable.js +3 -4
- package/dist/hooks/use-make-copilot-readable.js.map +1 -1
- package/dist/hooks/use-make-copilot-readable.mjs +2 -2
- package/dist/index.d.ts +1 -3
- package/dist/index.js +239 -497
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +12 -31
- package/dist/lib/copilot-task.d.ts +1 -0
- package/dist/lib/copilot-task.js +34 -110
- package/dist/lib/copilot-task.js.map +1 -1
- package/dist/lib/copilot-task.mjs +3 -4
- package/dist/lib/index.d.ts +1 -0
- package/dist/lib/index.js +36 -110
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/index.mjs +3 -4
- package/dist/utils/extract.d.ts +1 -0
- package/dist/utils/extract.js +53 -109
- package/dist/utils/extract.js.map +1 -1
- package/dist/utils/extract.mjs +3 -4
- package/dist/utils/index.d.ts +1 -1
- package/dist/utils/index.js +56 -132
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/index.mjs +5 -13
- package/package.json +6 -5
- package/src/components/copilot-provider/copilotkit-props.tsx +2 -2
- package/src/components/copilot-provider/copilotkit.tsx +16 -37
- package/src/context/copilot-context.tsx +11 -30
- package/src/hooks/use-chat.ts +179 -208
- package/src/hooks/use-copilot-action.ts +7 -8
- package/src/hooks/use-copilot-chat.ts +9 -23
- package/src/hooks/use-make-copilot-actionable.ts +4 -4
- package/src/index.tsx +0 -1
- package/src/lib/copilot-task.ts +45 -42
- package/src/utils/extract.ts +64 -36
- package/src/utils/index.ts +0 -7
- package/dist/chunk-2EQGN5QK.mjs +0 -137
- package/dist/chunk-2EQGN5QK.mjs.map +0 -1
- package/dist/chunk-4OIVQMEM.mjs.map +0 -1
- package/dist/chunk-7GFKOIO7.mjs +0 -1
- package/dist/chunk-B2H3NC4E.mjs +0 -204
- package/dist/chunk-B2H3NC4E.mjs.map +0 -1
- package/dist/chunk-BABVSMJR.mjs +0 -1
- package/dist/chunk-BABVSMJR.mjs.map +0 -1
- package/dist/chunk-CYDWEPFL.mjs +0 -1
- package/dist/chunk-CYDWEPFL.mjs.map +0 -1
- package/dist/chunk-DY63PD22.mjs.map +0 -1
- package/dist/chunk-FRAKUJWH.mjs +0 -1
- package/dist/chunk-FRAKUJWH.mjs.map +0 -1
- package/dist/chunk-HUKLBIUK.mjs.map +0 -1
- package/dist/chunk-LLU5URI5.mjs.map +0 -1
- package/dist/chunk-MJKBCG4U.mjs +0 -91
- package/dist/chunk-MJKBCG4U.mjs.map +0 -1
- package/dist/chunk-NSUYO6TP.mjs.map +0 -1
- package/dist/chunk-SR4RW4CU.mjs.map +0 -1
- package/dist/chunk-Z5FB4WBL.mjs.map +0 -1
- package/dist/chunk-ZFS5SQUT.mjs +0 -31
- package/dist/chunk-ZFS5SQUT.mjs.map +0 -1
- package/dist/openai-assistants/hooks/index.d.ts +0 -2
- package/dist/openai-assistants/hooks/index.js +0 -277
- package/dist/openai-assistants/hooks/index.js.map +0 -1
- package/dist/openai-assistants/hooks/index.mjs +0 -18
- package/dist/openai-assistants/hooks/index.mjs.map +0 -1
- package/dist/openai-assistants/hooks/use-assistants.d.ts +0 -17
- package/dist/openai-assistants/hooks/use-assistants.js +0 -154
- package/dist/openai-assistants/hooks/use-assistants.js.map +0 -1
- package/dist/openai-assistants/hooks/use-assistants.mjs +0 -92
- package/dist/openai-assistants/hooks/use-assistants.mjs.map +0 -1
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.d.ts +0 -44
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.js +0 -277
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.js.map +0 -1
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs +0 -19
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs.map +0 -1
- package/dist/openai-assistants/index.d.ts +0 -3
- package/dist/openai-assistants/index.js +0 -279
- package/dist/openai-assistants/index.js.map +0 -1
- package/dist/openai-assistants/index.mjs +0 -22
- package/dist/openai-assistants/index.mjs.map +0 -1
- package/dist/openai-assistants/utils/index.d.ts +0 -1
- package/dist/openai-assistants/utils/index.js +0 -73
- package/dist/openai-assistants/utils/index.js.map +0 -1
- package/dist/openai-assistants/utils/index.mjs +0 -9
- package/dist/openai-assistants/utils/index.mjs.map +0 -1
- package/dist/openai-assistants/utils/process-message-stream.d.ts +0 -3
- package/dist/openai-assistants/utils/process-message-stream.js +0 -71
- package/dist/openai-assistants/utils/process-message-stream.js.map +0 -1
- package/dist/openai-assistants/utils/process-message-stream.mjs +0 -8
- package/dist/openai-assistants/utils/process-message-stream.mjs.map +0 -1
- package/dist/utils/fetch-chat-completion.d.ts +0 -36
- package/dist/utils/fetch-chat-completion.js +0 -141
- package/dist/utils/fetch-chat-completion.js.map +0 -1
- package/dist/utils/fetch-chat-completion.mjs +0 -12
- package/dist/utils/fetch-chat-completion.mjs.map +0 -1
- package/src/openai-assistants/hooks/index.ts +0 -9
- package/src/openai-assistants/hooks/use-assistants.ts +0 -112
- package/src/openai-assistants/hooks/use-copilot-chat-v2.ts +0 -189
- package/src/openai-assistants/index.ts +0 -2
- package/src/openai-assistants/utils/index.ts +0 -1
- package/src/openai-assistants/utils/process-message-stream.ts +0 -25
- package/src/utils/fetch-chat-completion.ts +0 -120
- /package/dist/{chunk-S5LWO5V3.mjs.map → chunk-7GPIOOXB.mjs.map} +0 -0
- /package/dist/{chunk-B244LK6F.mjs.map → chunk-QNJQKKD4.mjs.map} +0 -0
- /package/dist/{chunk-7GFKOIO7.mjs.map → chunk-YJLRG5U3.mjs.map} +0 -0
- /package/dist/{chunk-MNZXQ6UH.mjs.map → chunk-YM2JV2YQ.mjs.map} +0 -0
|
@@ -88,17 +88,16 @@ var import_react4 = require("react");
|
|
|
88
88
|
// src/context/copilot-context.tsx
|
|
89
89
|
var import_react = __toESM(require("react"));
|
|
90
90
|
var emptyCopilotContext = {
|
|
91
|
-
|
|
92
|
-
|
|
91
|
+
actions: {},
|
|
92
|
+
setAction: () => {
|
|
93
93
|
},
|
|
94
|
-
|
|
94
|
+
removeAction: () => {
|
|
95
95
|
},
|
|
96
96
|
chatComponentsCache: { current: {} },
|
|
97
97
|
getContextString: (documents, categories) => returnAndThrowInDebug(""),
|
|
98
98
|
addContext: () => "",
|
|
99
99
|
removeContext: () => {
|
|
100
100
|
},
|
|
101
|
-
getChatCompletionFunctionDescriptions: () => returnAndThrowInDebug([]),
|
|
102
101
|
getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
|
|
103
102
|
})),
|
|
104
103
|
messages: [],
|
|
@@ -137,228 +136,150 @@ function returnAndThrowInDebug(value) {
|
|
|
137
136
|
return value;
|
|
138
137
|
}
|
|
139
138
|
|
|
139
|
+
// src/hooks/use-copilot-chat.ts
|
|
140
|
+
var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
|
|
141
|
+
|
|
140
142
|
// src/hooks/use-chat.ts
|
|
141
143
|
var import_react2 = require("react");
|
|
142
|
-
var import_shared2 = require("@copilotkit/shared");
|
|
143
|
-
var import_nanoid = require("nanoid");
|
|
144
|
-
|
|
145
|
-
// src/utils/fetch-chat-completion.ts
|
|
146
144
|
var import_shared = require("@copilotkit/shared");
|
|
147
|
-
|
|
148
|
-
return __async(this, arguments, function* ({
|
|
149
|
-
copilotConfig,
|
|
150
|
-
model,
|
|
151
|
-
messages,
|
|
152
|
-
tools,
|
|
153
|
-
temperature,
|
|
154
|
-
headers,
|
|
155
|
-
body,
|
|
156
|
-
signal,
|
|
157
|
-
toolChoice
|
|
158
|
-
}) {
|
|
159
|
-
temperature || (temperature = 0.5);
|
|
160
|
-
tools || (tools = []);
|
|
161
|
-
const cleanedMessages = messages.map((message) => {
|
|
162
|
-
const { content, role, name, function_call } = message;
|
|
163
|
-
return { content, role, name, function_call };
|
|
164
|
-
});
|
|
165
|
-
toolChoice || (toolChoice = "auto");
|
|
166
|
-
const response = yield fetch(copilotConfig.chatApiEndpoint, {
|
|
167
|
-
method: "POST",
|
|
168
|
-
headers: __spreadValues(__spreadValues({
|
|
169
|
-
"Content-Type": "application/json"
|
|
170
|
-
}, copilotConfig.headers), headers ? __spreadValues({}, headers) : {}),
|
|
171
|
-
body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
|
|
172
|
-
model,
|
|
173
|
-
messages: cleanedMessages,
|
|
174
|
-
stream: true
|
|
175
|
-
}, tools.length ? { tools } : {}), temperature ? { temperature } : {}), tools.length != 0 ? { tool_choice: toolChoice } : {}), copilotConfig.body), copilotConfig.backendOnlyProps), excludeBackendOnlyProps(copilotConfig)), body ? __spreadValues({}, body) : {}), copilotConfig.cloud ? { cloud: copilotConfig.cloud } : {})),
|
|
176
|
-
signal,
|
|
177
|
-
credentials: copilotConfig.credentials
|
|
178
|
-
});
|
|
179
|
-
return response;
|
|
180
|
-
});
|
|
181
|
-
}
|
|
182
|
-
function excludeBackendOnlyProps(copilotConfig) {
|
|
183
|
-
var _a;
|
|
184
|
-
const backendOnlyProps = (_a = copilotConfig.backendOnlyProps) != null ? _a : {};
|
|
185
|
-
if (Object.keys(backendOnlyProps).length > 0) {
|
|
186
|
-
return {
|
|
187
|
-
[import_shared.EXCLUDE_FROM_FORWARD_PROPS_KEYS]: Object.keys(backendOnlyProps)
|
|
188
|
-
};
|
|
189
|
-
} else {
|
|
190
|
-
return {};
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
function fetchAndDecodeChatCompletion(params) {
|
|
194
|
-
return __async(this, null, function* () {
|
|
195
|
-
const response = yield fetchChatCompletion(params);
|
|
196
|
-
if (!response.ok || !response.body) {
|
|
197
|
-
response.events = null;
|
|
198
|
-
} else {
|
|
199
|
-
const events = yield (0, import_shared.decodeChatCompletion)((0, import_shared.parseChatCompletion)(response.body));
|
|
200
|
-
response.events = events;
|
|
201
|
-
}
|
|
202
|
-
return response;
|
|
203
|
-
});
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
// src/hooks/use-chat.ts
|
|
207
|
-
var import_untruncate_json = __toESM(require("untruncate-json"));
|
|
145
|
+
var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
|
|
208
146
|
function useChat(options) {
|
|
209
|
-
const {
|
|
147
|
+
const {
|
|
148
|
+
messages,
|
|
149
|
+
setMessages,
|
|
150
|
+
makeSystemMessageCallback,
|
|
151
|
+
copilotConfig,
|
|
152
|
+
setIsLoading,
|
|
153
|
+
initialMessages,
|
|
154
|
+
isLoading,
|
|
155
|
+
actions,
|
|
156
|
+
onFunctionCall
|
|
157
|
+
} = options;
|
|
210
158
|
const abortControllerRef = (0, import_react2.useRef)();
|
|
211
159
|
const threadIdRef = (0, import_react2.useRef)(null);
|
|
212
160
|
const runIdRef = (0, import_react2.useRef)(null);
|
|
213
|
-
const publicApiKey =
|
|
214
|
-
const headers = __spreadValues(__spreadValues({},
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
161
|
+
const publicApiKey = copilotConfig.publicApiKey;
|
|
162
|
+
const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [import_shared.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
|
|
163
|
+
const runtimeClient = new import_runtime_client_gql.CopilotRuntimeClient({
|
|
164
|
+
url: copilotConfig.chatApiEndpoint,
|
|
165
|
+
publicApiKey: copilotConfig.publicApiKey,
|
|
166
|
+
headers
|
|
167
|
+
});
|
|
168
|
+
const runChatCompletion = (previousMessages) => __async(this, null, function* () {
|
|
169
|
+
var _a, _b, _c, _d, _e, _f;
|
|
170
|
+
setIsLoading(true);
|
|
171
|
+
let newMessages = [
|
|
172
|
+
new import_runtime_client_gql.TextMessage({
|
|
221
173
|
content: "",
|
|
222
|
-
role:
|
|
223
|
-
}
|
|
174
|
+
role: import_runtime_client_gql.Role.Assistant
|
|
175
|
+
})
|
|
224
176
|
];
|
|
225
177
|
const abortController = new AbortController();
|
|
226
178
|
abortControllerRef.current = abortController;
|
|
227
|
-
setMessages([...
|
|
228
|
-
const copilotConfigBody = options.copilotConfig.body || {};
|
|
229
|
-
if (threadIdRef.current) {
|
|
230
|
-
copilotConfigBody.threadId = threadIdRef.current;
|
|
231
|
-
}
|
|
232
|
-
if (runIdRef.current) {
|
|
233
|
-
copilotConfigBody.runId = runIdRef.current;
|
|
234
|
-
}
|
|
179
|
+
setMessages([...previousMessages, ...newMessages]);
|
|
235
180
|
const systemMessage = makeSystemMessageCallback();
|
|
236
|
-
const messagesWithContext = [systemMessage, ...
|
|
237
|
-
const
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
181
|
+
const messagesWithContext = [systemMessage, ...initialMessages || [], ...previousMessages];
|
|
182
|
+
const stream = import_runtime_client_gql.CopilotRuntimeClient.asStream(
|
|
183
|
+
runtimeClient.generateCopilotResponse(
|
|
184
|
+
__spreadValues({
|
|
185
|
+
frontend: {
|
|
186
|
+
actions: actions.map((action) => ({
|
|
187
|
+
name: action.name,
|
|
188
|
+
description: action.description || "",
|
|
189
|
+
jsonSchema: JSON.stringify((0, import_shared.actionParametersToJsonSchema)(action.parameters || []))
|
|
190
|
+
}))
|
|
191
|
+
},
|
|
192
|
+
threadId: threadIdRef.current,
|
|
193
|
+
runId: runIdRef.current,
|
|
194
|
+
messages: (0, import_runtime_client_gql.convertMessagesToGqlInput)(messagesWithContext)
|
|
195
|
+
}, copilotConfig.cloud ? {
|
|
196
|
+
cloud: {
|
|
197
|
+
guardrails: {
|
|
198
|
+
inputValidationRules: {
|
|
199
|
+
allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,
|
|
200
|
+
denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
} : {}),
|
|
205
|
+
copilotConfig.properties,
|
|
206
|
+
(_a = abortControllerRef.current) == null ? void 0 : _a.signal
|
|
207
|
+
)
|
|
208
|
+
);
|
|
209
|
+
const guardrailsEnabled = ((_d = (_c = (_b = copilotConfig.cloud) == null ? void 0 : _b.guardrails) == null ? void 0 : _c.input) == null ? void 0 : _d.restrictToTopic.enabled) || false;
|
|
210
|
+
const reader = stream.getReader();
|
|
211
|
+
let results = {};
|
|
265
212
|
try {
|
|
266
213
|
while (true) {
|
|
267
214
|
const { done, value } = yield reader.read();
|
|
268
215
|
if (done) {
|
|
269
216
|
break;
|
|
270
217
|
}
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
};
|
|
303
|
-
newMessages.push(currentMessage);
|
|
304
|
-
}
|
|
305
|
-
if (value.type === "function") {
|
|
306
|
-
currentMessage.function_call = {
|
|
307
|
-
name: value.name,
|
|
308
|
-
arguments: JSON.stringify(value.arguments),
|
|
309
|
-
scope: value.scope
|
|
310
|
-
};
|
|
311
|
-
} else if (value.type === "partial") {
|
|
312
|
-
let partialArguments = {};
|
|
313
|
-
try {
|
|
314
|
-
partialArguments = JSON.parse((0, import_untruncate_json.default)(value.arguments));
|
|
315
|
-
} catch (e) {
|
|
316
|
-
}
|
|
317
|
-
currentMessage.partialFunctionCall = {
|
|
318
|
-
name: value.name,
|
|
319
|
-
arguments: partialArguments
|
|
320
|
-
};
|
|
321
|
-
}
|
|
322
|
-
newMessages[newMessages.length - 1] = currentMessage;
|
|
323
|
-
setMessages([...messages2, ...newMessages]);
|
|
324
|
-
if (value.type === "function") {
|
|
325
|
-
try {
|
|
326
|
-
if (options.onFunctionCall && value.scope === "client") {
|
|
327
|
-
const result = yield options.onFunctionCall(
|
|
328
|
-
messages2,
|
|
329
|
-
currentMessage.function_call
|
|
330
|
-
);
|
|
331
|
-
currentMessage = {
|
|
332
|
-
id: (0, import_nanoid.nanoid)(),
|
|
333
|
-
role: "function",
|
|
334
|
-
content: (0, import_shared2.encodeResult)(result),
|
|
335
|
-
name: currentMessage.function_call.name
|
|
336
|
-
};
|
|
337
|
-
newMessages.push(currentMessage);
|
|
338
|
-
setMessages([...messages2, ...newMessages]);
|
|
339
|
-
feedback = true;
|
|
218
|
+
if (!(value == null ? void 0 : value.generateCopilotResponse)) {
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
threadIdRef.current = value.generateCopilotResponse.threadId || null;
|
|
222
|
+
runIdRef.current = value.generateCopilotResponse.runId || null;
|
|
223
|
+
const messages2 = (0, import_runtime_client_gql.convertGqlOutputToMessages)(value.generateCopilotResponse.messages);
|
|
224
|
+
if (messages2.length === 0) {
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
newMessages = [];
|
|
228
|
+
if (((_e = value.generateCopilotResponse.status) == null ? void 0 : _e.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
|
|
229
|
+
newMessages = [
|
|
230
|
+
new import_runtime_client_gql.TextMessage({
|
|
231
|
+
role: import_runtime_client_gql.MessageRole.Assistant,
|
|
232
|
+
content: ((_f = value.generateCopilotResponse.status.details) == null ? void 0 : _f.guardrailsReason) || ""
|
|
233
|
+
})
|
|
234
|
+
];
|
|
235
|
+
} else {
|
|
236
|
+
for (const message of messages2) {
|
|
237
|
+
newMessages.push(message);
|
|
238
|
+
if (message instanceof import_runtime_client_gql.ActionExecutionMessage && message.status.code !== import_runtime_client_gql.MessageStatusCode.Pending && message.scope === "client" && onFunctionCall) {
|
|
239
|
+
if (!(message.id in results)) {
|
|
240
|
+
if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
|
|
241
|
+
break;
|
|
242
|
+
}
|
|
243
|
+
const result = yield onFunctionCall({
|
|
244
|
+
messages: previousMessages,
|
|
245
|
+
name: message.name,
|
|
246
|
+
args: message.arguments
|
|
247
|
+
});
|
|
248
|
+
results[message.id] = result;
|
|
340
249
|
}
|
|
341
|
-
|
|
342
|
-
|
|
250
|
+
newMessages.push(
|
|
251
|
+
new import_runtime_client_gql.ResultMessage({
|
|
252
|
+
result: import_runtime_client_gql.ResultMessage.encodeResult(results[message.id]),
|
|
253
|
+
actionExecutionId: message.id,
|
|
254
|
+
actionName: message.name
|
|
255
|
+
})
|
|
256
|
+
);
|
|
343
257
|
}
|
|
344
258
|
}
|
|
345
259
|
}
|
|
260
|
+
if (newMessages.length > 0) {
|
|
261
|
+
setMessages([...previousMessages, ...newMessages]);
|
|
262
|
+
}
|
|
346
263
|
}
|
|
347
|
-
if (
|
|
264
|
+
if (
|
|
265
|
+
// if we have client side results
|
|
266
|
+
Object.values(results).length || // or the last message we received is a result
|
|
267
|
+
newMessages.length && newMessages[newMessages.length - 1] instanceof import_runtime_client_gql.ResultMessage
|
|
268
|
+
) {
|
|
348
269
|
yield new Promise((resolve) => setTimeout(resolve, 10));
|
|
349
|
-
return yield runChatCompletion([...
|
|
270
|
+
return yield runChatCompletion([...previousMessages, ...newMessages]);
|
|
350
271
|
} else {
|
|
351
272
|
return newMessages.slice();
|
|
352
273
|
}
|
|
353
274
|
} finally {
|
|
354
|
-
|
|
275
|
+
setIsLoading(false);
|
|
355
276
|
}
|
|
356
277
|
});
|
|
357
278
|
const runChatCompletionAndHandleFunctionCall = (messages2) => __async(this, null, function* () {
|
|
358
279
|
yield runChatCompletion(messages2);
|
|
359
280
|
});
|
|
360
281
|
const append = (message) => __async(this, null, function* () {
|
|
361
|
-
if (
|
|
282
|
+
if (isLoading) {
|
|
362
283
|
return;
|
|
363
284
|
}
|
|
364
285
|
const newMessages = [...messages, message];
|
|
@@ -366,12 +287,12 @@ function useChat(options) {
|
|
|
366
287
|
return runChatCompletionAndHandleFunctionCall(newMessages);
|
|
367
288
|
});
|
|
368
289
|
const reload = () => __async(this, null, function* () {
|
|
369
|
-
if (
|
|
290
|
+
if (isLoading || messages.length === 0) {
|
|
370
291
|
return;
|
|
371
292
|
}
|
|
372
293
|
let newMessages = [...messages];
|
|
373
294
|
const lastMessage = messages[messages.length - 1];
|
|
374
|
-
if (lastMessage.role === "assistant") {
|
|
295
|
+
if (lastMessage instanceof import_runtime_client_gql.TextMessage && lastMessage.role === "assistant") {
|
|
375
296
|
newMessages = newMessages.slice(0, -1);
|
|
376
297
|
}
|
|
377
298
|
setMessages(newMessages);
|
|
@@ -390,7 +311,7 @@ function useChat(options) {
|
|
|
390
311
|
|
|
391
312
|
// src/components/copilot-provider/copilotkit.tsx
|
|
392
313
|
var import_react3 = require("react");
|
|
393
|
-
var
|
|
314
|
+
var import_shared2 = require("@copilotkit/shared");
|
|
394
315
|
var import_jsx_runtime = require("react/jsx-runtime");
|
|
395
316
|
var defaultCopilotContextCategories = ["global"];
|
|
396
317
|
|
|
@@ -403,14 +324,14 @@ function useCopilotChat(_a = {}) {
|
|
|
403
324
|
]);
|
|
404
325
|
const {
|
|
405
326
|
getContextString,
|
|
406
|
-
getChatCompletionFunctionDescriptions,
|
|
407
327
|
getFunctionCallHandler,
|
|
408
328
|
copilotApiConfig,
|
|
409
329
|
messages,
|
|
410
330
|
setMessages,
|
|
411
331
|
isLoading,
|
|
412
332
|
setIsLoading,
|
|
413
|
-
chatInstructions
|
|
333
|
+
chatInstructions,
|
|
334
|
+
actions
|
|
414
335
|
} = (0, import_react4.useContext)(CopilotContext);
|
|
415
336
|
const latestGetContextString = useUpdatedRef(getContextString);
|
|
416
337
|
const deleteMessage = (0, import_react4.useCallback)(
|
|
@@ -422,34 +343,24 @@ function useCopilotChat(_a = {}) {
|
|
|
422
343
|
const makeSystemMessageCallback = (0, import_react4.useCallback)(() => {
|
|
423
344
|
const systemMessageMaker = makeSystemMessage || defaultSystemMessage;
|
|
424
345
|
const contextString = latestGetContextString.current([], defaultCopilotContextCategories);
|
|
425
|
-
return {
|
|
426
|
-
id: "system",
|
|
346
|
+
return new import_runtime_client_gql2.TextMessage({
|
|
427
347
|
content: systemMessageMaker(contextString, chatInstructions),
|
|
428
|
-
role:
|
|
429
|
-
};
|
|
348
|
+
role: import_runtime_client_gql2.Role.System
|
|
349
|
+
});
|
|
430
350
|
}, [getContextString, makeSystemMessage, chatInstructions]);
|
|
431
|
-
const functionDescriptions = (0, import_react4.useMemo)(() => {
|
|
432
|
-
return getChatCompletionFunctionDescriptions();
|
|
433
|
-
}, [getChatCompletionFunctionDescriptions]);
|
|
434
351
|
const { append, reload, stop } = useChat(__spreadProps(__spreadValues({}, options), {
|
|
352
|
+
actions: Object.values(actions),
|
|
435
353
|
copilotConfig: copilotApiConfig,
|
|
436
|
-
id: options.id,
|
|
437
354
|
initialMessages: options.initialMessages || [],
|
|
438
|
-
tools: functionDescriptions,
|
|
439
355
|
onFunctionCall: getFunctionCallHandler(),
|
|
440
|
-
headers: __spreadValues({}, options.headers),
|
|
441
|
-
body: __spreadValues({}, options.body),
|
|
442
356
|
messages,
|
|
443
357
|
setMessages,
|
|
444
358
|
makeSystemMessageCallback,
|
|
445
359
|
isLoading,
|
|
446
360
|
setIsLoading
|
|
447
361
|
}));
|
|
448
|
-
const visibleMessages = messages.filter(
|
|
449
|
-
(message) => message.role === "user" || message.role === "assistant" || message.role === "function"
|
|
450
|
-
);
|
|
451
362
|
return {
|
|
452
|
-
visibleMessages,
|
|
363
|
+
visibleMessages: messages,
|
|
453
364
|
appendMessage: append,
|
|
454
365
|
setMessages,
|
|
455
366
|
reloadMessages: reload,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hooks/use-copilot-chat.ts","../../src/context/copilot-context.tsx","../../src/hooks/use-chat.ts","../../src/utils/fetch-chat-completion.ts","../../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["/**\n * A hook for accessing Copilot's chat API.\n *\n * `useCopilotChat` is a React hook that lets you directly interact with the\n * Copilot instance. Use to implement a fully custom UI (headless UI) or to\n * programmatically interact with the Copilot instance managed by the default\n * UI.\n *\n * <RequestExample>\n * ```jsx useCopilotChat Example\n * import { useCopilotChat }\n * from \"@copilotkit/react-core\";\n *\n * const { appendMessage } = useCopilotChat();\n * appendMessage({ content: \"Hello, world!\", role: \"user\", id: \"1\" });\n * ```\n * </RequestExample>\n *\n * useCopilotChat returns an object with the following properties:\n * - `visibleMessages`: An array of messages that are currently visible in the chat.\n * - `appendMessage`: A function to append a message to the chat.\n * - `setMessages`: A function to set the messages in the chat.\n * - `deleteMessage`: A function to delete a message from the chat.\n * - `reloadMessages`: A function to reload the messages from the API.\n * - `stopGeneration`: A function to stop the generation of the next message.\n * - `isLoading`: A boolean indicating if the chat is loading.\n *\n */\nimport { useMemo, useContext, useRef, useEffect, useCallback } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { Message, ToolDefinition } from \"@copilotkit/shared\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useChat } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\n\nexport interface UseCopilotChatOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * Extra body object to be sent with the API request.\n * @example\n * Send a `sessionId` to the API along with the messages.\n * ```js\n * useChat({\n * body: {\n * sessionId: '123',\n * }\n * })\n * ```\n */\n body?: object;\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n}\n\nexport interface UseCopilotChatReturn {\n visibleMessages: Message[];\n appendMessage: (message: Message) => Promise<void>;\n setMessages: (messages: Message[]) => void;\n deleteMessage: (messageId: string) => void;\n reloadMessages: () => Promise<void>;\n stopGeneration: () => void;\n isLoading: boolean;\n}\n\nexport function useCopilotChat({\n makeSystemMessage,\n ...options\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const {\n getContextString,\n getChatCompletionFunctionDescriptions,\n getFunctionCallHandler,\n copilotApiConfig,\n messages,\n setMessages,\n isLoading,\n setIsLoading,\n chatInstructions,\n } = useContext(CopilotContext);\n\n // We need to ensure that makeSystemMessageCallback always uses the latest\n // useCopilotReadable data.\n const latestGetContextString = useUpdatedRef(getContextString);\n const deleteMessage = useCallback(\n (messageId: string) => {\n setMessages((prev) => prev.filter((message) => message.id !== messageId));\n },\n [setMessages],\n );\n\n const makeSystemMessageCallback = useCallback(() => {\n const systemMessageMaker = makeSystemMessage || defaultSystemMessage;\n // this always gets the latest context string\n const contextString = latestGetContextString.current([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return {\n id: \"system\",\n content: systemMessageMaker(contextString, chatInstructions),\n role: \"system\",\n } as Message;\n }, [getContextString, makeSystemMessage, chatInstructions]);\n\n const functionDescriptions: ToolDefinition[] = useMemo(() => {\n return getChatCompletionFunctionDescriptions();\n }, [getChatCompletionFunctionDescriptions]);\n\n const { append, reload, stop } = useChat({\n ...options,\n copilotConfig: copilotApiConfig,\n id: options.id,\n initialMessages: options.initialMessages || [],\n tools: functionDescriptions,\n onFunctionCall: getFunctionCallHandler(),\n headers: { ...options.headers },\n body: {\n ...options.body,\n },\n messages,\n setMessages,\n makeSystemMessageCallback,\n isLoading,\n setIsLoading,\n });\n\n const visibleMessages = messages.filter(\n (message) =>\n message.role === \"user\" || message.role === \"assistant\" || message.role === \"function\",\n );\n\n return {\n visibleMessages,\n appendMessage: append,\n setMessages,\n reloadMessages: reload,\n stopGeneration: stop,\n deleteMessage,\n isLoading,\n };\n}\n\n// store `value` in a ref and update\n// it whenever it changes.\nfunction useUpdatedRef<T>(value: T) {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref;\n}\n\nexport function defaultSystemMessage(\n contextString: string,\n additionalInstructions?: string,\n): string {\n return (\n `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n","import {\n CopilotCloudConfig,\n FunctionCallHandler,\n Message,\n ToolDefinition,\n} from \"@copilotkit/shared\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * The endpoint for the chat API v2.\n */\n chatApiEndpointV2: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Additional body params to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'message': 'Hello, world!'\n * }\n * ```\n */\n body: Record<string, any>;\n\n /**\n * Backend only props that will be combined to body params to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n backendOnlyProps?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n}\n\nexport type InChatRenderFunction = (props: ActionRenderProps<any>) => string | JSX.Element;\n\nexport interface CopilotContextParams {\n // function-calling\n entryPoints: Record<string, FrontendAction<any>>;\n setEntryPoint: (id: string, entryPoint: FrontendAction<any>) => void;\n removeEntryPoint: (id: string) => void;\n chatComponentsCache: React.RefObject<Record<string, InChatRenderFunction | string>>;\n getChatCompletionFunctionDescriptions: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => ToolDefinition[];\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n // chat\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n entryPoints: {},\n setEntryPoint: () => {},\n removeEntryPoint: () => {},\n\n chatComponentsCache: { current: {} },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n\n getChatCompletionFunctionDescriptions: () => returnAndThrowInDebug([]),\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n messages: [],\n setMessages: () => returnAndThrowInDebug([]),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n get chatApiEndpointV2(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n return React.useContext(CopilotContext);\n}\n\nfunction returnAndThrowInDebug<T>(value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n return value;\n}\n","import { useRef, useState, useContext, useEffect } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport {\n Message,\n ToolDefinition,\n FunctionCallHandler,\n encodeResult,\n FunctionCall,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n} from \"@copilotkit/shared\";\n\nimport { nanoid } from \"nanoid\";\nimport { fetchAndDecodeChatCompletion } from \"../utils/fetch-chat-completion\";\nimport { CopilotApiConfig } from \"../context\";\nimport untruncateJson from \"untruncate-json\";\n\nexport type UseChatOptions = {\n /**\n * The API endpoint that accepts a `{ messages: Message[] }` object and returns\n * a stream of tokens of the AI chat response. Defaults to `/api/chat`.\n */\n api?: string;\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n /**\n * Callback function to be called when a function call is received.\n * If the function returns a `ChatRequest` object, the request will be sent\n * automatically to the API and will be used to update the chat.\n */\n onFunctionCall?: FunctionCallHandler;\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n /**\n * Extra body object to be sent with the API request.\n * @example\n * Send a `sessionId` to the API along with the messages.\n * ```js\n * useChat({\n * body: {\n * sessionId: '123',\n * }\n * })\n * ```\n */\n body?: object;\n /**\n * Function definitions to be sent to the API.\n */\n tools?: ToolDefinition[];\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: () => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n};\n\nexport type UseChatOptionsWithCopilotConfig = UseChatOptions & {\n copilotConfig: CopilotApiConfig;\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * A callback to get the latest system message.\n */\n makeSystemMessageCallback: () => Message;\n\n /**\n * Whether the API request is in progress\n */\n isLoading: boolean;\n\n /**\n * setState-powered method to update the isChatLoading value\n */\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n};\n\nexport function useChat(options: UseChatOptionsWithCopilotConfig): UseChatHelpers {\n const { messages, setMessages, makeSystemMessageCallback } = options;\n const abortControllerRef = useRef<AbortController>();\n const threadIdRef = useRef<string | null>(null);\n const runIdRef = useRef<string | null>(null);\n const publicApiKey = options.copilotConfig.publicApiKey;\n const headers = {\n ...(options.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const runChatCompletion = async (messages: Message[]): Promise<Message[]> => {\n options.setIsLoading(true);\n\n const newMessages: Message[] = [\n {\n id: nanoid(),\n createdAt: new Date(),\n content: \"\",\n role: \"assistant\",\n },\n ];\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setMessages([...messages, ...newMessages]);\n // add threadId and runId to the body if it exists\n const copilotConfigBody = options.copilotConfig.body || {};\n if (threadIdRef.current) {\n copilotConfigBody.threadId = threadIdRef.current;\n }\n if (runIdRef.current) {\n copilotConfigBody.runId = runIdRef.current;\n }\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(options.initialMessages || []), ...messages];\n const response = await fetchAndDecodeChatCompletion({\n copilotConfig: { ...options.copilotConfig, body: copilotConfigBody },\n messages: messagesWithContext,\n tools: options.tools,\n headers: headers,\n signal: abortController.signal,\n });\n\n if (response.headers.get(\"threadid\")) {\n threadIdRef.current = response.headers.get(\"threadid\");\n }\n\n if (response.headers.get(\"runid\")) {\n runIdRef.current = response.headers.get(\"runid\");\n }\n\n if (!response.events) {\n setMessages([\n ...messages,\n {\n id: nanoid(),\n createdAt: new Date(),\n content: response.statusText,\n role: \"assistant\",\n },\n ]);\n options.setIsLoading(false);\n throw new Error(\"Failed to fetch chat completion\");\n }\n\n const reader = response.events.getReader();\n\n // Whether to feed back the new messages to GPT\n let feedback = false;\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n let currentMessage = Object.assign({}, newMessages[newMessages.length - 1]);\n\n if (value.type === \"content\") {\n if (currentMessage.function_call || currentMessage.role === \"function\") {\n // Create a new message if the previous one is a function call or result\n currentMessage = {\n id: nanoid(),\n createdAt: new Date(),\n content: \"\",\n role: \"assistant\",\n };\n newMessages.push(currentMessage);\n }\n currentMessage.content += value.content;\n newMessages[newMessages.length - 1] = currentMessage;\n setMessages([...messages, ...newMessages]);\n } else if (value.type === \"result\") {\n // When we get a result message, it is already complete\n currentMessage = {\n id: nanoid(),\n role: \"function\",\n content: value.content,\n name: value.name,\n };\n newMessages.push(currentMessage);\n setMessages([...messages, ...newMessages]);\n\n // After receiving a result, feed back the new messages to GPT\n feedback = true;\n } else if (value.type === \"function\" || value.type === \"partial\") {\n // Create a new message if the previous one is not empty\n if (\n currentMessage.content != \"\" ||\n currentMessage.function_call ||\n currentMessage.role == \"function\"\n ) {\n currentMessage = {\n id: nanoid(),\n createdAt: new Date(),\n content: \"\",\n role: \"assistant\",\n };\n newMessages.push(currentMessage);\n }\n if (value.type === \"function\") {\n currentMessage.function_call = {\n name: value.name,\n arguments: JSON.stringify(value.arguments),\n scope: value.scope,\n };\n } else if (value.type === \"partial\") {\n let partialArguments: any = {};\n try {\n partialArguments = JSON.parse(untruncateJson(value.arguments));\n } catch (e) {}\n\n currentMessage.partialFunctionCall = {\n name: value.name,\n arguments: partialArguments,\n };\n }\n\n newMessages[newMessages.length - 1] = currentMessage;\n setMessages([...messages, ...newMessages]);\n\n if (value.type === \"function\") {\n // Execute the function call\n try {\n if (options.onFunctionCall && value.scope === \"client\") {\n const result = await options.onFunctionCall(\n messages,\n currentMessage.function_call as FunctionCall,\n );\n\n currentMessage = {\n id: nanoid(),\n role: \"function\",\n content: encodeResult(result),\n name: (currentMessage.function_call! as FunctionCall).name!,\n };\n newMessages.push(currentMessage);\n setMessages([...messages, ...newMessages]);\n\n // After a function call, feed back the new messages to GPT\n feedback = true;\n }\n } catch (error) {\n console.error(\"Failed to execute function call\", error);\n // TODO: Handle error\n // this should go to the message itself\n }\n }\n }\n }\n\n // If we want feedback, run the completion again and return the results\n if (feedback) {\n // wait for next tick to make sure all the react state updates\n // TODO: This is a hack, is there a more robust way to do this?\n // - tried using react-dom's flushSync, but it did not work\n await new Promise((resolve) => setTimeout(resolve, 10));\n\n return await runChatCompletion([...messages, ...newMessages]);\n }\n // otherwise, return the new messages\n else {\n return newMessages.slice();\n }\n } finally {\n options.setIsLoading(false);\n }\n };\n\n const runChatCompletionAndHandleFunctionCall = async (messages: Message[]): Promise<void> => {\n await runChatCompletion(messages);\n };\n\n const append = async (message: Message): Promise<void> => {\n if (options.isLoading) {\n return;\n }\n const newMessages = [...messages, message];\n setMessages(newMessages);\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const reload = async (): Promise<void> => {\n if (options.isLoading || messages.length === 0) {\n return;\n }\n let newMessages = [...messages];\n const lastMessage = messages[messages.length - 1];\n\n if (lastMessage.role === \"assistant\") {\n newMessages = newMessages.slice(0, -1);\n }\n setMessages(newMessages);\n\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const stop = (): void => {\n abortControllerRef.current?.abort();\n };\n\n return {\n append,\n reload,\n stop,\n };\n}\n","import {\n Message,\n ToolDefinition,\n ChatCompletionEvent,\n decodeChatCompletion,\n parseChatCompletion,\n decodeChatCompletionAsText,\n EXCLUDE_FROM_FORWARD_PROPS_KEYS,\n} from \"@copilotkit/shared\";\nimport { CopilotApiConfig } from \"../context\";\n\nexport interface FetchChatCompletionParams {\n copilotConfig: CopilotApiConfig;\n model?: string;\n messages: Message[];\n tools?: ToolDefinition[];\n temperature?: number;\n maxTokens?: number;\n headers?: Record<string, string> | Headers;\n body?: object;\n signal?: AbortSignal;\n toolChoice?: string | { type: \"function\"; function: { name: string } };\n}\n\nexport async function fetchChatCompletion({\n copilotConfig,\n model,\n messages,\n tools,\n temperature,\n headers,\n body,\n signal,\n toolChoice,\n}: FetchChatCompletionParams): Promise<Response> {\n temperature ||= 0.5;\n tools ||= [];\n\n // clean up any extra properties from messages\n const cleanedMessages = messages.map((message) => {\n const { content, role, name, function_call } = message;\n return { content, role, name, function_call };\n });\n\n toolChoice ||= \"auto\";\n\n const response = await fetch(copilotConfig.chatApiEndpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...copilotConfig.headers,\n ...(headers ? { ...headers } : {}),\n },\n body: JSON.stringify({\n model,\n messages: cleanedMessages,\n stream: true,\n ...(tools.length ? { tools } : {}),\n ...(temperature ? { temperature } : {}),\n ...(tools.length != 0 ? { tool_choice: toolChoice } : {}),\n ...copilotConfig.body,\n ...copilotConfig.backendOnlyProps,\n ...excludeBackendOnlyProps(copilotConfig),\n ...(body ? { ...body } : {}),\n ...(copilotConfig.cloud ? { cloud: copilotConfig.cloud } : {}),\n }),\n signal,\n credentials: copilotConfig.credentials,\n });\n\n return response;\n}\n\nfunction excludeBackendOnlyProps(copilotConfig: any) {\n const backendOnlyProps = copilotConfig.backendOnlyProps ?? {};\n if (Object.keys(backendOnlyProps).length > 0) {\n return {\n [EXCLUDE_FROM_FORWARD_PROPS_KEYS]: Object.keys(backendOnlyProps),\n };\n } else {\n return {};\n }\n}\n\nexport interface DecodedChatCompletionResponse extends Response {\n events: ReadableStream<ChatCompletionEvent> | null;\n}\n\nexport async function fetchAndDecodeChatCompletion(\n params: FetchChatCompletionParams,\n): Promise<DecodedChatCompletionResponse> {\n const response = await fetchChatCompletion(params);\n if (!response.ok || !response.body) {\n (response as any).events = null;\n } else {\n const events = await decodeChatCompletion(parseChatCompletion(response.body));\n (response as any).events = events;\n }\n return response as any;\n}\n\nexport interface DecodedChatCompletionResponseAsText extends Response {\n events: ReadableStream<string> | null;\n}\n\nexport async function fetchAndDecodeChatCompletionAsText(\n params: FetchChatCompletionParams,\n): Promise<DecodedChatCompletionResponseAsText> {\n const response = await fetchChatCompletion(params);\n if (!response.ok || !response.body) {\n (response as any).events = null;\n } else {\n const events = await decodeChatCompletionAsText(\n decodeChatCompletion(parseChatCompletion(response.body)),\n );\n (response as any).events = events;\n }\n\n return response as any;\n}\n","/**\n * Provides the Copilot context to its children.\n * \n * <img\n * referrerPolicy=\"no-referrer-when-downgrade\"\n * src=\"https://static.scarf.sh/a.png?x-pxid=a9b290bb-38f9-4518-ac3b-8f54fdbf43be\"\n * />\n * \n * This component provides the Copilot context to its children.\n * It can be configured either with a chat API endpoint or a `CopilotApiConfig`.\n * \n * <Note>\n * The backend can use OpenAI, or you can bring your own LLM. For examples of the\n * backend api implementation, see `examples/next-openai` or the [runtime\n * docs](https://docs.copilotkit.ai/getting-started/quickstart-runtime).\n * </Note>\n * \n * <RequestExample>\n * ```jsx CopilotKit Example\n * import { CopilotKit } from \"@copilotkit/react-core\";\n * \n * <CopilotKit \n * runtimeUrl=\"https://your.copilotkit.api\">\n * <YourApp/>\n * </CopilotKit>\n * ```\n * </RequestExample>\n * \n * ## Example usage\n * \n * ```jsx\n * <CopilotKit publicApiKey=\"the api key or self host (see below)\">\n * <App />\n * </CopilotKit>\n```\n */\nimport { Ref, useCallback, useRef, useState } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n InChatRenderFunction,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { CopilotChatSuggestionConfiguration, DocumentPointer } from \"../../types\";\n\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n Message,\n actionToChatCompletionFunction,\n} from \"@copilotkit/shared\";\n\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { ToolDefinition } from \"@copilotkit/shared\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n // Compute all the functions and properties that we need to pass\n // to the CopilotContext.\n\n if (!props.runtimeUrl && !props.url && !props.publicApiKey) {\n throw new Error(\"Please provide either a url or a publicApiKey to the CopilotKit component.\");\n }\n\n const chatApiEndpoint = props.runtimeUrl || props.url || COPILOT_CLOUD_CHAT_URL;\n\n const [entryPoints, setEntryPoints] = useState<Record<string, FrontendAction<any>>>({});\n const chatComponentsCache = useRef<Record<string, InChatRenderFunction | string>>({});\n const { addElement, removeElement, printTree } = useTree();\n const [messages, setMessages] = useState<Message[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n const setEntryPoint = useCallback((id: string, entryPoint: FrontendAction<any>) => {\n setEntryPoints((prevPoints) => {\n return {\n ...prevPoints,\n [id]: entryPoint,\n };\n });\n }, []);\n\n const removeEntryPoint = useCallback((id: string) => {\n setEntryPoints((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getChatCompletionFunctionDescriptions = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToChatCompletionFunctions(Object.values(customEntryPoints || entryPoints));\n },\n [entryPoints],\n );\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || entryPoints));\n },\n [entryPoints],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n if (!props.publicApiKey) {\n if (props.cloudRestrictToTopic) {\n throw new Error(\n \"To use the cloudRestrictToTopic feature, please sign up at https://copilotkit.ai and provide a publicApiKey.\",\n );\n }\n }\n\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (props.publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: props.cloudRestrictToTopic ? true : false,\n validTopics: props.cloudRestrictToTopic?.validTopics || [],\n invalidTopics: props.cloudRestrictToTopic?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = {\n publicApiKey: props.publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n chatApiEndpointV2: `${props.url}/v2`,\n headers: props.headers || {},\n body: {\n ...props.body,\n ...props.backendOnlyProps,\n },\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n };\n\n const removeChatSuggestionConfiguration = (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n };\n\n return (\n <CopilotContext.Provider\n value={{\n entryPoints,\n chatComponentsCache,\n getChatCompletionFunctionDescriptions,\n getFunctionCallHandler,\n setEntryPoint,\n removeEntryPoint,\n getContextString,\n addContext,\n removeContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n messages,\n setMessages,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n }}\n >\n {children}\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToChatCompletionFunctions(actions: FrontendAction<any>[]): ToolDefinition[] {\n return actions.map(actionToChatCompletionFunction);\n}\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async (chatMessages, functionCall) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[functionCall.name || \"\"];\n if (action) {\n let functionCallArguments: Record<string, any>[] = [];\n if (functionCall.arguments) {\n functionCallArguments = JSON.parse(functionCall.arguments);\n }\n return await action.handler(functionCallArguments);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA4BA,IAAAA,gBAAoE;;;ACrBpE,mBAAkB;AAgIlB,IAAM,sBAA4C;AAAA,EAChD,aAAa,CAAC;AAAA,EACd,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,kBAAkB,MAAM;AAAA,EAAC;AAAA,EAEzB,qBAAqB,EAAE,SAAS,CAAC,EAAE;AAAA,EACnC,kBAAkB,CAAC,WAA8B,eAC/C,sBAAsB,EAAE;AAAA,EAC1B,YAAY,MAAM;AAAA,EA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e;AAAA,IACf;AAAA,IACA,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB;AAAA,IACA;AAAA,EACF;AACF;AAIA,SAAS,cAAiB,OAAU;AAClC,QAAM,UAAM,sBAAO,KAAK;AAExB,+BAAU,MAAM;AACd,QAAI,UAAU;AAAA,EAChB,GAAG,CAAC,KAAK,CAAC;AAEV,SAAO;AACT;AAEO,SAAS,qBACd,eACA,wBACQ;AACR,SACE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAUG,yBAAyB;AAAA;AAAA,EAAO,2BAA2B;AAEhE;","names":["import_react","React","import_react","import_shared","messages","untruncateJson","import_react","import_shared"]}
|
|
1
|
+
{"version":3,"sources":["../../src/hooks/use-copilot-chat.ts","../../src/context/copilot-context.tsx","../../src/hooks/use-chat.ts","../../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["/**\n * A hook for accessing Copilot's chat API.\n *\n * `useCopilotChat` is a React hook that lets you directly interact with the\n * Copilot instance. Use to implement a fully custom UI (headless UI) or to\n * programmatically interact with the Copilot instance managed by the default\n * UI.\n *\n * <RequestExample>\n * ```jsx useCopilotChat Example\n * import { useCopilotChat }\n * from \"@copilotkit/react-core\";\n *\n * const { appendMessage } = useCopilotChat();\n * appendMessage({ content: \"Hello, world!\", role: \"user\", id: \"1\" });\n * ```\n * </RequestExample>\n *\n * useCopilotChat returns an object with the following properties:\n * - `visibleMessages`: An array of messages that are currently visible in the chat.\n * - `appendMessage`: A function to append a message to the chat.\n * - `setMessages`: A function to set the messages in the chat.\n * - `deleteMessage`: A function to delete a message from the chat.\n * - `reloadMessages`: A function to reload the messages from the API.\n * - `stopGeneration`: A function to stop the generation of the next message.\n * - `isLoading`: A boolean indicating if the chat is loading.\n *\n */\nimport { useContext, useRef, useEffect, useCallback } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { Message, Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useChat } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { MessageStatusCode } from \"@copilotkit/runtime-client-gql\";\n\nexport interface UseCopilotChatOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * Extra body object to be sent with the API request.\n * @example\n * Send a `sessionId` to the API along with the messages.\n * ```js\n * useChat({\n * body: {\n * sessionId: '123',\n * }\n * })\n * ```\n */\n body?: object;\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n}\n\nexport interface UseCopilotChatReturn {\n visibleMessages: Message[];\n appendMessage: (message: Message) => Promise<void>;\n setMessages: (messages: Message[]) => void;\n deleteMessage: (messageId: string) => void;\n reloadMessages: () => Promise<void>;\n stopGeneration: () => void;\n isLoading: boolean;\n}\n\nexport function useCopilotChat({\n makeSystemMessage,\n ...options\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const {\n getContextString,\n getFunctionCallHandler,\n copilotApiConfig,\n messages,\n setMessages,\n isLoading,\n setIsLoading,\n chatInstructions,\n actions,\n } = useContext(CopilotContext);\n\n // We need to ensure that makeSystemMessageCallback always uses the latest\n // useCopilotReadable data.\n const latestGetContextString = useUpdatedRef(getContextString);\n const deleteMessage = useCallback(\n (messageId: string) => {\n setMessages((prev) => prev.filter((message) => message.id !== messageId));\n },\n [setMessages],\n );\n\n const makeSystemMessageCallback = useCallback(() => {\n const systemMessageMaker = makeSystemMessage || defaultSystemMessage;\n // this always gets the latest context string\n const contextString = latestGetContextString.current([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return new TextMessage({\n content: systemMessageMaker(contextString, chatInstructions),\n role: Role.System,\n });\n }, [getContextString, makeSystemMessage, chatInstructions]);\n\n const { append, reload, stop } = useChat({\n ...options,\n actions: Object.values(actions),\n copilotConfig: copilotApiConfig,\n initialMessages: options.initialMessages || [],\n onFunctionCall: getFunctionCallHandler(),\n messages,\n setMessages,\n makeSystemMessageCallback,\n isLoading,\n setIsLoading,\n });\n\n return {\n visibleMessages: messages,\n appendMessage: append,\n setMessages,\n reloadMessages: reload,\n stopGeneration: stop,\n deleteMessage,\n isLoading,\n };\n}\n\n// store `value` in a ref and update\n// it whenever it changes.\nfunction useUpdatedRef<T>(value: T) {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref;\n}\n\nexport function defaultSystemMessage(\n contextString: string,\n additionalInstructions?: string,\n): string {\n return (\n `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n","import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\nimport { Message } from \"@copilotkit/runtime-client-gql\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * The endpoint for the chat API v2.\n */\n chatApiEndpointV2: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Custom properties to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n properties?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n}\n\nexport type InChatRenderFunction = (props: ActionRenderProps<any>) => string | JSX.Element;\n\nexport interface CopilotContextParams {\n // function-calling\n actions: Record<string, FrontendAction<any>>;\n setAction: (id: string, action: FrontendAction<any>) => void;\n removeAction: (id: string) => void;\n chatComponentsCache: React.RefObject<Record<string, InChatRenderFunction | string>>;\n\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n // chat\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n chatComponentsCache: { current: {} },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n messages: [],\n setMessages: () => returnAndThrowInDebug([]),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n get chatApiEndpointV2(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n return React.useContext(CopilotContext);\n}\n\nfunction returnAndThrowInDebug<T>(value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n return value;\n}\n","import { useRef } from \"react\";\nimport {\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n Action,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport {\n Message,\n TextMessage,\n ActionExecutionMessage,\n ResultMessage,\n CopilotRuntimeClient,\n convertMessagesToGqlInput,\n convertGqlOutputToMessages,\n MessageStatusCode,\n MessageRole,\n Role,\n} from \"@copilotkit/runtime-client-gql\";\n\nimport { CopilotApiConfig } from \"../context\";\n\nexport type UseChatOptions = {\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n /**\n * Callback function to be called when a function call is received.\n * If the function returns a `ChatRequest` object, the request will be sent\n * automatically to the API and will be used to update the chat.\n */\n onFunctionCall?: FunctionCallHandler;\n /**\n * Function definitions to be sent to the API.\n */\n actions: Action[];\n\n /**\n * The CopilotKit API configuration.\n */\n copilotConfig: CopilotApiConfig;\n\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * A callback to get the latest system message.\n */\n makeSystemMessageCallback: () => TextMessage;\n\n /**\n * Whether the API request is in progress\n */\n isLoading: boolean;\n\n /**\n * setState-powered method to update the isChatLoading value\n */\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: () => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n};\n\nexport function useChat(options: UseChatOptions): UseChatHelpers {\n const {\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n } = options;\n const abortControllerRef = useRef<AbortController>();\n const threadIdRef = useRef<string | null>(null);\n const runIdRef = useRef<string | null>(null);\n const publicApiKey = copilotConfig.publicApiKey;\n const headers = {\n ...(copilotConfig.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const runtimeClient = new CopilotRuntimeClient({\n url: copilotConfig.chatApiEndpoint,\n publicApiKey: copilotConfig.publicApiKey,\n headers,\n });\n\n const runChatCompletion = async (previousMessages: Message[]): Promise<Message[]> => {\n setIsLoading(true);\n\n // this message is just a placeholder. It will disappear once the first real message\n // is received\n let newMessages: Message[] = [\n new TextMessage({\n content: \"\",\n role: Role.Assistant,\n }),\n ];\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setMessages([...previousMessages, ...newMessages]);\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(initialMessages || []), ...previousMessages];\n\n const stream = CopilotRuntimeClient.asStream(\n runtimeClient.generateCopilotResponse(\n {\n frontend: {\n actions: actions.map((action) => ({\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n })),\n },\n threadId: threadIdRef.current,\n runId: runIdRef.current,\n messages: convertMessagesToGqlInput(messagesWithContext),\n ...(copilotConfig.cloud\n ? {\n cloud: {\n guardrails: {\n inputValidationRules: {\n allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,\n denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics,\n },\n },\n },\n }\n : {}),\n },\n copilotConfig.properties,\n abortControllerRef.current?.signal,\n ),\n );\n\n const guardrailsEnabled =\n copilotConfig.cloud?.guardrails?.input?.restrictToTopic.enabled || false;\n\n const reader = stream.getReader();\n\n let results: { [id: string]: string } = {};\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (!value?.generateCopilotResponse) {\n continue;\n }\n\n threadIdRef.current = value.generateCopilotResponse.threadId || null;\n runIdRef.current = value.generateCopilotResponse.runId || null;\n\n const messages = convertGqlOutputToMessages(value.generateCopilotResponse.messages);\n\n if (messages.length === 0) {\n continue;\n }\n\n newMessages = [];\n\n // request failed, display error message\n if (\n value.generateCopilotResponse.status?.__typename === \"FailedResponseStatus\" &&\n value.generateCopilotResponse.status.reason === \"GUARDRAILS_VALIDATION_FAILED\"\n ) {\n newMessages = [\n new TextMessage({\n role: MessageRole.Assistant,\n content: value.generateCopilotResponse.status.details?.guardrailsReason || \"\",\n }),\n ];\n }\n\n // add messages to the chat\n else {\n for (const message of messages) {\n newMessages.push(message);\n\n if (\n message instanceof ActionExecutionMessage &&\n message.status.code !== MessageStatusCode.Pending &&\n message.scope === \"client\" &&\n onFunctionCall\n ) {\n if (!(message.id in results)) {\n // Do not execute a function call if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute action\n const result = await onFunctionCall({\n messages: previousMessages,\n name: message.name,\n args: message.arguments,\n });\n results[message.id] = result;\n }\n\n // add the result message\n newMessages.push(\n new ResultMessage({\n result: ResultMessage.encodeResult(results[message.id]),\n actionExecutionId: message.id,\n actionName: message.name,\n }),\n );\n }\n }\n }\n\n if (newMessages.length > 0) {\n setMessages([...previousMessages, ...newMessages]);\n }\n }\n\n if (\n // if we have client side results\n Object.values(results).length ||\n // or the last message we received is a result\n (newMessages.length && newMessages[newMessages.length - 1] instanceof ResultMessage)\n ) {\n // run the completion again and return the result\n\n // wait for next tick to make sure all the react state updates\n // - tried using react-dom's flushSync, but it did not work\n await new Promise((resolve) => setTimeout(resolve, 10));\n\n return await runChatCompletion([...previousMessages, ...newMessages]);\n } else {\n return newMessages.slice();\n }\n } finally {\n setIsLoading(false);\n }\n };\n\n const runChatCompletionAndHandleFunctionCall = async (messages: Message[]): Promise<void> => {\n await runChatCompletion(messages);\n };\n\n const append = async (message: Message): Promise<void> => {\n if (isLoading) {\n return;\n }\n const newMessages = [...messages, message];\n setMessages(newMessages);\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const reload = async (): Promise<void> => {\n if (isLoading || messages.length === 0) {\n return;\n }\n let newMessages = [...messages];\n const lastMessage = messages[messages.length - 1];\n\n if (lastMessage instanceof TextMessage && lastMessage.role === \"assistant\") {\n newMessages = newMessages.slice(0, -1);\n }\n\n setMessages(newMessages);\n\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const stop = (): void => {\n abortControllerRef.current?.abort();\n };\n\n return {\n append,\n reload,\n stop,\n };\n}\n","/**\n * Provides the Copilot context to its children.\n * \n * <img\n * referrerPolicy=\"no-referrer-when-downgrade\"\n * src=\"https://static.scarf.sh/a.png?x-pxid=a9b290bb-38f9-4518-ac3b-8f54fdbf43be\"\n * />\n * \n * This component provides the Copilot context to its children.\n * It can be configured either with a chat API endpoint or a `CopilotApiConfig`.\n * \n * <Note>\n * The backend can use OpenAI, or you can bring your own LLM. For examples of the\n * backend api implementation, see `examples/next-openai` or the [runtime\n * docs](https://docs.copilotkit.ai/getting-started/quickstart-runtime).\n * </Note>\n * \n * <RequestExample>\n * ```jsx CopilotKit Example\n * import { CopilotKit } from \"@copilotkit/react-core\";\n * \n * <CopilotKit \n * runtimeUrl=\"https://your.copilotkit.api\">\n * <YourApp/>\n * </CopilotKit>\n * ```\n * </RequestExample>\n * \n * ## Example usage\n * \n * ```jsx\n * <CopilotKit publicApiKey=\"the api key or self host (see below)\">\n * <App />\n * </CopilotKit>\n```\n */\nimport { Ref, useCallback, useRef, useState } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n InChatRenderFunction,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { CopilotChatSuggestionConfiguration, DocumentPointer } from \"../../types\";\n\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n} from \"@copilotkit/shared\";\nimport { Message } from \"@copilotkit/runtime-client-gql\";\n\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\n\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n // Compute all the functions and properties that we need to pass\n // to the CopilotContext.\n\n if (!props.runtimeUrl && !props.url && !props.publicApiKey) {\n throw new Error(\"Please provide either a url or a publicApiKey to the CopilotKit component.\");\n }\n\n const chatApiEndpoint = props.runtimeUrl || props.url || COPILOT_CLOUD_CHAT_URL;\n\n const [actions, setActions] = useState<Record<string, FrontendAction<any>>>({});\n const chatComponentsCache = useRef<Record<string, InChatRenderFunction | string>>({});\n const { addElement, removeElement, printTree } = useTree();\n const [messages, setMessages] = useState<Message[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [chatInstructions, setChatInstructions] = useState(\"\");\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n const setAction = useCallback((id: string, action: FrontendAction<any>) => {\n setActions((prevPoints) => {\n return {\n ...prevPoints,\n [id]: action,\n };\n });\n }, []);\n\n const removeAction = useCallback((id: string) => {\n setActions((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 getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));\n },\n [actions],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n if (!props.publicApiKey) {\n if (props.cloudRestrictToTopic) {\n throw new Error(\n \"To use the cloudRestrictToTopic feature, please sign up at https://copilotkit.ai and provide a publicApiKey.\",\n );\n }\n }\n\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (props.publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: props.cloudRestrictToTopic ? true : false,\n validTopics: props.cloudRestrictToTopic?.validTopics || [],\n invalidTopics: props.cloudRestrictToTopic?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = {\n publicApiKey: props.publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n chatApiEndpointV2: `${props.url}/v2`,\n headers: props.headers || {},\n properties: props.properties || {},\n transcribeAudioUrl: props.transcribeAudioUrl,\n textToSpeechUrl: props.textToSpeechUrl,\n credentials: props.credentials,\n };\n\n const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = useState<{\n [key: string]: CopilotChatSuggestionConfiguration;\n }>({});\n\n const addChatSuggestionConfiguration = (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => {\n setChatSuggestionConfiguration((prev) => ({ ...prev, [id]: suggestion }));\n };\n\n const removeChatSuggestionConfiguration = (id: string) => {\n setChatSuggestionConfiguration((prev) => {\n const { [id]: _, ...rest } = prev;\n return rest;\n });\n };\n\n return (\n <CopilotContext.Provider\n value={{\n actions,\n chatComponentsCache,\n getFunctionCallHandler,\n setAction,\n removeAction,\n getContextString,\n addContext,\n removeContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n messages,\n setMessages,\n isLoading,\n setIsLoading,\n chatSuggestionConfiguration,\n addChatSuggestionConfiguration,\n removeChatSuggestionConfiguration,\n chatInstructions,\n setChatInstructions,\n }}\n >\n {children}\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async ({ messages, name, args }) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[name];\n if (action) {\n return await action.handler(args);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA4BA,IAAAA,gBAA2D;;;ACzB3D,mBAAkB;AAkHlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,qBAAqB,EAAE,SAAS,CAAC,EAAE;AAAA,EACnC,kBAAkB,CAAC,WAA8B,eAC/C,sBAAsB,EAAE;AAAA,EAC1B,YAAY,MAAM;AAAA,EAClB,eAAe,MAAM;AAAA,EAAC;AAAA,EAEtB,wBAAwB,MAAM,sBAAsB,MAAY;AAAA,EAAC,EAAC;AAAA,EAElE,UAAU,CAAC;AAAA,EACX,aAAa,MAAM,sBAAsB,CAAC,CAAC;AAAA,EAE3C,WAAW;AAAA,EACX,cAAc,MAAM,sBAAsB,KAAK;AAAA,EAE/C,kBAAkB;AAAA,EAClB,qBAAqB,MAAM,sBAAsB,EAAE;AAAA,EAEnD,qBAAqB,CAAC,eAAyB,sBAAsB,CAAC,CAAC;AAAA,E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AAEV,SAAO;AACT;AAEO,SAAS,qBACd,eACA,wBACQ;AACR,SACE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAUG,yBAAyB;AAAA;AAAA,EAAO,2BAA2B;AAEhE;","names":["import_react","React","import_runtime_client_gql","import_react","messages","import_react","import_shared"]}
|