@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
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) => {
@@ -475,7 +463,7 @@ ${nonDocumentStrings}`;
475
463
  chatApiEndpoint,
476
464
  chatApiEndpointV2: `${props.url}/v2`,
477
465
  headers: props.headers || {},
478
- body: __spreadValues(__spreadValues({}, props.body), props.backendOnlyProps),
466
+ properties: props.properties || {},
479
467
  transcribeAudioUrl: props.transcribeAudioUrl,
480
468
  textToSpeechUrl: props.textToSpeechUrl,
481
469
  credentials: props.credentials
@@ -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,265 +509,164 @@ ${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
- options.setIsLoading(true);
639
- const newMessages = [
640
- {
641
- id: (0, import_nanoid3.nanoid)(),
642
- 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, _f;
557
+ setIsLoading(true);
558
+ let newMessages = [
559
+ new import_runtime_client_gql.TextMessage({
643
560
  content: "",
644
- role: "assistant"
645
- }
561
+ role: import_runtime_client_gql.Role.Assistant
562
+ })
646
563
  ];
647
564
  const abortController = new AbortController();
648
565
  abortControllerRef.current = abortController;
649
- setMessages([...messages2, ...newMessages]);
650
- const copilotConfigBody = options.copilotConfig.body || {};
651
- if (threadIdRef.current) {
652
- copilotConfigBody.threadId = threadIdRef.current;
653
- }
654
- if (runIdRef.current) {
655
- copilotConfigBody.runId = runIdRef.current;
656
- }
566
+ setMessages([...previousMessages, ...newMessages]);
657
567
  const systemMessage = makeSystemMessageCallback();
658
- const messagesWithContext = [systemMessage, ...options.initialMessages || [], ...messages2];
659
- const response = yield fetchAndDecodeChatCompletion({
660
- copilotConfig: __spreadProps(__spreadValues({}, options.copilotConfig), { body: copilotConfigBody }),
661
- messages: messagesWithContext,
662
- tools: options.tools,
663
- headers,
664
- signal: abortController.signal
665
- });
666
- if (response.headers.get("threadid")) {
667
- threadIdRef.current = response.headers.get("threadid");
668
- }
669
- if (response.headers.get("runid")) {
670
- runIdRef.current = response.headers.get("runid");
671
- }
672
- if (!response.events) {
673
- setMessages([
674
- ...messages2,
675
- {
676
- id: (0, import_nanoid3.nanoid)(),
677
- createdAt: /* @__PURE__ */ new Date(),
678
- content: response.statusText,
679
- role: "assistant"
680
- }
681
- ]);
682
- options.setIsLoading(false);
683
- throw new Error("Failed to fetch chat completion");
684
- }
685
- const reader = response.events.getReader();
686
- let feedback = false;
568
+ const messagesWithContext = [systemMessage, ...initialMessages || [], ...previousMessages];
569
+ const stream = import_runtime_client_gql.CopilotRuntimeClient.asStream(
570
+ runtimeClient.generateCopilotResponse(
571
+ __spreadValues({
572
+ frontend: {
573
+ actions: actions.map((action) => ({
574
+ name: action.name,
575
+ description: action.description || "",
576
+ jsonSchema: JSON.stringify((0, import_shared2.actionParametersToJsonSchema)(action.parameters || []))
577
+ }))
578
+ },
579
+ threadId: threadIdRef.current,
580
+ runId: runIdRef.current,
581
+ messages: (0, import_runtime_client_gql.convertMessagesToGqlInput)(messagesWithContext)
582
+ }, copilotConfig.cloud ? {
583
+ cloud: {
584
+ guardrails: {
585
+ inputValidationRules: {
586
+ allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,
587
+ denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics
588
+ }
589
+ }
590
+ }
591
+ } : {}),
592
+ copilotConfig.properties,
593
+ (_a = abortControllerRef.current) == null ? void 0 : _a.signal
594
+ )
595
+ );
596
+ const guardrailsEnabled = ((_d = (_c = (_b = copilotConfig.cloud) == null ? void 0 : _b.guardrails) == null ? void 0 : _c.input) == null ? void 0 : _d.restrictToTopic.enabled) || false;
597
+ const reader = stream.getReader();
598
+ let results = {};
687
599
  try {
688
600
  while (true) {
689
601
  const { done, value } = yield reader.read();
690
602
  if (done) {
691
603
  break;
692
604
  }
693
- let currentMessage = Object.assign({}, newMessages[newMessages.length - 1]);
694
- if (value.type === "content") {
695
- if (currentMessage.function_call || currentMessage.role === "function") {
696
- currentMessage = {
697
- id: (0, import_nanoid3.nanoid)(),
698
- createdAt: /* @__PURE__ */ new Date(),
699
- content: "",
700
- role: "assistant"
701
- };
702
- newMessages.push(currentMessage);
703
- }
704
- currentMessage.content += value.content;
705
- newMessages[newMessages.length - 1] = currentMessage;
706
- setMessages([...messages2, ...newMessages]);
707
- } else if (value.type === "result") {
708
- currentMessage = {
709
- id: (0, import_nanoid3.nanoid)(),
710
- role: "function",
711
- content: value.content,
712
- name: value.name
713
- };
714
- newMessages.push(currentMessage);
715
- setMessages([...messages2, ...newMessages]);
716
- feedback = true;
717
- } else if (value.type === "function" || value.type === "partial") {
718
- if (currentMessage.content != "" || currentMessage.function_call || currentMessage.role == "function") {
719
- currentMessage = {
720
- id: (0, import_nanoid3.nanoid)(),
721
- createdAt: /* @__PURE__ */ new Date(),
722
- content: "",
723
- role: "assistant"
724
- };
725
- newMessages.push(currentMessage);
726
- }
727
- if (value.type === "function") {
728
- currentMessage.function_call = {
729
- name: value.name,
730
- arguments: JSON.stringify(value.arguments),
731
- scope: value.scope
732
- };
733
- } else if (value.type === "partial") {
734
- let partialArguments = {};
735
- try {
736
- partialArguments = JSON.parse((0, import_untruncate_json.default)(value.arguments));
737
- } catch (e) {
738
- }
739
- currentMessage.partialFunctionCall = {
740
- name: value.name,
741
- arguments: partialArguments
742
- };
743
- }
744
- newMessages[newMessages.length - 1] = currentMessage;
745
- setMessages([...messages2, ...newMessages]);
746
- if (value.type === "function") {
747
- try {
748
- if (options.onFunctionCall && value.scope === "client") {
749
- const result = yield options.onFunctionCall(
750
- messages2,
751
- currentMessage.function_call
752
- );
753
- currentMessage = {
754
- id: (0, import_nanoid3.nanoid)(),
755
- role: "function",
756
- content: (0, import_shared3.encodeResult)(result),
757
- name: currentMessage.function_call.name
758
- };
759
- newMessages.push(currentMessage);
760
- setMessages([...messages2, ...newMessages]);
761
- feedback = true;
605
+ if (!(value == null ? void 0 : value.generateCopilotResponse)) {
606
+ continue;
607
+ }
608
+ threadIdRef.current = value.generateCopilotResponse.threadId || null;
609
+ runIdRef.current = value.generateCopilotResponse.runId || null;
610
+ const messages2 = (0, import_runtime_client_gql.convertGqlOutputToMessages)(value.generateCopilotResponse.messages);
611
+ if (messages2.length === 0) {
612
+ continue;
613
+ }
614
+ newMessages = [];
615
+ if (((_e = value.generateCopilotResponse.status) == null ? void 0 : _e.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
616
+ newMessages = [
617
+ new import_runtime_client_gql.TextMessage({
618
+ role: import_runtime_client_gql.MessageRole.Assistant,
619
+ content: ((_f = value.generateCopilotResponse.status.details) == null ? void 0 : _f.guardrailsReason) || ""
620
+ })
621
+ ];
622
+ } else {
623
+ for (const message of messages2) {
624
+ newMessages.push(message);
625
+ if (message instanceof import_runtime_client_gql.ActionExecutionMessage && message.status.code !== import_runtime_client_gql.MessageStatusCode.Pending && message.scope === "client" && onFunctionCall) {
626
+ if (!(message.id in results)) {
627
+ if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
628
+ break;
629
+ }
630
+ const result = yield onFunctionCall({
631
+ messages: previousMessages,
632
+ name: message.name,
633
+ args: message.arguments
634
+ });
635
+ results[message.id] = result;
762
636
  }
763
- } catch (error) {
764
- console.error("Failed to execute function call", error);
637
+ newMessages.push(
638
+ new import_runtime_client_gql.ResultMessage({
639
+ result: import_runtime_client_gql.ResultMessage.encodeResult(results[message.id]),
640
+ actionExecutionId: message.id,
641
+ actionName: message.name
642
+ })
643
+ );
765
644
  }
766
645
  }
767
646
  }
647
+ if (newMessages.length > 0) {
648
+ setMessages([...previousMessages, ...newMessages]);
649
+ }
768
650
  }
769
- if (feedback) {
651
+ if (
652
+ // if we have client side results
653
+ Object.values(results).length || // or the last message we received is a result
654
+ newMessages.length && newMessages[newMessages.length - 1] instanceof import_runtime_client_gql.ResultMessage
655
+ ) {
770
656
  yield new Promise((resolve) => setTimeout(resolve, 10));
771
- return yield runChatCompletion([...messages2, ...newMessages]);
657
+ return yield runChatCompletion([...previousMessages, ...newMessages]);
772
658
  } else {
773
659
  return newMessages.slice();
774
660
  }
775
661
  } finally {
776
- options.setIsLoading(false);
662
+ setIsLoading(false);
777
663
  }
778
664
  });
779
665
  const runChatCompletionAndHandleFunctionCall = (messages2) => __async(this, null, function* () {
780
666
  yield runChatCompletion(messages2);
781
667
  });
782
668
  const append = (message) => __async(this, null, function* () {
783
- if (options.isLoading) {
669
+ if (isLoading) {
784
670
  return;
785
671
  }
786
672
  const newMessages = [...messages, message];
@@ -788,12 +674,12 @@ function useChat(options) {
788
674
  return runChatCompletionAndHandleFunctionCall(newMessages);
789
675
  });
790
676
  const reload = () => __async(this, null, function* () {
791
- if (options.isLoading || messages.length === 0) {
677
+ if (isLoading || messages.length === 0) {
792
678
  return;
793
679
  }
794
680
  let newMessages = [...messages];
795
681
  const lastMessage = messages[messages.length - 1];
796
- if (lastMessage.role === "assistant") {
682
+ if (lastMessage instanceof import_runtime_client_gql.TextMessage && lastMessage.role === "assistant") {
797
683
  newMessages = newMessages.slice(0, -1);
798
684
  }
799
685
  setMessages(newMessages);
@@ -819,14 +705,14 @@ function useCopilotChat(_a = {}) {
819
705
  ]);
820
706
  const {
821
707
  getContextString,
822
- getChatCompletionFunctionDescriptions,
823
708
  getFunctionCallHandler,
824
709
  copilotApiConfig,
825
710
  messages,
826
711
  setMessages,
827
712
  isLoading,
828
713
  setIsLoading,
829
- chatInstructions
714
+ chatInstructions,
715
+ actions
830
716
  } = (0, import_react6.useContext)(CopilotContext);
831
717
  const latestGetContextString = useUpdatedRef(getContextString);
832
718
  const deleteMessage = (0, import_react6.useCallback)(
@@ -838,34 +724,24 @@ function useCopilotChat(_a = {}) {
838
724
  const makeSystemMessageCallback = (0, import_react6.useCallback)(() => {
839
725
  const systemMessageMaker = makeSystemMessage2 || defaultSystemMessage;
840
726
  const contextString = latestGetContextString.current([], defaultCopilotContextCategories);
841
- return {
842
- id: "system",
727
+ return new import_runtime_client_gql2.TextMessage({
843
728
  content: systemMessageMaker(contextString, chatInstructions),
844
- role: "system"
845
- };
729
+ role: import_runtime_client_gql2.Role.System
730
+ });
846
731
  }, [getContextString, makeSystemMessage2, chatInstructions]);
847
- const functionDescriptions = (0, import_react6.useMemo)(() => {
848
- return getChatCompletionFunctionDescriptions();
849
- }, [getChatCompletionFunctionDescriptions]);
850
732
  const { append, reload, stop } = useChat(__spreadProps(__spreadValues({}, options), {
733
+ actions: Object.values(actions),
851
734
  copilotConfig: copilotApiConfig,
852
- id: options.id,
853
735
  initialMessages: options.initialMessages || [],
854
- tools: functionDescriptions,
855
736
  onFunctionCall: getFunctionCallHandler(),
856
- headers: __spreadValues({}, options.headers),
857
- body: __spreadValues({}, options.body),
858
737
  messages,
859
738
  setMessages,
860
739
  makeSystemMessageCallback,
861
740
  isLoading,
862
741
  setIsLoading
863
742
  }));
864
- const visibleMessages = messages.filter(
865
- (message) => message.role === "user" || message.role === "assistant" || message.role === "function"
866
- );
867
743
  return {
868
- visibleMessages,
744
+ visibleMessages: messages,
869
745
  appendMessage: append,
870
746
  setMessages,
871
747
  reloadMessages: reload,
@@ -907,11 +783,11 @@ ${additionalInstructions}` : "");
907
783
 
908
784
  // src/hooks/use-make-copilot-actionable.ts
909
785
  var import_react7 = require("react");
910
- var import_nanoid4 = require("nanoid");
911
- var import_shared4 = require("@copilotkit/shared");
786
+ var import_nanoid3 = require("nanoid");
787
+ var import_shared3 = require("@copilotkit/shared");
912
788
  function useMakeCopilotActionable(annotatedFunction, dependencies) {
913
- const idRef = (0, import_react7.useRef)((0, import_nanoid4.nanoid)());
914
- const { setEntryPoint, removeEntryPoint } = (0, import_react7.useContext)(CopilotContext);
789
+ const idRef = (0, import_react7.useRef)((0, import_nanoid3.nanoid)());
790
+ const { setAction, removeAction } = (0, import_react7.useContext)(CopilotContext);
915
791
  const memoizedAnnotatedFunction = (0, import_react7.useMemo)(
916
792
  () => ({
917
793
  name: annotatedFunction.name,
@@ -922,23 +798,23 @@ function useMakeCopilotActionable(annotatedFunction, dependencies) {
922
798
  dependencies
923
799
  );
924
800
  (0, import_react7.useEffect)(() => {
925
- const action = (0, import_shared4.annotatedFunctionToAction)(memoizedAnnotatedFunction);
926
- setEntryPoint(idRef.current, action);
801
+ const action = (0, import_shared3.annotatedFunctionToAction)(memoizedAnnotatedFunction);
802
+ setAction(idRef.current, action);
927
803
  return () => {
928
- removeEntryPoint(idRef.current);
804
+ removeAction(idRef.current);
929
805
  };
930
- }, [memoizedAnnotatedFunction, setEntryPoint, removeEntryPoint]);
806
+ }, [memoizedAnnotatedFunction, setAction, removeAction]);
931
807
  }
932
808
 
933
809
  // src/hooks/use-copilot-action.ts
934
810
  var import_react8 = require("react");
935
- var import_nanoid5 = require("nanoid");
811
+ var import_nanoid4 = require("nanoid");
936
812
  function useCopilotAction(action, dependencies) {
937
- const { setEntryPoint, removeEntryPoint, entryPoints, chatComponentsCache } = (0, import_react8.useContext)(CopilotContext);
938
- const idRef = (0, import_react8.useRef)((0, import_nanoid5.nanoid)());
813
+ const { setAction, removeAction, actions, chatComponentsCache } = (0, import_react8.useContext)(CopilotContext);
814
+ const idRef = (0, import_react8.useRef)((0, import_nanoid4.nanoid)());
939
815
  if (dependencies === void 0) {
940
- if (entryPoints[idRef.current]) {
941
- entryPoints[idRef.current].handler = action.handler;
816
+ if (actions[idRef.current]) {
817
+ actions[idRef.current].handler = action.handler;
942
818
  if (typeof action.render === "function") {
943
819
  if (chatComponentsCache.current !== null) {
944
820
  chatComponentsCache.current[action.name] = action.render;
@@ -947,16 +823,16 @@ function useCopilotAction(action, dependencies) {
947
823
  }
948
824
  }
949
825
  (0, import_react8.useEffect)(() => {
950
- setEntryPoint(idRef.current, action);
826
+ setAction(idRef.current, action);
951
827
  if (chatComponentsCache.current !== null && action.render !== void 0) {
952
828
  chatComponentsCache.current[action.name] = action.render;
953
829
  }
954
830
  return () => {
955
- removeEntryPoint(idRef.current);
831
+ removeAction(idRef.current);
956
832
  };
957
833
  }, [
958
- setEntryPoint,
959
- removeEntryPoint,
834
+ setAction,
835
+ removeAction,
960
836
  action.description,
961
837
  action.name,
962
838
  // This should be faster than deep equality checking
@@ -1019,150 +895,9 @@ function useCopilotReadable({ description, value, parentId, categories, convert
1019
895
  return idRef.current;
1020
896
  }
1021
897
 
1022
- // src/openai-assistants/hooks/use-copilot-chat-v2.ts
1023
- var import_react12 = require("react");
1024
-
1025
- // src/openai-assistants/utils/process-message-stream.ts
1026
- function processMessageStream(reader, processMessage) {
1027
- return __async(this, null, function* () {
1028
- const decoder = new TextDecoder();
1029
- let buffer = "";
1030
- while (true) {
1031
- const { done, value } = yield reader.read();
1032
- if (done) {
1033
- if (buffer.length > 0) {
1034
- processMessage(buffer);
1035
- }
1036
- break;
1037
- }
1038
- buffer += decoder.decode(value, { stream: true });
1039
- let endIndex;
1040
- while ((endIndex = buffer.indexOf("\n")) !== -1) {
1041
- processMessage(buffer.substring(0, endIndex).trim());
1042
- buffer = buffer.substring(endIndex + 1);
1043
- }
1044
- }
1045
- });
1046
- }
1047
-
1048
- // src/openai-assistants/hooks/use-copilot-chat-v2.ts
1049
- var import_shared5 = require("@copilotkit/shared");
1050
- function useCopilotChatV2(options) {
1051
- const {
1052
- getContextString,
1053
- getChatCompletionFunctionDescriptions,
1054
- getFunctionCallHandler,
1055
- copilotApiConfig
1056
- } = (0, import_react12.useContext)(CopilotContext);
1057
- const [messages, setMessages] = (0, import_react12.useState)([]);
1058
- const [input, setInput] = (0, import_react12.useState)("");
1059
- const [threadId, setThreadId] = (0, import_react12.useState)(void 0);
1060
- const [status, setStatus] = (0, import_react12.useState)("awaiting_message");
1061
- const [error, setError] = (0, import_react12.useState)(void 0);
1062
- const systemMessage = (0, import_react12.useMemo)(() => {
1063
- const systemMessageMaker = options.makeSystemMessage || defaultSystemMessage2;
1064
- const contextString = getContextString([], defaultCopilotContextCategories);
1065
- return {
1066
- id: "system",
1067
- content: systemMessageMaker(contextString),
1068
- role: "system"
1069
- };
1070
- }, [getContextString, options.makeSystemMessage]);
1071
- const handleInputChange = (e) => {
1072
- setInput(e.target.value);
1073
- };
1074
- const submitMessage = (e) => __async(this, null, function* () {
1075
- var _a, _b;
1076
- e.preventDefault();
1077
- if (input === "") {
1078
- return;
1079
- }
1080
- setStatus("in_progress");
1081
- setMessages((messages2) => [...messages2, { id: "", role: "user", content: input }]);
1082
- setInput("");
1083
- const apiUrl = copilotApiConfig.chatApiEndpointV2;
1084
- const functions = getChatCompletionFunctionDescriptions();
1085
- const result = yield fetch(apiUrl, {
1086
- method: "POST",
1087
- headers: __spreadValues(__spreadValues({
1088
- "Content-Type": "application/json"
1089
- }, copilotApiConfig.headers), options.headers),
1090
- body: JSON.stringify(__spreadValues(__spreadValues(__spreadValues({
1091
- // always use user-provided threadId when available:
1092
- threadId: (_b = (_a = options.threadId) != null ? _a : threadId) != null ? _b : null,
1093
- message: input
1094
- }, functions.length > 0 && { functions }), copilotApiConfig.body), options.body))
1095
- });
1096
- if (result.body == null) {
1097
- throw new Error("The response body is empty.");
1098
- }
1099
- yield processMessageStream(result.body.getReader(), (message) => {
1100
- try {
1101
- const { type, value } = (0, import_shared5.parseStreamPart)(message);
1102
- switch (type) {
1103
- case "assistant_message": {
1104
- setMessages((messages2) => [
1105
- ...messages2,
1106
- {
1107
- id: value.id,
1108
- role: value.role,
1109
- content: value.content[0].text.value
1110
- }
1111
- ]);
1112
- break;
1113
- }
1114
- case "assistant_control_data": {
1115
- setThreadId(value.threadId);
1116
- setMessages((messages2) => {
1117
- const lastMessage = messages2[messages2.length - 1];
1118
- lastMessage.id = value.messageId;
1119
- return [...messages2.slice(0, messages2.length - 1), lastMessage];
1120
- });
1121
- break;
1122
- }
1123
- case "error": {
1124
- setError(value);
1125
- break;
1126
- }
1127
- }
1128
- } catch (error2) {
1129
- setError(error2);
1130
- }
1131
- });
1132
- setStatus("awaiting_message");
1133
- });
1134
- return {
1135
- messages,
1136
- input,
1137
- handleInputChange,
1138
- submitMessage,
1139
- status,
1140
- error
1141
- };
1142
- }
1143
- function defaultSystemMessage2(contextString) {
1144
- return `
1145
- Please act as an efficient, competent, conscientious, and industrious professional assistant.
1146
-
1147
- 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.
1148
- Always be polite and respectful, and prefer brevity over verbosity.
1149
-
1150
- The user has provided you with the following context:
1151
- \`\`\`
1152
- ${contextString}
1153
- \`\`\`
1154
-
1155
- 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.
1156
-
1157
- Please assist them as best you can.
1158
-
1159
- 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.
1160
-
1161
- If you would like to call a function, call it without saying anything else.
1162
- `;
1163
- }
1164
-
1165
898
  // src/lib/copilot-task.ts
899
+ var import_runtime_client_gql3 = require("@copilotkit/runtime-client-gql");
900
+ var import_shared4 = require("@copilotkit/shared");
1166
901
  var CopilotTask = class {
1167
902
  constructor(config) {
1168
903
  this.instructions = config.instructions;
@@ -1177,9 +912,10 @@ var CopilotTask = class {
1177
912
  */
1178
913
  run(context, data) {
1179
914
  return __async(this, null, function* () {
1180
- const entryPoints = this.includeCopilotActions ? Object.assign({}, context.entryPoints) : {};
915
+ var _a, _b;
916
+ const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};
1181
917
  for (const fn of this.actions) {
1182
- entryPoints[fn.name] = fn;
918
+ actions[fn.name] = fn;
1183
919
  }
1184
920
  let contextString = "";
1185
921
  if (data) {
@@ -1188,43 +924,39 @@ var CopilotTask = class {
1188
924
  if (this.includeCopilotReadable) {
1189
925
  contextString += context.getContextString([], defaultCopilotContextCategories);
1190
926
  }
1191
- const systemMessage = {
1192
- id: "system",
927
+ const systemMessage = new import_runtime_client_gql3.TextMessage({
1193
928
  content: taskSystemMessage(contextString, this.instructions),
1194
- role: "system"
1195
- };
929
+ role: import_runtime_client_gql3.Role.System
930
+ });
1196
931
  const messages = [systemMessage];
1197
- const response = yield fetchAndDecodeChatCompletion({
1198
- copilotConfig: context.copilotApiConfig,
1199
- messages,
1200
- tools: context.getChatCompletionFunctionDescriptions(entryPoints),
1201
- headers: context.copilotApiConfig.headers,
1202
- body: context.copilotApiConfig.body
932
+ const runtimeClient = new import_runtime_client_gql3.CopilotRuntimeClient({
933
+ url: context.copilotApiConfig.chatApiEndpoint,
934
+ publicApiKey: context.copilotApiConfig.publicApiKey,
935
+ headers: context.copilotApiConfig.headers
1203
936
  });
1204
- if (!response.events) {
1205
- throw new Error("Failed to execute task");
1206
- }
1207
- const reader = response.events.getReader();
1208
- let functionCalls = [];
1209
- while (true) {
1210
- const { done, value } = yield reader.read();
1211
- if (done) {
1212
- break;
1213
- }
1214
- if (value.type === "function") {
1215
- functionCalls.push({
1216
- name: value.name,
1217
- arguments: JSON.stringify(value.arguments)
1218
- });
1219
- break;
1220
- }
1221
- }
1222
- if (!functionCalls.length) {
1223
- throw new Error("No function call occurred");
1224
- }
1225
- const functionCallHandler = context.getFunctionCallHandler(entryPoints);
937
+ const response = yield runtimeClient.generateCopilotResponse(
938
+ {
939
+ frontend: {
940
+ actions: Object.values(actions).map((action) => ({
941
+ name: action.name,
942
+ description: action.description || "",
943
+ jsonSchema: JSON.stringify((0, import_shared4.actionParametersToJsonSchema)(action.parameters || []))
944
+ }))
945
+ },
946
+ messages: (0, import_runtime_client_gql3.convertMessagesToGqlInput)(messages)
947
+ },
948
+ context.copilotApiConfig.properties
949
+ ).toPromise();
950
+ const functionCallHandler = context.getFunctionCallHandler(actions);
951
+ const functionCalls = (0, import_runtime_client_gql3.convertGqlOutputToMessages)(
952
+ ((_b = (_a = response.data) == null ? void 0 : _a.generateCopilotResponse) == null ? void 0 : _b.messages) || []
953
+ ).filter((m) => m instanceof import_runtime_client_gql3.ActionExecutionMessage);
1226
954
  for (const functionCall of functionCalls) {
1227
- yield functionCallHandler(messages, functionCall);
955
+ yield functionCallHandler({
956
+ messages,
957
+ name: functionCall.name,
958
+ args: functionCall.arguments
959
+ });
1228
960
  }
1229
961
  });
1230
962
  }
@@ -1256,8 +988,10 @@ ${instructions}
1256
988
  }
1257
989
 
1258
990
  // src/utils/extract.ts
1259
- var import_shared6 = require("@copilotkit/shared");
1260
- var import_untruncate_json2 = __toESM(require("untruncate-json"));
991
+ var import_shared5 = require("@copilotkit/shared");
992
+ var import_runtime_client_gql4 = require("@copilotkit/runtime-client-gql");
993
+ var import_runtime_client_gql5 = require("@copilotkit/runtime-client-gql");
994
+ var import_runtime_client_gql6 = require("@copilotkit/runtime-client-gql");
1261
995
  function extract(_0) {
1262
996
  return __async(this, arguments, function* ({
1263
997
  context,
@@ -1285,51 +1019,64 @@ function extract(_0) {
1285
1019
  if (includeReadable) {
1286
1020
  contextString += context.getContextString([], defaultCopilotContextCategories);
1287
1021
  }
1288
- const systemMessage = {
1289
- id: "system",
1022
+ const systemMessage = new import_runtime_client_gql4.TextMessage({
1290
1023
  content: makeSystemMessage(contextString, instructions),
1291
- role: "system"
1292
- };
1293
- const headers = __spreadValues(__spreadValues({}, context.copilotApiConfig.headers || {}), context.copilotApiConfig.publicApiKey ? { [import_shared6.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: context.copilotApiConfig.publicApiKey } : {});
1294
- const response = yield fetchAndDecodeChatCompletion({
1295
- copilotConfig: context.copilotApiConfig,
1296
- messages: includeMessages ? [systemMessage, ...messages] : [systemMessage],
1297
- tools: context.getChatCompletionFunctionDescriptions({ extract: action }),
1298
- headers,
1299
- body: context.copilotApiConfig.body,
1300
- toolChoice: { type: "function", function: { name: "extract" } },
1301
- signal: abortSignal
1024
+ role: import_runtime_client_gql4.Role.System
1302
1025
  });
1303
- if (!response.events) {
1304
- throw new Error("extract() failed: Could not fetch chat completion");
1305
- }
1306
- const reader = response.events.getReader();
1026
+ const headers = __spreadValues(__spreadValues({}, context.copilotApiConfig.headers || {}), context.copilotApiConfig.publicApiKey ? { [import_shared5.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: context.copilotApiConfig.publicApiKey } : {});
1027
+ const runtimeClient = new import_runtime_client_gql5.CopilotRuntimeClient({
1028
+ url: context.copilotApiConfig.chatApiEndpoint,
1029
+ publicApiKey: context.copilotApiConfig.publicApiKey,
1030
+ headers
1031
+ });
1032
+ const response = import_runtime_client_gql5.CopilotRuntimeClient.asStream(
1033
+ runtimeClient.generateCopilotResponse(
1034
+ {
1035
+ frontend: {
1036
+ actions: [
1037
+ {
1038
+ name: action.name,
1039
+ description: action.description || "",
1040
+ jsonSchema: JSON.stringify((0, import_shared5.actionParametersToJsonSchema)(action.parameters || []))
1041
+ }
1042
+ ]
1043
+ },
1044
+ messages: (0, import_runtime_client_gql6.convertMessagesToGqlInput)(
1045
+ includeMessages ? [systemMessage, ...messages] : [systemMessage]
1046
+ )
1047
+ },
1048
+ context.copilotApiConfig.properties,
1049
+ abortSignal
1050
+ )
1051
+ );
1052
+ const reader = response.getReader();
1307
1053
  let isInitial = true;
1054
+ let actionExecutionMessage = void 0;
1308
1055
  while (true) {
1309
1056
  const { done, value } = yield reader.read();
1310
1057
  if (done) {
1311
1058
  break;
1312
1059
  }
1313
- if (value.type === "partial") {
1314
- try {
1315
- let partialArguments = JSON.parse((0, import_untruncate_json2.default)(value.arguments));
1316
- stream == null ? void 0 : stream({
1317
- status: isInitial ? "initial" : "inProgress",
1318
- args: partialArguments
1319
- });
1320
- isInitial = false;
1321
- } catch (e) {
1322
- }
1323
- }
1324
- if (value.type === "function") {
1325
- stream == null ? void 0 : stream({
1326
- status: "complete",
1327
- args: value.arguments
1328
- });
1329
- return value.arguments;
1060
+ actionExecutionMessage = (0, import_runtime_client_gql4.convertGqlOutputToMessages)(
1061
+ value.generateCopilotResponse.messages
1062
+ ).find((msg) => msg instanceof import_runtime_client_gql4.ActionExecutionMessage);
1063
+ if (!actionExecutionMessage) {
1064
+ continue;
1330
1065
  }
1066
+ stream == null ? void 0 : stream({
1067
+ status: isInitial ? "initial" : "inProgress",
1068
+ args: actionExecutionMessage.arguments
1069
+ });
1070
+ isInitial = false;
1331
1071
  }
1332
- throw new Error("extract() failed: No function call occurred");
1072
+ if (!actionExecutionMessage) {
1073
+ throw new Error("extract() failed: No function call occurred");
1074
+ }
1075
+ stream == null ? void 0 : stream({
1076
+ status: "complete",
1077
+ args: actionExecutionMessage.arguments
1078
+ });
1079
+ return actionExecutionMessage.arguments;
1333
1080
  });
1334
1081
  }
1335
1082
  function makeSystemMessage(contextString, instructions) {
@@ -1344,7 +1091,7 @@ The user has provided you with the following context:
1344
1091
  ${contextString}
1345
1092
  \`\`\`
1346
1093
 
1347
- They have also provided you with a function you MUST call to initiate actions on their behalf.
1094
+ They have also provided you with a function called extract you MUST call to initiate actions on their behalf.
1348
1095
 
1349
1096
  Please assist them as best you can.
1350
1097
 
@@ -1366,13 +1113,8 @@ Any additional messages provided are for providing context only and should not b
1366
1113
  CopilotTask,
1367
1114
  defaultCopilotContextCategories,
1368
1115
  extract,
1369
- fetchAndDecodeChatCompletion,
1370
- fetchAndDecodeChatCompletionAsText,
1371
- fetchChatCompletion,
1372
- processMessageStream,
1373
1116
  useCopilotAction,
1374
1117
  useCopilotChat,
1375
- useCopilotChatV2,
1376
1118
  useCopilotContext,
1377
1119
  useCopilotReadable,
1378
1120
  useMakeCopilotActionable,