@copilotkit/react-core 0.25.0 → 0.36.0-mme-pre.1

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 (150) hide show
  1. package/.turbo/turbo-build.log +184 -165
  2. package/CHANGELOG.md +22 -0
  3. package/dist/{chunk-72BJ3A3S.mjs → chunk-2C4UBKRR.mjs} +2 -2
  4. package/dist/{chunk-KTUNGBJF.mjs → chunk-2DKLSG5S.mjs} +2 -2
  5. package/dist/{chunk-4NNFSZOY.mjs → chunk-32T4S22Q.mjs} +3 -3
  6. package/dist/chunk-32T4S22Q.mjs.map +1 -0
  7. package/dist/{chunk-CGT3AVYT.mjs → chunk-7YTDTTX5.mjs} +6 -4
  8. package/dist/chunk-7YTDTTX5.mjs.map +1 -0
  9. package/dist/{chunk-ZIR7KCEA.mjs → chunk-B5CULQRZ.mjs} +2 -2
  10. package/dist/chunk-B5CULQRZ.mjs.map +1 -0
  11. package/dist/chunk-BTJD4QON.mjs +122 -0
  12. package/dist/chunk-BTJD4QON.mjs.map +1 -0
  13. package/dist/chunk-CYDWEPFL.mjs +1 -0
  14. package/dist/{chunk-6ARSX7BW.mjs → chunk-FHGMPFKO.mjs} +2 -2
  15. package/dist/{chunk-PC6FY3LD.mjs → chunk-GJGYNK46.mjs} +2 -2
  16. package/dist/{chunk-7LVVZQRG.mjs → chunk-JWANHQCM.mjs} +22 -6
  17. package/dist/chunk-JWANHQCM.mjs.map +1 -0
  18. package/dist/{chunk-M6WULIFO.mjs → chunk-L3LL6N7J.mjs} +5 -5
  19. package/dist/{chunk-6VF626RG.mjs → chunk-S2YA76YW.mjs} +5 -5
  20. package/dist/{chunk-MRXNTQOX.mjs → chunk-SKC7AJIV.mjs} +3 -1
  21. package/dist/chunk-SKC7AJIV.mjs.map +1 -0
  22. package/dist/{chunk-OWBDHSLH.mjs → chunk-T6UD6AJ2.mjs} +9 -4
  23. package/dist/chunk-T6UD6AJ2.mjs.map +1 -0
  24. package/dist/{chunk-O35YOIHC.mjs → chunk-TW5FS2QT.mjs} +8 -3
  25. package/dist/chunk-TW5FS2QT.mjs.map +1 -0
  26. package/dist/{chunk-VUY2K2DI.mjs → chunk-YWITCRBI.mjs} +2 -2
  27. package/dist/{chunk-MZ5UN3BY.mjs → chunk-ZFS5SQUT.mjs} +2 -2
  28. package/dist/components/copilot-provider/copilotkit-props.d.ts +18 -12
  29. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  30. package/dist/components/copilot-provider/copilotkit.d.ts +0 -20
  31. package/dist/components/copilot-provider/copilotkit.js +24 -3
  32. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  33. package/dist/components/copilot-provider/copilotkit.mjs +4 -4
  34. package/dist/components/copilot-provider/index.js +24 -3
  35. package/dist/components/copilot-provider/index.js.map +1 -1
  36. package/dist/components/copilot-provider/index.mjs +4 -4
  37. package/dist/components/index.js +24 -3
  38. package/dist/components/index.js.map +1 -1
  39. package/dist/components/index.mjs +4 -4
  40. package/dist/context/copilot-context.d.ts +14 -0
  41. package/dist/context/copilot-context.js +6 -1
  42. package/dist/context/copilot-context.js.map +1 -1
  43. package/dist/context/copilot-context.mjs +2 -2
  44. package/dist/context/index.d.ts +1 -0
  45. package/dist/context/index.js +6 -1
  46. package/dist/context/index.js.map +1 -1
  47. package/dist/context/index.mjs +2 -2
  48. package/dist/hooks/index.d.ts +1 -0
  49. package/dist/hooks/index.js +10 -3
  50. package/dist/hooks/index.js.map +1 -1
  51. package/dist/hooks/index.mjs +12 -12
  52. package/dist/hooks/use-chat.d.ts +1 -0
  53. package/dist/hooks/use-chat.js +4 -2
  54. package/dist/hooks/use-chat.js.map +1 -1
  55. package/dist/hooks/use-chat.mjs +3 -3
  56. package/dist/hooks/use-copilot-action.js +6 -1
  57. package/dist/hooks/use-copilot-action.js.map +1 -1
  58. package/dist/hooks/use-copilot-action.mjs +3 -3
  59. package/dist/hooks/use-copilot-chat.d.ts +1 -0
  60. package/dist/hooks/use-copilot-chat.js +10 -3
  61. package/dist/hooks/use-copilot-chat.js.map +1 -1
  62. package/dist/hooks/use-copilot-chat.mjs +7 -7
  63. package/dist/hooks/use-copilot-readable.js +6 -1
  64. package/dist/hooks/use-copilot-readable.js.map +1 -1
  65. package/dist/hooks/use-copilot-readable.mjs +3 -3
  66. package/dist/hooks/use-flat-category-store.mjs +1 -1
  67. package/dist/hooks/use-make-copilot-actionable.js +6 -1
  68. package/dist/hooks/use-make-copilot-actionable.js.map +1 -1
  69. package/dist/hooks/use-make-copilot-actionable.mjs +3 -3
  70. package/dist/hooks/use-make-copilot-document-readable.js +6 -1
  71. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  72. package/dist/hooks/use-make-copilot-document-readable.mjs +3 -3
  73. package/dist/hooks/use-make-copilot-readable.js +6 -1
  74. package/dist/hooks/use-make-copilot-readable.js.map +1 -1
  75. package/dist/hooks/use-make-copilot-readable.mjs +3 -3
  76. package/dist/hooks/use-tree.mjs +2 -2
  77. package/dist/index.d.ts +2 -0
  78. package/dist/index.js +143 -8
  79. package/dist/index.js.map +1 -1
  80. package/dist/index.mjs +20 -15
  81. package/dist/lib/copilot-task.d.ts +98 -1
  82. package/dist/lib/copilot-task.js +9 -2
  83. package/dist/lib/copilot-task.js.map +1 -1
  84. package/dist/lib/copilot-task.mjs +6 -6
  85. package/dist/lib/index.d.ts +1 -0
  86. package/dist/lib/index.js +9 -2
  87. package/dist/lib/index.js.map +1 -1
  88. package/dist/lib/index.mjs +6 -6
  89. package/dist/openai-assistants/hooks/index.js +6 -1
  90. package/dist/openai-assistants/hooks/index.js.map +1 -1
  91. package/dist/openai-assistants/hooks/index.mjs +6 -6
  92. package/dist/openai-assistants/hooks/use-assistants.mjs +2 -2
  93. package/dist/openai-assistants/hooks/use-copilot-chat-v2.js +6 -1
  94. package/dist/openai-assistants/hooks/use-copilot-chat-v2.js.map +1 -1
  95. package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs +6 -6
  96. package/dist/openai-assistants/index.js +6 -1
  97. package/dist/openai-assistants/index.js.map +1 -1
  98. package/dist/openai-assistants/index.mjs +6 -6
  99. package/dist/openai-assistants/utils/index.mjs +2 -2
  100. package/dist/openai-assistants/utils/process-message-stream.mjs +2 -2
  101. package/dist/types/chat-suggestion-configuration.d.ts +22 -0
  102. package/dist/types/chat-suggestion-configuration.js +19 -0
  103. package/dist/types/chat-suggestion-configuration.js.map +1 -0
  104. package/dist/types/chat-suggestion-configuration.mjs +1 -0
  105. package/dist/types/chat-suggestion-configuration.mjs.map +1 -0
  106. package/dist/types/index.d.ts +1 -0
  107. package/dist/types/index.js.map +1 -1
  108. package/dist/utils/extract.d.ts +37 -0
  109. package/dist/utils/extract.js +245 -0
  110. package/dist/utils/extract.js.map +1 -0
  111. package/dist/utils/extract.mjs +15 -0
  112. package/dist/utils/extract.mjs.map +1 -0
  113. package/dist/utils/fetch-chat-completion.d.ts +8 -1
  114. package/dist/utils/fetch-chat-completion.js +4 -2
  115. package/dist/utils/fetch-chat-completion.js.map +1 -1
  116. package/dist/utils/fetch-chat-completion.mjs +2 -2
  117. package/dist/utils/index.d.ts +9 -0
  118. package/dist/utils/index.js +267 -0
  119. package/dist/utils/index.js.map +1 -0
  120. package/dist/utils/index.mjs +23 -0
  121. package/dist/utils/index.mjs.map +1 -0
  122. package/package.json +4 -4
  123. package/src/components/copilot-provider/copilotkit-props.tsx +20 -12
  124. package/src/components/copilot-provider/copilotkit.tsx +62 -21
  125. package/src/context/copilot-context.tsx +24 -1
  126. package/src/hooks/use-chat.ts +2 -2
  127. package/src/hooks/use-copilot-readable.ts +94 -0
  128. package/src/index.tsx +1 -6
  129. package/src/lib/copilot-task.ts +97 -1
  130. package/src/types/chat-suggestion-configuration.ts +23 -0
  131. package/src/types/index.ts +1 -0
  132. package/src/utils/extract.ts +164 -0
  133. package/src/utils/fetch-chat-completion.ts +5 -1
  134. package/src/utils/index.ts +8 -0
  135. package/typedoc.json +4 -0
  136. package/dist/chunk-4NNFSZOY.mjs.map +0 -1
  137. package/dist/chunk-7LVVZQRG.mjs.map +0 -1
  138. package/dist/chunk-CGT3AVYT.mjs.map +0 -1
  139. package/dist/chunk-O35YOIHC.mjs.map +0 -1
  140. package/dist/chunk-OWBDHSLH.mjs.map +0 -1
  141. package/dist/chunk-ZIR7KCEA.mjs.map +0 -1
  142. /package/dist/{chunk-72BJ3A3S.mjs.map → chunk-2C4UBKRR.mjs.map} +0 -0
  143. /package/dist/{chunk-KTUNGBJF.mjs.map → chunk-2DKLSG5S.mjs.map} +0 -0
  144. /package/dist/{chunk-MRXNTQOX.mjs.map → chunk-CYDWEPFL.mjs.map} +0 -0
  145. /package/dist/{chunk-6ARSX7BW.mjs.map → chunk-FHGMPFKO.mjs.map} +0 -0
  146. /package/dist/{chunk-PC6FY3LD.mjs.map → chunk-GJGYNK46.mjs.map} +0 -0
  147. /package/dist/{chunk-M6WULIFO.mjs.map → chunk-L3LL6N7J.mjs.map} +0 -0
  148. /package/dist/{chunk-6VF626RG.mjs.map → chunk-S2YA76YW.mjs.map} +0 -0
  149. /package/dist/{chunk-VUY2K2DI.mjs.map → chunk-YWITCRBI.mjs.map} +0 -0
  150. /package/dist/{chunk-MZ5UN3BY.mjs.map → chunk-ZFS5SQUT.mjs.map} +0 -0
@@ -1,3 +1,97 @@
1
+ /**
2
+ * A hook for providing app-state & other information to the Copilot.
3
+ *
4
+ * <img referrerPolicy="no-referrer-when-downgrade" src="https://static.scarf.sh/a.png?x-pxid=a9b290bb-38f9-4518-ac3b-8f54fdbf43be" />
5
+ *
6
+ * `useCopilotReadable` is a React hook that provides app-state and other information
7
+ * to the Copilot. Optionally, the hook can also handle hierarchical state within your
8
+ * application, passing these parent-child relationships to the Copilot.
9
+ *
10
+ * <RequestExample>
11
+ * ```jsx useCopilotReadable Example
12
+ * import { useCopilotReadable }
13
+ * from "@copilotkit/react-core";
14
+ *
15
+ * const myAppState = ...;
16
+ * useCopilotReadable({
17
+ * description: "The current state of the app",
18
+ * value: myAppState
19
+ * });
20
+ * ```
21
+ * </RequestExample>
22
+ *
23
+ * In its most basic usage, useCopilotReadable accepts a single string argument
24
+ * representing any piece of app state, making it available for the Copilot to use
25
+ * as context when responding to user input.
26
+ *
27
+ * For example:
28
+ *
29
+ * ```jsx simple state example
30
+ * import { useCopilotReadable } from "@copilotkit/react-core";
31
+ *
32
+ * const userName = "Rust Cohle";
33
+ * useCopilotReadable({
34
+ * description: "The name of the user",
35
+ * value: userName
36
+ * });
37
+ * ```
38
+ *
39
+ * You can also pass in an object representing your app state,
40
+ * for example:
41
+ *
42
+ * ```jsx using state
43
+ * import { useCopilotReadable } from "@copilotkit/react-core";
44
+ *
45
+ * const myAppState = {
46
+ * userName: "Rust Cohle",
47
+ * userAddress: {
48
+ * street: "4500 Old Spanish Trail",
49
+ * city: "New Orleans",
50
+ * state: "LA",
51
+ * zip: "70129"
52
+ * }
53
+ * };
54
+ * useCopilotReadable({
55
+ * description: "The current state of the app",
56
+ * value: myAppState
57
+ * });
58
+ * ```
59
+ *
60
+ * Optionally, you can maintain the hierarchical structure of information by passing
61
+ * `parentId`:
62
+ *
63
+ * ```jsx parentId example
64
+ * import { useCopilotReadable } from "@copilotkit/react-core";
65
+ *
66
+ *
67
+ * function Employee(props: EmployeeProps) {
68
+ * const { employeeName, workProfile, metadata } = props;
69
+ *
70
+ * // propagate any information copilot
71
+ * const employeeContextId = useCopilotReadable({
72
+ * description: "Employee name",
73
+ * value: employeeName
74
+ * });
75
+ *
76
+ * // Pass a parentID to maintain a hierarchical structure.
77
+ * // Especially useful with child React components, list elements, etc.
78
+ * useCopilotReadable({
79
+ * description: "Work profile",
80
+ * value: workProfile.description(),
81
+ * parentId: employeeContextId
82
+ * });
83
+ * useCopilotReadable({
84
+ * description: "Employee metadata",
85
+ * value: metadata.description(),
86
+ * parentId: employeeContextId
87
+ * });
88
+ *
89
+ * return (
90
+ * // Render as usual...
91
+ * );
92
+ * }
93
+ * ```
94
+ */
1
95
  import { useContext, useEffect, useRef } from "react";
2
96
  import { CopilotContext } from "../context/copilot-context";
3
97
 
package/src/index.tsx CHANGED
@@ -5,9 +5,4 @@ export * from "./hooks";
5
5
  export * from "./types";
6
6
  export * from "./openai-assistants";
7
7
  export * from "./lib";
8
- export {
9
- type FetchChatCompletionParams,
10
- fetchChatCompletion,
11
- fetchAndDecodeChatCompletion,
12
- fetchAndDecodeChatCompletionAsText,
13
- } from "./utils/fetch-chat-completion";
8
+ export * from "./utils";
@@ -1,3 +1,94 @@
1
+ /**
2
+ * Execute one-off tasks using Copilot intelligence.
3
+ *
4
+ * <img referrerPolicy="no-referrer-when-downgrade" src="https://static.scarf.sh/a.png?x-pxid=a9b290bb-38f9-4518-ac3b-8f54fdbf43be" />
5
+ *
6
+ * This class is used to execute one-off tasks, for example on button press. It
7
+ * can use the context available via [useCopilotReadable](../useCopilotReadable)
8
+ * and the actions provided by [useCopilotAction](../useCopilotAction), or
9
+ * you can provide your own context and actions.
10
+ *
11
+ * <RequestExample>
12
+ * ```jsx CopilotTask Example
13
+ * import {
14
+ * CopilotTask,
15
+ * useCopilotContext
16
+ * } from "@copilotkit/react-core";
17
+ *
18
+ * const task = new CopilotTask({
19
+ * instructions: "Set a random message",
20
+ * actions: [
21
+ * {
22
+ * name: "setMessage",
23
+ * description: "Set the message.",
24
+ * argumentAnnotations: [
25
+ * {
26
+ * name: "message",
27
+ * type: "string",
28
+ * description:
29
+ * "A message to display.",
30
+ * required: true,
31
+ * },
32
+ * ],
33
+ *
34
+ * implementation: async (message) => {
35
+ * // ...
36
+ * },
37
+ * }
38
+ * ]
39
+ * });
40
+ * const context = useCopilotContext();
41
+ * await task.run(context);
42
+ * ```
43
+ * </RequestExample>
44
+ *
45
+ * In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.
46
+ *
47
+ * ```jsx
48
+ * import {
49
+ * CopilotTask,
50
+ * useCopilotContext
51
+ * } from "@copilotkit/react-core";
52
+ *
53
+ * const randomSlideTask = new CopilotTask({
54
+ * instructions: "Make a random slide",
55
+ * });
56
+ *
57
+ * const context = useCopilotContext();
58
+ *
59
+ * return (
60
+ * <button onClick={() => randomSlideTask.run(context)}>
61
+ * Make a random slide
62
+ * </button>
63
+ * );
64
+ * ```
65
+ *
66
+ * Have a look at the [Presentation example](https://github.com/CopilotKit/CopilotKit/blob/main/CopilotKit/examples/next-openai/src/app/presentation/page.tsx)
67
+ * for a more complete example.
68
+ *
69
+ * It's also possible to provide your own context and actions. In addition, you can specify to ignore
70
+ * `useCopilotReadable` and `useCopilotAction`.
71
+ *
72
+ * ```jsx
73
+ * import {
74
+ * CopilotTask,
75
+ * useCopilotContext
76
+ * } from "@copilotkit/react-core";
77
+ *
78
+ * const standaloneTask = new CopilotTask({
79
+ * instructions: "Do something standalone",
80
+ * data: [...],
81
+ * actions: [...],
82
+ * includeCopilotReadable: false, // Don't use current context
83
+ * includeCopilotActions: false, // Don't use current actions
84
+ * });
85
+ *
86
+ * const context = useCopilotContext();
87
+ *
88
+ * standaloneTask.run(context);
89
+ * ```
90
+ */
91
+
1
92
  import { FunctionCall, Message } from "@copilotkit/shared";
2
93
  import { FrontendAction } from "../types/frontend-action";
3
94
  import { CopilotContextParams } from "../context";
@@ -10,7 +101,7 @@ export interface CopilotTaskConfig {
10
101
  */
11
102
  instructions: string;
12
103
  /**
13
- * Action definitions to be sent to the API.
104
+ * An array of action definitions that can be called.
14
105
  */
15
106
  actions?: FrontendAction<any>[];
16
107
  /**
@@ -44,6 +135,11 @@ export class CopilotTask<T = any> {
44
135
  config.includeCopilotActions !== false && config.includeCopilotActionable !== false;
45
136
  }
46
137
 
138
+ /**
139
+ * Run the task.
140
+ * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.
141
+ * @param data The data to use for the task.
142
+ */
47
143
  async run(context: CopilotContextParams, data?: T): Promise<void> {
48
144
  const entryPoints = this.includeCopilotActions ? Object.assign({}, context.entryPoints) : {};
49
145
 
@@ -0,0 +1,23 @@
1
+ export interface CopilotChatSuggestionConfiguration {
2
+ /**
3
+ * A prompt or instructions for the GPT to generate suggestions.
4
+ */
5
+ instructions: string;
6
+
7
+ /**
8
+ * The minimum number of suggestions to generate. Defaults to `1`.
9
+ * @default 1
10
+ */
11
+ minSuggestions?: number;
12
+
13
+ /**
14
+ * The maximum number of suggestions to generate. Defaults to `3`.
15
+ * @default 1
16
+ */
17
+ maxSuggestions?: number;
18
+
19
+ /**
20
+ * An optional class name to apply to the suggestions.
21
+ */
22
+ className?: string;
23
+ }
@@ -1,3 +1,4 @@
1
1
  export type { DocumentPointer } from "./document-pointer";
2
2
  export type { SystemMessageFunction } from "./system-message";
3
3
  export type { ActionRenderProps, RenderFunctionStatus } from "./frontend-action";
4
+ export type { CopilotChatSuggestionConfiguration } from "./chat-suggestion-configuration";
@@ -0,0 +1,164 @@
1
+ import {
2
+ Action,
3
+ COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,
4
+ MappedParameterTypes,
5
+ Message,
6
+ Parameter,
7
+ } from "@copilotkit/shared";
8
+ import { CopilotContextParams } from "../context";
9
+ import { defaultCopilotContextCategories } from "../components";
10
+ import { fetchAndDecodeChatCompletion } from "./fetch-chat-completion";
11
+ import untruncateJson from "untruncate-json";
12
+
13
+ interface InitialState<T extends Parameter[] | [] = []> {
14
+ status: "initial";
15
+ args: Partial<MappedParameterTypes<T>>;
16
+ }
17
+
18
+ interface InProgressState<T extends Parameter[] | [] = []> {
19
+ status: "inProgress";
20
+ args: Partial<MappedParameterTypes<T>>;
21
+ }
22
+
23
+ interface CompleteState<T extends Parameter[] | [] = []> {
24
+ status: "complete";
25
+ args: MappedParameterTypes<T>;
26
+ }
27
+
28
+ type StreamHandlerArgs<T extends Parameter[] | [] = []> =
29
+ | InitialState<T>
30
+ | InProgressState<T>
31
+ | CompleteState<T>;
32
+
33
+ interface ExtractOptions<T extends Parameter[]> {
34
+ context: CopilotContextParams;
35
+ instructions: string;
36
+ parameters: T;
37
+ include?: IncludeOptions;
38
+ data?: any;
39
+ abortSignal?: AbortSignal;
40
+ stream?: (args: StreamHandlerArgs<T>) => void;
41
+ }
42
+
43
+ interface IncludeOptions {
44
+ readable?: boolean;
45
+ messages?: boolean;
46
+ }
47
+
48
+ export async function extract<const T extends Parameter[]>({
49
+ context,
50
+ instructions,
51
+ parameters,
52
+ include,
53
+ data,
54
+ abortSignal,
55
+ stream,
56
+ }: ExtractOptions<T>): Promise<MappedParameterTypes<T>> {
57
+ const { messages } = context;
58
+
59
+ const action: Action<any> = {
60
+ name: "extract",
61
+ parameters,
62
+ handler: (args: any) => {},
63
+ };
64
+
65
+ const includeReadable = include?.readable ?? false;
66
+ const includeMessages = include?.messages ?? false;
67
+
68
+ let contextString = "";
69
+
70
+ if (data) {
71
+ contextString = (typeof data === "string" ? data : JSON.stringify(data)) + "\n\n";
72
+ }
73
+
74
+ if (includeReadable) {
75
+ contextString += context.getContextString([], defaultCopilotContextCategories);
76
+ }
77
+
78
+ const systemMessage: Message = {
79
+ id: "system",
80
+ content: makeSystemMessage(contextString, instructions),
81
+ role: "system",
82
+ };
83
+
84
+ const headers = {
85
+ ...(context.copilotApiConfig.headers || {}),
86
+ ...(context.copilotApiConfig.publicApiKey
87
+ ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: context.copilotApiConfig.publicApiKey }
88
+ : {}),
89
+ };
90
+
91
+ const response = await fetchAndDecodeChatCompletion({
92
+ copilotConfig: context.copilotApiConfig,
93
+ messages: includeMessages ? [systemMessage, ...messages] : [systemMessage],
94
+ tools: context.getChatCompletionFunctionDescriptions({ extract: action }),
95
+ headers,
96
+ body: context.copilotApiConfig.body,
97
+ toolChoice: { type: "function", function: { name: "extract" } },
98
+ signal: abortSignal,
99
+ });
100
+
101
+ if (!response.events) {
102
+ throw new Error("extract() failed: Could not fetch chat completion");
103
+ }
104
+
105
+ const reader = response.events.getReader();
106
+ let isInitial = true;
107
+
108
+ while (true) {
109
+ const { done, value } = await reader.read();
110
+
111
+ if (done) {
112
+ break;
113
+ }
114
+
115
+ if (value.type === "partial") {
116
+ try {
117
+ let partialArguments = JSON.parse(untruncateJson(value.arguments));
118
+ stream?.({
119
+ status: isInitial ? "initial" : "inProgress",
120
+ args: partialArguments as Partial<MappedParameterTypes<T>>,
121
+ });
122
+ isInitial = false;
123
+ } catch (e) {}
124
+ }
125
+
126
+ if (value.type === "function") {
127
+ stream?.({
128
+ status: "complete",
129
+ args: value.arguments as MappedParameterTypes<T>,
130
+ });
131
+ return value.arguments as MappedParameterTypes<T>;
132
+ }
133
+ }
134
+
135
+ throw new Error("extract() failed: No function call occurred");
136
+ }
137
+
138
+ function makeSystemMessage(contextString: string, instructions: string): string {
139
+ return `
140
+ Please act as an efficient, competent, conscientious, and industrious professional assistant.
141
+
142
+ 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.
143
+ Always be polite and respectful, and prefer brevity over verbosity.
144
+
145
+ The user has provided you with the following context:
146
+ \`\`\`
147
+ ${contextString}
148
+ \`\`\`
149
+
150
+ They have also provided you with a function you MUST call to initiate actions on their behalf.
151
+
152
+ Please assist them as best you can.
153
+
154
+ This is not a conversation, so please do not ask questions. Just call the function without saying anything else.
155
+
156
+ The user has given you the following task to complete:
157
+
158
+ \`\`\`
159
+ ${instructions}
160
+ \`\`\`
161
+
162
+ Any additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.
163
+ `;
164
+ }
@@ -19,6 +19,7 @@ export interface FetchChatCompletionParams {
19
19
  headers?: Record<string, string> | Headers;
20
20
  body?: object;
21
21
  signal?: AbortSignal;
22
+ toolChoice?: string | { type: "function"; function: { name: string } };
22
23
  }
23
24
 
24
25
  export async function fetchChatCompletion({
@@ -30,6 +31,7 @@ export async function fetchChatCompletion({
30
31
  headers,
31
32
  body,
32
33
  signal,
34
+ toolChoice,
33
35
  }: FetchChatCompletionParams): Promise<Response> {
34
36
  temperature ||= 0.5;
35
37
  tools ||= [];
@@ -40,6 +42,8 @@ export async function fetchChatCompletion({
40
42
  return { content, role, name, function_call };
41
43
  });
42
44
 
45
+ toolChoice ||= "auto";
46
+
43
47
  const response = await fetch(copilotConfig.chatApiEndpoint, {
44
48
  method: "POST",
45
49
  headers: {
@@ -53,7 +57,7 @@ export async function fetchChatCompletion({
53
57
  stream: true,
54
58
  ...(tools.length ? { tools } : {}),
55
59
  ...(temperature ? { temperature } : {}),
56
- ...(tools.length != 0 ? { tool_choice: "auto" } : {}),
60
+ ...(tools.length != 0 ? { tool_choice: toolChoice } : {}),
57
61
  ...copilotConfig.body,
58
62
  ...copilotConfig.backendOnlyProps,
59
63
  ...excludeBackendOnlyProps(copilotConfig),
@@ -0,0 +1,8 @@
1
+ export {
2
+ type FetchChatCompletionParams,
3
+ fetchChatCompletion,
4
+ fetchAndDecodeChatCompletion,
5
+ fetchAndDecodeChatCompletionAsText,
6
+ } from "./fetch-chat-completion";
7
+
8
+ export { extract } from "./extract";
package/typedoc.json ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "extends": ["../../typedoc.base.json"],
3
+ "entryPoints": ["src/index.tsx"]
4
+ }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/hooks/use-chat.ts"],"sourcesContent":["import { useRef, useState } from \"react\";\nimport {\n Message,\n ToolDefinition,\n FunctionCallHandler,\n encodeResult,\n FunctionCall,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n} from \"@copilotkit/shared\";\n\nimport { nanoid } from \"nanoid\";\nimport { fetchAndDecodeChatCompletion } from \"../utils/fetch-chat-completion\";\nimport { CopilotApiConfig } from \"../context\";\nimport untruncateJson from \"untruncate-json\";\n\nexport type UseChatOptions = {\n /**\n * The API endpoint that accepts a `{ messages: Message[] }` object and returns\n * a stream of tokens of the AI chat response. Defaults to `/api/chat`.\n */\n api?: string;\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n /**\n * Callback function to be called when a function call is received.\n * If the function returns a `ChatRequest` object, the request will be sent\n * automatically to the API and will be used to update the chat.\n */\n onFunctionCall?: FunctionCallHandler;\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n /**\n * Extra body object to be sent with the API request.\n * @example\n * Send a `sessionId` to the API along with the messages.\n * ```js\n * useChat({\n * body: {\n * sessionId: '123',\n * }\n * })\n * ```\n */\n body?: object;\n /**\n * Function definitions to be sent to the API.\n */\n tools?: ToolDefinition[];\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: () => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport type UseChatOptionsWithCopilotConfig = UseChatOptions & {\n copilotConfig: CopilotApiConfig;\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n};\n\nexport function useChat(options: UseChatOptionsWithCopilotConfig): UseChatHelpers {\n const { messages, setMessages } = options;\n const [input, setInput] = useState(\"\");\n const [isLoading, setIsLoading] = useState(false);\n const abortControllerRef = useRef<AbortController>();\n const threadIdRef = useRef<string | null>(null);\n const runIdRef = useRef<string | null>(null);\n const publicApiKey = options.copilotConfig.publicApiKey;\n const headers = {\n ...(options.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const runChatCompletion = async (messages: Message[]): Promise<Message[]> => {\n setIsLoading(true);\n\n const newMessages: Message[] = [\n {\n id: nanoid(),\n createdAt: new Date(),\n content: \"\",\n role: \"assistant\",\n },\n ];\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setMessages([...messages, ...newMessages]);\n\n // add threadId and runId to the body if it exists\n const copilotConfigBody = options.copilotConfig.body || {};\n if (threadIdRef.current) {\n copilotConfigBody.threadId = threadIdRef.current;\n }\n if (runIdRef.current) {\n copilotConfigBody.runId = runIdRef.current;\n }\n\n const messagesWithContext = [...(options.initialMessages || []), ...messages];\n const response = await fetchAndDecodeChatCompletion({\n copilotConfig: { ...options.copilotConfig, body: copilotConfigBody },\n messages: messagesWithContext,\n tools: options.tools,\n headers: headers,\n signal: abortController.signal,\n });\n\n if (response.headers.get(\"threadid\")) {\n threadIdRef.current = response.headers.get(\"threadid\");\n }\n\n if (response.headers.get(\"runid\")) {\n runIdRef.current = response.headers.get(\"runid\");\n }\n\n if (!response.events) {\n setMessages([\n ...messages,\n {\n id: nanoid(),\n createdAt: new Date(),\n content: response.statusText,\n role: \"assistant\",\n },\n ]);\n setIsLoading(false);\n throw new Error(\"Failed to fetch chat completion\");\n }\n\n const reader = response.events.getReader();\n\n // Whether to feed back the new messages to GPT\n let feedback = false;\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n let currentMessage = Object.assign({}, newMessages[newMessages.length - 1]);\n\n if (value.type === \"content\") {\n if (currentMessage.function_call || currentMessage.role === \"function\") {\n // Create a new message if the previous one is a function call or result\n currentMessage = {\n id: nanoid(),\n createdAt: new Date(),\n content: \"\",\n role: \"assistant\",\n };\n newMessages.push(currentMessage);\n }\n currentMessage.content += value.content;\n newMessages[newMessages.length - 1] = currentMessage;\n setMessages([...messages, ...newMessages]);\n } else if (value.type === \"result\") {\n // When we get a result message, it is already complete\n currentMessage = {\n id: nanoid(),\n role: \"function\",\n content: value.content,\n name: value.name,\n };\n newMessages.push(currentMessage);\n setMessages([...messages, ...newMessages]);\n\n // After receiving a result, feed back the new messages to GPT\n feedback = true;\n } else if (value.type === \"function\" || value.type === \"partial\") {\n // Create a new message if the previous one is not empty\n if (\n currentMessage.content != \"\" ||\n currentMessage.function_call ||\n currentMessage.role == \"function\"\n ) {\n currentMessage = {\n id: nanoid(),\n createdAt: new Date(),\n content: \"\",\n role: \"assistant\",\n };\n newMessages.push(currentMessage);\n }\n if (value.type === \"function\") {\n currentMessage.function_call = {\n name: value.name,\n arguments: JSON.stringify(value.arguments),\n scope: value.scope,\n };\n } else if (value.type === \"partial\") {\n let partialArguments: any = {};\n try {\n partialArguments = JSON.parse(untruncateJson(value.arguments));\n } catch (e) {}\n\n currentMessage.partialFunctionCall = {\n name: value.name,\n arguments: partialArguments,\n };\n }\n\n newMessages[newMessages.length - 1] = currentMessage;\n setMessages([...messages, ...newMessages]);\n\n if (value.type === \"function\") {\n // Execute the function call\n try {\n if (options.onFunctionCall && value.scope === \"client\") {\n const result = await options.onFunctionCall(\n messages,\n currentMessage.function_call as FunctionCall,\n );\n\n currentMessage = {\n id: nanoid(),\n role: \"function\",\n content: encodeResult(result),\n name: (currentMessage.function_call! as FunctionCall).name!,\n };\n newMessages.push(currentMessage);\n setMessages([...messages, ...newMessages]);\n\n // After a function call, feed back the new messages to GPT\n feedback = true;\n }\n } catch (error) {\n console.error(\"Failed to execute function call\", error);\n // TODO: Handle error\n // this should go to the message itself\n }\n }\n }\n }\n\n // If we want feedback, run the completion again and return the results\n if (feedback) {\n return await runChatCompletion([...messages, ...newMessages]);\n }\n // otherwise, return the new messages\n else {\n return newMessages.slice();\n }\n } finally {\n setIsLoading(false);\n }\n };\n\n const runChatCompletionAndHandleFunctionCall = async (messages: Message[]): Promise<void> => {\n await runChatCompletion(messages);\n };\n\n const append = async (message: Message): Promise<void> => {\n if (isLoading) {\n return;\n }\n const newMessages = [...messages, message];\n setMessages(newMessages);\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const reload = async (): Promise<void> => {\n if (isLoading || messages.length === 0) {\n return;\n }\n let newMessages = [...messages];\n const lastMessage = messages[messages.length - 1];\n\n if (lastMessage.role === \"assistant\") {\n newMessages = newMessages.slice(0, -1);\n }\n setMessages(newMessages);\n\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const stop = (): void => {\n abortControllerRef.current?.abort();\n };\n\n return {\n append,\n reload,\n stop,\n isLoading,\n input,\n setInput,\n };\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAS,QAAQ,gBAAgB;AACjC;AAAA,EAIE;AAAA,EAEA;AAAA,OACK;AAEP,SAAS,cAAc;AAGvB,OAAO,oBAAoB;AAoFpB,SAAS,QAAQ,SAA0D;AAChF,QAAM,EAAE,UAAU,YAAY,IAAI;AAClC,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAS,EAAE;AACrC,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAChD,QAAM,qBAAqB,OAAwB;AACnD,QAAM,cAAc,OAAsB,IAAI;AAC9C,QAAM,WAAW,OAAsB,IAAI;AAC3C,QAAM,eAAe,QAAQ,cAAc;AAC3C,QAAM,UAAU,kCACV,QAAQ,WAAW,CAAC,IACpB,eAAe,EAAE,CAAC,mCAAmC,GAAG,aAAa,IAAI,CAAC;AAGhF,QAAM,oBAAoB,CAAOA,cAA4C;AAC3E,iBAAa,IAAI;AAEjB,UAAM,cAAyB;AAAA,MAC7B;AAAA,QACE,IAAI,OAAO;AAAA,QACX,WAAW,oBAAI,KAAK;AAAA,QACpB,SAAS;AAAA,QACT,MAAM;AAAA,MACR;AAAA,IACF;AACA,UAAM,kBAAkB,IAAI,gBAAgB;AAC5C,uBAAmB,UAAU;AAE7B,gBAAY,CAAC,GAAGA,WAAU,GAAG,WAAW,CAAC;AAGzC,UAAM,oBAAoB,QAAQ,cAAc,QAAQ,CAAC;AACzD,QAAI,YAAY,SAAS;AACvB,wBAAkB,WAAW,YAAY;AAAA,IAC3C;AACA,QAAI,SAAS,SAAS;AACpB,wBAAkB,QAAQ,SAAS;AAAA,IACrC;AAEA,UAAM,sBAAsB,CAAC,GAAI,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 -1 +0,0 @@
1
- {"version":3,"sources":["../src/components/copilot-provider/copilotkit.tsx"],"sourcesContent":["import { Ref, useCallback, useRef, useState } from \"react\";\nimport {\n CopilotContext,\n CopilotApiConfig,\n InChatRenderFunction,\n} from \"../../context/copilot-context\";\nimport useTree from \"../../hooks/use-tree\";\nimport { DocumentPointer } from \"../../types\";\nimport {\n COPILOT_CLOUD_CHAT_URL,\n CopilotCloudConfig,\n FunctionCallHandler,\n Message,\n actionToChatCompletionFunction,\n} from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../../types/frontend-action\";\nimport useFlatCategoryStore from \"../../hooks/use-flat-category-store\";\nimport { CopilotKitProps } from \"./copilotkit-props\";\nimport { ToolDefinition } from \"@copilotkit/shared\";\n\n/**\n * The CopilotKit component.\n * This component provides the Copilot context to its children.\n * It can be configured either with a chat API endpoint or a CopilotApiConfig.\n *\n * NOTE: The backend can use OpenAI, or you can bring your own LLM.\n * For examples of the backend api implementation, see `examples/next-openai` usage (under `src/api/copilotkit`),\n * or read the documentation at https://docs.copilotkit.ai\n * In particular, Getting-Started > Quickstart-Runtime: https://docs.copilotkit.ai/getting-started/quickstart-runtime\n *\n * Example usage:\n * ```\n * <CopilotKit url=\"https://your.copilotkit.api\">\n * <App />\n * </CopilotKit>\n * ```\n *\n * @param props - The props for the component.\n * @returns The CopilotKit component.\n */\nexport function CopilotKit({ children, ...props }: CopilotKitProps) {\n // Compute all the functions and properties that we need to pass\n // to the CopilotContext.\n\n if (!props.runtimeUrl && !props.url && !props.publicApiKey) {\n throw new Error(\"Please provide either a url or a publicApiKey to the CopilotKit component.\");\n }\n\n const chatApiEndpoint = props.runtimeUrl || props.url || COPILOT_CLOUD_CHAT_URL;\n\n const [entryPoints, setEntryPoints] = useState<Record<string, FrontendAction<any>>>({});\n const chatComponentsCache = useRef<Record<string, InChatRenderFunction | string>>({});\n const { addElement, removeElement, printTree } = useTree();\n const [messages, setMessages] = useState<Message[]>([]);\n\n const {\n addElement: addDocument,\n removeElement: removeDocument,\n allElements: allDocuments,\n } = useFlatCategoryStore<DocumentPointer>();\n\n const setEntryPoint = useCallback((id: string, entryPoint: FrontendAction<any>) => {\n setEntryPoints((prevPoints) => {\n return {\n ...prevPoints,\n [id]: entryPoint,\n };\n });\n }, []);\n\n const removeEntryPoint = useCallback((id: string) => {\n setEntryPoints((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const getContextString = useCallback(\n (documents: DocumentPointer[], categories: string[]) => {\n const documentsString = documents\n .map((document) => {\n return `${document.name} (${document.sourceApplication}):\\n${document.getContents()}`;\n })\n .join(\"\\n\\n\");\n\n const nonDocumentStrings = printTree(categories);\n\n return `${documentsString}\\n\\n${nonDocumentStrings}`;\n },\n [printTree],\n );\n\n const addContext = useCallback(\n (\n context: string,\n parentId?: string,\n categories: string[] = defaultCopilotContextCategories,\n ) => {\n return addElement(context, categories, parentId);\n },\n [addElement],\n );\n\n const removeContext = useCallback(\n (id: string) => {\n removeElement(id);\n },\n [removeElement],\n );\n\n const getChatCompletionFunctionDescriptions = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToChatCompletionFunctions(Object.values(customEntryPoints || entryPoints));\n },\n [entryPoints],\n );\n\n const getFunctionCallHandler = useCallback(\n (customEntryPoints?: Record<string, FrontendAction<any>>) => {\n return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || entryPoints));\n },\n [entryPoints],\n );\n\n const getDocumentsContext = useCallback(\n (categories: string[]) => {\n return allDocuments(categories);\n },\n [allDocuments],\n );\n\n const addDocumentContext = useCallback(\n (documentPointer: DocumentPointer, categories: string[] = defaultCopilotContextCategories) => {\n return addDocument(documentPointer, categories);\n },\n [addDocument],\n );\n\n const removeDocumentContext = useCallback(\n (documentId: string) => {\n removeDocument(documentId);\n },\n [removeDocument],\n );\n\n if (!props.publicApiKey) {\n if (props.cloudRestrictToTopic) {\n throw new Error(\n \"To use the cloudRestrictToTopic feature, please sign up at https://copilotkit.ai and provide a publicApiKey.\",\n );\n }\n }\n\n let cloud: CopilotCloudConfig | undefined = undefined;\n if (props.publicApiKey) {\n cloud = {\n guardrails: {\n input: {\n restrictToTopic: {\n enabled: props.cloudRestrictToTopic ? true : false,\n validTopics: props.cloudRestrictToTopic?.validTopics || [],\n invalidTopics: props.cloudRestrictToTopic?.invalidTopics || [],\n },\n },\n },\n };\n }\n\n // get the appropriate CopilotApiConfig from the props\n const copilotApiConfig: CopilotApiConfig = {\n publicApiKey: props.publicApiKey,\n ...(cloud ? { cloud } : {}),\n chatApiEndpoint: chatApiEndpoint,\n chatApiEndpointV2: `${props.url}/v2`,\n headers: props.headers || {},\n body: {\n ...props.body,\n ...props.backendOnlyProps,\n },\n };\n\n return (\n <CopilotContext.Provider\n value={{\n entryPoints,\n chatComponentsCache,\n getChatCompletionFunctionDescriptions,\n getFunctionCallHandler,\n setEntryPoint,\n removeEntryPoint,\n getContextString,\n addContext,\n removeContext,\n getDocumentsContext,\n addDocumentContext,\n removeDocumentContext,\n copilotApiConfig: copilotApiConfig,\n messages,\n setMessages,\n }}\n >\n {children}\n </CopilotContext.Provider>\n );\n}\n\nexport const defaultCopilotContextCategories = [\"global\"];\n\nfunction entryPointsToChatCompletionFunctions(actions: FrontendAction<any>[]): ToolDefinition[] {\n return actions.map(actionToChatCompletionFunction);\n}\n\nfunction entryPointsToFunctionCallHandler(actions: FrontendAction<any>[]): FunctionCallHandler {\n return async (chatMessages, functionCall) => {\n let actionsByFunctionName: Record<string, FrontendAction<any>> = {};\n for (let action of actions) {\n actionsByFunctionName[action.name] = action;\n }\n\n const action = actionsByFunctionName[functionCall.name || \"\"];\n if (action) {\n let functionCallArguments: Record<string, any>[] = [];\n if (functionCall.arguments) {\n functionCallArguments = JSON.parse(functionCall.arguments);\n }\n return await action.handler(functionCallArguments);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA,SAAc,aAAa,QAAQ,gBAAgB;AAQnD;AAAA,EACE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-chat-completion.ts"],"sourcesContent":["import {\n Message,\n ToolDefinition,\n ChatCompletionEvent,\n decodeChatCompletion,\n parseChatCompletion,\n decodeChatCompletionAsText,\n EXCLUDE_FROM_FORWARD_PROPS_KEYS,\n} from \"@copilotkit/shared\";\nimport { CopilotApiConfig } from \"../context\";\n\nexport interface FetchChatCompletionParams {\n copilotConfig: CopilotApiConfig;\n model?: string;\n messages: Message[];\n tools?: ToolDefinition[];\n temperature?: number;\n maxTokens?: number;\n headers?: Record<string, string> | Headers;\n body?: object;\n signal?: AbortSignal;\n}\n\nexport async function fetchChatCompletion({\n copilotConfig,\n model,\n messages,\n tools,\n temperature,\n headers,\n body,\n signal,\n}: FetchChatCompletionParams): Promise<Response> {\n temperature ||= 0.5;\n tools ||= [];\n\n // clean up any extra properties from messages\n const cleanedMessages = messages.map((message) => {\n const { content, role, name, function_call } = message;\n return { content, role, name, function_call };\n });\n\n const response = await fetch(copilotConfig.chatApiEndpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...copilotConfig.headers,\n ...(headers ? { ...headers } : {}),\n },\n body: JSON.stringify({\n model,\n messages: cleanedMessages,\n stream: true,\n ...(tools.length ? { tools } : {}),\n ...(temperature ? { temperature } : {}),\n ...(tools.length != 0 ? { tool_choice: \"auto\" } : {}),\n ...copilotConfig.body,\n ...copilotConfig.backendOnlyProps,\n ...excludeBackendOnlyProps(copilotConfig),\n ...(body ? { ...body } : {}),\n ...(copilotConfig.cloud ? { cloud: copilotConfig.cloud } : {}),\n }),\n signal,\n });\n\n return response;\n}\n\nfunction excludeBackendOnlyProps(copilotConfig: any) {\n const backendOnlyProps = copilotConfig.backendOnlyProps ?? {};\n if (Object.keys(backendOnlyProps).length > 0) {\n return {\n [EXCLUDE_FROM_FORWARD_PROPS_KEYS]: Object.keys(backendOnlyProps),\n };\n } else {\n return {};\n }\n}\n\nexport interface DecodedChatCompletionResponse extends Response {\n events: ReadableStream<ChatCompletionEvent> | null;\n}\n\nexport async function fetchAndDecodeChatCompletion(\n params: FetchChatCompletionParams,\n): Promise<DecodedChatCompletionResponse> {\n const response = await fetchChatCompletion(params);\n if (!response.ok || !response.body) {\n (response as any).events = null;\n } else {\n const events = await decodeChatCompletion(parseChatCompletion(response.body));\n (response as any).events = events;\n }\n return response as any;\n}\n\nexport interface DecodedChatCompletionResponseAsText extends Response {\n events: ReadableStream<string> | null;\n}\n\nexport async function fetchAndDecodeChatCompletionAsText(\n params: FetchChatCompletionParams,\n): Promise<DecodedChatCompletionResponseAsText> {\n const response = await fetchChatCompletion(params);\n if (!response.ok || !response.body) {\n (response as any).events = null;\n } else {\n const events = await decodeChatCompletionAsText(\n decodeChatCompletion(parseChatCompletion(response.body)),\n );\n (response as any).events = events;\n }\n\n return response as any;\n}\n"],"mappings":";;;;;;AAAA;AAAA,EAIE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAeP,SAAsB,oBAAoB,IASO;AAAA,6CATP;AAAA,IACxC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAAiD;AAC/C,kCAAgB;AAChB,sBAAU,CAAC;AAGX,UAAM,kBAAkB,SAAS,IAAI,CAAC,YAAY;AAChD,YAAM,EAAE,SAAS,MAAM,MAAM,cAAc,IAAI;AAC/C,aAAO,EAAE,SAAS,MAAM,MAAM,cAAc;AAAA,IAC9C,CAAC;AAED,UAAM,WAAW,MAAM,MAAM,cAAc,iBAAiB;AAAA,MAC1D,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,SACb,cAAc,UACb,UAAU,mBAAK,WAAY,CAAC;AAAA,MAElC,MAAM,KAAK,UAAU;AAAA,QACnB;AAAA,QACA,UAAU;AAAA,QACV,QAAQ;AAAA,SACJ,MAAM,SAAS,EAAE,MAAM,IAAI,CAAC,IAC5B,cAAc,EAAE,YAAY,IAAI,CAAC,IACjC,MAAM,UAAU,IAAI,EAAE,aAAa,OAAO,IAAI,CAAC,IAChD,cAAc,OACd,cAAc,mBACd,wBAAwB,aAAa,IACpC,OAAO,mBAAK,QAAS,CAAC,IACtB,cAAc,QAAQ,EAAE,OAAO,cAAc,MAAM,IAAI,CAAC,EAC7D;AAAA,MACD;AAAA,IACF,CAAC;AAED,WAAO;AAAA,EACT;AAAA;AAEA,SAAS,wBAAwB,eAAoB;AApErD;AAqEE,QAAM,oBAAmB,mBAAc,qBAAd,YAAkC,CAAC;AAC5D,MAAI,OAAO,KAAK,gBAAgB,EAAE,SAAS,GAAG;AAC5C,WAAO;AAAA,MACL,CAAC,+BAA+B,GAAG,OAAO,KAAK,gBAAgB;AAAA,IACjE;AAAA,EACF,OAAO;AACL,WAAO,CAAC;AAAA,EACV;AACF;AAMA,SAAsB,6BACpB,QACwC;AAAA;AACxC,UAAM,WAAW,MAAM,oBAAoB,MAAM;AACjD,QAAI,CAAC,SAAS,MAAM,CAAC,SAAS,MAAM;AAClC,MAAC,SAAiB,SAAS;AAAA,IAC7B,OAAO;AACL,YAAM,SAAS,MAAM,qBAAqB,oBAAoB,SAAS,IAAI,CAAC;AAC5E,MAAC,SAAiB,SAAS;AAAA,IAC7B;AACA,WAAO;AAAA,EACT;AAAA;AAMA,SAAsB,mCACpB,QAC8C;AAAA;AAC9C,UAAM,WAAW,MAAM,oBAAoB,MAAM;AACjD,QAAI,CAAC,SAAS,MAAM,CAAC,SAAS,MAAM;AAClC,MAAC,SAAiB,SAAS;AAAA,IAC7B,OAAO;AACL,YAAM,SAAS,MAAM;AAAA,QACnB,qBAAqB,oBAAoB,SAAS,IAAI,CAAC;AAAA,MACzD;AACA,MAAC,SAAiB,SAAS;AAAA,IAC7B;AAEA,WAAO;AAAA,EACT;AAAA;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/context/copilot-context.tsx"],"sourcesContent":["import {\n CopilotCloudConfig,\n FunctionCallHandler,\n Message,\n ToolDefinition,\n} from \"@copilotkit/shared\";\nimport { ActionRenderProps, FrontendAction } from \"../types/frontend-action\";\nimport React, { Ref } from \"react\";\nimport { TreeNodeId } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the chat API v2.\n */\n chatApiEndpointV2: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Additional body params to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'message': 'Hello, world!'\n * }\n * ```\n */\n body: Record<string, any>;\n\n /**\n * Backend only props that will be combined to body params to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n backendOnlyProps?: Record<string, any>;\n}\n\nexport type InChatRenderFunction = (props: ActionRenderProps<any>) => string | JSX.Element;\n\nexport interface CopilotContextParams {\n // function-calling\n entryPoints: Record<string, FrontendAction<any>>;\n setEntryPoint: (id: string, entryPoint: FrontendAction<any>) => void;\n removeEntryPoint: (id: string) => void;\n chatComponentsCache: React.RefObject<Record<string, InChatRenderFunction | string>>;\n getChatCompletionFunctionDescriptions: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => ToolDefinition[];\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n messages: Message[];\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n entryPoints: {},\n setEntryPoint: () => {},\n removeEntryPoint: () => {},\n getChatCompletionFunctionDescriptions: () => returnAndThrowInDebug([]),\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n chatComponentsCache: { current: {} },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n messages: [],\n setMessages: () => returnAndThrowInDebug([]),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n get chatApiEndpointV2(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n return React.useContext(CopilotContext);\n}\n\nfunction returnAndThrowInDebug<T>(value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n return value;\n}\n"],"mappings":";;;;;AAOA,OAAO,WAAoB;AAiG3B,IAAM,sBAA4C;AAAA,EAChD,aAAa,CAAC;AAAA,EACd,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,kBAAkB,MAAM;AAAA,EAAC;AAAA,EACzB,uCAAuC,MAAM,sBAAsB,CAAC,CAAC;AAAA,EACrE,wBAAwB,MAAM,sBAAsB,MAAY;AAAA,EAAC,EAAC;AAAA,EAClE,qBAAqB,EAAE,SAAS,CAAC,EAAE;AAAA,EACnC,kBAAkB,CAAC,WAA8B,eAC/C,sBAAsB,EAAE;AAAA,EAC1B,YAAY,MAAM;AAAA,EAClB,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,UAAU,CAAC;AAAA,EACX,aAAa,MAAM,sBAAsB,CAAC,CAAC;AAAA,EAE3C,qBAAqB,CAAC,eAAyB,sBAAsB,CAAC,CAAC;AAAA,EACvE,oBAAoB,MAAM,sBAAsB,EAAE;AAAA,EAClD,uBAAuB,MAAM;AAAA,EAAC;AAAA,EAE9B,kBAAkB,IAAK,MAAkC;AAAA,IACvD,IAAI,kBAA0B;AAC5B,YAAM,IAAI,MAAM,uEAAuE;AAAA,IACzF;AAAA,IACA,IAAI,oBAA4B;AAC9B,YAAM,IAAI,MAAM,uEAAuE;AAAA,IACzF;AAAA,IACA,IAAI,UAAkC;AACpC,aAAO,CAAC;AAAA,IACV;AAAA,IACA,IAAI,OAA4B;AAC9B,aAAO,CAAC;AAAA,IACV;AAAA,EACF,EAAG;AACL;AAEO,IAAM,iBAAiB,MAAM,cAAoC,mBAAmB;AAEpF,SAAS,oBAA0C;AACxD,SAAO,MAAM,WAAW,cAAc;AACxC;AAEA,SAAS,sBAAyB,OAAa;AAC7C,QAAM,IAAI,MAAM,uEAAuE;AACvF,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/copilot-task.ts"],"sourcesContent":["import { FunctionCall, Message } from \"@copilotkit/shared\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { fetchAndDecodeChatCompletion } from \"../utils/fetch-chat-completion\";\n\nexport interface CopilotTaskConfig {\n /**\n * The instructions to be given to the assistant.\n */\n instructions: string;\n /**\n * Action definitions to be sent to the API.\n */\n actions?: FrontendAction<any>[];\n /**\n * Whether to include the copilot readable context in the task.\n */\n includeCopilotReadable?: boolean;\n\n /**\n * Whether to include actions defined via useCopilotAction in the task.\n * @deprecated Use the `includeCopilotActions` property instead.\n */\n includeCopilotActionable?: boolean;\n\n /**\n * Whether to include actions defined via useCopilotAction in the task.\n */\n includeCopilotActions?: boolean;\n}\n\nexport class CopilotTask<T = any> {\n private instructions: string;\n private actions: FrontendAction<any>[];\n private includeCopilotReadable: boolean;\n private includeCopilotActions: boolean;\n\n constructor(config: CopilotTaskConfig) {\n this.instructions = config.instructions;\n this.actions = config.actions || [];\n this.includeCopilotReadable = config.includeCopilotReadable !== false;\n this.includeCopilotActions =\n config.includeCopilotActions !== false && config.includeCopilotActionable !== false;\n }\n\n async run(context: CopilotContextParams, data?: T): Promise<void> {\n const entryPoints = this.includeCopilotActions ? Object.assign({}, context.entryPoints) : {};\n\n // merge functions into entry points\n for (const fn of this.actions) {\n entryPoints[fn.name] = fn;\n }\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (this.includeCopilotReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage: Message = {\n id: \"system\",\n content: taskSystemMessage(contextString, this.instructions),\n role: \"system\",\n };\n\n const messages = [systemMessage];\n\n const response = await fetchAndDecodeChatCompletion({\n copilotConfig: context.copilotApiConfig,\n messages: messages,\n tools: context.getChatCompletionFunctionDescriptions(entryPoints),\n headers: context.copilotApiConfig.headers,\n body: context.copilotApiConfig.body,\n });\n\n if (!response.events) {\n throw new Error(\"Failed to execute task\");\n }\n\n const reader = response.events.getReader();\n let functionCalls: FunctionCall[] = [];\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (value.type === \"function\") {\n functionCalls.push({\n name: value.name,\n arguments: JSON.stringify(value.arguments),\n });\n break;\n }\n }\n\n if (!functionCalls.length) {\n throw new Error(\"No function call occurred\");\n }\n\n const functionCallHandler = context.getFunctionCallHandler(entryPoints);\n for (const functionCall of functionCalls) {\n await functionCallHandler(messages, functionCall);\n }\n }\n}\n\nfunction taskSystemMessage(contextString: string, instructions: string): string {\n return `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp 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.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf.\n\nPlease assist them as best you can.\n\nThis is not a conversation, so please do not ask questions. Just call a function without saying anything else.\n\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n`;\n}\n"],"mappings":";;;;;;;;;;;AAgCO,IAAM,cAAN,MAA2B;AAAA,EAMhC,YAAY,QAA2B;AACrC,SAAK,eAAe,OAAO;AAC3B,SAAK,UAAU,OAAO,WAAW,CAAC;AAClC,SAAK,yBAAyB,OAAO,2BAA2B;AAChE,SAAK,wBACH,OAAO,0BAA0B,SAAS,OAAO,6BAA6B;AAAA,EAClF;AAAA,EAEM,IAAI,SAA+B,MAAyB;AAAA;AAChE,YAAM,cAAc,KAAK,wBAAwB,OAAO,OAAO,CAAC,GAAG,QAAQ,WAAW,IAAI,CAAC;AAG3F,iBAAW,MAAM,KAAK,SAAS;AAC7B,oBAAY,GAAG,IAAI,IAAI;AAAA,MACzB;AAEA,UAAI,gBAAgB;AAEpB,UAAI,MAAM;AACR,yBAAiB,OAAO,SAAS,WAAW,OAAO,KAAK,UAAU,IAAI,KAAK;AAAA,MAC7E;AAEA,UAAI,KAAK,wBAAwB;AAC/B,yBAAiB,QAAQ,iBAAiB,CAAC,GAAG,+BAA+B;AAAA,MAC/E;AAEA,YAAM,gBAAyB;AAAA,QAC7B,IAAI;AAAA,QACJ,SAAS,kBAAkB,eAAe,KAAK,YAAY;AAAA,QAC3D,MAAM;AAAA,MACR;AAEA,YAAM,WAAW,CAAC,aAAa;AAE/B,YAAM,WAAW,MAAM,6BAA6B;AAAA,QAClD,eAAe,QAAQ;AAAA,QACvB;AAAA,QACA,OAAO,QAAQ,sCAAsC,WAAW;AAAA,QAChE,SAAS,QAAQ,iBAAiB;AAAA,QAClC,MAAM,QAAQ,iBAAiB;AAAA,MACjC,CAAC;AAED,UAAI,CAAC,SAAS,QAAQ;AACpB,cAAM,IAAI,MAAM,wBAAwB;AAAA,MAC1C;AAEA,YAAM,SAAS,SAAS,OAAO,UAAU;AACzC,UAAI,gBAAgC,CAAC;AAErC,aAAO,MAAM;AACX,cAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAE1C,YAAI,MAAM;AACR;AAAA,QACF;AAEA,YAAI,MAAM,SAAS,YAAY;AAC7B,wBAAc,KAAK;AAAA,YACjB,MAAM,MAAM;AAAA,YACZ,WAAW,KAAK,UAAU,MAAM,SAAS;AAAA,UAC3C,CAAC;AACD;AAAA,QACF;AAAA,MACF;AAEA,UAAI,CAAC,cAAc,QAAQ;AACzB,cAAM,IAAI,MAAM,2BAA2B;AAAA,MAC7C;AAEA,YAAM,sBAAsB,QAAQ,uBAAuB,WAAW;AACtE,iBAAW,gBAAgB,eAAe;AACxC,cAAM,oBAAoB,UAAU,YAAY;AAAA,MAClD;AAAA,IACF;AAAA;AACF;AAEA,SAAS,kBAAkB,eAAuB,cAA8B;AAC9E,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQP;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA;AAAA;AAAA;AAGF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/hooks/use-copilot-readable.ts"],"sourcesContent":["import { useContext, useEffect, useRef } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\n\n/**\n * Options for the useCopilotReadable hook.\n */\nexport interface UseCopilotReadableOptions {\n /**\n * The description of the information to be added to the Copilot context.\n */\n description: string;\n /**\n * The value to be added to the Copilot context.\n */\n value: any;\n /**\n * The ID of the parent context, if any.\n */\n parentId?: string;\n /**\n * An array of categories to control which context are visible where. Particularly useful\n * with CopilotTextarea (see `useMakeAutosuggestionFunction`)\n */\n categories?: string[];\n\n /**\n * A custom conversion function to use to serialize the value to a string. If not provided, the value\n * will be serialized using `JSON.stringify`.\n */\n convert?: (description: string, value: any) => string;\n}\n\nfunction convertToJSON(description: string, value: any): string {\n return `${description}: ${typeof value === \"string\" ? value : JSON.stringify(value)}`;\n}\n\n/**\n * Adds the given information to the Copilot context to make it readable by Copilot.\n */\nexport function useCopilotReadable(\n { description, value, parentId, categories, convert }: UseCopilotReadableOptions,\n dependencies?: any[],\n): string | undefined {\n const { addContext, removeContext } = useContext(CopilotContext);\n const idRef = useRef<string>();\n convert = convert || convertToJSON;\n\n const information = convert(description, value);\n\n useEffect(() => {\n const id = addContext(information, parentId, categories);\n idRef.current = id;\n\n return () => {\n removeContext(id);\n };\n }, [information, parentId, addContext, removeContext, ...(dependencies || [])]);\n\n return idRef.current;\n}\n"],"mappings":";;;;;AAAA,SAAS,YAAY,WAAW,cAAc;AAgC9C,SAAS,cAAc,aAAqB,OAAoB;AAC9D,SAAO,GAAG,gBAAgB,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,KAAK;AACpF;AAKO,SAAS,mBACd,EAAE,aAAa,OAAO,UAAU,YAAY,QAAQ,GACpD,cACoB;AACpB,QAAM,EAAE,YAAY,cAAc,IAAI,WAAW,cAAc;AAC/D,QAAM,QAAQ,OAAe;AAC7B,YAAU,WAAW;AAErB,QAAM,cAAc,QAAQ,aAAa,KAAK;AAE9C,YAAU,MAAM;AACd,UAAM,KAAK,WAAW,aAAa,UAAU,UAAU;AACvD,UAAM,UAAU;AAEhB,WAAO,MAAM;AACX,oBAAc,EAAE;AAAA,IAClB;AAAA,EACF,GAAG,CAAC,aAAa,UAAU,YAAY,eAAe,GAAI,gBAAgB,CAAC,CAAE,CAAC;AAE9E,SAAO,MAAM;AACf;","names":[]}