@copilotkit/react-core 0.16.0 → 0.17.0-alpha.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.
Files changed (142) hide show
  1. package/.turbo/turbo-build.log +168 -134
  2. package/CHANGELOG.md +6 -0
  3. package/dist/components/copilot-provider/copilot-provider-props.d.ts +3 -3
  4. package/dist/components/copilot-provider/copilot-provider-props.mjs +1 -2
  5. package/dist/components/copilot-provider/copilot-provider-props.mjs.map +1 -1
  6. package/dist/components/copilot-provider/copilot-provider.d.ts +3 -3
  7. package/dist/components/copilot-provider/copilot-provider.mjs +468 -7
  8. package/dist/components/copilot-provider/copilot-provider.mjs.map +1 -1
  9. package/dist/components/copilot-provider/index.d.ts +3 -3
  10. package/dist/components/copilot-provider/index.mjs +467 -8
  11. package/dist/components/copilot-provider/index.mjs.map +1 -1
  12. package/dist/components/copilot-provider/standard-copilot-api-config.d.ts +3 -3
  13. package/dist/components/copilot-provider/standard-copilot-api-config.mjs +12 -3
  14. package/dist/components/copilot-provider/standard-copilot-api-config.mjs.map +1 -1
  15. package/dist/components/index.d.ts +3 -3
  16. package/dist/components/index.mjs +467 -9
  17. package/dist/components/index.mjs.map +1 -1
  18. package/dist/context/copilot-context.d.ts +4 -8
  19. package/dist/context/copilot-context.mjs +70 -3
  20. package/dist/context/copilot-context.mjs.map +1 -1
  21. package/dist/context/index.d.ts +4 -4
  22. package/dist/context/index.mjs +69 -4
  23. package/dist/context/index.mjs.map +1 -1
  24. package/dist/hooks/index.d.ts +6 -1
  25. package/dist/hooks/index.mjs +654 -14
  26. package/dist/hooks/index.mjs.map +1 -1
  27. package/dist/hooks/use-chat.d.ts +84 -0
  28. package/dist/hooks/use-chat.mjs +461 -0
  29. package/dist/hooks/use-chat.mjs.map +1 -0
  30. package/dist/hooks/use-copilot-chat.d.ts +10 -3
  31. package/dist/hooks/use-copilot-chat.mjs +599 -10
  32. package/dist/hooks/use-copilot-chat.mjs.map +1 -1
  33. package/dist/hooks/use-flat-category-store.mjs +68 -3
  34. package/dist/hooks/use-flat-category-store.mjs.map +1 -1
  35. package/dist/hooks/use-make-copilot-actionable.mjs +95 -4
  36. package/dist/hooks/use-make-copilot-actionable.mjs.map +1 -1
  37. package/dist/hooks/use-make-copilot-document-readable.mjs +87 -4
  38. package/dist/hooks/use-make-copilot-document-readable.mjs.map +1 -1
  39. package/dist/hooks/use-make-copilot-readable.mjs +87 -4
  40. package/dist/hooks/use-make-copilot-readable.mjs.map +1 -1
  41. package/dist/hooks/use-tree.mjs +153 -3
  42. package/dist/hooks/use-tree.mjs.map +1 -1
  43. package/dist/index.d.ts +6 -2
  44. package/dist/index.mjs +1204 -21
  45. package/dist/index.mjs.map +1 -1
  46. package/dist/openai/chat-completion-client.d.ts +56 -0
  47. package/dist/openai/chat-completion-client.mjs +360 -0
  48. package/dist/openai/chat-completion-client.mjs.map +1 -0
  49. package/dist/openai/chat-completion-stream.d.ts +21 -0
  50. package/dist/openai/chat-completion-stream.mjs +221 -0
  51. package/dist/openai/chat-completion-stream.mjs.map +1 -0
  52. package/dist/openai/chat-completion-transport.d.ts +40 -0
  53. package/dist/openai/chat-completion-transport.mjs +181 -0
  54. package/dist/openai/chat-completion-transport.mjs.map +1 -0
  55. package/dist/openai/index.d.ts +10 -0
  56. package/dist/openai/index.mjs +221 -0
  57. package/dist/openai/index.mjs.map +1 -0
  58. package/dist/openai-assistants/hooks/index.mjs +235 -14
  59. package/dist/openai-assistants/hooks/index.mjs.map +1 -1
  60. package/dist/openai-assistants/hooks/use-assistants.mjs +52 -8
  61. package/dist/openai-assistants/hooks/use-assistants.mjs.map +1 -1
  62. package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs +236 -13
  63. package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs.map +1 -1
  64. package/dist/openai-assistants/index.mjs +236 -15
  65. package/dist/openai-assistants/index.mjs.map +1 -1
  66. package/dist/openai-assistants/utils/index.mjs +46 -4
  67. package/dist/openai-assistants/utils/index.mjs.map +1 -1
  68. package/dist/openai-assistants/utils/process-message-stream.mjs +46 -3
  69. package/dist/openai-assistants/utils/process-message-stream.mjs.map +1 -1
  70. package/dist/types/annotated-function.mjs +0 -2
  71. package/dist/types/annotated-function.mjs.map +1 -1
  72. package/dist/types/base.d.ts +56 -0
  73. package/dist/types/base.mjs +1 -0
  74. package/dist/types/base.mjs.map +1 -0
  75. package/dist/types/document-pointer.mjs +0 -2
  76. package/dist/types/document-pointer.mjs.map +1 -1
  77. package/dist/types/index.d.ts +1 -0
  78. package/dist/types/index.mjs +0 -2
  79. package/dist/types/index.mjs.map +1 -1
  80. package/dist/types/message.d.ts +2 -0
  81. package/dist/types/message.mjs +1 -0
  82. package/dist/types/message.mjs.map +1 -0
  83. package/dist/utils/utils.mjs +0 -2
  84. package/dist/utils/utils.mjs.map +1 -1
  85. package/dist/utils/utils.test.mjs +0 -1
  86. package/dist/utils/utils.test.mjs.map +1 -1
  87. package/package.json +4 -4
  88. package/src/components/copilot-provider/copilot-provider.tsx +4 -5
  89. package/src/context/copilot-context.tsx +1 -12
  90. package/src/context/index.ts +0 -1
  91. package/src/hooks/index.ts +1 -0
  92. package/src/hooks/use-chat.ts +197 -0
  93. package/src/hooks/use-copilot-chat.ts +10 -22
  94. package/src/index.tsx +1 -0
  95. package/src/openai/chat-completion-client.ts +240 -0
  96. package/src/openai/chat-completion-stream.ts +56 -0
  97. package/src/openai/chat-completion-transport.ts +190 -0
  98. package/src/openai/index.tsx +5 -0
  99. package/src/openai-assistants/hooks/use-copilot-chat-v2.ts +2 -2
  100. package/src/types/base.ts +61 -0
  101. package/src/types/index.ts +1 -0
  102. package/src/types/message.ts +0 -0
  103. package/dist/chunk-7GFKOIO7.mjs +0 -3
  104. package/dist/chunk-7GFKOIO7.mjs.map +0 -1
  105. package/dist/chunk-BABVSMJR.mjs +0 -3
  106. package/dist/chunk-BABVSMJR.mjs.map +0 -1
  107. package/dist/chunk-DE37LEZJ.mjs +0 -79
  108. package/dist/chunk-DE37LEZJ.mjs.map +0 -1
  109. package/dist/chunk-EFZPSZWO.mjs +0 -3
  110. package/dist/chunk-EFZPSZWO.mjs.map +0 -1
  111. package/dist/chunk-EV26IMLL.mjs +0 -165
  112. package/dist/chunk-EV26IMLL.mjs.map +0 -1
  113. package/dist/chunk-F2JIAPZQ.mjs +0 -13
  114. package/dist/chunk-F2JIAPZQ.mjs.map +0 -1
  115. package/dist/chunk-FRAKUJWH.mjs +0 -3
  116. package/dist/chunk-FRAKUJWH.mjs.map +0 -1
  117. package/dist/chunk-IF64NU27.mjs +0 -125
  118. package/dist/chunk-IF64NU27.mjs.map +0 -1
  119. package/dist/chunk-JD7BAH7U.mjs +0 -3
  120. package/dist/chunk-JD7BAH7U.mjs.map +0 -1
  121. package/dist/chunk-MRXNTQOX.mjs +0 -55
  122. package/dist/chunk-MRXNTQOX.mjs.map +0 -1
  123. package/dist/chunk-MZ5UN3BY.mjs +0 -28
  124. package/dist/chunk-MZ5UN3BY.mjs.map +0 -1
  125. package/dist/chunk-PF7LXYPO.mjs +0 -19
  126. package/dist/chunk-PF7LXYPO.mjs.map +0 -1
  127. package/dist/chunk-QACD2U6P.mjs +0 -3
  128. package/dist/chunk-QACD2U6P.mjs.map +0 -1
  129. package/dist/chunk-RFZQHCNS.mjs +0 -19
  130. package/dist/chunk-RFZQHCNS.mjs.map +0 -1
  131. package/dist/chunk-SPCZTZCY.mjs +0 -3
  132. package/dist/chunk-SPCZTZCY.mjs.map +0 -1
  133. package/dist/chunk-VUY2K2DI.mjs +0 -135
  134. package/dist/chunk-VUY2K2DI.mjs.map +0 -1
  135. package/dist/chunk-WL2MC3E2.mjs +0 -27
  136. package/dist/chunk-WL2MC3E2.mjs.map +0 -1
  137. package/dist/chunk-YGJFU4ZP.mjs +0 -58
  138. package/dist/chunk-YGJFU4ZP.mjs.map +0 -1
  139. package/dist/chunk-YPSGKPDA.mjs +0 -3
  140. package/dist/chunk-YPSGKPDA.mjs.map +0 -1
  141. package/dist/chunk-YULKJPY3.mjs +0 -70
  142. package/dist/chunk-YULKJPY3.mjs.map +0 -1
@@ -1,15 +1,655 @@
1
- import '../chunk-QACD2U6P.mjs';
2
- export { useCopilotChat } from '../chunk-DE37LEZJ.mjs';
3
- import '../chunk-JD7BAH7U.mjs';
4
- import '../chunk-SPCZTZCY.mjs';
5
- import '../chunk-EV26IMLL.mjs';
6
- import '../chunk-F2JIAPZQ.mjs';
7
- import '../chunk-VUY2K2DI.mjs';
8
- import '../chunk-YULKJPY3.mjs';
9
- export { useMakeCopilotActionable } from '../chunk-WL2MC3E2.mjs';
10
- export { useMakeCopilotDocumentReadable } from '../chunk-RFZQHCNS.mjs';
11
- export { useMakeCopilotReadable } from '../chunk-PF7LXYPO.mjs';
12
- import '../chunk-YGJFU4ZP.mjs';
13
- import '../chunk-MRXNTQOX.mjs';
14
- //# sourceMappingURL=out.js.map
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __objRest = (source, exclude) => {
21
+ var target = {};
22
+ for (var prop in source)
23
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
+ target[prop] = source[prop];
25
+ if (source != null && __getOwnPropSymbols)
26
+ for (var prop of __getOwnPropSymbols(source)) {
27
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
+ target[prop] = source[prop];
29
+ }
30
+ return target;
31
+ };
32
+ var __async = (__this, __arguments, generator) => {
33
+ return new Promise((resolve, reject) => {
34
+ var fulfilled = (value) => {
35
+ try {
36
+ step(generator.next(value));
37
+ } catch (e) {
38
+ reject(e);
39
+ }
40
+ };
41
+ var rejected = (value) => {
42
+ try {
43
+ step(generator.throw(value));
44
+ } catch (e) {
45
+ reject(e);
46
+ }
47
+ };
48
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
49
+ step((generator = generator.apply(__this, __arguments)).next());
50
+ });
51
+ };
52
+
53
+ // src/hooks/use-copilot-chat.ts
54
+ import { useMemo, useContext } from "react";
55
+
56
+ // src/context/copilot-context.tsx
57
+ import React from "react";
58
+ var emptyCopilotContext = {
59
+ entryPoints: {},
60
+ setEntryPoint: () => {
61
+ },
62
+ removeEntryPoint: () => {
63
+ },
64
+ getChatCompletionFunctionDescriptions: () => returnAndThrowInDebug([]),
65
+ getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
66
+ })),
67
+ getContextString: (documents, categories) => returnAndThrowInDebug(""),
68
+ addContext: () => "",
69
+ removeContext: () => {
70
+ },
71
+ getDocumentsContext: (categories) => returnAndThrowInDebug([]),
72
+ addDocumentContext: () => returnAndThrowInDebug(""),
73
+ removeDocumentContext: () => {
74
+ },
75
+ copilotApiConfig: new class {
76
+ get chatApiEndpoint() {
77
+ throw new Error(
78
+ "Remember to wrap your app in a `<CopilotProvider> {...} </CopilotProvider>` !!!"
79
+ );
80
+ }
81
+ get chatApiEndpointV2() {
82
+ throw new Error(
83
+ "Remember to wrap your app in a `<CopilotProvider> {...} </CopilotProvider>` !!!"
84
+ );
85
+ }
86
+ get headers() {
87
+ return {};
88
+ }
89
+ get body() {
90
+ return {};
91
+ }
92
+ }()
93
+ };
94
+ var CopilotContext = React.createContext(emptyCopilotContext);
95
+ function returnAndThrowInDebug(value) {
96
+ throw new Error(
97
+ "Remember to wrap your app in a `<CopilotProvider> {...} </CopilotProvider>` !!!"
98
+ );
99
+ return value;
100
+ }
101
+
102
+ // src/hooks/use-chat.ts
103
+ import { useState } from "react";
104
+ import { nanoid } from "nanoid";
105
+
106
+ // src/openai/chat-completion-client.ts
107
+ import EventEmitter2 from "eventemitter3";
108
+
109
+ // src/openai/chat-completion-transport.ts
110
+ import EventEmitter from "eventemitter3";
111
+ var DEFAULT_MODEL = "gpt-4-1106-preview";
112
+ var ChatCompletionTransport = class extends EventEmitter {
113
+ constructor({ url }) {
114
+ super();
115
+ this.buffer = new Uint8Array();
116
+ this.bodyReader = null;
117
+ this.url = url;
118
+ }
119
+ cleanup() {
120
+ return __async(this, null, function* () {
121
+ if (this.bodyReader) {
122
+ try {
123
+ yield this.bodyReader.cancel();
124
+ } catch (error) {
125
+ console.warn("Failed to cancel body reader:", error);
126
+ }
127
+ }
128
+ this.bodyReader = null;
129
+ this.buffer = new Uint8Array();
130
+ });
131
+ }
132
+ fetch(_0) {
133
+ return __async(this, arguments, function* ({
134
+ model,
135
+ messages,
136
+ copilotConfig,
137
+ functions,
138
+ temperature,
139
+ headers,
140
+ body,
141
+ signal
142
+ }) {
143
+ yield this.cleanup();
144
+ temperature || (temperature = 0.5);
145
+ functions || (functions = []);
146
+ model || (model = DEFAULT_MODEL);
147
+ const cleanedMessages = messages.map((message) => {
148
+ const { content, role, name, function_call } = message;
149
+ return { content, role, name, function_call };
150
+ });
151
+ try {
152
+ const response = yield fetch(this.url, {
153
+ method: "POST",
154
+ headers: __spreadValues(__spreadValues({
155
+ "Content-Type": "application/json"
156
+ }, copilotConfig.headers), headers ? __spreadValues({}, headers) : {}),
157
+ body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
158
+ model,
159
+ messages: cleanedMessages,
160
+ stream: true
161
+ }, functions.length ? { functions } : {}), temperature ? { temperature } : {}), functions.length != 0 ? { function_call: "auto" } : {}), copilotConfig.body), body ? __spreadValues({}, body) : {})),
162
+ signal
163
+ });
164
+ if (!response.ok) {
165
+ try {
166
+ const errorText = yield response.text();
167
+ yield this.cleanup();
168
+ const msg = `Error ${response.status}: ${errorText}`;
169
+ this.emit("error", new Error(msg));
170
+ } catch (_error) {
171
+ yield this.cleanup();
172
+ const msg = `Error ${response.status}: ${response.statusText}`;
173
+ this.emit("error", new Error(msg));
174
+ }
175
+ return;
176
+ }
177
+ if (response.body == null) {
178
+ yield this.cleanup();
179
+ const msg = "Response body is null";
180
+ this.emit("error", new Error(msg));
181
+ return;
182
+ }
183
+ this.bodyReader = response.body.getReader();
184
+ yield this.streamBody();
185
+ } catch (error) {
186
+ yield this.cleanup();
187
+ this.emit("error", error);
188
+ return;
189
+ }
190
+ });
191
+ }
192
+ streamBody() {
193
+ return __async(this, null, function* () {
194
+ while (true) {
195
+ try {
196
+ const { done, value } = yield this.bodyReader.read();
197
+ if (done) {
198
+ yield this.cleanup();
199
+ this.emit("end");
200
+ return;
201
+ }
202
+ const shouldContinue = yield this.processData(value);
203
+ if (!shouldContinue) {
204
+ return;
205
+ }
206
+ } catch (error) {
207
+ yield this.cleanup();
208
+ this.emit("error", error);
209
+ return;
210
+ }
211
+ }
212
+ });
213
+ }
214
+ processData(data) {
215
+ return __async(this, null, function* () {
216
+ const newBuffer = new Uint8Array(this.buffer.length + data.length);
217
+ newBuffer.set(this.buffer);
218
+ newBuffer.set(data, this.buffer.length);
219
+ this.buffer = newBuffer;
220
+ const dataString = new TextDecoder("utf-8").decode(this.buffer);
221
+ let lines = dataString.split("\n").filter((line) => line.trim() !== "");
222
+ if (!dataString.endsWith("\n")) {
223
+ const lastLine = lines.pop() || "";
224
+ const remainingBytes = new TextEncoder().encode(lastLine);
225
+ this.buffer = new Uint8Array(remainingBytes);
226
+ } else {
227
+ this.buffer = new Uint8Array();
228
+ }
229
+ for (const line of lines) {
230
+ const cleanedLine = line.replace(/^data: /, "");
231
+ if (cleanedLine === "[DONE]") {
232
+ yield this.cleanup();
233
+ this.emit("end");
234
+ return false;
235
+ }
236
+ let json;
237
+ try {
238
+ json = JSON.parse(cleanedLine);
239
+ } catch (error) {
240
+ console.error("Failed to parse JSON:", error);
241
+ continue;
242
+ }
243
+ this.emit("data", json);
244
+ }
245
+ return true;
246
+ });
247
+ }
248
+ };
249
+
250
+ // src/openai/chat-completion-client.ts
251
+ var DEFAULT_MAX_TOKENS = 8192;
252
+ var ChatCompletionClient = class extends EventEmitter2 {
253
+ constructor(params) {
254
+ super();
255
+ this.chatCompletionTransport = null;
256
+ this.mode = null;
257
+ this.functionCallName = "";
258
+ this.functionCallArguments = "";
259
+ this.onData = (data) => {
260
+ if (this.mode === "function" && !data.choices[0].delta.function_call) {
261
+ const success = this.tryFlushFunctionCall();
262
+ if (!success) {
263
+ return;
264
+ }
265
+ }
266
+ this.mode = data.choices[0].delta.function_call ? "function" : "message";
267
+ if (this.mode === "message") {
268
+ if (data.choices[0].delta.content) {
269
+ this.emit("content", data.choices[0].delta.content);
270
+ }
271
+ return;
272
+ } else if (this.mode === "function") {
273
+ if (data.choices[0].delta.function_call.name) {
274
+ this.functionCallName = data.choices[0].delta.function_call.name;
275
+ }
276
+ if (data.choices[0].delta.function_call.arguments) {
277
+ this.functionCallArguments += data.choices[0].delta.function_call.arguments;
278
+ }
279
+ this.emit("partial", this.functionCallName, this.functionCallArguments);
280
+ return;
281
+ }
282
+ };
283
+ this.onError = (error) => {
284
+ this.emit("error", error);
285
+ this.cleanup();
286
+ };
287
+ this.onEnd = () => {
288
+ if (this.mode === "function") {
289
+ const success = this.tryFlushFunctionCall();
290
+ if (!success) {
291
+ return;
292
+ }
293
+ }
294
+ this.emit("end");
295
+ this.cleanup();
296
+ };
297
+ this.model = params.model;
298
+ this.url = params.url;
299
+ }
300
+ fetch(params) {
301
+ return __async(this, null, function* () {
302
+ params = __spreadValues({}, params);
303
+ if (this.model && this.model in maxTokensByModel) {
304
+ params.maxTokens || (params.maxTokens = maxTokensByModel[this.model]);
305
+ } else {
306
+ params.maxTokens || (params.maxTokens = DEFAULT_MAX_TOKENS);
307
+ }
308
+ params.functions || (params.functions = []);
309
+ params.model = this.model;
310
+ params.messages = this.buildPrompt(params);
311
+ return yield this.runPrompt(params);
312
+ });
313
+ }
314
+ buildPrompt(params) {
315
+ let maxTokens = params.maxTokens;
316
+ const messages = params.messages;
317
+ const functions = params.functions;
318
+ const functionsNumTokens = countFunctionsTokens(functions);
319
+ if (functionsNumTokens > maxTokens) {
320
+ throw new Error(`Too many tokens in function calls: ${functionsNumTokens} > ${maxTokens}`);
321
+ }
322
+ maxTokens -= functionsNumTokens;
323
+ for (const message of messages) {
324
+ if (message.role === "system") {
325
+ const numTokens = this.countTokens(message);
326
+ maxTokens -= numTokens;
327
+ if (maxTokens < 0) {
328
+ throw new Error("Not enough tokens for system message.");
329
+ }
330
+ }
331
+ }
332
+ const result = [];
333
+ let cutoff = false;
334
+ const reversedMessages = [...messages].reverse();
335
+ for (const message of reversedMessages) {
336
+ if (message.role === "system") {
337
+ result.unshift(message);
338
+ continue;
339
+ } else if (cutoff) {
340
+ continue;
341
+ }
342
+ let numTokens = this.countTokens(message);
343
+ if (maxTokens < numTokens) {
344
+ cutoff = true;
345
+ continue;
346
+ }
347
+ result.unshift(message);
348
+ maxTokens -= numTokens;
349
+ }
350
+ return result;
351
+ }
352
+ runPrompt(params) {
353
+ return __async(this, null, function* () {
354
+ this.chatCompletionTransport = new ChatCompletionTransport({
355
+ url: this.url
356
+ });
357
+ this.chatCompletionTransport.on("data", this.onData);
358
+ this.chatCompletionTransport.on("error", this.onError);
359
+ this.chatCompletionTransport.on("end", this.onEnd);
360
+ yield this.chatCompletionTransport.fetch(params);
361
+ });
362
+ }
363
+ tryFlushFunctionCall() {
364
+ let args = null;
365
+ try {
366
+ args = JSON.parse(this.functionCallArguments);
367
+ } catch (error) {
368
+ this.emit("error", error);
369
+ this.cleanup();
370
+ return false;
371
+ }
372
+ this.emit("function", {
373
+ name: this.functionCallName,
374
+ arguments: args
375
+ });
376
+ this.mode = null;
377
+ this.functionCallName = "";
378
+ this.functionCallArguments = "";
379
+ return true;
380
+ }
381
+ cleanup() {
382
+ if (this.chatCompletionTransport) {
383
+ this.chatCompletionTransport.off("data", this.onData);
384
+ this.chatCompletionTransport.off("error", this.onError);
385
+ this.chatCompletionTransport.off("end", this.onEnd);
386
+ }
387
+ this.chatCompletionTransport = null;
388
+ this.mode = null;
389
+ this.functionCallName = "";
390
+ this.functionCallArguments = "";
391
+ }
392
+ countTokens(message) {
393
+ if (message.content) {
394
+ return estimateTokens(message.content);
395
+ } else if (message.function_call) {
396
+ return estimateTokens(JSON.stringify(message.function_call));
397
+ }
398
+ return 0;
399
+ }
400
+ };
401
+ var maxTokensByModel = {
402
+ "gpt-3.5-turbo": 4097,
403
+ "gpt-3.5-turbo-16k": 16385,
404
+ "gpt-4": 8192,
405
+ "gpt-4-1106-preview": 8192,
406
+ "gpt-4-32k": 32768,
407
+ "gpt-3.5-turbo-0301": 4097,
408
+ "gpt-4-0314": 8192,
409
+ "gpt-4-32k-0314": 32768,
410
+ "gpt-3.5-turbo-0613": 4097,
411
+ "gpt-4-0613": 8192,
412
+ "gpt-4-32k-0613": 32768,
413
+ "gpt-3.5-turbo-16k-0613": 16385
414
+ };
415
+ function estimateTokens(text) {
416
+ return text.length / 3;
417
+ }
418
+ function countFunctionsTokens(functions) {
419
+ if (functions.length === 0) {
420
+ return 0;
421
+ }
422
+ const json = JSON.stringify(functions);
423
+ return estimateTokens(json);
424
+ }
425
+
426
+ // src/hooks/use-chat.ts
427
+ function useChat(options) {
428
+ const [messages, setMessages] = useState([]);
429
+ const [input, setInput] = useState("");
430
+ const [isLoading, setIsLoading] = useState(false);
431
+ const runChatCompletion = (messages2) => __async(this, null, function* () {
432
+ return new Promise((resolve, reject) => {
433
+ setIsLoading(true);
434
+ const assistantMessage = {
435
+ id: nanoid(),
436
+ createdAt: /* @__PURE__ */ new Date(),
437
+ content: "",
438
+ role: "assistant"
439
+ };
440
+ setMessages([...messages2, __spreadValues({}, assistantMessage)]);
441
+ const messagesWithContext = [...options.initialMessages || [], ...messages2];
442
+ const client = new ChatCompletionClient({
443
+ url: options.api || "/api/copilotkit/openai"
444
+ });
445
+ const cleanup = () => {
446
+ client.off("content");
447
+ client.off("end");
448
+ client.off("error");
449
+ client.off("function");
450
+ };
451
+ client.on("content", (content) => {
452
+ assistantMessage.content += content;
453
+ setMessages([...messages2, __spreadValues({}, assistantMessage)]);
454
+ });
455
+ client.on("end", () => {
456
+ setIsLoading(false);
457
+ cleanup();
458
+ resolve(__spreadValues({}, assistantMessage));
459
+ });
460
+ client.on("error", (error) => {
461
+ setIsLoading(false);
462
+ cleanup();
463
+ reject(error);
464
+ });
465
+ client.on("function", (functionCall) => __async(this, null, function* () {
466
+ assistantMessage.function_call = {
467
+ name: functionCall.name,
468
+ arguments: JSON.stringify(functionCall.arguments)
469
+ };
470
+ setMessages([...messages2, __spreadValues({}, assistantMessage)]);
471
+ setIsLoading(false);
472
+ cleanup();
473
+ resolve(__spreadValues({}, assistantMessage));
474
+ }));
475
+ client.fetch({
476
+ messages: messagesWithContext,
477
+ functions: options.functions,
478
+ headers: options.headers,
479
+ copilotConfig: options.copilotConfig
480
+ });
481
+ });
482
+ });
483
+ const runChatCompletionAndHandleFunctionCall = (messages2) => __async(this, null, function* () {
484
+ const message = yield runChatCompletion(messages2);
485
+ if (message.function_call && options.onFunctionCall) {
486
+ yield options.onFunctionCall(messages2, message.function_call);
487
+ }
488
+ });
489
+ const append = (message) => __async(this, null, function* () {
490
+ if (isLoading) {
491
+ return;
492
+ }
493
+ const newMessages = [...messages, message];
494
+ setMessages(newMessages);
495
+ return runChatCompletionAndHandleFunctionCall(newMessages);
496
+ });
497
+ const reload = () => __async(this, null, function* () {
498
+ if (isLoading || messages.length === 0) {
499
+ return;
500
+ }
501
+ let newMessages = [...messages];
502
+ const lastMessage = messages[messages.length - 1];
503
+ if (lastMessage.role === "assistant") {
504
+ newMessages = newMessages.slice(0, -1);
505
+ }
506
+ setMessages(newMessages);
507
+ return runChatCompletionAndHandleFunctionCall(newMessages);
508
+ });
509
+ const stop = () => {
510
+ throw new Error("Not implemented");
511
+ };
512
+ return {
513
+ messages,
514
+ append,
515
+ reload,
516
+ stop,
517
+ isLoading,
518
+ input,
519
+ setInput
520
+ };
521
+ }
522
+
523
+ // src/components/copilot-provider/copilot-provider.tsx
524
+ import { useCallback, useState as useState2 } from "react";
525
+ import { jsx } from "react/jsx-runtime";
526
+ var defaultCopilotContextCategories = ["global"];
527
+
528
+ // src/hooks/use-copilot-chat.ts
529
+ function useCopilotChat(_a) {
530
+ var _b = _a, {
531
+ makeSystemMessage
532
+ } = _b, options = __objRest(_b, [
533
+ "makeSystemMessage"
534
+ ]);
535
+ const {
536
+ getContextString,
537
+ getChatCompletionFunctionDescriptions,
538
+ getFunctionCallHandler,
539
+ copilotApiConfig
540
+ } = useContext(CopilotContext);
541
+ const systemMessage = useMemo(() => {
542
+ const systemMessageMaker = makeSystemMessage || defaultSystemMessage;
543
+ const contextString = getContextString([], defaultCopilotContextCategories);
544
+ return {
545
+ id: "system",
546
+ content: systemMessageMaker(contextString),
547
+ role: "system"
548
+ };
549
+ }, [getContextString, makeSystemMessage]);
550
+ const functionDescriptions = useMemo(() => {
551
+ return getChatCompletionFunctionDescriptions();
552
+ }, [getChatCompletionFunctionDescriptions]);
553
+ const { messages, append, reload, stop, isLoading, input, setInput } = useChat(__spreadProps(__spreadValues({}, options), {
554
+ copilotConfig: copilotApiConfig,
555
+ id: options.id,
556
+ initialMessages: [systemMessage].concat(options.initialMessages || []),
557
+ functions: functionDescriptions,
558
+ onFunctionCall: getFunctionCallHandler(),
559
+ headers: __spreadValues({}, options.headers),
560
+ body: __spreadValues({}, options.body)
561
+ }));
562
+ const visibleMessages = messages.filter(
563
+ (message) => message.role === "user" || message.role === "assistant"
564
+ );
565
+ return {
566
+ visibleMessages,
567
+ append,
568
+ reload,
569
+ stop,
570
+ isLoading,
571
+ input,
572
+ setInput
573
+ };
574
+ }
575
+ function defaultSystemMessage(contextString) {
576
+ return `
577
+ Please act as an efficient, competent, conscientious, and industrious professional assistant.
578
+
579
+ 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.
580
+ Always be polite and respectful, and prefer brevity over verbosity.
581
+
582
+ The user has provided you with the following context:
583
+ \`\`\`
584
+ ${contextString}
585
+ \`\`\`
586
+
587
+ 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.
588
+
589
+ Please assist them as best you can.
590
+
591
+ 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.
592
+
593
+ If you would like to call a function, call it without saying anything else.
594
+ `;
595
+ }
596
+
597
+ // src/hooks/use-make-copilot-actionable.ts
598
+ import { useRef, useContext as useContext2, useEffect, useMemo as useMemo2 } from "react";
599
+ import { nanoid as nanoid2 } from "nanoid";
600
+ function useMakeCopilotActionable(annotatedFunction, dependencies) {
601
+ const idRef = useRef(nanoid2());
602
+ const { setEntryPoint, removeEntryPoint } = useContext2(CopilotContext);
603
+ const memoizedAnnotatedFunction = useMemo2(
604
+ () => ({
605
+ name: annotatedFunction.name,
606
+ description: annotatedFunction.description,
607
+ argumentAnnotations: annotatedFunction.argumentAnnotations,
608
+ implementation: annotatedFunction.implementation
609
+ }),
610
+ dependencies
611
+ );
612
+ useEffect(() => {
613
+ setEntryPoint(idRef.current, memoizedAnnotatedFunction);
614
+ return () => {
615
+ removeEntryPoint(idRef.current);
616
+ };
617
+ }, [memoizedAnnotatedFunction, setEntryPoint, removeEntryPoint]);
618
+ }
619
+
620
+ // src/hooks/use-make-copilot-readable.ts
621
+ import { useContext as useContext3, useEffect as useEffect2, useRef as useRef2 } from "react";
622
+ function useMakeCopilotReadable(information, parentId, categories) {
623
+ const { addContext, removeContext } = useContext3(CopilotContext);
624
+ const idRef = useRef2();
625
+ useEffect2(() => {
626
+ const id = addContext(information, parentId, categories);
627
+ idRef.current = id;
628
+ return () => {
629
+ removeContext(id);
630
+ };
631
+ }, [information, parentId, addContext, removeContext]);
632
+ return idRef.current;
633
+ }
634
+
635
+ // src/hooks/use-make-copilot-document-readable.ts
636
+ import { useContext as useContext4, useEffect as useEffect3, useRef as useRef3 } from "react";
637
+ function useMakeCopilotDocumentReadable(document, categories, dependencies = []) {
638
+ const { addDocumentContext, removeDocumentContext } = useContext4(CopilotContext);
639
+ const idRef = useRef3();
640
+ useEffect3(() => {
641
+ const id = addDocumentContext(document, categories);
642
+ idRef.current = id;
643
+ return () => {
644
+ removeDocumentContext(id);
645
+ };
646
+ }, [addDocumentContext, removeDocumentContext, ...dependencies]);
647
+ return idRef.current;
648
+ }
649
+ export {
650
+ useCopilotChat,
651
+ useMakeCopilotActionable,
652
+ useMakeCopilotDocumentReadable,
653
+ useMakeCopilotReadable
654
+ };
15
655
  //# sourceMappingURL=index.mjs.map