@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
package/dist/index.js CHANGED
@@ -86,13 +86,8 @@ __export(src_exports, {
86
86
  CopilotTask: () => CopilotTask,
87
87
  defaultCopilotContextCategories: () => defaultCopilotContextCategories,
88
88
  extract: () => extract,
89
- fetchAndDecodeChatCompletion: () => fetchAndDecodeChatCompletion,
90
- fetchAndDecodeChatCompletionAsText: () => fetchAndDecodeChatCompletionAsText,
91
- fetchChatCompletion: () => fetchChatCompletion,
92
- processMessageStream: () => processMessageStream,
93
89
  useCopilotAction: () => useCopilotAction,
94
90
  useCopilotChat: () => useCopilotChat,
95
- useCopilotChatV2: () => useCopilotChatV2,
96
91
  useCopilotContext: () => useCopilotContext,
97
92
  useCopilotReadable: () => useCopilotReadable,
98
93
  useMakeCopilotActionable: () => useMakeCopilotActionable,
@@ -107,17 +102,16 @@ var import_react4 = require("react");
107
102
  // src/context/copilot-context.tsx
108
103
  var import_react = __toESM(require("react"));
109
104
  var emptyCopilotContext = {
110
- entryPoints: {},
111
- setEntryPoint: () => {
105
+ actions: {},
106
+ setAction: () => {
112
107
  },
113
- removeEntryPoint: () => {
108
+ removeAction: () => {
114
109
  },
115
110
  chatComponentsCache: { current: {} },
116
111
  getContextString: (documents, categories) => returnAndThrowInDebug(""),
117
112
  addContext: () => "",
118
113
  removeContext: () => {
119
114
  },
120
- getChatCompletionFunctionDescriptions: () => returnAndThrowInDebug([]),
121
115
  getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
122
116
  })),
123
117
  messages: [],
@@ -368,7 +362,7 @@ function CopilotKit(_a) {
368
362
  throw new Error("Please provide either a url or a publicApiKey to the CopilotKit component.");
369
363
  }
370
364
  const chatApiEndpoint = props.runtimeUrl || props.url || import_shared.COPILOT_CLOUD_CHAT_URL;
371
- const [entryPoints, setEntryPoints] = (0, import_react4.useState)({});
365
+ const [actions, setActions] = (0, import_react4.useState)({});
372
366
  const chatComponentsCache = (0, import_react4.useRef)({});
373
367
  const { addElement, removeElement, printTree } = use_tree_default();
374
368
  const [messages, setMessages] = (0, import_react4.useState)([]);
@@ -379,15 +373,15 @@ function CopilotKit(_a) {
379
373
  removeElement: removeDocument,
380
374
  allElements: allDocuments
381
375
  } = use_flat_category_store_default();
382
- const setEntryPoint = (0, import_react4.useCallback)((id, entryPoint) => {
383
- setEntryPoints((prevPoints) => {
376
+ const setAction = (0, import_react4.useCallback)((id, action) => {
377
+ setActions((prevPoints) => {
384
378
  return __spreadProps(__spreadValues({}, prevPoints), {
385
- [id]: entryPoint
379
+ [id]: action
386
380
  });
387
381
  });
388
382
  }, []);
389
- const removeEntryPoint = (0, import_react4.useCallback)((id) => {
390
- setEntryPoints((prevPoints) => {
383
+ const removeAction = (0, import_react4.useCallback)((id) => {
384
+ setActions((prevPoints) => {
391
385
  const newPoints = __spreadValues({}, prevPoints);
392
386
  delete newPoints[id];
393
387
  return newPoints;
@@ -418,17 +412,11 @@ ${nonDocumentStrings}`;
418
412
  },
419
413
  [removeElement]
420
414
  );
421
- const getChatCompletionFunctionDescriptions = (0, import_react4.useCallback)(
422
- (customEntryPoints) => {
423
- return entryPointsToChatCompletionFunctions(Object.values(customEntryPoints || entryPoints));
424
- },
425
- [entryPoints]
426
- );
427
415
  const getFunctionCallHandler = (0, import_react4.useCallback)(
428
416
  (customEntryPoints) => {
429
- return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || entryPoints));
417
+ return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));
430
418
  },
431
- [entryPoints]
419
+ [actions]
432
420
  );
433
421
  const getDocumentsContext = (0, import_react4.useCallback)(
434
422
  (categories) => {
@@ -494,12 +482,11 @@ ${nonDocumentStrings}`;
494
482
  CopilotContext.Provider,
495
483
  {
496
484
  value: {
497
- entryPoints,
485
+ actions,
498
486
  chatComponentsCache,
499
- getChatCompletionFunctionDescriptions,
500
487
  getFunctionCallHandler,
501
- setEntryPoint,
502
- removeEntryPoint,
488
+ setAction,
489
+ removeAction,
503
490
  getContextString,
504
491
  addContext,
505
492
  removeContext,
@@ -522,266 +509,160 @@ ${nonDocumentStrings}`;
522
509
  );
523
510
  }
524
511
  var defaultCopilotContextCategories = ["global"];
525
- function entryPointsToChatCompletionFunctions(actions) {
526
- return actions.map(import_shared.actionToChatCompletionFunction);
527
- }
528
512
  function entryPointsToFunctionCallHandler(actions) {
529
- return (chatMessages, functionCall) => __async(this, null, function* () {
513
+ return (_0) => __async(this, [_0], function* ({ messages, name, args }) {
530
514
  let actionsByFunctionName = {};
531
515
  for (let action2 of actions) {
532
516
  actionsByFunctionName[action2.name] = action2;
533
517
  }
534
- const action = actionsByFunctionName[functionCall.name || ""];
518
+ const action = actionsByFunctionName[name];
535
519
  if (action) {
536
- let functionCallArguments = [];
537
- if (functionCall.arguments) {
538
- functionCallArguments = JSON.parse(functionCall.arguments);
539
- }
540
- return yield action.handler(functionCallArguments);
520
+ return yield action.handler(args);
541
521
  }
542
522
  });
543
523
  }
544
524
 
545
525
  // src/hooks/use-copilot-chat.ts
546
526
  var import_react6 = require("react");
527
+ var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
547
528
 
548
529
  // src/hooks/use-chat.ts
549
530
  var import_react5 = require("react");
550
- var import_shared3 = require("@copilotkit/shared");
551
- var import_nanoid3 = require("nanoid");
552
-
553
- // src/utils/fetch-chat-completion.ts
554
531
  var import_shared2 = require("@copilotkit/shared");
555
- function fetchChatCompletion(_0) {
556
- return __async(this, arguments, function* ({
557
- copilotConfig,
558
- model,
559
- messages,
560
- tools,
561
- temperature,
562
- headers,
563
- body,
564
- signal,
565
- toolChoice
566
- }) {
567
- temperature || (temperature = 0.5);
568
- tools || (tools = []);
569
- const cleanedMessages = messages.map((message) => {
570
- const { content, role, name, function_call } = message;
571
- return { content, role, name, function_call };
572
- });
573
- toolChoice || (toolChoice = "auto");
574
- const response = yield fetch(copilotConfig.chatApiEndpoint, {
575
- method: "POST",
576
- headers: __spreadValues(__spreadValues({
577
- "Content-Type": "application/json"
578
- }, copilotConfig.headers), headers ? __spreadValues({}, headers) : {}),
579
- body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
580
- model,
581
- messages: cleanedMessages,
582
- stream: true
583
- }, 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 } : {})),
584
- signal,
585
- credentials: copilotConfig.credentials
586
- });
587
- return response;
588
- });
589
- }
590
- function excludeBackendOnlyProps(copilotConfig) {
591
- var _a;
592
- const backendOnlyProps = (_a = copilotConfig.backendOnlyProps) != null ? _a : {};
593
- if (Object.keys(backendOnlyProps).length > 0) {
594
- return {
595
- [import_shared2.EXCLUDE_FROM_FORWARD_PROPS_KEYS]: Object.keys(backendOnlyProps)
596
- };
597
- } else {
598
- return {};
599
- }
600
- }
601
- function fetchAndDecodeChatCompletion(params) {
602
- return __async(this, null, function* () {
603
- const response = yield fetchChatCompletion(params);
604
- if (!response.ok || !response.body) {
605
- response.events = null;
606
- } else {
607
- const events = yield (0, import_shared2.decodeChatCompletion)((0, import_shared2.parseChatCompletion)(response.body));
608
- response.events = events;
609
- }
610
- return response;
611
- });
612
- }
613
- function fetchAndDecodeChatCompletionAsText(params) {
614
- return __async(this, null, function* () {
615
- const response = yield fetchChatCompletion(params);
616
- if (!response.ok || !response.body) {
617
- response.events = null;
618
- } else {
619
- const events = yield (0, import_shared2.decodeChatCompletionAsText)(
620
- (0, import_shared2.decodeChatCompletion)((0, import_shared2.parseChatCompletion)(response.body))
621
- );
622
- response.events = events;
623
- }
624
- return response;
625
- });
626
- }
627
-
628
- // src/hooks/use-chat.ts
629
- var import_untruncate_json = __toESM(require("untruncate-json"));
532
+ var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
630
533
  function useChat(options) {
631
- const { messages, setMessages, makeSystemMessageCallback } = options;
534
+ const {
535
+ messages,
536
+ setMessages,
537
+ makeSystemMessageCallback,
538
+ copilotConfig,
539
+ setIsLoading,
540
+ initialMessages,
541
+ isLoading,
542
+ actions,
543
+ onFunctionCall
544
+ } = options;
632
545
  const abortControllerRef = (0, import_react5.useRef)();
633
546
  const threadIdRef = (0, import_react5.useRef)(null);
634
547
  const runIdRef = (0, import_react5.useRef)(null);
635
- const publicApiKey = options.copilotConfig.publicApiKey;
636
- const headers = __spreadValues(__spreadValues({}, options.headers || {}), publicApiKey ? { [import_shared3.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
637
- const runChatCompletion = (messages2) => __async(this, null, function* () {
638
- var _a, _b;
639
- options.setIsLoading(true);
640
- const newMessages = [
641
- {
642
- id: (0, import_nanoid3.nanoid)(),
643
- createdAt: /* @__PURE__ */ new Date(),
548
+ const publicApiKey = copilotConfig.publicApiKey;
549
+ const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [import_shared2.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
550
+ const runtimeClient = new import_runtime_client_gql.CopilotRuntimeClient({
551
+ url: copilotConfig.chatApiEndpoint,
552
+ publicApiKey: copilotConfig.publicApiKey,
553
+ headers
554
+ });
555
+ const runChatCompletion = (previousMessages) => __async(this, null, function* () {
556
+ var _a, _b, _c, _d, _e;
557
+ setIsLoading(true);
558
+ let newMessages = [
559
+ new import_runtime_client_gql.TextMessage({
644
560
  content: "",
645
- role: "assistant"
646
- }
561
+ role: import_runtime_client_gql.Role.Assistant
562
+ })
647
563
  ];
648
564
  const abortController = new AbortController();
649
565
  abortControllerRef.current = abortController;
650
- setMessages([...messages2, ...newMessages]);
651
- const copilotConfigBody = options.copilotConfig.body || {};
652
- if (threadIdRef.current) {
653
- copilotConfigBody.threadId = threadIdRef.current;
654
- }
655
- if (runIdRef.current) {
656
- copilotConfigBody.runId = runIdRef.current;
657
- }
566
+ setMessages([...previousMessages, ...newMessages]);
658
567
  const systemMessage = makeSystemMessageCallback();
659
- const messagesWithContext = [systemMessage, ...options.initialMessages || [], ...messages2];
660
- const response = yield fetchAndDecodeChatCompletion({
661
- copilotConfig: __spreadProps(__spreadValues({}, options.copilotConfig), { body: copilotConfigBody }),
662
- messages: messagesWithContext,
663
- tools: (_a = options.tools) == null ? void 0 : _a.current,
664
- headers,
665
- signal: abortController.signal
666
- });
667
- if (response.headers.get("threadid")) {
668
- threadIdRef.current = response.headers.get("threadid");
669
- }
670
- if (response.headers.get("runid")) {
671
- runIdRef.current = response.headers.get("runid");
672
- }
673
- if (!response.events) {
674
- setMessages([
675
- ...messages2,
676
- {
677
- id: (0, import_nanoid3.nanoid)(),
678
- createdAt: /* @__PURE__ */ new Date(),
679
- content: response.statusText,
680
- role: "assistant"
568
+ const messagesWithContext = [systemMessage, ...initialMessages || [], ...previousMessages];
569
+ const stream = import_runtime_client_gql.CopilotRuntimeClient.asStream(
570
+ runtimeClient.generateCopilotResponse(__spreadValues({
571
+ frontend: {
572
+ actions: actions.map((action) => ({
573
+ name: action.name,
574
+ description: action.description || "",
575
+ jsonSchema: JSON.stringify((0, import_shared2.actionParametersToJsonSchema)(action.parameters || []))
576
+ }))
577
+ },
578
+ threadId: threadIdRef.current,
579
+ runId: runIdRef.current,
580
+ messages: (0, import_runtime_client_gql.convertMessagesToGqlInput)(messagesWithContext)
581
+ }, copilotConfig.cloud ? {
582
+ cloud: {
583
+ guardrails: {
584
+ inputValidationRules: {
585
+ allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,
586
+ denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics
587
+ }
588
+ }
681
589
  }
682
- ]);
683
- options.setIsLoading(false);
684
- throw new Error("Failed to fetch chat completion");
685
- }
686
- const reader = response.events.getReader();
687
- let feedback = false;
590
+ } : {}))
591
+ );
592
+ const guardrailsEnabled = ((_c = (_b = (_a = copilotConfig.cloud) == null ? void 0 : _a.guardrails) == null ? void 0 : _b.input) == null ? void 0 : _c.restrictToTopic.enabled) || false;
593
+ const reader = stream.getReader();
594
+ let results = {};
688
595
  try {
689
596
  while (true) {
690
597
  const { done, value } = yield reader.read();
691
598
  if (done) {
692
599
  break;
693
600
  }
694
- let currentMessage = Object.assign({}, newMessages[newMessages.length - 1]);
695
- if (value.type === "content") {
696
- if (currentMessage.function_call || currentMessage.role === "function") {
697
- currentMessage = {
698
- id: (0, import_nanoid3.nanoid)(),
699
- createdAt: /* @__PURE__ */ new Date(),
700
- content: "",
701
- role: "assistant"
702
- };
703
- newMessages.push(currentMessage);
704
- }
705
- currentMessage.content += value.content;
706
- newMessages[newMessages.length - 1] = currentMessage;
707
- setMessages([...messages2, ...newMessages]);
708
- } else if (value.type === "result") {
709
- currentMessage = {
710
- id: (0, import_nanoid3.nanoid)(),
711
- role: "function",
712
- content: value.content,
713
- name: value.name
714
- };
715
- newMessages.push(currentMessage);
716
- setMessages([...messages2, ...newMessages]);
717
- feedback = true;
718
- } else if (value.type === "function" || value.type === "partial") {
719
- if (currentMessage.content != "" || currentMessage.function_call || currentMessage.role == "function") {
720
- currentMessage = {
721
- id: (0, import_nanoid3.nanoid)(),
722
- createdAt: /* @__PURE__ */ new Date(),
723
- content: "",
724
- role: "assistant"
725
- };
726
- newMessages.push(currentMessage);
727
- }
728
- if (value.type === "function") {
729
- currentMessage.function_call = {
730
- name: value.name,
731
- arguments: JSON.stringify(value.arguments),
732
- scope: value.scope
733
- };
734
- } else if (value.type === "partial") {
735
- let partialArguments = {};
736
- try {
737
- partialArguments = JSON.parse((0, import_untruncate_json.default)(value.arguments));
738
- } catch (e) {
739
- }
740
- currentMessage.partialFunctionCall = {
741
- name: value.name,
742
- arguments: partialArguments
743
- };
744
- }
745
- newMessages[newMessages.length - 1] = currentMessage;
746
- setMessages([...messages2, ...newMessages]);
747
- if (value.type === "function") {
748
- try {
749
- if (((_b = options.onFunctionCall) == null ? void 0 : _b.current) && value.scope === "client") {
750
- const result = yield options.onFunctionCall.current(
751
- messages2,
752
- currentMessage.function_call
753
- );
754
- currentMessage = {
755
- id: (0, import_nanoid3.nanoid)(),
756
- role: "function",
757
- content: (0, import_shared3.encodeResult)(result),
758
- name: currentMessage.function_call.name
759
- };
760
- newMessages.push(currentMessage);
761
- setMessages([...messages2, ...newMessages]);
762
- feedback = true;
601
+ if (!value.generateCopilotResponse) {
602
+ continue;
603
+ }
604
+ threadIdRef.current = value.generateCopilotResponse.threadId || null;
605
+ runIdRef.current = value.generateCopilotResponse.runId || null;
606
+ const messages2 = (0, import_runtime_client_gql.convertGqlOutputToMessages)(value.generateCopilotResponse.messages);
607
+ if (messages2.length === 0) {
608
+ continue;
609
+ }
610
+ newMessages = [];
611
+ if (((_d = value.generateCopilotResponse.status) == null ? void 0 : _d.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
612
+ newMessages = [
613
+ new import_runtime_client_gql.TextMessage({
614
+ role: import_runtime_client_gql.MessageRole.Assistant,
615
+ content: ((_e = value.generateCopilotResponse.status.details) == null ? void 0 : _e.guardrailsReason) || ""
616
+ })
617
+ ];
618
+ } else {
619
+ for (const message of messages2) {
620
+ newMessages.push(message);
621
+ if (message instanceof import_runtime_client_gql.ActionExecutionMessage && message.status.code !== import_runtime_client_gql.MessageStatusCode.Pending && message.scope === "client" && onFunctionCall) {
622
+ if (!(message.id in results)) {
623
+ if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
624
+ break;
625
+ }
626
+ const result = yield onFunctionCall({
627
+ messages: previousMessages,
628
+ name: message.name,
629
+ args: message.arguments
630
+ });
631
+ results[message.id] = result;
763
632
  }
764
- } catch (error) {
765
- console.error("Failed to execute function call", error);
633
+ newMessages.push(
634
+ new import_runtime_client_gql.ResultMessage({
635
+ result: import_runtime_client_gql.ResultMessage.encodeResult(results[message.id]),
636
+ actionExecutionId: message.id,
637
+ actionName: message.name
638
+ })
639
+ );
766
640
  }
767
641
  }
768
642
  }
643
+ if (newMessages.length > 0) {
644
+ setMessages([...previousMessages, ...newMessages]);
645
+ }
769
646
  }
770
- if (feedback) {
647
+ if (
648
+ // if we have client side results
649
+ Object.values(results).length || // or the last message we received is a result
650
+ newMessages.length && newMessages[newMessages.length - 1] instanceof import_runtime_client_gql.ResultMessage
651
+ ) {
771
652
  yield new Promise((resolve) => setTimeout(resolve, 10));
772
- return yield runChatCompletion([...messages2, ...newMessages]);
653
+ return yield runChatCompletion([...previousMessages, ...newMessages]);
773
654
  } else {
774
655
  return newMessages.slice();
775
656
  }
776
657
  } finally {
777
- options.setIsLoading(false);
658
+ setIsLoading(false);
778
659
  }
779
660
  });
780
661
  const runChatCompletionAndHandleFunctionCall = (messages2) => __async(this, null, function* () {
781
662
  yield runChatCompletion(messages2);
782
663
  });
783
664
  const append = (message) => __async(this, null, function* () {
784
- if (options.isLoading) {
665
+ if (isLoading) {
785
666
  return;
786
667
  }
787
668
  const newMessages = [...messages, message];
@@ -789,12 +670,12 @@ function useChat(options) {
789
670
  return runChatCompletionAndHandleFunctionCall(newMessages);
790
671
  });
791
672
  const reload = () => __async(this, null, function* () {
792
- if (options.isLoading || messages.length === 0) {
673
+ if (isLoading || messages.length === 0) {
793
674
  return;
794
675
  }
795
676
  let newMessages = [...messages];
796
677
  const lastMessage = messages[messages.length - 1];
797
- if (lastMessage.role === "assistant") {
678
+ if (lastMessage instanceof import_runtime_client_gql.TextMessage && lastMessage.role === "assistant") {
798
679
  newMessages = newMessages.slice(0, -1);
799
680
  }
800
681
  setMessages(newMessages);
@@ -820,14 +701,14 @@ function useCopilotChat(_a = {}) {
820
701
  ]);
821
702
  const {
822
703
  getContextString,
823
- getChatCompletionFunctionDescriptions,
824
704
  getFunctionCallHandler,
825
705
  copilotApiConfig,
826
706
  messages,
827
707
  setMessages,
828
708
  isLoading,
829
709
  setIsLoading,
830
- chatInstructions
710
+ chatInstructions,
711
+ actions
831
712
  } = (0, import_react6.useContext)(CopilotContext);
832
713
  const latestGetContextString = useUpdatedRef(getContextString);
833
714
  const deleteMessage = (0, import_react6.useCallback)(
@@ -839,36 +720,24 @@ function useCopilotChat(_a = {}) {
839
720
  const makeSystemMessageCallback = (0, import_react6.useCallback)(() => {
840
721
  const systemMessageMaker = makeSystemMessage2 || defaultSystemMessage;
841
722
  const contextString = latestGetContextString.current([], defaultCopilotContextCategories);
842
- return {
843
- id: "system",
723
+ return new import_runtime_client_gql2.TextMessage({
844
724
  content: systemMessageMaker(contextString, chatInstructions),
845
- role: "system"
846
- };
725
+ role: import_runtime_client_gql2.Role.System
726
+ });
847
727
  }, [getContextString, makeSystemMessage2, chatInstructions]);
848
- const functionDescriptions = (0, import_react6.useMemo)(() => {
849
- return getChatCompletionFunctionDescriptions();
850
- }, [getChatCompletionFunctionDescriptions]);
851
- const tools = useUpdatedRef(functionDescriptions);
852
- const onFunctionCall = useUpdatedRef(getFunctionCallHandler());
853
728
  const { append, reload, stop } = useChat(__spreadProps(__spreadValues({}, options), {
729
+ actions: Object.values(actions),
854
730
  copilotConfig: copilotApiConfig,
855
- id: options.id,
856
731
  initialMessages: options.initialMessages || [],
857
- tools,
858
- onFunctionCall,
859
- headers: __spreadValues({}, options.headers),
860
- body: __spreadValues({}, options.body),
732
+ onFunctionCall: getFunctionCallHandler(),
861
733
  messages,
862
734
  setMessages,
863
735
  makeSystemMessageCallback,
864
736
  isLoading,
865
737
  setIsLoading
866
738
  }));
867
- const visibleMessages = messages.filter(
868
- (message) => message.role === "user" || message.role === "assistant" || message.role === "function"
869
- );
870
739
  return {
871
- visibleMessages,
740
+ visibleMessages: messages,
872
741
  appendMessage: append,
873
742
  setMessages,
874
743
  reloadMessages: reload,
@@ -910,11 +779,11 @@ ${additionalInstructions}` : "");
910
779
 
911
780
  // src/hooks/use-make-copilot-actionable.ts
912
781
  var import_react7 = require("react");
913
- var import_nanoid4 = require("nanoid");
914
- var import_shared4 = require("@copilotkit/shared");
782
+ var import_nanoid3 = require("nanoid");
783
+ var import_shared3 = require("@copilotkit/shared");
915
784
  function useMakeCopilotActionable(annotatedFunction, dependencies) {
916
- const idRef = (0, import_react7.useRef)((0, import_nanoid4.nanoid)());
917
- const { setEntryPoint, removeEntryPoint } = (0, import_react7.useContext)(CopilotContext);
785
+ const idRef = (0, import_react7.useRef)((0, import_nanoid3.nanoid)());
786
+ const { setAction, removeAction } = (0, import_react7.useContext)(CopilotContext);
918
787
  const memoizedAnnotatedFunction = (0, import_react7.useMemo)(
919
788
  () => ({
920
789
  name: annotatedFunction.name,
@@ -925,23 +794,23 @@ function useMakeCopilotActionable(annotatedFunction, dependencies) {
925
794
  dependencies
926
795
  );
927
796
  (0, import_react7.useEffect)(() => {
928
- const action = (0, import_shared4.annotatedFunctionToAction)(memoizedAnnotatedFunction);
929
- setEntryPoint(idRef.current, action);
797
+ const action = (0, import_shared3.annotatedFunctionToAction)(memoizedAnnotatedFunction);
798
+ setAction(idRef.current, action);
930
799
  return () => {
931
- removeEntryPoint(idRef.current);
800
+ removeAction(idRef.current);
932
801
  };
933
- }, [memoizedAnnotatedFunction, setEntryPoint, removeEntryPoint]);
802
+ }, [memoizedAnnotatedFunction, setAction, removeAction]);
934
803
  }
935
804
 
936
805
  // src/hooks/use-copilot-action.ts
937
806
  var import_react8 = require("react");
938
- var import_nanoid5 = require("nanoid");
807
+ var import_nanoid4 = require("nanoid");
939
808
  function useCopilotAction(action, dependencies) {
940
- const { setEntryPoint, removeEntryPoint, entryPoints, chatComponentsCache } = (0, import_react8.useContext)(CopilotContext);
941
- const idRef = (0, import_react8.useRef)((0, import_nanoid5.nanoid)());
809
+ const { setAction, removeAction, actions, chatComponentsCache } = (0, import_react8.useContext)(CopilotContext);
810
+ const idRef = (0, import_react8.useRef)((0, import_nanoid4.nanoid)());
942
811
  if (dependencies === void 0) {
943
- if (entryPoints[idRef.current]) {
944
- entryPoints[idRef.current].handler = action.handler;
812
+ if (actions[idRef.current]) {
813
+ actions[idRef.current].handler = action.handler;
945
814
  if (typeof action.render === "function") {
946
815
  if (chatComponentsCache.current !== null) {
947
816
  chatComponentsCache.current[action.name] = action.render;
@@ -950,16 +819,16 @@ function useCopilotAction(action, dependencies) {
950
819
  }
951
820
  }
952
821
  (0, import_react8.useEffect)(() => {
953
- setEntryPoint(idRef.current, action);
822
+ setAction(idRef.current, action);
954
823
  if (chatComponentsCache.current !== null && action.render !== void 0) {
955
824
  chatComponentsCache.current[action.name] = action.render;
956
825
  }
957
826
  return () => {
958
- removeEntryPoint(idRef.current);
827
+ removeAction(idRef.current);
959
828
  };
960
829
  }, [
961
- setEntryPoint,
962
- removeEntryPoint,
830
+ setAction,
831
+ removeAction,
963
832
  action.description,
964
833
  action.name,
965
834
  // This should be faster than deep equality checking
@@ -1022,150 +891,9 @@ function useCopilotReadable({ description, value, parentId, categories, convert
1022
891
  return idRef.current;
1023
892
  }
1024
893
 
1025
- // src/openai-assistants/hooks/use-copilot-chat-v2.ts
1026
- var import_react12 = require("react");
1027
-
1028
- // src/openai-assistants/utils/process-message-stream.ts
1029
- function processMessageStream(reader, processMessage) {
1030
- return __async(this, null, function* () {
1031
- const decoder = new TextDecoder();
1032
- let buffer = "";
1033
- while (true) {
1034
- const { done, value } = yield reader.read();
1035
- if (done) {
1036
- if (buffer.length > 0) {
1037
- processMessage(buffer);
1038
- }
1039
- break;
1040
- }
1041
- buffer += decoder.decode(value, { stream: true });
1042
- let endIndex;
1043
- while ((endIndex = buffer.indexOf("\n")) !== -1) {
1044
- processMessage(buffer.substring(0, endIndex).trim());
1045
- buffer = buffer.substring(endIndex + 1);
1046
- }
1047
- }
1048
- });
1049
- }
1050
-
1051
- // src/openai-assistants/hooks/use-copilot-chat-v2.ts
1052
- var import_shared5 = require("@copilotkit/shared");
1053
- function useCopilotChatV2(options) {
1054
- const {
1055
- getContextString,
1056
- getChatCompletionFunctionDescriptions,
1057
- getFunctionCallHandler,
1058
- copilotApiConfig
1059
- } = (0, import_react12.useContext)(CopilotContext);
1060
- const [messages, setMessages] = (0, import_react12.useState)([]);
1061
- const [input, setInput] = (0, import_react12.useState)("");
1062
- const [threadId, setThreadId] = (0, import_react12.useState)(void 0);
1063
- const [status, setStatus] = (0, import_react12.useState)("awaiting_message");
1064
- const [error, setError] = (0, import_react12.useState)(void 0);
1065
- const systemMessage = (0, import_react12.useMemo)(() => {
1066
- const systemMessageMaker = options.makeSystemMessage || defaultSystemMessage2;
1067
- const contextString = getContextString([], defaultCopilotContextCategories);
1068
- return {
1069
- id: "system",
1070
- content: systemMessageMaker(contextString),
1071
- role: "system"
1072
- };
1073
- }, [getContextString, options.makeSystemMessage]);
1074
- const handleInputChange = (e) => {
1075
- setInput(e.target.value);
1076
- };
1077
- const submitMessage = (e) => __async(this, null, function* () {
1078
- var _a, _b;
1079
- e.preventDefault();
1080
- if (input === "") {
1081
- return;
1082
- }
1083
- setStatus("in_progress");
1084
- setMessages((messages2) => [...messages2, { id: "", role: "user", content: input }]);
1085
- setInput("");
1086
- const apiUrl = copilotApiConfig.chatApiEndpointV2;
1087
- const functions = getChatCompletionFunctionDescriptions();
1088
- const result = yield fetch(apiUrl, {
1089
- method: "POST",
1090
- headers: __spreadValues(__spreadValues({
1091
- "Content-Type": "application/json"
1092
- }, copilotApiConfig.headers), options.headers),
1093
- body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues({
1094
- // always use user-provided threadId when available:
1095
- threadId: (_b = (_a = options.threadId) != null ? _a : threadId) != null ? _b : null,
1096
- message: input
1097
- }, functions.length > 0 && { functions }), copilotApiConfig.body), options.body))
1098
- });
1099
- if (result.body == null) {
1100
- throw new Error("The response body is empty.");
1101
- }
1102
- yield processMessageStream(result.body.getReader(), (message) => {
1103
- try {
1104
- const { type, value } = (0, import_shared5.parseStreamPart)(message);
1105
- switch (type) {
1106
- case "assistant_message": {
1107
- setMessages((messages2) => [
1108
- ...messages2,
1109
- {
1110
- id: value.id,
1111
- role: value.role,
1112
- content: value.content[0].text.value
1113
- }
1114
- ]);
1115
- break;
1116
- }
1117
- case "assistant_control_data": {
1118
- setThreadId(value.threadId);
1119
- setMessages((messages2) => {
1120
- const lastMessage = messages2[messages2.length - 1];
1121
- lastMessage.id = value.messageId;
1122
- return [...messages2.slice(0, messages2.length - 1), lastMessage];
1123
- });
1124
- break;
1125
- }
1126
- case "error": {
1127
- setError(value);
1128
- break;
1129
- }
1130
- }
1131
- } catch (error2) {
1132
- setError(error2);
1133
- }
1134
- });
1135
- setStatus("awaiting_message");
1136
- });
1137
- return {
1138
- messages,
1139
- input,
1140
- handleInputChange,
1141
- submitMessage,
1142
- status,
1143
- error
1144
- };
1145
- }
1146
- function defaultSystemMessage2(contextString) {
1147
- return `
1148
- Please act as an efficient, competent, conscientious, and industrious professional assistant.
1149
-
1150
- Help the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.
1151
- Always be polite and respectful, and prefer brevity over verbosity.
1152
-
1153
- The user has provided you with the following context:
1154
- \`\`\`
1155
- ${contextString}
1156
- \`\`\`
1157
-
1158
- They have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.
1159
-
1160
- Please assist them as best you can.
1161
-
1162
- You can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.
1163
-
1164
- If you would like to call a function, call it without saying anything else.
1165
- `;
1166
- }
1167
-
1168
894
  // src/lib/copilot-task.ts
895
+ var import_runtime_client_gql3 = require("@copilotkit/runtime-client-gql");
896
+ var import_shared4 = require("@copilotkit/shared");
1169
897
  var CopilotTask = class {
1170
898
  constructor(config) {
1171
899
  this.instructions = config.instructions;
@@ -1180,9 +908,10 @@ var CopilotTask = class {
1180
908
  */
1181
909
  run(context, data) {
1182
910
  return __async(this, null, function* () {
1183
- const entryPoints = this.includeCopilotActions ? Object.assign({}, context.entryPoints) : {};
911
+ var _a, _b;
912
+ const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};
1184
913
  for (const fn of this.actions) {
1185
- entryPoints[fn.name] = fn;
914
+ actions[fn.name] = fn;
1186
915
  }
1187
916
  let contextString = "";
1188
917
  if (data) {
@@ -1191,43 +920,36 @@ var CopilotTask = class {
1191
920
  if (this.includeCopilotReadable) {
1192
921
  contextString += context.getContextString([], defaultCopilotContextCategories);
1193
922
  }
1194
- const systemMessage = {
1195
- id: "system",
923
+ const systemMessage = new import_runtime_client_gql3.TextMessage({
1196
924
  content: taskSystemMessage(contextString, this.instructions),
1197
- role: "system"
1198
- };
925
+ role: import_runtime_client_gql3.Role.System
926
+ });
1199
927
  const messages = [systemMessage];
1200
- const response = yield fetchAndDecodeChatCompletion({
1201
- copilotConfig: context.copilotApiConfig,
1202
- messages,
1203
- tools: context.getChatCompletionFunctionDescriptions(entryPoints),
1204
- headers: context.copilotApiConfig.headers,
1205
- body: context.copilotApiConfig.body
928
+ const runtimeClient = new import_runtime_client_gql3.CopilotRuntimeClient({
929
+ url: context.copilotApiConfig.chatApiEndpoint,
930
+ publicApiKey: context.copilotApiConfig.publicApiKey,
931
+ headers: context.copilotApiConfig.headers
1206
932
  });
1207
- if (!response.events) {
1208
- throw new Error("Failed to execute task");
1209
- }
1210
- const reader = response.events.getReader();
1211
- let functionCalls = [];
1212
- while (true) {
1213
- const { done, value } = yield reader.read();
1214
- if (done) {
1215
- break;
1216
- }
1217
- if (value.type === "function") {
1218
- functionCalls.push({
1219
- name: value.name,
1220
- arguments: JSON.stringify(value.arguments)
1221
- });
1222
- break;
1223
- }
1224
- }
1225
- if (!functionCalls.length) {
1226
- throw new Error("No function call occurred");
1227
- }
1228
- const functionCallHandler = context.getFunctionCallHandler(entryPoints);
933
+ const response = yield runtimeClient.generateCopilotResponse({
934
+ frontend: {
935
+ actions: Object.values(actions).map((action) => ({
936
+ name: action.name,
937
+ description: action.description || "",
938
+ jsonSchema: JSON.stringify((0, import_shared4.actionParametersToJsonSchema)(action.parameters || []))
939
+ }))
940
+ },
941
+ messages: (0, import_runtime_client_gql3.convertMessagesToGqlInput)(messages)
942
+ }).toPromise();
943
+ const functionCallHandler = context.getFunctionCallHandler(actions);
944
+ const functionCalls = (0, import_runtime_client_gql3.convertGqlOutputToMessages)(
945
+ ((_b = (_a = response.data) == null ? void 0 : _a.generateCopilotResponse) == null ? void 0 : _b.messages) || []
946
+ ).filter((m) => m instanceof import_runtime_client_gql3.ActionExecutionMessage);
1229
947
  for (const functionCall of functionCalls) {
1230
- yield functionCallHandler(messages, functionCall);
948
+ yield functionCallHandler({
949
+ messages,
950
+ name: functionCall.name,
951
+ args: functionCall.arguments
952
+ });
1231
953
  }
1232
954
  });
1233
955
  }
@@ -1259,8 +981,10 @@ ${instructions}
1259
981
  }
1260
982
 
1261
983
  // src/utils/extract.ts
1262
- var import_shared6 = require("@copilotkit/shared");
1263
- var import_untruncate_json2 = __toESM(require("untruncate-json"));
984
+ var import_shared5 = require("@copilotkit/shared");
985
+ var import_runtime_client_gql4 = require("@copilotkit/runtime-client-gql");
986
+ var import_runtime_client_gql5 = require("@copilotkit/runtime-client-gql");
987
+ var import_runtime_client_gql6 = require("@copilotkit/runtime-client-gql");
1264
988
  function extract(_0) {
1265
989
  return __async(this, arguments, function* ({
1266
990
  context,
@@ -1288,51 +1012,60 @@ function extract(_0) {
1288
1012
  if (includeReadable) {
1289
1013
  contextString += context.getContextString([], defaultCopilotContextCategories);
1290
1014
  }
1291
- const systemMessage = {
1292
- id: "system",
1015
+ const systemMessage = new import_runtime_client_gql4.TextMessage({
1293
1016
  content: makeSystemMessage(contextString, instructions),
1294
- role: "system"
1295
- };
1296
- const headers = __spreadValues(__spreadValues({}, context.copilotApiConfig.headers || {}), context.copilotApiConfig.publicApiKey ? { [import_shared6.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: context.copilotApiConfig.publicApiKey } : {});
1297
- const response = yield fetchAndDecodeChatCompletion({
1298
- copilotConfig: context.copilotApiConfig,
1299
- messages: includeMessages ? [systemMessage, ...messages] : [systemMessage],
1300
- tools: context.getChatCompletionFunctionDescriptions({ extract: action }),
1301
- headers,
1302
- body: context.copilotApiConfig.body,
1303
- toolChoice: { type: "function", function: { name: "extract" } },
1304
- signal: abortSignal
1017
+ role: import_runtime_client_gql4.Role.System
1305
1018
  });
1306
- if (!response.events) {
1307
- throw new Error("extract() failed: Could not fetch chat completion");
1308
- }
1309
- const reader = response.events.getReader();
1019
+ const headers = __spreadValues(__spreadValues({}, context.copilotApiConfig.headers || {}), context.copilotApiConfig.publicApiKey ? { [import_shared5.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: context.copilotApiConfig.publicApiKey } : {});
1020
+ const runtimeClient = new import_runtime_client_gql5.CopilotRuntimeClient({
1021
+ url: context.copilotApiConfig.chatApiEndpoint,
1022
+ publicApiKey: context.copilotApiConfig.publicApiKey,
1023
+ headers
1024
+ });
1025
+ const response = import_runtime_client_gql5.CopilotRuntimeClient.asStream(
1026
+ runtimeClient.generateCopilotResponse({
1027
+ frontend: {
1028
+ actions: [
1029
+ {
1030
+ name: action.name,
1031
+ description: action.description || "",
1032
+ jsonSchema: JSON.stringify((0, import_shared5.actionParametersToJsonSchema)(action.parameters || []))
1033
+ }
1034
+ ]
1035
+ },
1036
+ messages: (0, import_runtime_client_gql6.convertMessagesToGqlInput)(
1037
+ includeMessages ? [systemMessage, ...messages] : [systemMessage]
1038
+ )
1039
+ })
1040
+ );
1041
+ const reader = response.getReader();
1310
1042
  let isInitial = true;
1043
+ let actionExecutionMessage = void 0;
1311
1044
  while (true) {
1312
1045
  const { done, value } = yield reader.read();
1313
1046
  if (done) {
1314
1047
  break;
1315
1048
  }
1316
- if (value.type === "partial") {
1317
- try {
1318
- let partialArguments = JSON.parse((0, import_untruncate_json2.default)(value.arguments));
1319
- stream == null ? void 0 : stream({
1320
- status: isInitial ? "initial" : "inProgress",
1321
- args: partialArguments
1322
- });
1323
- isInitial = false;
1324
- } catch (e) {
1325
- }
1326
- }
1327
- if (value.type === "function") {
1328
- stream == null ? void 0 : stream({
1329
- status: "complete",
1330
- args: value.arguments
1331
- });
1332
- return value.arguments;
1049
+ actionExecutionMessage = (0, import_runtime_client_gql4.convertGqlOutputToMessages)(
1050
+ value.generateCopilotResponse.messages
1051
+ ).find((msg) => msg instanceof import_runtime_client_gql4.ActionExecutionMessage);
1052
+ if (!actionExecutionMessage) {
1053
+ continue;
1333
1054
  }
1055
+ stream == null ? void 0 : stream({
1056
+ status: isInitial ? "initial" : "inProgress",
1057
+ args: actionExecutionMessage.arguments
1058
+ });
1059
+ isInitial = false;
1334
1060
  }
1335
- throw new Error("extract() failed: No function call occurred");
1061
+ if (!actionExecutionMessage) {
1062
+ throw new Error("extract() failed: No function call occurred");
1063
+ }
1064
+ stream == null ? void 0 : stream({
1065
+ status: "complete",
1066
+ args: actionExecutionMessage.arguments
1067
+ });
1068
+ return actionExecutionMessage.arguments;
1336
1069
  });
1337
1070
  }
1338
1071
  function makeSystemMessage(contextString, instructions) {
@@ -1347,7 +1080,7 @@ The user has provided you with the following context:
1347
1080
  ${contextString}
1348
1081
  \`\`\`
1349
1082
 
1350
- They have also provided you with a function you MUST call to initiate actions on their behalf.
1083
+ They have also provided you with a function called extract you MUST call to initiate actions on their behalf.
1351
1084
 
1352
1085
  Please assist them as best you can.
1353
1086
 
@@ -1369,13 +1102,8 @@ Any additional messages provided are for providing context only and should not b
1369
1102
  CopilotTask,
1370
1103
  defaultCopilotContextCategories,
1371
1104
  extract,
1372
- fetchAndDecodeChatCompletion,
1373
- fetchAndDecodeChatCompletionAsText,
1374
- fetchChatCompletion,
1375
- processMessageStream,
1376
1105
  useCopilotAction,
1377
1106
  useCopilotChat,
1378
- useCopilotChatV2,
1379
1107
  useCopilotContext,
1380
1108
  useCopilotReadable,
1381
1109
  useMakeCopilotActionable,