@copilotkit/react-core 0.38.0-mme-pre.0 → 0.38.0-mme-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 (165) hide show
  1. package/.turbo/turbo-build.log +187 -234
  2. package/CHANGELOG.md +4 -3
  3. package/dist/{chunk-NKIUZSGZ.mjs → chunk-5Q7DU3XW.mjs} +40 -40
  4. package/dist/chunk-5Q7DU3XW.mjs.map +1 -0
  5. package/dist/{chunk-B244LK6F.mjs → chunk-ATWK243A.mjs} +2 -2
  6. package/dist/{chunk-AJSY6LS5.mjs → chunk-FY3TQ7Q6.mjs} +17 -32
  7. package/dist/chunk-FY3TQ7Q6.mjs.map +1 -0
  8. package/dist/{chunk-SR4RW4CU.mjs → chunk-GFQBAEJL.mjs} +6 -6
  9. package/dist/chunk-GFQBAEJL.mjs.map +1 -0
  10. package/dist/{chunk-DY63PD22.mjs → chunk-GLPZSBNA.mjs} +4 -5
  11. package/dist/chunk-GLPZSBNA.mjs.map +1 -0
  12. package/dist/{chunk-S5LWO5V3.mjs → chunk-IBOL6LE5.mjs} +2 -2
  13. package/dist/{chunk-NSUYO6TP.mjs → chunk-MI7BERU7.mjs} +9 -9
  14. package/dist/chunk-MI7BERU7.mjs.map +1 -0
  15. package/dist/chunk-MW2IVCDP.mjs +188 -0
  16. package/dist/chunk-MW2IVCDP.mjs.map +1 -0
  17. package/dist/{chunk-ZHYCHXIO.mjs → chunk-PSZAPRNZ.mjs} +56 -42
  18. package/dist/chunk-PSZAPRNZ.mjs.map +1 -0
  19. package/dist/{chunk-DY4YVUO3.mjs → chunk-WJIS7HTH.mjs} +14 -25
  20. package/dist/chunk-WJIS7HTH.mjs.map +1 -0
  21. package/dist/{chunk-MNZXQ6UH.mjs → chunk-WTGFKR3D.mjs} +2 -2
  22. package/dist/chunk-YJLRG5U3.mjs +1 -0
  23. package/dist/components/copilot-provider/copilotkit.js +17 -32
  24. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  25. package/dist/components/copilot-provider/copilotkit.mjs +2 -2
  26. package/dist/components/copilot-provider/index.js +17 -32
  27. package/dist/components/copilot-provider/index.js.map +1 -1
  28. package/dist/components/copilot-provider/index.mjs +2 -2
  29. package/dist/components/index.js +17 -32
  30. package/dist/components/index.js.map +1 -1
  31. package/dist/components/index.mjs +2 -2
  32. package/dist/context/copilot-context.d.ts +5 -5
  33. package/dist/context/copilot-context.js +3 -4
  34. package/dist/context/copilot-context.js.map +1 -1
  35. package/dist/context/copilot-context.mjs +1 -1
  36. package/dist/context/index.d.ts +1 -0
  37. package/dist/context/index.js +3 -4
  38. package/dist/context/index.js.map +1 -1
  39. package/dist/context/index.mjs +1 -1
  40. package/dist/hooks/index.d.ts +2 -1
  41. package/dist/hooks/index.js +136 -232
  42. package/dist/hooks/index.js.map +1 -1
  43. package/dist/hooks/index.mjs +9 -10
  44. package/dist/hooks/use-chat.d.ts +26 -52
  45. package/dist/hooks/use-chat.js +104 -203
  46. package/dist/hooks/use-chat.js.map +1 -1
  47. package/dist/hooks/use-chat.mjs +1 -2
  48. package/dist/hooks/use-copilot-action.js +10 -11
  49. package/dist/hooks/use-copilot-action.js.map +1 -1
  50. package/dist/hooks/use-copilot-action.mjs +2 -2
  51. package/dist/hooks/use-copilot-chat.d.ts +1 -1
  52. package/dist/hooks/use-copilot-chat.js +119 -215
  53. package/dist/hooks/use-copilot-chat.js.map +1 -1
  54. package/dist/hooks/use-copilot-chat.mjs +4 -5
  55. package/dist/hooks/use-copilot-readable.js +3 -4
  56. package/dist/hooks/use-copilot-readable.js.map +1 -1
  57. package/dist/hooks/use-copilot-readable.mjs +2 -2
  58. package/dist/hooks/use-make-copilot-actionable.js +7 -8
  59. package/dist/hooks/use-make-copilot-actionable.js.map +1 -1
  60. package/dist/hooks/use-make-copilot-actionable.mjs +2 -2
  61. package/dist/hooks/use-make-copilot-document-readable.js +3 -4
  62. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  63. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  64. package/dist/hooks/use-make-copilot-readable.js +3 -4
  65. package/dist/hooks/use-make-copilot-readable.js.map +1 -1
  66. package/dist/hooks/use-make-copilot-readable.mjs +2 -2
  67. package/dist/index.d.ts +1 -3
  68. package/dist/index.js +227 -499
  69. package/dist/index.js.map +1 -1
  70. package/dist/index.mjs +12 -31
  71. package/dist/lib/copilot-task.d.ts +1 -0
  72. package/dist/lib/copilot-task.js +31 -110
  73. package/dist/lib/copilot-task.js.map +1 -1
  74. package/dist/lib/copilot-task.mjs +3 -4
  75. package/dist/lib/index.d.ts +1 -0
  76. package/dist/lib/index.js +33 -110
  77. package/dist/lib/index.js.map +1 -1
  78. package/dist/lib/index.mjs +3 -4
  79. package/dist/utils/extract.d.ts +1 -0
  80. package/dist/utils/extract.js +49 -109
  81. package/dist/utils/extract.js.map +1 -1
  82. package/dist/utils/extract.mjs +3 -4
  83. package/dist/utils/index.d.ts +1 -1
  84. package/dist/utils/index.js +52 -132
  85. package/dist/utils/index.js.map +1 -1
  86. package/dist/utils/index.mjs +5 -13
  87. package/package.json +6 -5
  88. package/src/components/copilot-provider/copilotkit.tsx +16 -33
  89. package/src/context/copilot-context.tsx +9 -16
  90. package/src/hooks/use-chat.ts +204 -212
  91. package/src/hooks/use-copilot-action.ts +7 -8
  92. package/src/hooks/use-copilot-chat.ts +12 -36
  93. package/src/hooks/use-make-copilot-actionable.ts +4 -4
  94. package/src/index.tsx +0 -1
  95. package/src/lib/copilot-task.ts +42 -42
  96. package/src/utils/extract.ts +61 -36
  97. package/src/utils/index.ts +0 -7
  98. package/dist/chunk-36FKUOWM.mjs +0 -137
  99. package/dist/chunk-36FKUOWM.mjs.map +0 -1
  100. package/dist/chunk-3XVO5UEG.mjs +0 -205
  101. package/dist/chunk-3XVO5UEG.mjs.map +0 -1
  102. package/dist/chunk-7GFKOIO7.mjs +0 -1
  103. package/dist/chunk-AJSY6LS5.mjs.map +0 -1
  104. package/dist/chunk-BABVSMJR.mjs +0 -1
  105. package/dist/chunk-BABVSMJR.mjs.map +0 -1
  106. package/dist/chunk-CYDWEPFL.mjs +0 -1
  107. package/dist/chunk-CYDWEPFL.mjs.map +0 -1
  108. package/dist/chunk-DY4YVUO3.mjs.map +0 -1
  109. package/dist/chunk-DY63PD22.mjs.map +0 -1
  110. package/dist/chunk-FRAKUJWH.mjs +0 -1
  111. package/dist/chunk-FRAKUJWH.mjs.map +0 -1
  112. package/dist/chunk-MJKBCG4U.mjs +0 -91
  113. package/dist/chunk-MJKBCG4U.mjs.map +0 -1
  114. package/dist/chunk-NKIUZSGZ.mjs.map +0 -1
  115. package/dist/chunk-NSUYO6TP.mjs.map +0 -1
  116. package/dist/chunk-SR4RW4CU.mjs.map +0 -1
  117. package/dist/chunk-ZFS5SQUT.mjs +0 -31
  118. package/dist/chunk-ZFS5SQUT.mjs.map +0 -1
  119. package/dist/chunk-ZHYCHXIO.mjs.map +0 -1
  120. package/dist/openai-assistants/hooks/index.d.ts +0 -2
  121. package/dist/openai-assistants/hooks/index.js +0 -277
  122. package/dist/openai-assistants/hooks/index.js.map +0 -1
  123. package/dist/openai-assistants/hooks/index.mjs +0 -18
  124. package/dist/openai-assistants/hooks/index.mjs.map +0 -1
  125. package/dist/openai-assistants/hooks/use-assistants.d.ts +0 -17
  126. package/dist/openai-assistants/hooks/use-assistants.js +0 -154
  127. package/dist/openai-assistants/hooks/use-assistants.js.map +0 -1
  128. package/dist/openai-assistants/hooks/use-assistants.mjs +0 -92
  129. package/dist/openai-assistants/hooks/use-assistants.mjs.map +0 -1
  130. package/dist/openai-assistants/hooks/use-copilot-chat-v2.d.ts +0 -44
  131. package/dist/openai-assistants/hooks/use-copilot-chat-v2.js +0 -277
  132. package/dist/openai-assistants/hooks/use-copilot-chat-v2.js.map +0 -1
  133. package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs +0 -19
  134. package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs.map +0 -1
  135. package/dist/openai-assistants/index.d.ts +0 -3
  136. package/dist/openai-assistants/index.js +0 -279
  137. package/dist/openai-assistants/index.js.map +0 -1
  138. package/dist/openai-assistants/index.mjs +0 -22
  139. package/dist/openai-assistants/index.mjs.map +0 -1
  140. package/dist/openai-assistants/utils/index.d.ts +0 -1
  141. package/dist/openai-assistants/utils/index.js +0 -73
  142. package/dist/openai-assistants/utils/index.js.map +0 -1
  143. package/dist/openai-assistants/utils/index.mjs +0 -9
  144. package/dist/openai-assistants/utils/index.mjs.map +0 -1
  145. package/dist/openai-assistants/utils/process-message-stream.d.ts +0 -3
  146. package/dist/openai-assistants/utils/process-message-stream.js +0 -71
  147. package/dist/openai-assistants/utils/process-message-stream.js.map +0 -1
  148. package/dist/openai-assistants/utils/process-message-stream.mjs +0 -8
  149. package/dist/openai-assistants/utils/process-message-stream.mjs.map +0 -1
  150. package/dist/utils/fetch-chat-completion.d.ts +0 -36
  151. package/dist/utils/fetch-chat-completion.js +0 -141
  152. package/dist/utils/fetch-chat-completion.js.map +0 -1
  153. package/dist/utils/fetch-chat-completion.mjs +0 -12
  154. package/dist/utils/fetch-chat-completion.mjs.map +0 -1
  155. package/src/openai-assistants/hooks/index.ts +0 -9
  156. package/src/openai-assistants/hooks/use-assistants.ts +0 -112
  157. package/src/openai-assistants/hooks/use-copilot-chat-v2.ts +0 -189
  158. package/src/openai-assistants/index.ts +0 -2
  159. package/src/openai-assistants/utils/index.ts +0 -1
  160. package/src/openai-assistants/utils/process-message-stream.ts +0 -25
  161. package/src/utils/fetch-chat-completion.ts +0 -120
  162. /package/dist/{chunk-B244LK6F.mjs.map → chunk-ATWK243A.mjs.map} +0 -0
  163. /package/dist/{chunk-S5LWO5V3.mjs.map → chunk-IBOL6LE5.mjs.map} +0 -0
  164. /package/dist/{chunk-MNZXQ6UH.mjs.map → chunk-WTGFKR3D.mjs.map} +0 -0
  165. /package/dist/{chunk-7GFKOIO7.mjs.map → chunk-YJLRG5U3.mjs.map} +0 -0
@@ -1,12 +1,8 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
- var __defProps = Object.defineProperties;
5
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
8
5
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
- var __getProtoOf = Object.getPrototypeOf;
10
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
11
7
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
8
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -21,7 +17,6 @@ var __spreadValues = (a, b) => {
21
17
  }
22
18
  return a;
23
19
  };
24
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
20
  var __export = (target, all) => {
26
21
  for (var name in all)
27
22
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -34,14 +29,6 @@ var __copyProps = (to, from, except, desc) => {
34
29
  }
35
30
  return to;
36
31
  };
37
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
38
- // If the importer is in node compatibility mode or this is not an ESM
39
- // file that has been converted to a CommonJS file using a Babel-
40
- // compatible transform (i.e. "__esModule" has not been set), then set
41
- // "default" to the CommonJS "module.exports" for node compatibility.
42
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
43
- mod
44
- ));
45
32
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
46
33
  var __async = (__this, __arguments, generator) => {
47
34
  return new Promise((resolve, reject) => {
@@ -71,227 +58,141 @@ __export(use_chat_exports, {
71
58
  });
72
59
  module.exports = __toCommonJS(use_chat_exports);
73
60
  var import_react = require("react");
74
- var import_shared2 = require("@copilotkit/shared");
75
- var import_nanoid = require("nanoid");
76
-
77
- // src/utils/fetch-chat-completion.ts
78
61
  var import_shared = require("@copilotkit/shared");
79
- function fetchChatCompletion(_0) {
80
- return __async(this, arguments, function* ({
81
- copilotConfig,
82
- model,
83
- messages,
84
- tools,
85
- temperature,
86
- headers,
87
- body,
88
- signal,
89
- toolChoice
90
- }) {
91
- temperature || (temperature = 0.5);
92
- tools || (tools = []);
93
- const cleanedMessages = messages.map((message) => {
94
- const { content, role, name, function_call } = message;
95
- return { content, role, name, function_call };
96
- });
97
- toolChoice || (toolChoice = "auto");
98
- const response = yield fetch(copilotConfig.chatApiEndpoint, {
99
- method: "POST",
100
- headers: __spreadValues(__spreadValues({
101
- "Content-Type": "application/json"
102
- }, copilotConfig.headers), headers ? __spreadValues({}, headers) : {}),
103
- body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
104
- model,
105
- messages: cleanedMessages,
106
- stream: true
107
- }, 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 } : {})),
108
- signal,
109
- credentials: copilotConfig.credentials
110
- });
111
- return response;
112
- });
113
- }
114
- function excludeBackendOnlyProps(copilotConfig) {
115
- var _a;
116
- const backendOnlyProps = (_a = copilotConfig.backendOnlyProps) != null ? _a : {};
117
- if (Object.keys(backendOnlyProps).length > 0) {
118
- return {
119
- [import_shared.EXCLUDE_FROM_FORWARD_PROPS_KEYS]: Object.keys(backendOnlyProps)
120
- };
121
- } else {
122
- return {};
123
- }
124
- }
125
- function fetchAndDecodeChatCompletion(params) {
126
- return __async(this, null, function* () {
127
- const response = yield fetchChatCompletion(params);
128
- if (!response.ok || !response.body) {
129
- response.events = null;
130
- } else {
131
- const events = yield (0, import_shared.decodeChatCompletion)((0, import_shared.parseChatCompletion)(response.body));
132
- response.events = events;
133
- }
134
- return response;
135
- });
136
- }
137
-
138
- // src/hooks/use-chat.ts
139
- var import_untruncate_json = __toESM(require("untruncate-json"));
62
+ var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
140
63
  function useChat(options) {
141
- const { messages, setMessages, makeSystemMessageCallback } = options;
64
+ const {
65
+ messages,
66
+ setMessages,
67
+ makeSystemMessageCallback,
68
+ copilotConfig,
69
+ setIsLoading,
70
+ initialMessages,
71
+ isLoading,
72
+ actions,
73
+ onFunctionCall
74
+ } = options;
142
75
  const abortControllerRef = (0, import_react.useRef)();
143
76
  const threadIdRef = (0, import_react.useRef)(null);
144
77
  const runIdRef = (0, import_react.useRef)(null);
145
- const publicApiKey = options.copilotConfig.publicApiKey;
146
- const headers = __spreadValues(__spreadValues({}, options.headers || {}), publicApiKey ? { [import_shared2.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
147
- const runChatCompletion = (messages2) => __async(this, null, function* () {
148
- var _a, _b;
149
- options.setIsLoading(true);
150
- const newMessages = [
151
- {
152
- id: (0, import_nanoid.nanoid)(),
153
- createdAt: /* @__PURE__ */ new Date(),
78
+ const publicApiKey = copilotConfig.publicApiKey;
79
+ const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [import_shared.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
80
+ const runtimeClient = new import_runtime_client_gql.CopilotRuntimeClient({
81
+ url: copilotConfig.chatApiEndpoint,
82
+ publicApiKey: copilotConfig.publicApiKey,
83
+ headers
84
+ });
85
+ const runChatCompletion = (previousMessages) => __async(this, null, function* () {
86
+ var _a, _b, _c, _d, _e;
87
+ setIsLoading(true);
88
+ let newMessages = [
89
+ new import_runtime_client_gql.TextMessage({
154
90
  content: "",
155
- role: "assistant"
156
- }
91
+ role: import_runtime_client_gql.Role.Assistant
92
+ })
157
93
  ];
158
94
  const abortController = new AbortController();
159
95
  abortControllerRef.current = abortController;
160
- setMessages([...messages2, ...newMessages]);
161
- const copilotConfigBody = options.copilotConfig.body || {};
162
- if (threadIdRef.current) {
163
- copilotConfigBody.threadId = threadIdRef.current;
164
- }
165
- if (runIdRef.current) {
166
- copilotConfigBody.runId = runIdRef.current;
167
- }
96
+ setMessages([...previousMessages, ...newMessages]);
168
97
  const systemMessage = makeSystemMessageCallback();
169
- const messagesWithContext = [systemMessage, ...options.initialMessages || [], ...messages2];
170
- const response = yield fetchAndDecodeChatCompletion({
171
- copilotConfig: __spreadProps(__spreadValues({}, options.copilotConfig), { body: copilotConfigBody }),
172
- messages: messagesWithContext,
173
- tools: (_a = options.tools) == null ? void 0 : _a.current,
174
- headers,
175
- signal: abortController.signal
176
- });
177
- if (response.headers.get("threadid")) {
178
- threadIdRef.current = response.headers.get("threadid");
179
- }
180
- if (response.headers.get("runid")) {
181
- runIdRef.current = response.headers.get("runid");
182
- }
183
- if (!response.events) {
184
- setMessages([
185
- ...messages2,
186
- {
187
- id: (0, import_nanoid.nanoid)(),
188
- createdAt: /* @__PURE__ */ new Date(),
189
- content: response.statusText,
190
- role: "assistant"
98
+ const messagesWithContext = [systemMessage, ...initialMessages || [], ...previousMessages];
99
+ const stream = import_runtime_client_gql.CopilotRuntimeClient.asStream(
100
+ runtimeClient.generateCopilotResponse(__spreadValues({
101
+ frontend: {
102
+ actions: actions.map((action) => ({
103
+ name: action.name,
104
+ description: action.description || "",
105
+ jsonSchema: JSON.stringify((0, import_shared.actionParametersToJsonSchema)(action.parameters || []))
106
+ }))
107
+ },
108
+ threadId: threadIdRef.current,
109
+ runId: runIdRef.current,
110
+ messages: (0, import_runtime_client_gql.convertMessagesToGqlInput)(messagesWithContext)
111
+ }, copilotConfig.cloud ? {
112
+ cloud: {
113
+ guardrails: {
114
+ inputValidationRules: {
115
+ allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,
116
+ denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics
117
+ }
118
+ }
191
119
  }
192
- ]);
193
- options.setIsLoading(false);
194
- throw new Error("Failed to fetch chat completion");
195
- }
196
- const reader = response.events.getReader();
197
- let feedback = false;
120
+ } : {}))
121
+ );
122
+ const guardrailsEnabled = ((_c = (_b = (_a = copilotConfig.cloud) == null ? void 0 : _a.guardrails) == null ? void 0 : _b.input) == null ? void 0 : _c.restrictToTopic.enabled) || false;
123
+ const reader = stream.getReader();
124
+ let results = {};
198
125
  try {
199
126
  while (true) {
200
127
  const { done, value } = yield reader.read();
201
128
  if (done) {
202
129
  break;
203
130
  }
204
- let currentMessage = Object.assign({}, newMessages[newMessages.length - 1]);
205
- if (value.type === "content") {
206
- if (currentMessage.function_call || currentMessage.role === "function") {
207
- currentMessage = {
208
- id: (0, import_nanoid.nanoid)(),
209
- createdAt: /* @__PURE__ */ new Date(),
210
- content: "",
211
- role: "assistant"
212
- };
213
- newMessages.push(currentMessage);
214
- }
215
- currentMessage.content += value.content;
216
- newMessages[newMessages.length - 1] = currentMessage;
217
- setMessages([...messages2, ...newMessages]);
218
- } else if (value.type === "result") {
219
- currentMessage = {
220
- id: (0, import_nanoid.nanoid)(),
221
- role: "function",
222
- content: value.content,
223
- name: value.name
224
- };
225
- newMessages.push(currentMessage);
226
- setMessages([...messages2, ...newMessages]);
227
- feedback = true;
228
- } else if (value.type === "function" || value.type === "partial") {
229
- if (currentMessage.content != "" || currentMessage.function_call || currentMessage.role == "function") {
230
- currentMessage = {
231
- id: (0, import_nanoid.nanoid)(),
232
- createdAt: /* @__PURE__ */ new Date(),
233
- content: "",
234
- role: "assistant"
235
- };
236
- newMessages.push(currentMessage);
237
- }
238
- if (value.type === "function") {
239
- currentMessage.function_call = {
240
- name: value.name,
241
- arguments: JSON.stringify(value.arguments),
242
- scope: value.scope
243
- };
244
- } else if (value.type === "partial") {
245
- let partialArguments = {};
246
- try {
247
- partialArguments = JSON.parse((0, import_untruncate_json.default)(value.arguments));
248
- } catch (e) {
249
- }
250
- currentMessage.partialFunctionCall = {
251
- name: value.name,
252
- arguments: partialArguments
253
- };
254
- }
255
- newMessages[newMessages.length - 1] = currentMessage;
256
- setMessages([...messages2, ...newMessages]);
257
- if (value.type === "function") {
258
- try {
259
- if (((_b = options.onFunctionCall) == null ? void 0 : _b.current) && value.scope === "client") {
260
- const result = yield options.onFunctionCall.current(
261
- messages2,
262
- currentMessage.function_call
263
- );
264
- currentMessage = {
265
- id: (0, import_nanoid.nanoid)(),
266
- role: "function",
267
- content: (0, import_shared2.encodeResult)(result),
268
- name: currentMessage.function_call.name
269
- };
270
- newMessages.push(currentMessage);
271
- setMessages([...messages2, ...newMessages]);
272
- feedback = true;
131
+ if (!value.generateCopilotResponse) {
132
+ continue;
133
+ }
134
+ threadIdRef.current = value.generateCopilotResponse.threadId || null;
135
+ runIdRef.current = value.generateCopilotResponse.runId || null;
136
+ const messages2 = (0, import_runtime_client_gql.convertGqlOutputToMessages)(value.generateCopilotResponse.messages);
137
+ if (messages2.length === 0) {
138
+ continue;
139
+ }
140
+ newMessages = [];
141
+ if (((_d = value.generateCopilotResponse.status) == null ? void 0 : _d.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
142
+ newMessages = [
143
+ new import_runtime_client_gql.TextMessage({
144
+ role: import_runtime_client_gql.MessageRole.Assistant,
145
+ content: ((_e = value.generateCopilotResponse.status.details) == null ? void 0 : _e.guardrailsReason) || ""
146
+ })
147
+ ];
148
+ } else {
149
+ for (const message of messages2) {
150
+ newMessages.push(message);
151
+ if (message instanceof import_runtime_client_gql.ActionExecutionMessage && message.status.code !== import_runtime_client_gql.MessageStatusCode.Pending && message.scope === "client" && onFunctionCall) {
152
+ if (!(message.id in results)) {
153
+ if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
154
+ break;
155
+ }
156
+ const result = yield onFunctionCall({
157
+ messages: previousMessages,
158
+ name: message.name,
159
+ args: message.arguments
160
+ });
161
+ results[message.id] = result;
273
162
  }
274
- } catch (error) {
275
- console.error("Failed to execute function call", error);
163
+ newMessages.push(
164
+ new import_runtime_client_gql.ResultMessage({
165
+ result: import_runtime_client_gql.ResultMessage.encodeResult(results[message.id]),
166
+ actionExecutionId: message.id,
167
+ actionName: message.name
168
+ })
169
+ );
276
170
  }
277
171
  }
278
172
  }
173
+ if (newMessages.length > 0) {
174
+ setMessages([...previousMessages, ...newMessages]);
175
+ }
279
176
  }
280
- if (feedback) {
177
+ if (
178
+ // if we have client side results
179
+ Object.values(results).length || // or the last message we received is a result
180
+ newMessages.length && newMessages[newMessages.length - 1] instanceof import_runtime_client_gql.ResultMessage
181
+ ) {
281
182
  yield new Promise((resolve) => setTimeout(resolve, 10));
282
- return yield runChatCompletion([...messages2, ...newMessages]);
183
+ return yield runChatCompletion([...previousMessages, ...newMessages]);
283
184
  } else {
284
185
  return newMessages.slice();
285
186
  }
286
187
  } finally {
287
- options.setIsLoading(false);
188
+ setIsLoading(false);
288
189
  }
289
190
  });
290
191
  const runChatCompletionAndHandleFunctionCall = (messages2) => __async(this, null, function* () {
291
192
  yield runChatCompletion(messages2);
292
193
  });
293
194
  const append = (message) => __async(this, null, function* () {
294
- if (options.isLoading) {
195
+ if (isLoading) {
295
196
  return;
296
197
  }
297
198
  const newMessages = [...messages, message];
@@ -299,12 +200,12 @@ function useChat(options) {
299
200
  return runChatCompletionAndHandleFunctionCall(newMessages);
300
201
  });
301
202
  const reload = () => __async(this, null, function* () {
302
- if (options.isLoading || messages.length === 0) {
203
+ if (isLoading || messages.length === 0) {
303
204
  return;
304
205
  }
305
206
  let newMessages = [...messages];
306
207
  const lastMessage = messages[messages.length - 1];
307
- if (lastMessage.role === "assistant") {
208
+ if (lastMessage instanceof import_runtime_client_gql.TextMessage && lastMessage.role === "assistant") {
308
209
  newMessages = newMessages.slice(0, -1);
309
210
  }
310
211
  setMessages(newMessages);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/use-chat.ts","../../src/utils/fetch-chat-completion.ts"],"sourcesContent":["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?: React.MutableRefObject<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?: React.MutableRefObject<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?.current,\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?.current && value.scope === \"client\") {\n const result = await options.onFunctionCall.current(\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAwD;AAExD,IAAAA,iBAOO;AAEP,oBAAuB;;;ACXvB,oBAQO;AAgBP,SAAsB,oBAAoB,IAUO;AAAA,6CAVP;AAAA,IACxC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAAiD;AAC/C,kCAAgB;AAChB,sBAAU,CAAC;AAGX,UAAM,kBAAkB,SAAS,IAAI,CAAC,YAAY;AAChD,YAAM,EAAE,SAAS,MAAM,MAAM,cAAc,IAAI;AAC/C,aAAO,EAAE,SAAS,MAAM,MAAM,cAAc;AAAA,IAC9C,CAAC;AAED,gCAAe;AAEf,UAAM,WAAW,MAAM,MAAM,cAAc,iBAAiB;AAAA,MAC1D,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,SACb,cAAc,UACb,UAAU,mBAAK,WAAY,CAAC;AAAA,MAElC,MAAM,KAAK,UAAU;AAAA,QACnB;AAAA,QACA,UAAU;AAAA,QACV,QAAQ;AAAA,SACJ,MAAM,SAAS,EAAE,MAAM,IAAI,CAAC,IAC5B,cAAc,EAAE,YAAY,IAAI,CAAC,IACjC,MAAM,UAAU,IAAI,EAAE,aAAa,WAAW,IAAI,CAAC,IACpD,cAAc,OACd,cAAc,mBACd,wBAAwB,aAAa,IACpC,OAAO,mBAAK,Q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AW;AAAA,EAC3D;AAEA,QAAM,SAAS,MAA2B;AACxC,QAAI,QAAQ,aAAa,SAAS,WAAW,GAAG;AAC9C;AAAA,IACF;AACA,QAAI,cAAc,CAAC,GAAG,QAAQ;AAC9B,UAAM,cAAc,SAAS,SAAS,SAAS,CAAC;AAEhD,QAAI,YAAY,SAAS,aAAa;AACpC,oBAAc,YAAY,MAAM,GAAG,EAAE;AAAA,IACvC;AACA,gBAAY,WAAW;AAEvB,WAAO,uCAAuC,WAAW;AAAA,EAC3D;AAEA,QAAM,OAAO,MAAY;AAzU3B;AA0UI,6BAAmB,YAAnB,mBAA4B;AAAA,EAC9B;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["import_shared","messages","untruncateJson"]}
1
+ {"version":3,"sources":["../../src/hooks/use-chat.ts"],"sourcesContent":["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 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 );\n\n const guardrailsEnabled =\n copilotConfig.cloud?.guardrails?.input?.restrictToTopic.enabled || false;\n\n // TODO-PROTOCOL make sure all options are included in the final version\n //\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 // TODO-PROTOCOL handle errors\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 = 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;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SAAS,MAA2B;AACxC,QAAI,aAAa,SAAS,WAAW,GAAG;AACtC;AAAA,IACF;AACA,QAAI,cAAc,CAAC,GAAG,QAAQ;AAC9B,UAAM,cAAc,SAAS,SAAS,SAAS,CAAC;AAEhD,QAAI,uBAAuB,yCAAe,YAAY,SAAS,aAAa;AAC1E,oBAAc,YAAY,MAAM,GAAG,EAAE;AAAA,IACvC;AAEA,gBAAY,WAAW;AAEvB,WAAO,uCAAuC,WAAW;AAAA,EAC3D;AAEA,QAAM,OAAO,MAAY;AAjU3B;AAkUI,6BAAmB,YAAnB,mBAA4B;AAAA,EAC9B;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["messages"]}
@@ -1,7 +1,6 @@
1
1
  import {
2
2
  useChat
3
- } from "../chunk-3XVO5UEG.mjs";
4
- import "../chunk-MJKBCG4U.mjs";
3
+ } from "../chunk-MW2IVCDP.mjs";
5
4
  import "../chunk-SKC7AJIV.mjs";
6
5
  export {
7
6
  useChat
@@ -58,17 +58,16 @@ var import_react2 = require("react");
58
58
  // src/context/copilot-context.tsx
59
59
  var import_react = __toESM(require("react"));
60
60
  var emptyCopilotContext = {
61
- entryPoints: {},
62
- setEntryPoint: () => {
61
+ actions: {},
62
+ setAction: () => {
63
63
  },
64
- removeEntryPoint: () => {
64
+ removeAction: () => {
65
65
  },
66
66
  chatComponentsCache: { current: {} },
67
67
  getContextString: (documents, categories) => returnAndThrowInDebug(""),
68
68
  addContext: () => "",
69
69
  removeContext: () => {
70
70
  },
71
- getChatCompletionFunctionDescriptions: () => returnAndThrowInDebug([]),
72
71
  getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
73
72
  })),
74
73
  messages: [],
@@ -110,11 +109,11 @@ function returnAndThrowInDebug(value) {
110
109
  // src/hooks/use-copilot-action.ts
111
110
  var import_nanoid = require("nanoid");
112
111
  function useCopilotAction(action, dependencies) {
113
- const { setEntryPoint, removeEntryPoint, entryPoints, chatComponentsCache } = (0, import_react2.useContext)(CopilotContext);
112
+ const { setAction, removeAction, actions, chatComponentsCache } = (0, import_react2.useContext)(CopilotContext);
114
113
  const idRef = (0, import_react2.useRef)((0, import_nanoid.nanoid)());
115
114
  if (dependencies === void 0) {
116
- if (entryPoints[idRef.current]) {
117
- entryPoints[idRef.current].handler = action.handler;
115
+ if (actions[idRef.current]) {
116
+ actions[idRef.current].handler = action.handler;
118
117
  if (typeof action.render === "function") {
119
118
  if (chatComponentsCache.current !== null) {
120
119
  chatComponentsCache.current[action.name] = action.render;
@@ -123,16 +122,16 @@ function useCopilotAction(action, dependencies) {
123
122
  }
124
123
  }
125
124
  (0, import_react2.useEffect)(() => {
126
- setEntryPoint(idRef.current, action);
125
+ setAction(idRef.current, action);
127
126
  if (chatComponentsCache.current !== null && action.render !== void 0) {
128
127
  chatComponentsCache.current[action.name] = action.render;
129
128
  }
130
129
  return () => {
131
- removeEntryPoint(idRef.current);
130
+ removeAction(idRef.current);
132
131
  };
133
132
  }, [
134
- setEntryPoint,
135
- removeEntryPoint,
133
+ setAction,
134
+ removeAction,
136
135
  action.description,
137
136
  action.name,
138
137
  // This should be faster than deep equality checking
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/use-copilot-action.ts","../../src/context/copilot-context.tsx"],"sourcesContent":["import { useRef, useContext, useEffect } from \"react\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { nanoid } from \"nanoid\";\nimport { Parameter } from \"@copilotkit/shared\";\n\n// We implement useCopilotAction dependency handling so that\n// the developer has the option to not provide any dependencies.\n// In this case, we assume they want to update the handler on each rerender.\n// To avoid getting stuck in an infinite loop, we update the handler directly,\n// skipping React state updates.\n// This is ok in this case, because the handler is not part of any UI that\n// needs to be updated.\n// useCallback, useMemo or other memoization techniques are not suitable here,\n// because they will cause a infinite rerender loop.\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { setEntryPoint, removeEntryPoint, entryPoints, chatComponentsCache } =\n useContext(CopilotContext);\n const idRef = useRef<string>(nanoid());\n\n // If the developer doesn't provide dependencies, we assume they want to\n // update handler and render function when the action object changes.\n // This ensures that any captured variables in the handler are up to date.\n if (dependencies === undefined) {\n if (entryPoints[idRef.current]) {\n entryPoints[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current[action.name] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n setEntryPoint(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current[action.name] = action.render;\n }\n return () => {\n // NOTE: For now, we don't remove the chatComponentsCache entry when the action is removed.\n // This is because we currently don't have access to the messages array in CopilotContext.\n removeEntryPoint(idRef.current);\n };\n }, [\n setEntryPoint,\n removeEntryPoint,\n action.description,\n action.name,\n // This should be faster than deep equality checking\n // In addition, all major JS engines guarantee the order of object keys\n JSON.stringify(action.parameters),\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n\n// Usage Example:\n// useCopilotAction({\n// name: \"myAction\",\n// parameters: [\n// { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n// { name: \"arg2\", type: \"number\" },\n// {\n// name: \"arg3\",\n// type: \"object\",\n// attributes: [\n// { name: \"nestedArg1\", type: \"boolean\" },\n// { name: \"xyz\", required: false },\n// ],\n// },\n// { name: \"arg4\", type: \"number[]\" },\n// ],\n// handler: ({ arg1, arg2, arg3, arg4 }) => {\n// const x = arg3.nestedArg1;\n// const z = arg3.xyz;\n// console.log(arg1, arg2, arg3);\n// },\n// });\n\n// useCopilotAction({\n// name: \"myAction\",\n// handler: () => {\n// console.log(\"No parameters provided.\");\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,gBAA8C;;;ACO9C,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,EAClB,eAAe,MAAM;AAAA,EAAC;AAAA,EAEtB,uCAAuC,MAAM,sBAAsB,CAAC,CAAC;AAAA,EACrE,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,EACvE,oBAAoB,MAAM,sBAA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,EACF,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,OAAO;AAAA;AAAA;AAAA,IAGP,KAAK,UAAU,OAAO,UAAU;AAAA;AAAA,IAEhC,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA;AAAA,IAEpD,GAAI,gBAAgB,CAAC;AAAA,EACvB,CAAC;AACH;","names":["import_react","React"]}
1
+ {"version":3,"sources":["../../src/hooks/use-copilot-action.ts","../../src/context/copilot-context.tsx"],"sourcesContent":["import { useRef, useContext, useEffect } from \"react\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { nanoid } from \"nanoid\";\nimport { Parameter } from \"@copilotkit/shared\";\n\n// We implement useCopilotAction dependency handling so that\n// the developer has the option to not provide any dependencies.\n// In this case, we assume they want to update the handler on each rerender.\n// To avoid getting stuck in an infinite loop, we update the handler directly,\n// skipping React state updates.\n// This is ok in this case, because the handler is not part of any UI that\n// needs to be updated.\n// useCallback, useMemo or other memoization techniques are not suitable here,\n// because they will cause a infinite rerender loop.\nexport function useCopilotAction<const T extends Parameter[] | [] = []>(\n action: FrontendAction<T>,\n dependencies?: any[],\n): void {\n const { setAction, removeAction, actions, chatComponentsCache } = useContext(CopilotContext);\n const idRef = useRef<string>(nanoid());\n\n // If the developer doesn't provide dependencies, we assume they want to\n // update handler and render function when the action object changes.\n // This ensures that any captured variables in the handler are up to date.\n if (dependencies === undefined) {\n if (actions[idRef.current]) {\n actions[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current[action.name] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n setAction(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current[action.name] = action.render;\n }\n return () => {\n // NOTE: For now, we don't remove the chatComponentsCache entry when the action is removed.\n // This is because we currently don't have access to the messages array in CopilotContext.\n removeAction(idRef.current);\n };\n }, [\n setAction,\n removeAction,\n action.description,\n action.name,\n // This should be faster than deep equality checking\n // In addition, all major JS engines guarantee the order of object keys\n JSON.stringify(action.parameters),\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n\n// Usage Example:\n// useCopilotAction({\n// name: \"myAction\",\n// parameters: [\n// { name: \"arg1\", type: \"string\", enum: [\"option1\", \"option2\", \"option3\"], required: false },\n// { name: \"arg2\", type: \"number\" },\n// {\n// name: \"arg3\",\n// type: \"object\",\n// attributes: [\n// { name: \"nestedArg1\", type: \"boolean\" },\n// { name: \"xyz\", required: false },\n// ],\n// },\n// { name: \"arg4\", type: \"number[]\" },\n// ],\n// handler: ({ arg1, arg2, arg3, arg4 }) => {\n// const x = arg3.nestedArg1;\n// const z = arg3.xyz;\n// console.log(arg1, arg2, arg3);\n// },\n// });\n\n// useCopilotAction({\n// name: \"myAction\",\n// handler: () => {\n// console.log(\"No parameters provided.\");\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 * 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 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,gBAA8C;;;ACG9C,mBAAkB;AA8HlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM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e,sBAAO,CAAC;AAKrC,MAAI,iBAAiB,QAAW;AAC9B,QAAI,QAAQ,MAAM,OAAO,GAAG;AAC1B,cAAQ,MAAM,OAAO,EAAE,UAAU,OAAO;AACxC,UAAI,OAAO,OAAO,WAAW,YAAY;AACvC,YAAI,oBAAoB,YAAY,MAAM;AACxC,8BAAoB,QAAQ,OAAO,IAAI,IAAI,OAAO;AAAA,QACpD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,+BAAU,MAAM;AACd,cAAU,MAAM,SAAS,MAAa;AACtC,QAAI,oBAAoB,YAAY,QAAQ,OAAO,WAAW,QAAW;AACvE,0BAAoB,QAAQ,OAAO,IAAI,IAAI,OAAO;AAAA,IACpD;AACA,WAAO,MAAM;AAGX,mBAAa,MAAM,OAAO;AAAA,IAC5B;AAAA,EACF,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,OAAO;AAAA;AAAA;AAAA,IAGP,KAAK,UAAU,OAAO,UAAU;AAAA;AAAA,IAEhC,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA;AAAA,IAEpD,GAAI,gBAAgB,CAAC;AAAA,EACvB,CAAC;AACH;","names":["import_react","React"]}
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  useCopilotAction
3
- } from "../chunk-NSUYO6TP.mjs";
4
- import "../chunk-DY63PD22.mjs";
3
+ } from "../chunk-MI7BERU7.mjs";
4
+ import "../chunk-GLPZSBNA.mjs";
5
5
  import "../chunk-SKC7AJIV.mjs";
6
6
  export {
7
7
  useCopilotAction
@@ -1,4 +1,4 @@
1
- import { Message } from '@copilotkit/shared';
1
+ import { Message } from '@copilotkit/runtime-client-gql';
2
2
  import { SystemMessageFunction } from '../types/system-message.js';
3
3
 
4
4
  interface UseCopilotChatOptions {