@copilotkit/react-core 0.37.0 → 0.38.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/.turbo/turbo-build.log +187 -234
  2. package/CHANGELOG.md +12 -0
  3. package/dist/{chunk-HUKLBIUK.mjs → chunk-5CKW6KE7.mjs} +13 -22
  4. package/dist/chunk-5CKW6KE7.mjs.map +1 -0
  5. package/dist/{chunk-S5LWO5V3.mjs → chunk-7GPIOOXB.mjs} +2 -2
  6. package/dist/{chunk-LLU5URI5.mjs → chunk-DDHJCFFV.mjs} +18 -33
  7. package/dist/chunk-DDHJCFFV.mjs.map +1 -0
  8. package/dist/{chunk-SR4RW4CU.mjs → chunk-IQCLNCGL.mjs} +6 -6
  9. package/dist/chunk-IQCLNCGL.mjs.map +1 -0
  10. package/dist/{chunk-DY63PD22.mjs → chunk-K6EV2CNB.mjs} +4 -5
  11. package/dist/chunk-K6EV2CNB.mjs.map +1 -0
  12. package/dist/{chunk-NSUYO6TP.mjs → chunk-LZVHW3T3.mjs} +9 -9
  13. package/dist/chunk-LZVHW3T3.mjs.map +1 -0
  14. package/dist/{chunk-Z5FB4WBL.mjs → chunk-NY6QSOU7.mjs} +43 -40
  15. package/dist/chunk-NY6QSOU7.mjs.map +1 -0
  16. package/dist/chunk-PHMHNAYC.mjs +192 -0
  17. package/dist/chunk-PHMHNAYC.mjs.map +1 -0
  18. package/dist/{chunk-B244LK6F.mjs → chunk-QNJQKKD4.mjs} +2 -2
  19. package/dist/{chunk-4OIVQMEM.mjs → chunk-WU3I3G3G.mjs} +60 -42
  20. package/dist/chunk-WU3I3G3G.mjs.map +1 -0
  21. package/dist/chunk-YJLRG5U3.mjs +1 -0
  22. package/dist/{chunk-MNZXQ6UH.mjs → chunk-YM2JV2YQ.mjs} +2 -2
  23. package/dist/components/copilot-provider/copilotkit-props.d.ts +2 -2
  24. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  25. package/dist/components/copilot-provider/copilotkit.js +18 -33
  26. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  27. package/dist/components/copilot-provider/copilotkit.mjs +2 -2
  28. package/dist/components/copilot-provider/index.js +18 -33
  29. package/dist/components/copilot-provider/index.js.map +1 -1
  30. package/dist/components/copilot-provider/index.mjs +2 -2
  31. package/dist/components/index.js +18 -33
  32. package/dist/components/index.js.map +1 -1
  33. package/dist/components/index.mjs +2 -2
  34. package/dist/context/copilot-context.d.ts +7 -18
  35. package/dist/context/copilot-context.js +3 -4
  36. package/dist/context/copilot-context.js.map +1 -1
  37. package/dist/context/copilot-context.mjs +1 -1
  38. package/dist/context/index.d.ts +1 -0
  39. package/dist/context/index.js +3 -4
  40. package/dist/context/index.js.map +1 -1
  41. package/dist/context/index.mjs +1 -1
  42. package/dist/hooks/index.d.ts +2 -1
  43. package/dist/hooks/index.js +140 -229
  44. package/dist/hooks/index.js.map +1 -1
  45. package/dist/hooks/index.mjs +9 -10
  46. package/dist/hooks/use-chat.d.ts +25 -51
  47. package/dist/hooks/use-chat.js +109 -203
  48. package/dist/hooks/use-chat.js.map +1 -1
  49. package/dist/hooks/use-chat.mjs +1 -2
  50. package/dist/hooks/use-copilot-action.js +10 -11
  51. package/dist/hooks/use-copilot-action.js.map +1 -1
  52. package/dist/hooks/use-copilot-action.mjs +2 -2
  53. package/dist/hooks/use-copilot-chat.d.ts +1 -1
  54. package/dist/hooks/use-copilot-chat.js +123 -212
  55. package/dist/hooks/use-copilot-chat.js.map +1 -1
  56. package/dist/hooks/use-copilot-chat.mjs +4 -5
  57. package/dist/hooks/use-copilot-readable.js +3 -4
  58. package/dist/hooks/use-copilot-readable.js.map +1 -1
  59. package/dist/hooks/use-copilot-readable.mjs +2 -2
  60. package/dist/hooks/use-make-copilot-actionable.js +7 -8
  61. package/dist/hooks/use-make-copilot-actionable.js.map +1 -1
  62. package/dist/hooks/use-make-copilot-actionable.mjs +2 -2
  63. package/dist/hooks/use-make-copilot-document-readable.js +3 -4
  64. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  65. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  66. package/dist/hooks/use-make-copilot-readable.js +3 -4
  67. package/dist/hooks/use-make-copilot-readable.js.map +1 -1
  68. package/dist/hooks/use-make-copilot-readable.mjs +2 -2
  69. package/dist/index.d.ts +1 -3
  70. package/dist/index.js +239 -497
  71. package/dist/index.js.map +1 -1
  72. package/dist/index.mjs +12 -31
  73. package/dist/lib/copilot-task.d.ts +1 -0
  74. package/dist/lib/copilot-task.js +34 -110
  75. package/dist/lib/copilot-task.js.map +1 -1
  76. package/dist/lib/copilot-task.mjs +3 -4
  77. package/dist/lib/index.d.ts +1 -0
  78. package/dist/lib/index.js +36 -110
  79. package/dist/lib/index.js.map +1 -1
  80. package/dist/lib/index.mjs +3 -4
  81. package/dist/utils/extract.d.ts +1 -0
  82. package/dist/utils/extract.js +53 -109
  83. package/dist/utils/extract.js.map +1 -1
  84. package/dist/utils/extract.mjs +3 -4
  85. package/dist/utils/index.d.ts +1 -1
  86. package/dist/utils/index.js +56 -132
  87. package/dist/utils/index.js.map +1 -1
  88. package/dist/utils/index.mjs +5 -13
  89. package/package.json +6 -5
  90. package/src/components/copilot-provider/copilotkit-props.tsx +2 -2
  91. package/src/components/copilot-provider/copilotkit.tsx +16 -37
  92. package/src/context/copilot-context.tsx +11 -30
  93. package/src/hooks/use-chat.ts +179 -208
  94. package/src/hooks/use-copilot-action.ts +7 -8
  95. package/src/hooks/use-copilot-chat.ts +9 -23
  96. package/src/hooks/use-make-copilot-actionable.ts +4 -4
  97. package/src/index.tsx +0 -1
  98. package/src/lib/copilot-task.ts +45 -42
  99. package/src/utils/extract.ts +64 -36
  100. package/src/utils/index.ts +0 -7
  101. package/dist/chunk-2EQGN5QK.mjs +0 -137
  102. package/dist/chunk-2EQGN5QK.mjs.map +0 -1
  103. package/dist/chunk-4OIVQMEM.mjs.map +0 -1
  104. package/dist/chunk-7GFKOIO7.mjs +0 -1
  105. package/dist/chunk-B2H3NC4E.mjs +0 -204
  106. package/dist/chunk-B2H3NC4E.mjs.map +0 -1
  107. package/dist/chunk-BABVSMJR.mjs +0 -1
  108. package/dist/chunk-BABVSMJR.mjs.map +0 -1
  109. package/dist/chunk-CYDWEPFL.mjs +0 -1
  110. package/dist/chunk-CYDWEPFL.mjs.map +0 -1
  111. package/dist/chunk-DY63PD22.mjs.map +0 -1
  112. package/dist/chunk-FRAKUJWH.mjs +0 -1
  113. package/dist/chunk-FRAKUJWH.mjs.map +0 -1
  114. package/dist/chunk-HUKLBIUK.mjs.map +0 -1
  115. package/dist/chunk-LLU5URI5.mjs.map +0 -1
  116. package/dist/chunk-MJKBCG4U.mjs +0 -91
  117. package/dist/chunk-MJKBCG4U.mjs.map +0 -1
  118. package/dist/chunk-NSUYO6TP.mjs.map +0 -1
  119. package/dist/chunk-SR4RW4CU.mjs.map +0 -1
  120. package/dist/chunk-Z5FB4WBL.mjs.map +0 -1
  121. package/dist/chunk-ZFS5SQUT.mjs +0 -31
  122. package/dist/chunk-ZFS5SQUT.mjs.map +0 -1
  123. package/dist/openai-assistants/hooks/index.d.ts +0 -2
  124. package/dist/openai-assistants/hooks/index.js +0 -277
  125. package/dist/openai-assistants/hooks/index.js.map +0 -1
  126. package/dist/openai-assistants/hooks/index.mjs +0 -18
  127. package/dist/openai-assistants/hooks/index.mjs.map +0 -1
  128. package/dist/openai-assistants/hooks/use-assistants.d.ts +0 -17
  129. package/dist/openai-assistants/hooks/use-assistants.js +0 -154
  130. package/dist/openai-assistants/hooks/use-assistants.js.map +0 -1
  131. package/dist/openai-assistants/hooks/use-assistants.mjs +0 -92
  132. package/dist/openai-assistants/hooks/use-assistants.mjs.map +0 -1
  133. package/dist/openai-assistants/hooks/use-copilot-chat-v2.d.ts +0 -44
  134. package/dist/openai-assistants/hooks/use-copilot-chat-v2.js +0 -277
  135. package/dist/openai-assistants/hooks/use-copilot-chat-v2.js.map +0 -1
  136. package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs +0 -19
  137. package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs.map +0 -1
  138. package/dist/openai-assistants/index.d.ts +0 -3
  139. package/dist/openai-assistants/index.js +0 -279
  140. package/dist/openai-assistants/index.js.map +0 -1
  141. package/dist/openai-assistants/index.mjs +0 -22
  142. package/dist/openai-assistants/index.mjs.map +0 -1
  143. package/dist/openai-assistants/utils/index.d.ts +0 -1
  144. package/dist/openai-assistants/utils/index.js +0 -73
  145. package/dist/openai-assistants/utils/index.js.map +0 -1
  146. package/dist/openai-assistants/utils/index.mjs +0 -9
  147. package/dist/openai-assistants/utils/index.mjs.map +0 -1
  148. package/dist/openai-assistants/utils/process-message-stream.d.ts +0 -3
  149. package/dist/openai-assistants/utils/process-message-stream.js +0 -71
  150. package/dist/openai-assistants/utils/process-message-stream.js.map +0 -1
  151. package/dist/openai-assistants/utils/process-message-stream.mjs +0 -8
  152. package/dist/openai-assistants/utils/process-message-stream.mjs.map +0 -1
  153. package/dist/utils/fetch-chat-completion.d.ts +0 -36
  154. package/dist/utils/fetch-chat-completion.js +0 -141
  155. package/dist/utils/fetch-chat-completion.js.map +0 -1
  156. package/dist/utils/fetch-chat-completion.mjs +0 -12
  157. package/dist/utils/fetch-chat-completion.mjs.map +0 -1
  158. package/src/openai-assistants/hooks/index.ts +0 -9
  159. package/src/openai-assistants/hooks/use-assistants.ts +0 -112
  160. package/src/openai-assistants/hooks/use-copilot-chat-v2.ts +0 -189
  161. package/src/openai-assistants/index.ts +0 -2
  162. package/src/openai-assistants/utils/index.ts +0 -1
  163. package/src/openai-assistants/utils/process-message-stream.ts +0 -25
  164. package/src/utils/fetch-chat-completion.ts +0 -120
  165. /package/dist/{chunk-S5LWO5V3.mjs.map → chunk-7GPIOOXB.mjs.map} +0 -0
  166. /package/dist/{chunk-B244LK6F.mjs.map → chunk-QNJQKKD4.mjs.map} +0 -0
  167. /package/dist/{chunk-7GFKOIO7.mjs.map → chunk-YJLRG5U3.mjs.map} +0 -0
  168. /package/dist/{chunk-MNZXQ6UH.mjs.map → chunk-YM2JV2YQ.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,226 +58,145 @@ __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
- options.setIsLoading(true);
149
- const newMessages = [
150
- {
151
- id: (0, import_nanoid.nanoid)(),
152
- 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, _f;
87
+ setIsLoading(true);
88
+ let newMessages = [
89
+ new import_runtime_client_gql.TextMessage({
153
90
  content: "",
154
- role: "assistant"
155
- }
91
+ role: import_runtime_client_gql.Role.Assistant
92
+ })
156
93
  ];
157
94
  const abortController = new AbortController();
158
95
  abortControllerRef.current = abortController;
159
- setMessages([...messages2, ...newMessages]);
160
- const copilotConfigBody = options.copilotConfig.body || {};
161
- if (threadIdRef.current) {
162
- copilotConfigBody.threadId = threadIdRef.current;
163
- }
164
- if (runIdRef.current) {
165
- copilotConfigBody.runId = runIdRef.current;
166
- }
96
+ setMessages([...previousMessages, ...newMessages]);
167
97
  const systemMessage = makeSystemMessageCallback();
168
- const messagesWithContext = [systemMessage, ...options.initialMessages || [], ...messages2];
169
- const response = yield fetchAndDecodeChatCompletion({
170
- copilotConfig: __spreadProps(__spreadValues({}, options.copilotConfig), { body: copilotConfigBody }),
171
- messages: messagesWithContext,
172
- tools: options.tools,
173
- headers,
174
- signal: abortController.signal
175
- });
176
- if (response.headers.get("threadid")) {
177
- threadIdRef.current = response.headers.get("threadid");
178
- }
179
- if (response.headers.get("runid")) {
180
- runIdRef.current = response.headers.get("runid");
181
- }
182
- if (!response.events) {
183
- setMessages([
184
- ...messages2,
185
- {
186
- id: (0, import_nanoid.nanoid)(),
187
- createdAt: /* @__PURE__ */ new Date(),
188
- content: response.statusText,
189
- role: "assistant"
190
- }
191
- ]);
192
- options.setIsLoading(false);
193
- throw new Error("Failed to fetch chat completion");
194
- }
195
- const reader = response.events.getReader();
196
- let feedback = false;
98
+ const messagesWithContext = [systemMessage, ...initialMessages || [], ...previousMessages];
99
+ const stream = import_runtime_client_gql.CopilotRuntimeClient.asStream(
100
+ runtimeClient.generateCopilotResponse(
101
+ __spreadValues({
102
+ frontend: {
103
+ actions: actions.map((action) => ({
104
+ name: action.name,
105
+ description: action.description || "",
106
+ jsonSchema: JSON.stringify((0, import_shared.actionParametersToJsonSchema)(action.parameters || []))
107
+ }))
108
+ },
109
+ threadId: threadIdRef.current,
110
+ runId: runIdRef.current,
111
+ messages: (0, import_runtime_client_gql.convertMessagesToGqlInput)(messagesWithContext)
112
+ }, copilotConfig.cloud ? {
113
+ cloud: {
114
+ guardrails: {
115
+ inputValidationRules: {
116
+ allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,
117
+ denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics
118
+ }
119
+ }
120
+ }
121
+ } : {}),
122
+ copilotConfig.properties,
123
+ (_a = abortControllerRef.current) == null ? void 0 : _a.signal
124
+ )
125
+ );
126
+ const guardrailsEnabled = ((_d = (_c = (_b = copilotConfig.cloud) == null ? void 0 : _b.guardrails) == null ? void 0 : _c.input) == null ? void 0 : _d.restrictToTopic.enabled) || false;
127
+ const reader = stream.getReader();
128
+ let results = {};
197
129
  try {
198
130
  while (true) {
199
131
  const { done, value } = yield reader.read();
200
132
  if (done) {
201
133
  break;
202
134
  }
203
- let currentMessage = Object.assign({}, newMessages[newMessages.length - 1]);
204
- if (value.type === "content") {
205
- if (currentMessage.function_call || currentMessage.role === "function") {
206
- currentMessage = {
207
- id: (0, import_nanoid.nanoid)(),
208
- createdAt: /* @__PURE__ */ new Date(),
209
- content: "",
210
- role: "assistant"
211
- };
212
- newMessages.push(currentMessage);
213
- }
214
- currentMessage.content += value.content;
215
- newMessages[newMessages.length - 1] = currentMessage;
216
- setMessages([...messages2, ...newMessages]);
217
- } else if (value.type === "result") {
218
- currentMessage = {
219
- id: (0, import_nanoid.nanoid)(),
220
- role: "function",
221
- content: value.content,
222
- name: value.name
223
- };
224
- newMessages.push(currentMessage);
225
- setMessages([...messages2, ...newMessages]);
226
- feedback = true;
227
- } else if (value.type === "function" || value.type === "partial") {
228
- if (currentMessage.content != "" || currentMessage.function_call || currentMessage.role == "function") {
229
- currentMessage = {
230
- id: (0, import_nanoid.nanoid)(),
231
- createdAt: /* @__PURE__ */ new Date(),
232
- content: "",
233
- role: "assistant"
234
- };
235
- newMessages.push(currentMessage);
236
- }
237
- if (value.type === "function") {
238
- currentMessage.function_call = {
239
- name: value.name,
240
- arguments: JSON.stringify(value.arguments),
241
- scope: value.scope
242
- };
243
- } else if (value.type === "partial") {
244
- let partialArguments = {};
245
- try {
246
- partialArguments = JSON.parse((0, import_untruncate_json.default)(value.arguments));
247
- } catch (e) {
248
- }
249
- currentMessage.partialFunctionCall = {
250
- name: value.name,
251
- arguments: partialArguments
252
- };
253
- }
254
- newMessages[newMessages.length - 1] = currentMessage;
255
- setMessages([...messages2, ...newMessages]);
256
- if (value.type === "function") {
257
- try {
258
- if (options.onFunctionCall && value.scope === "client") {
259
- const result = yield options.onFunctionCall(
260
- messages2,
261
- currentMessage.function_call
262
- );
263
- currentMessage = {
264
- id: (0, import_nanoid.nanoid)(),
265
- role: "function",
266
- content: (0, import_shared2.encodeResult)(result),
267
- name: currentMessage.function_call.name
268
- };
269
- newMessages.push(currentMessage);
270
- setMessages([...messages2, ...newMessages]);
271
- feedback = true;
135
+ if (!(value == null ? void 0 : value.generateCopilotResponse)) {
136
+ continue;
137
+ }
138
+ threadIdRef.current = value.generateCopilotResponse.threadId || null;
139
+ runIdRef.current = value.generateCopilotResponse.runId || null;
140
+ const messages2 = (0, import_runtime_client_gql.convertGqlOutputToMessages)(value.generateCopilotResponse.messages);
141
+ if (messages2.length === 0) {
142
+ continue;
143
+ }
144
+ newMessages = [];
145
+ if (((_e = value.generateCopilotResponse.status) == null ? void 0 : _e.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
146
+ newMessages = [
147
+ new import_runtime_client_gql.TextMessage({
148
+ role: import_runtime_client_gql.MessageRole.Assistant,
149
+ content: ((_f = value.generateCopilotResponse.status.details) == null ? void 0 : _f.guardrailsReason) || ""
150
+ })
151
+ ];
152
+ } else {
153
+ for (const message of messages2) {
154
+ newMessages.push(message);
155
+ if (message instanceof import_runtime_client_gql.ActionExecutionMessage && message.status.code !== import_runtime_client_gql.MessageStatusCode.Pending && message.scope === "client" && onFunctionCall) {
156
+ if (!(message.id in results)) {
157
+ if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
158
+ break;
159
+ }
160
+ const result = yield onFunctionCall({
161
+ messages: previousMessages,
162
+ name: message.name,
163
+ args: message.arguments
164
+ });
165
+ results[message.id] = result;
272
166
  }
273
- } catch (error) {
274
- console.error("Failed to execute function call", error);
167
+ newMessages.push(
168
+ new import_runtime_client_gql.ResultMessage({
169
+ result: import_runtime_client_gql.ResultMessage.encodeResult(results[message.id]),
170
+ actionExecutionId: message.id,
171
+ actionName: message.name
172
+ })
173
+ );
275
174
  }
276
175
  }
277
176
  }
177
+ if (newMessages.length > 0) {
178
+ setMessages([...previousMessages, ...newMessages]);
179
+ }
278
180
  }
279
- if (feedback) {
181
+ if (
182
+ // if we have client side results
183
+ Object.values(results).length || // or the last message we received is a result
184
+ newMessages.length && newMessages[newMessages.length - 1] instanceof import_runtime_client_gql.ResultMessage
185
+ ) {
280
186
  yield new Promise((resolve) => setTimeout(resolve, 10));
281
- return yield runChatCompletion([...messages2, ...newMessages]);
187
+ return yield runChatCompletion([...previousMessages, ...newMessages]);
282
188
  } else {
283
189
  return newMessages.slice();
284
190
  }
285
191
  } finally {
286
- options.setIsLoading(false);
192
+ setIsLoading(false);
287
193
  }
288
194
  });
289
195
  const runChatCompletionAndHandleFunctionCall = (messages2) => __async(this, null, function* () {
290
196
  yield runChatCompletion(messages2);
291
197
  });
292
198
  const append = (message) => __async(this, null, function* () {
293
- if (options.isLoading) {
199
+ if (isLoading) {
294
200
  return;
295
201
  }
296
202
  const newMessages = [...messages, message];
@@ -298,12 +204,12 @@ function useChat(options) {
298
204
  return runChatCompletionAndHandleFunctionCall(newMessages);
299
205
  });
300
206
  const reload = () => __async(this, null, function* () {
301
- if (options.isLoading || messages.length === 0) {
207
+ if (isLoading || messages.length === 0) {
302
208
  return;
303
209
  }
304
210
  let newMessages = [...messages];
305
211
  const lastMessage = messages[messages.length - 1];
306
- if (lastMessage.role === "assistant") {
212
+ if (lastMessage instanceof import_runtime_client_gql.TextMessage && lastMessage.role === "assistant") {
307
213
  newMessages = newMessages.slice(0, -1);
308
214
  }
309
215
  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?: FunctionCallHandler;\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n /**\n * Extra body object to be sent with the API request.\n * @example\n * Send a `sessionId` to the API along with the messages.\n * ```js\n * useChat({\n * body: {\n * sessionId: '123',\n * }\n * })\n * ```\n */\n body?: object;\n /**\n * Function definitions to be sent to the API.\n */\n tools?: ToolDefinition[];\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: () => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n};\n\nexport type UseChatOptionsWithCopilotConfig = UseChatOptions & {\n copilotConfig: CopilotApiConfig;\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * A callback to get the latest system message.\n */\n makeSystemMessageCallback: () => Message;\n\n /**\n * Whether the API request is in progress\n */\n isLoading: boolean;\n\n /**\n * setState-powered method to update the isChatLoading value\n */\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n};\n\nexport function useChat(options: UseChatOptionsWithCopilotConfig): UseChatHelpers {\n const { messages, setMessages, makeSystemMessageCallback } = options;\n const abortControllerRef = useRef<AbortController>();\n const threadIdRef = useRef<string | null>(null);\n const runIdRef = useRef<string | null>(null);\n const publicApiKey = options.copilotConfig.publicApiKey;\n const headers = {\n ...(options.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const runChatCompletion = async (messages: Message[]): Promise<Message[]> => {\n options.setIsLoading(true);\n\n const newMessages: Message[] = [\n {\n id: nanoid(),\n createdAt: new Date(),\n content: \"\",\n role: \"assistant\",\n },\n ];\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setMessages([...messages, ...newMessages]);\n // add threadId and runId to the body if it exists\n const copilotConfigBody = options.copilotConfig.body || {};\n if (threadIdRef.current) {\n copilotConfigBody.threadId = threadIdRef.current;\n }\n if (runIdRef.current) {\n copilotConfigBody.runId = runIdRef.current;\n }\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(options.initialMessages || []), ...messages];\n const response = await fetchAndDecodeChatCompletion({\n copilotConfig: { ...options.copilotConfig, body: copilotConfigBody },\n messages: messagesWithContext,\n tools: options.tools,\n headers: headers,\n signal: abortController.signal,\n });\n\n if (response.headers.get(\"threadid\")) {\n threadIdRef.current = response.headers.get(\"threadid\");\n }\n\n if (response.headers.get(\"runid\")) {\n runIdRef.current = response.headers.get(\"runid\");\n }\n\n if (!response.events) {\n setMessages([\n ...messages,\n {\n id: nanoid(),\n createdAt: new Date(),\n content: response.statusText,\n role: \"assistant\",\n },\n ]);\n options.setIsLoading(false);\n throw new Error(\"Failed to fetch chat completion\");\n }\n\n const reader = response.events.getReader();\n\n // Whether to feed back the new messages to GPT\n let feedback = false;\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n let currentMessage = Object.assign({}, newMessages[newMessages.length - 1]);\n\n if (value.type === \"content\") {\n if (currentMessage.function_call || currentMessage.role === \"function\") {\n // Create a new message if the previous one is a function call or result\n currentMessage = {\n id: nanoid(),\n createdAt: new Date(),\n content: \"\",\n role: \"assistant\",\n };\n newMessages.push(currentMessage);\n }\n currentMessage.content += value.content;\n newMessages[newMessages.length - 1] = currentMessage;\n setMessages([...messages, ...newMessages]);\n } else if (value.type === \"result\") {\n // When we get a result message, it is already complete\n currentMessage = {\n id: nanoid(),\n role: \"function\",\n content: value.content,\n name: value.name,\n };\n newMessages.push(currentMessage);\n setMessages([...messages, ...newMessages]);\n\n // After receiving a result, feed back the new messages to GPT\n feedback = true;\n } else if (value.type === \"function\" || value.type === \"partial\") {\n // Create a new message if the previous one is not empty\n if (\n currentMessage.content != \"\" ||\n currentMessage.function_call ||\n currentMessage.role == \"function\"\n ) {\n currentMessage = {\n id: nanoid(),\n createdAt: new Date(),\n content: \"\",\n role: \"assistant\",\n };\n newMessages.push(currentMessage);\n }\n if (value.type === \"function\") {\n currentMessage.function_call = {\n name: value.name,\n arguments: JSON.stringify(value.arguments),\n scope: value.scope,\n };\n } else if (value.type === \"partial\") {\n let partialArguments: any = {};\n try {\n partialArguments = JSON.parse(untruncateJson(value.arguments));\n } catch (e) {}\n\n currentMessage.partialFunctionCall = {\n name: value.name,\n arguments: partialArguments,\n };\n }\n\n newMessages[newMessages.length - 1] = currentMessage;\n setMessages([...messages, ...newMessages]);\n\n if (value.type === \"function\") {\n // Execute the function call\n try {\n if (options.onFunctionCall && value.scope === \"client\") {\n const result = await options.onFunctionCall(\n messages,\n currentMessage.function_call as FunctionCall,\n );\n\n currentMessage = {\n id: nanoid(),\n role: \"function\",\n content: encodeResult(result),\n name: (currentMessage.function_call! as FunctionCall).name!,\n };\n newMessages.push(currentMessage);\n setMessages([...messages, ...newMessages]);\n\n // After a function call, feed back the new messages to GPT\n feedback = true;\n }\n } catch (error) {\n console.error(\"Failed to execute function call\", error);\n // TODO: Handle error\n // this should go to the message itself\n }\n }\n }\n }\n\n // If we want feedback, run the completion again and return the results\n if (feedback) {\n // wait for next tick to make sure all the react state updates\n // TODO: This is a hack, is there a more robust way to do this?\n // - tried using react-dom's flushSync, but it did not work\n await new Promise((resolve) => setTimeout(resolve, 10));\n\n return await runChatCompletion([...messages, ...newMessages]);\n }\n // otherwise, return the new messages\n else {\n return newMessages.slice();\n }\n } finally {\n options.setIsLoading(false);\n }\n };\n\n const runChatCompletionAndHandleFunctionCall = async (messages: Message[]): Promise<void> => {\n await runChatCompletion(messages);\n };\n\n const append = async (message: Message): Promise<void> => {\n if (options.isLoading) {\n return;\n }\n const newMessages = [...messages, message];\n setMessages(newMessages);\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const reload = async (): Promise<void> => {\n if (options.isLoading || messages.length === 0) {\n return;\n }\n let newMessages = [...messages];\n const lastMessage = messages[messages.length - 1];\n\n if (lastMessage.role === \"assistant\") {\n newMessages = newMessages.slice(0, -1);\n }\n setMessages(newMessages);\n\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const stop = (): void => {\n abortControllerRef.current?.abort();\n };\n\n return {\n append,\n reload,\n stop,\n };\n}\n","import {\n Message,\n ToolDefinition,\n ChatCompletionEvent,\n decodeChatCompletion,\n parseChatCompletion,\n decodeChatCompletionAsText,\n EXCLUDE_FROM_FORWARD_PROPS_KEYS,\n} from \"@copilotkit/shared\";\nimport { CopilotApiConfig } from \"../context\";\n\nexport interface FetchChatCompletionParams {\n copilotConfig: CopilotApiConfig;\n model?: string;\n messages: Message[];\n tools?: ToolDefinition[];\n temperature?: number;\n maxTokens?: number;\n headers?: Record<string, string> | Headers;\n body?: object;\n signal?: AbortSignal;\n toolChoice?: string | { type: \"function\"; function: { name: string } };\n}\n\nexport async function fetchChatCompletion({\n copilotConfig,\n model,\n messages,\n tools,\n temperature,\n headers,\n body,\n signal,\n toolChoice,\n}: FetchChatCompletionParams): Promise<Response> {\n temperature ||= 0.5;\n tools ||= [];\n\n // clean up any extra properties from messages\n const cleanedMessages = messages.map((message) => {\n const { content, role, name, function_call } = message;\n return { content, role, name, function_call };\n });\n\n toolChoice ||= \"auto\";\n\n const response = await fetch(copilotConfig.chatApiEndpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...copilotConfig.headers,\n ...(headers ? { ...headers } : {}),\n },\n body: JSON.stringify({\n model,\n messages: cleanedMessages,\n stream: true,\n ...(tools.length ? { tools } : {}),\n ...(temperature ? { temperature } : {}),\n ...(tools.length != 0 ? { tool_choice: toolChoice } : {}),\n ...copilotConfig.body,\n ...copilotConfig.backendOnlyProps,\n ...excludeBackendOnlyProps(copilotConfig),\n ...(body ? { ...body } : {}),\n ...(copilotConfig.cloud ? { cloud: copilotConfig.cloud } : {}),\n }),\n signal,\n credentials: copilotConfig.credentials,\n });\n\n return response;\n}\n\nfunction excludeBackendOnlyProps(copilotConfig: any) {\n const backendOnlyProps = copilotConfig.backendOnlyProps ?? {};\n if (Object.keys(backendOnlyProps).length > 0) {\n return {\n [EXCLUDE_FROM_FORWARD_PROPS_KEYS]: Object.keys(backendOnlyProps),\n };\n } else {\n return {};\n }\n}\n\nexport interface DecodedChatCompletionResponse extends Response {\n events: ReadableStream<ChatCompletionEvent> | null;\n}\n\nexport async function fetchAndDecodeChatCompletion(\n params: FetchChatCompletionParams,\n): Promise<DecodedChatCompletionResponse> {\n const response = await fetchChatCompletion(params);\n if (!response.ok || !response.body) {\n (response as any).events = null;\n } else {\n const events = await decodeChatCompletion(parseChatCompletion(response.body));\n (response as any).events = events;\n }\n return response as any;\n}\n\nexport interface DecodedChatCompletionResponseAsText extends Response {\n events: ReadableStream<string> | null;\n}\n\nexport async function fetchAndDecodeChatCompletionAsText(\n params: FetchChatCompletionParams,\n): Promise<DecodedChatCompletionResponseAsText> {\n const response = await fetchChatCompletion(params);\n if (!response.ok || !response.body) {\n (response as any).events = null;\n } else {\n const events = await decodeChatCompletionAsText(\n decodeChatCompletion(parseChatCompletion(response.body)),\n );\n (response as any).events = events;\n }\n\n return response as any;\n}\n"],"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,UAA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AAG,UAAU,OAAO;AACzC,gBAAY,WAAW;AACvB,WAAO,uCAAuC,WAAW;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 {\n frontend: {\n actions: actions.map((action) => ({\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n })),\n },\n threadId: threadIdRef.current,\n runId: runIdRef.current,\n messages: convertMessagesToGqlInput(messagesWithContext),\n ...(copilotConfig.cloud\n ? {\n cloud: {\n guardrails: {\n inputValidationRules: {\n allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,\n denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics,\n },\n },\n },\n }\n : {}),\n },\n copilotConfig.properties,\n abortControllerRef.current?.signal,\n ),\n );\n\n const guardrailsEnabled =\n copilotConfig.cloud?.guardrails?.input?.restrictToTopic.enabled || false;\n\n const reader = stream.getReader();\n\n let results: { [id: string]: string } = {};\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (!value?.generateCopilotResponse) {\n continue;\n }\n\n threadIdRef.current = value.generateCopilotResponse.threadId || null;\n runIdRef.current = value.generateCopilotResponse.runId || null;\n\n const messages = convertGqlOutputToMessages(value.generateCopilotResponse.messages);\n\n if (messages.length === 0) {\n continue;\n }\n\n newMessages = [];\n\n // request failed, display error message\n if (\n value.generateCopilotResponse.status?.__typename === \"FailedResponseStatus\" &&\n value.generateCopilotResponse.status.reason === \"GUARDRAILS_VALIDATION_FAILED\"\n ) {\n newMessages = [\n new TextMessage({\n role: MessageRole.Assistant,\n content: value.generateCopilotResponse.status.details?.guardrailsReason || \"\",\n }),\n ];\n }\n\n // add messages to the chat\n else {\n for (const message of messages) {\n newMessages.push(message);\n\n if (\n message instanceof ActionExecutionMessage &&\n message.status.code !== MessageStatusCode.Pending &&\n message.scope === \"client\" &&\n onFunctionCall\n ) {\n if (!(message.id in results)) {\n // Do not execute a function call if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute action\n const result = await onFunctionCall({\n messages: previousMessages,\n name: message.name,\n args: message.arguments,\n });\n results[message.id] = result;\n }\n\n // add the result message\n newMessages.push(\n new ResultMessage({\n result: ResultMessage.encodeResult(results[message.id]),\n actionExecutionId: message.id,\n actionName: message.name,\n }),\n );\n }\n }\n }\n\n if (newMessages.length > 0) {\n setMessages([...previousMessages, ...newMessages]);\n }\n }\n\n if (\n // if we have client side results\n Object.values(results).length ||\n // or the last message we received is a result\n (newMessages.length && newMessages[newMessages.length - 1] instanceof ResultMessage)\n ) {\n // run the completion again and return the result\n\n // wait for next tick to make sure all the react state updates\n // - tried using react-dom's flushSync, but it did not work\n await new Promise((resolve) => setTimeout(resolve, 10));\n\n return await runChatCompletion([...previousMessages, ...newMessages]);\n } else {\n return newMessages.slice();\n }\n } finally {\n setIsLoading(false);\n }\n };\n\n const runChatCompletionAndHandleFunctionCall = async (messages: Message[]): Promise<void> => {\n await runChatCompletion(messages);\n };\n\n const append = async (message: Message): Promise<void> => {\n if (isLoading) {\n return;\n }\n const newMessages = [...messages, message];\n setMessages(newMessages);\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const reload = async (): Promise<void> => {\n if (isLoading || messages.length === 0) {\n return;\n }\n let newMessages = [...messages];\n const lastMessage = messages[messages.length - 1];\n\n if (lastMessage instanceof TextMessage && lastMessage.role === \"assistant\") {\n newMessages = newMessages.slice(0, -1);\n }\n\n setMessages(newMessages);\n\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const stop = (): void => {\n abortControllerRef.current?.abort();\n };\n\n return {\n append,\n reload,\n stop,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAuB;AACvB,oBAKO;AACP,gCAWO;AAqEA,SAAS,QAAQ,SAAyC;AAC/D,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;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,SAAS,aAAa;AAC1E,oBAAc,YAAY,MAAM,GAAG,EAAE;AAAA,IACvC;AAEA,gBAAY,WAAW;AAEvB,WAAO,uCAAuC,WAAW;AAAA,EAC3D;AAEA,QAAM,OAAO,MAAY;AA5S3B;AA6SI,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-B2H3NC4E.mjs";
4
- import "../chunk-MJKBCG4U.mjs";
3
+ } from "../chunk-PHMHNAYC.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,sBAAsB,EAAE;AAAA,EAClD,uBAAuB,MAAM;AAAA,EAAC;AAAA,EAE9B,kBAAkB,IAAK,MAAkC;AAAA,IACvD,IAAI,kBAA0B;AAC5B,YAAM,IAAI,MAAM,uEAAuE;AAAA,IACzF;AAAA,IACA,IAAI,oBAA4B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AA,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 * Custom properties to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n properties?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n}\n\nexport type InChatRenderFunction = (props: ActionRenderProps<any>) => string | JSX.Element;\n\nexport interface CopilotContextParams {\n // function-calling\n actions: Record<string, FrontendAction<any>>;\n setAction: (id: string, action: FrontendAction<any>) => void;\n removeAction: (id: string) => void;\n chatComponentsCache: React.RefObject<Record<string, InChatRenderFunction | string>>;\n\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n // chat\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n chatComponentsCache: { current: {} },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n messages: [],\n setMessages: () => returnAndThrowInDebug([]),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n get chatApiEndpointV2(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n return React.useContext(CopilotContext);\n}\n\nfunction returnAndThrowInDebug<T>(value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n return value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,gBAA8C;;;ACG9C,mBAAkB;AAkHlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,qBAAqB,EAAE,SAAS,CAAC,EAAE;AAAA,EACnC,kBAAkB,CAAC,WAA8B,eAC/C,sBAAsB,EAAE;AAAA,EAC1B,YAAY,MAAM;AAAA,EAClB,eAAe,MAAM;AAAA,EAAC;AAAA,EAEtB,wBAAwB,MAAM,sBAAsB,MAAY;AAAA,EAAC,EAAC;AAAA,EAElE,UAAU,CAAC;AAAA,EACX,aAAa,MAAM,sBAAsB,CAAC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AU,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-LZVHW3T3.mjs";
4
+ import "../chunk-K6EV2CNB.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 {