@copilotkit/react-core 1.5.1-next.2 → 1.5.1-next.3
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.
- package/CHANGELOG.md +9 -0
- package/dist/{chunk-LNI2Z45S.mjs → chunk-2KCEHGSI.mjs} +50 -100
- package/dist/chunk-2KCEHGSI.mjs.map +1 -0
- package/dist/{chunk-2KT73RVG.mjs → chunk-6OR25P32.mjs} +19 -75
- package/dist/chunk-6OR25P32.mjs.map +1 -0
- package/dist/{chunk-3GQPEN4M.mjs → chunk-DDVXFNYA.mjs} +32 -66
- package/dist/chunk-DDVXFNYA.mjs.map +1 -0
- package/dist/{chunk-XOQMISG3.mjs → chunk-FXHKK52V.mjs} +13 -14
- package/dist/chunk-FXHKK52V.mjs.map +1 -0
- package/dist/{chunk-HIUT2NLX.mjs → chunk-H4VZMKR6.mjs} +2 -2
- package/dist/{chunk-X36DNILG.mjs → chunk-H7LSKIDK.mjs} +23 -71
- package/dist/chunk-H7LSKIDK.mjs.map +1 -0
- package/dist/chunk-JDQCJCAQ.mjs +295 -0
- package/dist/chunk-JDQCJCAQ.mjs.map +1 -0
- package/dist/chunk-L34MHAXR.mjs +1 -0
- package/dist/{chunk-WXREY7UP.mjs → chunk-LODRWFMB.mjs} +4 -16
- package/dist/chunk-LODRWFMB.mjs.map +1 -0
- package/dist/{chunk-EWKJMQOF.mjs → chunk-MWZO6TUR.mjs} +13 -29
- package/dist/chunk-MWZO6TUR.mjs.map +1 -0
- package/dist/{chunk-6BQVZFNO.mjs → chunk-ODN4H66E.mjs} +2 -6
- package/dist/chunk-ODN4H66E.mjs.map +1 -0
- package/dist/{chunk-FQ53HQYZ.mjs → chunk-QDGDXRRJ.mjs} +2 -2
- package/dist/{chunk-22XKTBPF.mjs → chunk-XINZBP3J.mjs} +3 -15
- package/dist/chunk-XINZBP3J.mjs.map +1 -0
- package/dist/components/copilot-provider/copilot-messages.d.ts +0 -9
- package/dist/components/copilot-provider/copilotkit-props.d.ts +0 -21
- package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.d.ts +0 -9
- package/dist/components/copilot-provider/copilotkit.js +95 -224
- package/dist/components/copilot-provider/copilotkit.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.mjs +8 -9
- package/dist/components/copilot-provider/index.d.ts +0 -9
- package/dist/components/copilot-provider/index.js +95 -224
- package/dist/components/copilot-provider/index.js.map +1 -1
- package/dist/components/copilot-provider/index.mjs +8 -9
- package/dist/components/index.d.ts +0 -9
- package/dist/components/index.js +95 -224
- package/dist/components/index.js.map +1 -1
- package/dist/components/index.mjs +8 -9
- package/dist/components/toast/toast-provider.d.ts +1 -2
- package/dist/components/toast/toast-provider.js +63 -77
- package/dist/components/toast/toast-provider.js.map +1 -1
- package/dist/components/toast/toast-provider.mjs +1 -1
- package/dist/context/copilot-context.d.ts +4 -37
- package/dist/context/copilot-context.js +3 -15
- package/dist/context/copilot-context.js.map +1 -1
- package/dist/context/copilot-context.mjs +1 -1
- package/dist/context/index.d.ts +1 -1
- package/dist/context/index.js +3 -15
- package/dist/context/index.js.map +1 -1
- package/dist/context/index.mjs +4 -4
- package/dist/hooks/index.d.ts +1 -3
- package/dist/hooks/index.js +297 -703
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +23 -35
- package/dist/hooks/use-chat.d.ts +3 -35
- package/dist/hooks/use-chat.js +205 -453
- package/dist/hooks/use-chat.js.map +1 -1
- package/dist/hooks/use-chat.mjs +3 -4
- package/dist/hooks/use-coagent-state-render.d.ts +2 -2
- package/dist/hooks/use-coagent-state-render.js +8 -43
- package/dist/hooks/use-coagent-state-render.js.map +1 -1
- package/dist/hooks/use-coagent-state-render.mjs +2 -4
- package/dist/hooks/use-coagent.d.ts +1 -14
- package/dist/hooks/use-coagent.js +265 -603
- package/dist/hooks/use-coagent.js.map +1 -1
- package/dist/hooks/use-coagent.mjs +12 -20
- package/dist/hooks/use-copilot-action.d.ts +2 -12
- package/dist/hooks/use-copilot-action.js +19 -169
- package/dist/hooks/use-copilot-action.js.map +1 -1
- package/dist/hooks/use-copilot-action.mjs +2 -4
- package/dist/hooks/use-copilot-chat.d.ts +0 -2
- package/dist/hooks/use-copilot-chat.js +240 -545
- package/dist/hooks/use-copilot-chat.js.map +1 -1
- package/dist/hooks/use-copilot-chat.mjs +11 -13
- package/dist/hooks/use-copilot-readable.js +3 -15
- package/dist/hooks/use-copilot-readable.js.map +1 -1
- package/dist/hooks/use-copilot-readable.mjs +2 -2
- package/dist/hooks/use-copilot-runtime-client.js +4 -110
- package/dist/hooks/use-copilot-runtime-client.js.map +1 -1
- package/dist/hooks/use-copilot-runtime-client.mjs +2 -2
- package/dist/hooks/use-make-copilot-document-readable.js +3 -15
- package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
- package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
- package/dist/index.d.ts +3 -4
- package/dist/index.js +398 -812
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +31 -43
- package/dist/lib/copilot-task.d.ts +1 -6
- package/dist/lib/copilot-task.js +17 -55
- package/dist/lib/copilot-task.js.map +1 -1
- package/dist/lib/copilot-task.mjs +9 -11
- package/dist/lib/index.d.ts +1 -1
- package/dist/lib/index.js +17 -55
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/index.mjs +9 -11
- package/dist/types/frontend-action.d.ts +2 -21
- package/dist/types/frontend-action.js +0 -34
- package/dist/types/frontend-action.js.map +1 -1
- package/dist/types/frontend-action.mjs +0 -7
- package/dist/types/index.d.ts +1 -2
- package/dist/types/index.js.map +1 -1
- package/dist/utils/extract.d.ts +2 -3
- package/dist/utils/extract.js +3 -21
- package/dist/utils/extract.js.map +1 -1
- package/dist/utils/extract.mjs +8 -9
- package/dist/utils/index.js +3 -21
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/index.mjs +9 -10
- package/package.json +5 -5
- package/dist/chunk-22XKTBPF.mjs.map +0 -1
- package/dist/chunk-2KT73RVG.mjs.map +0 -1
- package/dist/chunk-3GQPEN4M.mjs.map +0 -1
- package/dist/chunk-6BQVZFNO.mjs.map +0 -1
- package/dist/chunk-EWKJMQOF.mjs.map +0 -1
- package/dist/chunk-LHKIIAUQ.mjs +0 -59
- package/dist/chunk-LHKIIAUQ.mjs.map +0 -1
- package/dist/chunk-LNI2Z45S.mjs.map +0 -1
- package/dist/chunk-NR2BTA6Z.mjs +0 -1
- package/dist/chunk-VGOFRULA.mjs +0 -401
- package/dist/chunk-VGOFRULA.mjs.map +0 -1
- package/dist/chunk-VNTDIJSG.mjs +0 -37
- package/dist/chunk-VNTDIJSG.mjs.map +0 -1
- package/dist/chunk-WXREY7UP.mjs.map +0 -1
- package/dist/chunk-X36DNILG.mjs.map +0 -1
- package/dist/chunk-XERJQUHA.mjs +0 -31
- package/dist/chunk-XERJQUHA.mjs.map +0 -1
- package/dist/chunk-XOQMISG3.mjs.map +0 -1
- package/dist/components/error-boundary/error-boundary.d.ts +0 -22
- package/dist/components/error-boundary/error-boundary.js +0 -183
- package/dist/components/error-boundary/error-boundary.js.map +0 -1
- package/dist/components/error-boundary/error-boundary.mjs +0 -12
- package/dist/components/error-boundary/error-boundary.mjs.map +0 -1
- package/dist/components/error-boundary/error-utils.d.ts +0 -11
- package/dist/components/error-boundary/error-utils.js +0 -177
- package/dist/components/error-boundary/error-utils.js.map +0 -1
- package/dist/components/error-boundary/error-utils.mjs +0 -13
- package/dist/components/error-boundary/error-utils.mjs.map +0 -1
- package/dist/hooks/use-copilot-authenticated-action.d.ts +0 -8
- package/dist/hooks/use-copilot-authenticated-action.js +0 -418
- package/dist/hooks/use-copilot-authenticated-action.js.map +0 -1
- package/dist/hooks/use-copilot-authenticated-action.mjs +0 -12
- package/dist/hooks/use-copilot-authenticated-action.mjs.map +0 -1
- /package/dist/{chunk-HIUT2NLX.mjs.map → chunk-H4VZMKR6.mjs.map} +0 -0
- /package/dist/{chunk-NR2BTA6Z.mjs.map → chunk-L34MHAXR.mjs.map} +0 -0
- /package/dist/{chunk-FQ53HQYZ.mjs.map → chunk-QDGDXRRJ.mjs.map} +0 -0
|
@@ -1,13 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
2
|
defaultCopilotContextCategories
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-6OR25P32.mjs";
|
|
4
4
|
import {
|
|
5
|
-
|
|
6
|
-
} from "./chunk-XERJQUHA.mjs";
|
|
7
|
-
import {
|
|
8
|
-
__async,
|
|
9
|
-
__spreadProps,
|
|
10
|
-
__spreadValues
|
|
5
|
+
__async
|
|
11
6
|
} from "./chunk-SKC7AJIV.mjs";
|
|
12
7
|
|
|
13
8
|
// src/lib/copilot-task.ts
|
|
@@ -20,13 +15,13 @@ import {
|
|
|
20
15
|
filterAgentStateMessages,
|
|
21
16
|
CopilotRequestType
|
|
22
17
|
} from "@copilotkit/runtime-client-gql";
|
|
18
|
+
import { actionParametersToJsonSchema } from "@copilotkit/shared";
|
|
23
19
|
var CopilotTask = class {
|
|
24
20
|
constructor(config) {
|
|
25
21
|
this.instructions = config.instructions;
|
|
26
22
|
this.actions = config.actions || [];
|
|
27
23
|
this.includeCopilotReadable = config.includeCopilotReadable !== false;
|
|
28
24
|
this.includeCopilotActions = config.includeCopilotActions !== false;
|
|
29
|
-
this.forwardedParameters = config.forwardedParameters;
|
|
30
25
|
}
|
|
31
26
|
/**
|
|
32
27
|
* Run the task.
|
|
@@ -35,7 +30,7 @@ var CopilotTask = class {
|
|
|
35
30
|
*/
|
|
36
31
|
run(context, data) {
|
|
37
32
|
return __async(this, null, function* () {
|
|
38
|
-
var _a, _b
|
|
33
|
+
var _a, _b;
|
|
39
34
|
const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};
|
|
40
35
|
for (const fn of this.actions) {
|
|
41
36
|
actions[fn.name] = fn;
|
|
@@ -61,22 +56,26 @@ var CopilotTask = class {
|
|
|
61
56
|
const response = yield runtimeClient.generateCopilotResponse({
|
|
62
57
|
data: {
|
|
63
58
|
frontend: {
|
|
64
|
-
actions:
|
|
59
|
+
actions: Object.values(actions).map((action) => ({
|
|
60
|
+
name: action.name,
|
|
61
|
+
description: action.description || "",
|
|
62
|
+
jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || []))
|
|
63
|
+
})),
|
|
65
64
|
url: window.location.href
|
|
66
65
|
},
|
|
67
66
|
messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),
|
|
68
67
|
metadata: {
|
|
69
68
|
requestType: CopilotRequestType.Task
|
|
70
69
|
},
|
|
71
|
-
forwardedParameters:
|
|
70
|
+
forwardedParameters: {
|
|
72
71
|
toolChoice: "required"
|
|
73
|
-
}
|
|
72
|
+
}
|
|
74
73
|
},
|
|
75
74
|
properties: context.copilotApiConfig.properties
|
|
76
75
|
}).toPromise();
|
|
77
76
|
const functionCallHandler = context.getFunctionCallHandler(actions);
|
|
78
77
|
const functionCalls = convertGqlOutputToMessages(
|
|
79
|
-
((
|
|
78
|
+
((_b = (_a = response.data) == null ? void 0 : _a.generateCopilotResponse) == null ? void 0 : _b.messages) || []
|
|
80
79
|
).filter((m) => m.isActionExecutionMessage());
|
|
81
80
|
for (const functionCall of functionCalls) {
|
|
82
81
|
yield functionCallHandler({
|
|
@@ -117,4 +116,4 @@ ${instructions}
|
|
|
117
116
|
export {
|
|
118
117
|
CopilotTask
|
|
119
118
|
};
|
|
120
|
-
//# sourceMappingURL=chunk-
|
|
119
|
+
//# sourceMappingURL=chunk-FXHKK52V.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/copilot-task.ts"],"sourcesContent":["/**\n * This class is used to execute one-off tasks, for example on button press. It can use the context available via [useCopilotReadable](/reference/hooks/useCopilotReadable) and the actions provided by [useCopilotAction](/reference/hooks/useCopilotAction), or you can provide your own context and actions.\n *\n * ## Example\n * In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.\n *\n * ```tsx\n * import { CopilotTask, useCopilotContext } from \"@copilotkit/react-core\";\n *\n * export function MyComponent() {\n * const context = useCopilotContext();\n *\n * const task = new CopilotTask({\n * instructions: \"Set a random message\",\n * actions: [\n * {\n * name: \"setMessage\",\n * description: \"Set the message.\",\n * argumentAnnotations: [\n * {\n * name: \"message\",\n * type: \"string\",\n * description:\n * \"A message to display.\",\n * required: true,\n * },\n * ],\n * }\n * ]\n * });\n *\n * const executeTask = async () => {\n * await task.run(context, action);\n * }\n *\n * return (\n * <>\n * <button onClick={executeTask}>\n * Execute task\n * </button>\n * </>\n * )\n * }\n * ```\n *\n * Have a look at the [Presentation Example App](https://github.com/CopilotKit/CopilotKit/blob/main/CopilotKit/examples/next-openai/src/app/presentation/page.tsx) for a more complete example.\n */\n\nimport {\n ActionExecutionMessage,\n CopilotRuntimeClient,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n convertMessagesToGqlInput,\n filterAgentStateMessages,\n CopilotRequestType,\n} from \"@copilotkit/runtime-client-gql\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { MessageStatusCode } from \"@copilotkit/runtime-client-gql\";\nimport { actionParametersToJsonSchema } from \"@copilotkit/shared\";\n\nexport interface CopilotTaskConfig {\n /**\n * The instructions to be given to the assistant.\n */\n instructions: string;\n /**\n * An array of action definitions that can be called.\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 */\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 = config.includeCopilotActions !== false;\n }\n\n /**\n * Run the task.\n * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.\n * @param data The data to use for the task.\n */\n async run(context: CopilotContextParams, data?: T): Promise<void> {\n const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};\n\n // merge functions into entry points\n for (const fn of this.actions) {\n actions[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 = new TextMessage({\n content: taskSystemMessage(contextString, this.instructions),\n role: Role.System,\n });\n\n const messages: Message[] = [systemMessage];\n\n const runtimeClient = new CopilotRuntimeClient({\n url: context.copilotApiConfig.chatApiEndpoint,\n publicApiKey: context.copilotApiConfig.publicApiKey,\n headers: context.copilotApiConfig.headers,\n credentials: context.copilotApiConfig.credentials,\n });\n\n const response = await runtimeClient\n .generateCopilotResponse({\n data: {\n frontend: {\n actions: Object.values(actions).map((action) => ({\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n })),\n url: window.location.href,\n },\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messages)),\n metadata: {\n requestType: CopilotRequestType.Task,\n },\n forwardedParameters: {\n toolChoice: \"required\",\n },\n },\n properties: context.copilotApiConfig.properties,\n })\n .toPromise();\n\n const functionCallHandler = context.getFunctionCallHandler(actions);\n const functionCalls = convertGqlOutputToMessages(\n response.data?.generateCopilotResponse?.messages || [],\n ).filter((m): m is ActionExecutionMessage => m.isActionExecutionMessage());\n\n for (const functionCall of functionCalls) {\n await functionCallHandler({\n messages,\n name: functionCall.name,\n args: functionCall.arguments,\n });\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":";;;;;;;;AAgDA;AAAA,EAEE;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAKP,SAAS,oCAAoC;AAsBtC,IAAM,cAAN,MAA2B;AAAA,EAMhC,YAAY,QAA2B;AACrC,SAAK,eAAe,OAAO;AAC3B,SAAK,UAAU,OAAO,WAAW,CAAC;AAClC,SAAK,yBAAyB,OAAO,2BAA2B;AAChE,SAAK,wBAAwB,OAAO,0BAA0B;AAAA,EAChE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOM,IAAI,SAA+B,MAAyB;AAAA;AAvGpE;AAwGI,YAAM,UAAU,KAAK,wBAAwB,OAAO,OAAO,CAAC,GAAG,QAAQ,OAAO,IAAI,CAAC;AAGnF,iBAAW,MAAM,KAAK,SAAS;AAC7B,gBAAQ,GAAG,IAAI,IAAI;AAAA,MACrB;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,gBAAgB,IAAI,YAAY;AAAA,QACpC,SAAS,kBAAkB,eAAe,KAAK,YAAY;AAAA,QAC3D,MAAM,KAAK;AAAA,MACb,CAAC;AAED,YAAM,WAAsB,CAAC,aAAa;AAE1C,YAAM,gBAAgB,IAAI,qBAAqB;AAAA,QAC7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@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useCopilotContext
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-LODRWFMB.mjs";
|
|
4
4
|
|
|
5
5
|
// src/hooks/use-make-copilot-document-readable.ts
|
|
6
6
|
import { useEffect, useRef } from "react";
|
|
@@ -20,4 +20,4 @@ function useMakeCopilotDocumentReadable(document, categories, dependencies = [])
|
|
|
20
20
|
export {
|
|
21
21
|
useMakeCopilotDocumentReadable
|
|
22
22
|
};
|
|
23
|
-
//# sourceMappingURL=chunk-
|
|
23
|
+
//# sourceMappingURL=chunk-H4VZMKR6.mjs.map
|
|
@@ -1,18 +1,15 @@
|
|
|
1
|
-
import {
|
|
2
|
-
defaultCopilotContextCategories
|
|
3
|
-
} from "./chunk-2KT73RVG.mjs";
|
|
4
|
-
import {
|
|
5
|
-
useCopilotMessagesContext
|
|
6
|
-
} from "./chunk-DCTJZ742.mjs";
|
|
7
1
|
import {
|
|
8
2
|
useChat
|
|
9
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-JDQCJCAQ.mjs";
|
|
4
|
+
import {
|
|
5
|
+
defaultCopilotContextCategories
|
|
6
|
+
} from "./chunk-6OR25P32.mjs";
|
|
10
7
|
import {
|
|
11
8
|
useCopilotContext
|
|
12
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-LODRWFMB.mjs";
|
|
13
10
|
import {
|
|
14
|
-
|
|
15
|
-
} from "./chunk-
|
|
11
|
+
useCopilotMessagesContext
|
|
12
|
+
} from "./chunk-DCTJZ742.mjs";
|
|
16
13
|
import {
|
|
17
14
|
__async,
|
|
18
15
|
__objRest,
|
|
@@ -37,18 +34,11 @@ function useCopilotChat(_a = {}) {
|
|
|
37
34
|
setIsLoading,
|
|
38
35
|
chatInstructions,
|
|
39
36
|
actions,
|
|
40
|
-
|
|
41
|
-
|
|
37
|
+
coagentStates,
|
|
38
|
+
setCoagentStates,
|
|
42
39
|
coAgentStateRenders,
|
|
43
40
|
agentSession,
|
|
44
|
-
setAgentSession
|
|
45
|
-
forwardedParameters,
|
|
46
|
-
agentLock,
|
|
47
|
-
threadId,
|
|
48
|
-
setThreadId,
|
|
49
|
-
runId,
|
|
50
|
-
setRunId,
|
|
51
|
-
chatAbortControllerRef
|
|
41
|
+
setAgentSession
|
|
52
42
|
} = useCopilotContext();
|
|
53
43
|
const { messages, setMessages } = useCopilotMessagesContext();
|
|
54
44
|
const latestGetContextString = useUpdatedRef(getContextString);
|
|
@@ -66,7 +56,7 @@ function useCopilotChat(_a = {}) {
|
|
|
66
56
|
role: Role.System
|
|
67
57
|
});
|
|
68
58
|
}, [getContextString, makeSystemMessage, chatInstructions]);
|
|
69
|
-
const onCoAgentStateRender =
|
|
59
|
+
const onCoAgentStateRender = useCallback(
|
|
70
60
|
(args) => __async(this, null, function* () {
|
|
71
61
|
var _a2;
|
|
72
62
|
const { name, nodeName, state } = args;
|
|
@@ -84,7 +74,7 @@ function useCopilotChat(_a = {}) {
|
|
|
84
74
|
}),
|
|
85
75
|
[coAgentStateRenders]
|
|
86
76
|
);
|
|
87
|
-
const { append, reload, stop
|
|
77
|
+
const { append, reload, stop } = useChat(__spreadProps(__spreadValues({}, options), {
|
|
88
78
|
actions: Object.values(actions),
|
|
89
79
|
copilotConfig: copilotApiConfig,
|
|
90
80
|
initialMessages: options.initialMessages || [],
|
|
@@ -95,29 +85,22 @@ function useCopilotChat(_a = {}) {
|
|
|
95
85
|
makeSystemMessageCallback,
|
|
96
86
|
isLoading,
|
|
97
87
|
setIsLoading,
|
|
98
|
-
|
|
99
|
-
|
|
88
|
+
coagentStates,
|
|
89
|
+
setCoagentStates,
|
|
100
90
|
agentSession,
|
|
101
|
-
setAgentSession
|
|
102
|
-
forwardedParameters,
|
|
103
|
-
threadId,
|
|
104
|
-
setThreadId,
|
|
105
|
-
runId,
|
|
106
|
-
setRunId,
|
|
107
|
-
chatAbortControllerRef,
|
|
108
|
-
agentLock
|
|
91
|
+
setAgentSession
|
|
109
92
|
}));
|
|
110
93
|
const latestAppend = useUpdatedRef(append);
|
|
111
|
-
const latestAppendFunc =
|
|
112
|
-
(message) =>
|
|
113
|
-
return
|
|
114
|
-
}
|
|
94
|
+
const latestAppendFunc = useCallback(
|
|
95
|
+
(message) => {
|
|
96
|
+
return latestAppend.current(message);
|
|
97
|
+
},
|
|
115
98
|
[latestAppend]
|
|
116
99
|
);
|
|
117
100
|
const latestReload = useUpdatedRef(reload);
|
|
118
|
-
const latestReloadFunc =
|
|
119
|
-
return
|
|
120
|
-
}
|
|
101
|
+
const latestReloadFunc = useCallback(() => {
|
|
102
|
+
return latestReload.current();
|
|
103
|
+
}, [latestReload]);
|
|
121
104
|
const latestStop = useUpdatedRef(stop);
|
|
122
105
|
const latestStopFunc = useCallback(() => {
|
|
123
106
|
return latestStop.current();
|
|
@@ -136,44 +119,13 @@ function useCopilotChat(_a = {}) {
|
|
|
136
119
|
},
|
|
137
120
|
[latestSetMessages]
|
|
138
121
|
);
|
|
139
|
-
const latestRunChatCompletion = useUpdatedRef(runChatCompletion);
|
|
140
|
-
const latestRunChatCompletionFunc = useAsyncCallback(() => __async(this, null, function* () {
|
|
141
|
-
return yield latestRunChatCompletion.current();
|
|
142
|
-
}), [latestRunChatCompletion]);
|
|
143
|
-
const reset = useCallback(() => {
|
|
144
|
-
latestStopFunc();
|
|
145
|
-
setMessages([]);
|
|
146
|
-
setThreadId(null);
|
|
147
|
-
setRunId(null);
|
|
148
|
-
setCoagentStatesWithRef({});
|
|
149
|
-
let initialAgentSession = null;
|
|
150
|
-
if (agentLock) {
|
|
151
|
-
initialAgentSession = {
|
|
152
|
-
agentName: agentLock
|
|
153
|
-
};
|
|
154
|
-
}
|
|
155
|
-
setAgentSession(initialAgentSession);
|
|
156
|
-
}, [
|
|
157
|
-
latestStopFunc,
|
|
158
|
-
setMessages,
|
|
159
|
-
setThreadId,
|
|
160
|
-
setCoagentStatesWithRef,
|
|
161
|
-
setAgentSession,
|
|
162
|
-
agentLock
|
|
163
|
-
]);
|
|
164
|
-
const latestReset = useUpdatedRef(reset);
|
|
165
|
-
const latestResetFunc = useCallback(() => {
|
|
166
|
-
return latestReset.current();
|
|
167
|
-
}, [latestReset]);
|
|
168
122
|
return {
|
|
169
123
|
visibleMessages: messages,
|
|
170
124
|
appendMessage: latestAppendFunc,
|
|
171
125
|
setMessages: latestSetMessagesFunc,
|
|
172
126
|
reloadMessages: latestReloadFunc,
|
|
173
127
|
stopGeneration: latestStopFunc,
|
|
174
|
-
reset: latestResetFunc,
|
|
175
128
|
deleteMessage: latestDeleteFunc,
|
|
176
|
-
runChatCompletion: latestRunChatCompletionFunc,
|
|
177
129
|
isLoading
|
|
178
130
|
};
|
|
179
131
|
}
|
|
@@ -212,4 +164,4 @@ export {
|
|
|
212
164
|
useCopilotChat,
|
|
213
165
|
defaultSystemMessage
|
|
214
166
|
};
|
|
215
|
-
//# sourceMappingURL=chunk-
|
|
167
|
+
//# sourceMappingURL=chunk-H7LSKIDK.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-copilot-chat.ts"],"sourcesContent":["/**\n * `useCopilotChat` is a React hook that lets you directly interact with the\n * Copilot instance. Use to implement a fully custom UI (headless UI) or to\n * programmatically interact with the Copilot instance managed by the default\n * UI.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCopilotChat } from \"@copilotkit/react-core\";\n * import { Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\n *\n * export function YourComponent() {\n * const { appendMessage } = useCopilotChat();\n *\n * appendMessage(\n * new TextMessage({\n * content: \"Hello World\",\n * role: Role.User,\n * }),\n * );\n * }\n * ```\n *\n * `useCopilotChat` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * visibleMessages, // An array of messages that are currently visible in the chat.\n * appendMessage, // A function to append a message to the chat.\n * setMessages, // A function to set the messages in the chat.\n * deleteMessage, // A function to delete a message from the chat.\n * reloadMessages, // A function to reload the messages from the API.\n * stopGeneration, // A function to stop the generation of the next message.\n * isLoading, // A boolean indicating if the chat is loading.\n * } = useCopilotChat();\n * ```\n */\nimport { useRef, useEffect, useCallback } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { Message, Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useChat } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { MessageStatusCode } from \"@copilotkit/runtime-client-gql\";\nimport { CoAgentStateRenderHandlerArguments } from \"@copilotkit/shared\";\nimport { useCopilotMessagesContext } from \"../context\";\n\nexport interface UseCopilotChatOptions {\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 /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n}\n\nexport interface UseCopilotChatReturn {\n visibleMessages: Message[];\n appendMessage: (message: Message) => Promise<void>;\n setMessages: (messages: Message[]) => void;\n deleteMessage: (messageId: string) => void;\n reloadMessages: () => Promise<void>;\n stopGeneration: () => void;\n isLoading: boolean;\n}\n\nexport function useCopilotChat({\n makeSystemMessage,\n ...options\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const {\n getContextString,\n getFunctionCallHandler,\n copilotApiConfig,\n isLoading,\n setIsLoading,\n chatInstructions,\n actions,\n\n coagentStates,\n setCoagentStates,\n coAgentStateRenders,\n agentSession,\n setAgentSession,\n } = useCopilotContext();\n const { messages, setMessages } = useCopilotMessagesContext();\n\n // We need to ensure that makeSystemMessageCallback always uses the latest\n // useCopilotReadable data.\n const latestGetContextString = useUpdatedRef(getContextString);\n const deleteMessage = useCallback(\n (messageId: string) => {\n setMessages((prev) => prev.filter((message) => message.id !== messageId));\n },\n [setMessages],\n );\n\n const makeSystemMessageCallback = useCallback(() => {\n const systemMessageMaker = makeSystemMessage || defaultSystemMessage;\n // this always gets the latest context string\n const contextString = latestGetContextString.current([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return new TextMessage({\n content: systemMessageMaker(contextString, chatInstructions),\n role: Role.System,\n });\n }, [getContextString, makeSystemMessage, chatInstructions]);\n\n const onCoAgentStateRender = useCallback(\n async (args: CoAgentStateRenderHandlerArguments) => {\n const { name, nodeName, state } = args;\n let action = Object.values(coAgentStateRenders).find(\n (action) => action.name === name && action.nodeName === nodeName,\n );\n if (!action) {\n action = Object.values(coAgentStateRenders).find(\n (action) => action.name === name && !action.nodeName,\n );\n }\n if (action) {\n await action.handler?.({ state, nodeName });\n }\n },\n [coAgentStateRenders],\n );\n\n const { append, reload, stop } = useChat({\n ...options,\n actions: Object.values(actions),\n copilotConfig: copilotApiConfig,\n initialMessages: options.initialMessages || [],\n onFunctionCall: getFunctionCallHandler(),\n onCoAgentStateRender,\n messages,\n setMessages,\n makeSystemMessageCallback,\n isLoading,\n setIsLoading,\n coagentStates,\n setCoagentStates,\n agentSession,\n setAgentSession,\n });\n\n // this is a workaround born out of a bug that Athena insessently ran into.\n // We could not find the origin of the bug, however, it was clear that an outdated version of the append function was being used somehow --\n // it referecned the old state of the messages array, and not the latest one.\n //\n // We want to make copilotkit as abuse-proof as possible, so we are adding this workaround to ensure that the latest version of the append function is always used.\n //\n // How does this work?\n // we store the relevant function in a ref that is always up-to-date, and then we use that ref in the callback.\n const latestAppend = useUpdatedRef(append);\n const latestAppendFunc = useCallback(\n (message: Message) => {\n return latestAppend.current(message);\n },\n [latestAppend],\n );\n\n const latestReload = useUpdatedRef(reload);\n const latestReloadFunc = useCallback(() => {\n return latestReload.current();\n }, [latestReload]);\n\n const latestStop = useUpdatedRef(stop);\n const latestStopFunc = useCallback(() => {\n return latestStop.current();\n }, [latestStop]);\n\n const latestDelete = useUpdatedRef(deleteMessage);\n const latestDeleteFunc = useCallback(\n (messageId: string) => {\n return latestDelete.current(messageId);\n },\n [latestDelete],\n );\n\n const latestSetMessages = useUpdatedRef(setMessages);\n const latestSetMessagesFunc = useCallback(\n (messages: Message[]) => {\n return latestSetMessages.current(messages);\n },\n [latestSetMessages],\n );\n\n return {\n visibleMessages: messages,\n appendMessage: latestAppendFunc,\n setMessages: latestSetMessagesFunc,\n reloadMessages: latestReloadFunc,\n stopGeneration: latestStopFunc,\n deleteMessage: latestDeleteFunc,\n isLoading,\n };\n}\n\n// store `value` in a ref and update\n// it whenever it changes.\nfunction useUpdatedRef<T>(value: T) {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref;\n}\n\nexport function defaultSystemMessage(\n contextString: string,\n additionalInstructions?: string,\n): string {\n return (\n `\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, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou 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.\n\nIf you would like to call a function, call it without saying anything else.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAwCA,SAAS,QAAQ,WAAW,mBAAmB;AAE/C,SAAkB,MAAM,mBAAmB;AAyCpC,SAAS,eAAe,KAGJ,CAAC,GAAyB;AAHtB,eAC7B;AAAA;AAAA,EApFF,IAmF+B,IAE1B,oBAF0B,IAE1B;AAAA,IADH;AAAA;AAGA,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IAEA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ACd,eACA,wBACQ;AACR,SACE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAUG,yBAAyB;AAAA;AAAA,EAAO,2BAA2B;AAEhE;","names":["_a","action","messages"]}
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
import {
|
|
2
|
+
useCopilotRuntimeClient
|
|
3
|
+
} from "./chunk-ODN4H66E.mjs";
|
|
4
|
+
import {
|
|
5
|
+
useToast
|
|
6
|
+
} from "./chunk-2KCEHGSI.mjs";
|
|
7
|
+
import {
|
|
8
|
+
__async,
|
|
9
|
+
__spreadProps,
|
|
10
|
+
__spreadValues
|
|
11
|
+
} from "./chunk-SKC7AJIV.mjs";
|
|
12
|
+
|
|
13
|
+
// src/hooks/use-chat.ts
|
|
14
|
+
import { useRef } from "react";
|
|
15
|
+
import {
|
|
16
|
+
COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,
|
|
17
|
+
actionParametersToJsonSchema
|
|
18
|
+
} from "@copilotkit/shared";
|
|
19
|
+
import {
|
|
20
|
+
TextMessage,
|
|
21
|
+
ResultMessage,
|
|
22
|
+
convertMessagesToGqlInput,
|
|
23
|
+
filterAdjacentAgentStateMessages,
|
|
24
|
+
filterAgentStateMessages,
|
|
25
|
+
convertGqlOutputToMessages,
|
|
26
|
+
MessageStatusCode,
|
|
27
|
+
MessageRole,
|
|
28
|
+
Role,
|
|
29
|
+
CopilotRequestType,
|
|
30
|
+
ActionInputAvailability
|
|
31
|
+
} from "@copilotkit/runtime-client-gql";
|
|
32
|
+
function useChat(options) {
|
|
33
|
+
const {
|
|
34
|
+
messages,
|
|
35
|
+
setMessages,
|
|
36
|
+
makeSystemMessageCallback,
|
|
37
|
+
copilotConfig,
|
|
38
|
+
setIsLoading,
|
|
39
|
+
initialMessages,
|
|
40
|
+
isLoading,
|
|
41
|
+
actions,
|
|
42
|
+
onFunctionCall,
|
|
43
|
+
onCoAgentStateRender,
|
|
44
|
+
setCoagentStates,
|
|
45
|
+
coagentStates,
|
|
46
|
+
agentSession,
|
|
47
|
+
setAgentSession
|
|
48
|
+
} = options;
|
|
49
|
+
const abortControllerRef = useRef();
|
|
50
|
+
const threadIdRef = useRef(null);
|
|
51
|
+
const runIdRef = useRef(null);
|
|
52
|
+
const { addGraphQLErrorsToast } = useToast();
|
|
53
|
+
const runChatCompletionRef = useRef();
|
|
54
|
+
const coagentStatesRef = useRef(coagentStates);
|
|
55
|
+
coagentStatesRef.current = coagentStates;
|
|
56
|
+
const agentSessionRef = useRef(agentSession);
|
|
57
|
+
agentSessionRef.current = agentSession;
|
|
58
|
+
const publicApiKey = copilotConfig.publicApiKey;
|
|
59
|
+
const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
|
|
60
|
+
const runtimeClient = useCopilotRuntimeClient({
|
|
61
|
+
url: copilotConfig.chatApiEndpoint,
|
|
62
|
+
publicApiKey: copilotConfig.publicApiKey,
|
|
63
|
+
headers,
|
|
64
|
+
credentials: copilotConfig.credentials
|
|
65
|
+
});
|
|
66
|
+
const runChatCompletion = (previousMessages) => __async(this, null, function* () {
|
|
67
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
|
|
68
|
+
setIsLoading(true);
|
|
69
|
+
let newMessages = [
|
|
70
|
+
new TextMessage({
|
|
71
|
+
content: "",
|
|
72
|
+
role: Role.Assistant
|
|
73
|
+
})
|
|
74
|
+
];
|
|
75
|
+
const abortController = new AbortController();
|
|
76
|
+
abortControllerRef.current = abortController;
|
|
77
|
+
setMessages([...previousMessages, ...newMessages]);
|
|
78
|
+
const systemMessage = makeSystemMessageCallback();
|
|
79
|
+
const messagesWithContext = [systemMessage, ...initialMessages || [], ...previousMessages];
|
|
80
|
+
const stream = runtimeClient.asStream(
|
|
81
|
+
runtimeClient.generateCopilotResponse({
|
|
82
|
+
data: __spreadProps(__spreadValues(__spreadProps(__spreadValues({
|
|
83
|
+
frontend: {
|
|
84
|
+
actions: actions.filter(
|
|
85
|
+
(action) => action.available !== ActionInputAvailability.Disabled || !action.disabled
|
|
86
|
+
).map((action) => {
|
|
87
|
+
let available = ActionInputAvailability.Enabled;
|
|
88
|
+
if (action.disabled) {
|
|
89
|
+
available = ActionInputAvailability.Disabled;
|
|
90
|
+
} else if (action.available === "disabled") {
|
|
91
|
+
available = ActionInputAvailability.Disabled;
|
|
92
|
+
} else if (action.available === "remote") {
|
|
93
|
+
available = ActionInputAvailability.Remote;
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
name: action.name,
|
|
97
|
+
description: action.description || "",
|
|
98
|
+
jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),
|
|
99
|
+
available
|
|
100
|
+
};
|
|
101
|
+
}),
|
|
102
|
+
url: window.location.href
|
|
103
|
+
},
|
|
104
|
+
threadId: threadIdRef.current,
|
|
105
|
+
runId: runIdRef.current,
|
|
106
|
+
messages: convertMessagesToGqlInput(filterAgentStateMessages(messagesWithContext))
|
|
107
|
+
}, copilotConfig.cloud ? {
|
|
108
|
+
cloud: __spreadValues({}, ((_c = (_b = (_a = copilotConfig.cloud.guardrails) == null ? void 0 : _a.input) == null ? void 0 : _b.restrictToTopic) == null ? void 0 : _c.enabled) ? {
|
|
109
|
+
guardrails: {
|
|
110
|
+
inputValidationRules: {
|
|
111
|
+
allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,
|
|
112
|
+
denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
} : {})
|
|
116
|
+
} : {}), {
|
|
117
|
+
metadata: {
|
|
118
|
+
requestType: CopilotRequestType.Chat
|
|
119
|
+
}
|
|
120
|
+
}), agentSessionRef.current ? {
|
|
121
|
+
agentSession: agentSessionRef.current
|
|
122
|
+
} : {}), {
|
|
123
|
+
agentStates: Object.values(coagentStatesRef.current).map((state) => ({
|
|
124
|
+
agentName: state.name,
|
|
125
|
+
state: JSON.stringify(state.state)
|
|
126
|
+
}))
|
|
127
|
+
}),
|
|
128
|
+
properties: copilotConfig.properties,
|
|
129
|
+
signal: (_d = abortControllerRef.current) == null ? void 0 : _d.signal
|
|
130
|
+
})
|
|
131
|
+
);
|
|
132
|
+
const guardrailsEnabled = ((_g = (_f = (_e = copilotConfig.cloud) == null ? void 0 : _e.guardrails) == null ? void 0 : _f.input) == null ? void 0 : _g.restrictToTopic.enabled) || false;
|
|
133
|
+
const reader = stream.getReader();
|
|
134
|
+
let actionResults = {};
|
|
135
|
+
let executedCoAgentStateRenders = [];
|
|
136
|
+
let followUp = void 0;
|
|
137
|
+
try {
|
|
138
|
+
while (true) {
|
|
139
|
+
let done, value;
|
|
140
|
+
try {
|
|
141
|
+
const readResult = yield reader.read();
|
|
142
|
+
done = readResult.done;
|
|
143
|
+
value = readResult.value;
|
|
144
|
+
} catch (readError) {
|
|
145
|
+
break;
|
|
146
|
+
}
|
|
147
|
+
if (done) {
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
if (!(value == null ? void 0 : value.generateCopilotResponse)) {
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
threadIdRef.current = value.generateCopilotResponse.threadId || null;
|
|
154
|
+
runIdRef.current = value.generateCopilotResponse.runId || null;
|
|
155
|
+
const messages2 = convertGqlOutputToMessages(
|
|
156
|
+
filterAdjacentAgentStateMessages(value.generateCopilotResponse.messages)
|
|
157
|
+
);
|
|
158
|
+
if (messages2.length === 0) {
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
newMessages = [];
|
|
162
|
+
if (((_h = value.generateCopilotResponse.status) == null ? void 0 : _h.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
|
|
163
|
+
newMessages = [
|
|
164
|
+
new TextMessage({
|
|
165
|
+
role: MessageRole.Assistant,
|
|
166
|
+
content: ((_i = value.generateCopilotResponse.status.details) == null ? void 0 : _i.guardrailsReason) || ""
|
|
167
|
+
})
|
|
168
|
+
];
|
|
169
|
+
} else {
|
|
170
|
+
for (const message of messages2) {
|
|
171
|
+
newMessages.push(message);
|
|
172
|
+
if (message.isActionExecutionMessage() && message.status.code !== MessageStatusCode.Pending && message.scope === "client" && onFunctionCall) {
|
|
173
|
+
if (!(message.id in actionResults)) {
|
|
174
|
+
if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
try {
|
|
178
|
+
setMessages([...previousMessages, ...newMessages]);
|
|
179
|
+
const action = actions.find((action2) => action2.name === message.name);
|
|
180
|
+
if (action) {
|
|
181
|
+
followUp = action.followUp;
|
|
182
|
+
}
|
|
183
|
+
const result = yield onFunctionCall({
|
|
184
|
+
messages: previousMessages,
|
|
185
|
+
name: message.name,
|
|
186
|
+
args: message.arguments
|
|
187
|
+
});
|
|
188
|
+
actionResults[message.id] = result;
|
|
189
|
+
} catch (e) {
|
|
190
|
+
actionResults[message.id] = `Failed to execute action ${message.name}`;
|
|
191
|
+
console.error(`Failed to execute action ${message.name}: ${e}`);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
newMessages.push(
|
|
195
|
+
new ResultMessage({
|
|
196
|
+
result: ResultMessage.encodeResult(actionResults[message.id]),
|
|
197
|
+
actionExecutionId: message.id,
|
|
198
|
+
actionName: message.name
|
|
199
|
+
})
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
if (message.isAgentStateMessage() && !message.active && !executedCoAgentStateRenders.includes(message.id) && onCoAgentStateRender) {
|
|
203
|
+
if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
|
|
204
|
+
break;
|
|
205
|
+
}
|
|
206
|
+
yield onCoAgentStateRender({
|
|
207
|
+
name: message.agentName,
|
|
208
|
+
nodeName: message.nodeName,
|
|
209
|
+
state: message.state
|
|
210
|
+
});
|
|
211
|
+
executedCoAgentStateRenders.push(message.id);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
const lastAgentStateMessage = [...messages2].reverse().find((message) => message.isAgentStateMessage());
|
|
215
|
+
if (lastAgentStateMessage) {
|
|
216
|
+
setCoagentStates((prevAgentStates) => __spreadProps(__spreadValues({}, prevAgentStates), {
|
|
217
|
+
[lastAgentStateMessage.agentName]: {
|
|
218
|
+
name: lastAgentStateMessage.agentName,
|
|
219
|
+
state: lastAgentStateMessage.state,
|
|
220
|
+
running: lastAgentStateMessage.running,
|
|
221
|
+
active: lastAgentStateMessage.active,
|
|
222
|
+
threadId: lastAgentStateMessage.threadId,
|
|
223
|
+
nodeName: lastAgentStateMessage.nodeName,
|
|
224
|
+
runId: lastAgentStateMessage.runId
|
|
225
|
+
}
|
|
226
|
+
}));
|
|
227
|
+
if (lastAgentStateMessage.running) {
|
|
228
|
+
setAgentSession({
|
|
229
|
+
threadId: lastAgentStateMessage.threadId,
|
|
230
|
+
agentName: lastAgentStateMessage.agentName,
|
|
231
|
+
nodeName: lastAgentStateMessage.nodeName
|
|
232
|
+
});
|
|
233
|
+
} else {
|
|
234
|
+
setAgentSession(null);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
if (newMessages.length > 0) {
|
|
239
|
+
setMessages([...previousMessages, ...newMessages]);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
if (
|
|
243
|
+
// if followUp is not explicitly false
|
|
244
|
+
followUp !== false && // if we have client side results
|
|
245
|
+
(Object.values(actionResults).length || // or the last message we received is a result
|
|
246
|
+
newMessages.length && newMessages[newMessages.length - 1].isResultMessage())
|
|
247
|
+
) {
|
|
248
|
+
yield new Promise((resolve) => setTimeout(resolve, 10));
|
|
249
|
+
return yield runChatCompletionRef.current([...previousMessages, ...newMessages]);
|
|
250
|
+
} else {
|
|
251
|
+
return newMessages.slice();
|
|
252
|
+
}
|
|
253
|
+
} finally {
|
|
254
|
+
setIsLoading(false);
|
|
255
|
+
}
|
|
256
|
+
});
|
|
257
|
+
runChatCompletionRef.current = runChatCompletion;
|
|
258
|
+
const runChatCompletionAndHandleFunctionCall = (messages2) => __async(this, null, function* () {
|
|
259
|
+
yield runChatCompletionRef.current(messages2);
|
|
260
|
+
});
|
|
261
|
+
const append = (message) => __async(this, null, function* () {
|
|
262
|
+
if (isLoading) {
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
const newMessages = [...messages, message];
|
|
266
|
+
setMessages(newMessages);
|
|
267
|
+
return runChatCompletionAndHandleFunctionCall(newMessages);
|
|
268
|
+
});
|
|
269
|
+
const reload = () => __async(this, null, function* () {
|
|
270
|
+
if (isLoading || messages.length === 0) {
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
let newMessages = [...messages];
|
|
274
|
+
const lastMessage = messages[messages.length - 1];
|
|
275
|
+
if (lastMessage.isTextMessage() && lastMessage.role === "assistant") {
|
|
276
|
+
newMessages = newMessages.slice(0, -1);
|
|
277
|
+
}
|
|
278
|
+
setMessages(newMessages);
|
|
279
|
+
return runChatCompletionAndHandleFunctionCall(newMessages);
|
|
280
|
+
});
|
|
281
|
+
const stop = () => {
|
|
282
|
+
var _a;
|
|
283
|
+
(_a = abortControllerRef.current) == null ? void 0 : _a.abort();
|
|
284
|
+
};
|
|
285
|
+
return {
|
|
286
|
+
append,
|
|
287
|
+
reload,
|
|
288
|
+
stop
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export {
|
|
293
|
+
useChat
|
|
294
|
+
};
|
|
295
|
+
//# sourceMappingURL=chunk-JDQCJCAQ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-chat.ts"],"sourcesContent":["import { useRef } from \"react\";\nimport {\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n actionParametersToJsonSchema,\n CoAgentStateRenderHandler,\n} from \"@copilotkit/shared\";\nimport {\n Message,\n TextMessage,\n ResultMessage,\n convertMessagesToGqlInput,\n filterAdjacentAgentStateMessages,\n filterAgentStateMessages,\n convertGqlOutputToMessages,\n MessageStatusCode,\n MessageRole,\n Role,\n CopilotRequestType,\n ActionInputAvailability,\n} from \"@copilotkit/runtime-client-gql\";\n\nimport { CopilotApiConfig } from \"../context\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { AgentSession } from \"../context/copilot-context\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\n\nexport type UseChatOptions = {\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n /**\n * Callback function to be called when a function call is received.\n * If the function returns a `ChatRequest` object, the request will be sent\n * automatically to the API and will be used to update the chat.\n */\n onFunctionCall?: FunctionCallHandler;\n\n /**\n * Callback function to be called when a coagent action is received.\n */\n onCoAgentStateRender?: CoAgentStateRenderHandler;\n\n /**\n * Function definitions to be sent to the API.\n */\n actions: FrontendAction<any>[];\n\n /**\n * The CopilotKit API configuration.\n */\n copilotConfig: CopilotApiConfig;\n\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * A callback to get the latest system message.\n */\n makeSystemMessageCallback: () => TextMessage;\n\n /**\n * Whether the API request is in progress\n */\n isLoading: boolean;\n\n /**\n * setState-powered method to update the isChatLoading value\n */\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n /**\n * The current list of coagent states.\n */\n coagentStates: Record<string, CoagentState>;\n\n /**\n * setState-powered method to update the agent states\n */\n setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n\n /**\n * The current agent session.\n */\n agentSession: AgentSession | null;\n\n /**\n * setState-powered method to update the agent session\n */\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: () => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n};\n\nexport function useChat(options: UseChatOptions): UseChatHelpers {\n const {\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n onCoAgentStateRender,\n setCoagentStates,\n coagentStates,\n agentSession,\n setAgentSession,\n } = options;\n\n const abortControllerRef = useRef<AbortController>();\n const threadIdRef = useRef<string | null>(null);\n const runIdRef = useRef<string | null>(null);\n const { addGraphQLErrorsToast } = useToast();\n\n const runChatCompletionRef = useRef<(previousMessages: Message[]) => Promise<Message[]>>();\n // We need to keep a ref of coagent states because of renderAndWait - making sure\n // the latest state is sent to the API\n // This is a workaround and needs to be addressed in the future\n const coagentStatesRef = useRef<Record<string, CoagentState>>(coagentStates);\n coagentStatesRef.current = coagentStates;\n const agentSessionRef = useRef<AgentSession | null>(agentSession);\n agentSessionRef.current = agentSession;\n\n const publicApiKey = copilotConfig.publicApiKey;\n\n const headers = {\n ...(copilotConfig.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotConfig.chatApiEndpoint,\n publicApiKey: copilotConfig.publicApiKey,\n headers,\n credentials: copilotConfig.credentials,\n });\n\n const runChatCompletion = async (previousMessages: Message[]): Promise<Message[]> => {\n setIsLoading(true);\n\n // this message is just a placeholder. It will disappear once the first real message\n // is received\n let newMessages: Message[] = [\n new TextMessage({\n content: \"\",\n role: Role.Assistant,\n }),\n ];\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setMessages([...previousMessages, ...newMessages]);\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(initialMessages || []), ...previousMessages];\n\n const stream = runtimeClient.asStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: actions\n .filter(\n (action) =>\n action.available !== ActionInputAvailability.Disabled || !action.disabled,\n )\n .map((action) => {\n let available: ActionInputAvailability | undefined =\n ActionInputAvailability.Enabled;\n if (action.disabled) {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"disabled\") {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"remote\") {\n available = ActionInputAvailability.Remote;\n }\n return {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n available,\n };\n }),\n url: window.location.href,\n },\n threadId: threadIdRef.current,\n runId: runIdRef.current,\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messagesWithContext)),\n ...(copilotConfig.cloud\n ? {\n cloud: {\n ...(copilotConfig.cloud.guardrails?.input?.restrictToTopic?.enabled\n ? {\n guardrails: {\n inputValidationRules: {\n allowList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,\n denyList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics,\n },\n },\n }\n : {}),\n },\n }\n : {}),\n metadata: {\n requestType: CopilotRequestType.Chat,\n },\n ...(agentSessionRef.current\n ? {\n agentSession: agentSessionRef.current,\n }\n : {}),\n agentStates: Object.values(coagentStatesRef.current).map((state) => ({\n agentName: state.name,\n state: JSON.stringify(state.state),\n })),\n },\n properties: copilotConfig.properties,\n signal: abortControllerRef.current?.signal,\n }),\n );\n\n const guardrailsEnabled =\n copilotConfig.cloud?.guardrails?.input?.restrictToTopic.enabled || false;\n\n const reader = stream.getReader();\n\n let actionResults: { [id: string]: string } = {};\n let executedCoAgentStateRenders: string[] = [];\n let followUp: FrontendAction[\"followUp\"] = undefined;\n\n try {\n while (true) {\n let done, value;\n\n try {\n const readResult = await reader.read();\n done = readResult.done;\n value = readResult.value;\n } catch (readError) {\n break;\n }\n\n if (done) {\n break;\n }\n\n if (!value?.generateCopilotResponse) {\n continue;\n }\n\n threadIdRef.current = value.generateCopilotResponse.threadId || null;\n runIdRef.current = value.generateCopilotResponse.runId || null;\n\n const messages = convertGqlOutputToMessages(\n filterAdjacentAgentStateMessages(value.generateCopilotResponse.messages),\n );\n\n if (messages.length === 0) {\n continue;\n }\n\n newMessages = [];\n\n // request failed, display error message\n if (\n value.generateCopilotResponse.status?.__typename === \"FailedResponseStatus\" &&\n value.generateCopilotResponse.status.reason === \"GUARDRAILS_VALIDATION_FAILED\"\n ) {\n newMessages = [\n new TextMessage({\n role: MessageRole.Assistant,\n content: value.generateCopilotResponse.status.details?.guardrailsReason || \"\",\n }),\n ];\n }\n\n // add messages to the chat\n else {\n for (const message of messages) {\n newMessages.push(message);\n // execute regular action executions\n if (\n message.isActionExecutionMessage() &&\n message.status.code !== MessageStatusCode.Pending &&\n message.scope === \"client\" &&\n onFunctionCall\n ) {\n if (!(message.id in actionResults)) {\n // Do not execute a function call if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute action\n try {\n // We update the message state before calling the handler so that the render\n // function can be called with `executing` state\n setMessages([...previousMessages, ...newMessages]);\n\n const action = actions.find((action) => action.name === message.name);\n\n if (action) {\n followUp = action.followUp;\n }\n\n const result = await onFunctionCall({\n messages: previousMessages,\n name: message.name,\n args: message.arguments,\n });\n actionResults[message.id] = result;\n } catch (e) {\n actionResults[message.id] = `Failed to execute action ${message.name}`;\n console.error(`Failed to execute action ${message.name}: ${e}`);\n }\n }\n // add the result message\n newMessages.push(\n new ResultMessage({\n result: ResultMessage.encodeResult(actionResults[message.id]),\n actionExecutionId: message.id,\n actionName: message.name,\n }),\n );\n }\n // execute coagent actions\n if (\n message.isAgentStateMessage() &&\n !message.active &&\n !executedCoAgentStateRenders.includes(message.id) &&\n onCoAgentStateRender\n ) {\n // Do not execute a coagent action if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute coagent action\n await onCoAgentStateRender({\n name: message.agentName,\n nodeName: message.nodeName,\n state: message.state,\n });\n executedCoAgentStateRenders.push(message.id);\n }\n }\n\n const lastAgentStateMessage = [...messages]\n .reverse()\n .find((message) => message.isAgentStateMessage());\n\n if (lastAgentStateMessage) {\n setCoagentStates((prevAgentStates) => ({\n ...prevAgentStates,\n [lastAgentStateMessage.agentName]: {\n name: lastAgentStateMessage.agentName,\n state: lastAgentStateMessage.state,\n running: lastAgentStateMessage.running,\n active: lastAgentStateMessage.active,\n threadId: lastAgentStateMessage.threadId,\n nodeName: lastAgentStateMessage.nodeName,\n runId: lastAgentStateMessage.runId,\n },\n }));\n if (lastAgentStateMessage.running) {\n setAgentSession({\n threadId: lastAgentStateMessage.threadId,\n agentName: lastAgentStateMessage.agentName,\n nodeName: lastAgentStateMessage.nodeName,\n });\n } else {\n setAgentSession(null);\n }\n }\n }\n\n if (newMessages.length > 0) {\n // Update message state\n setMessages([...previousMessages, ...newMessages]);\n }\n }\n\n if (\n // if followUp is not explicitly false\n followUp !== false &&\n // if we have client side results\n (Object.values(actionResults).length ||\n // or the last message we received is a result\n (newMessages.length && newMessages[newMessages.length - 1].isResultMessage()))\n ) {\n // run the completion again and return the result\n\n // wait for next tick to make sure all the react state updates\n // - tried using react-dom's flushSync, but it did not work\n await new Promise((resolve) => setTimeout(resolve, 10));\n\n return await runChatCompletionRef.current!([...previousMessages, ...newMessages]);\n } else {\n return newMessages.slice();\n }\n } finally {\n setIsLoading(false);\n }\n };\n\n runChatCompletionRef.current = runChatCompletion;\n\n const runChatCompletionAndHandleFunctionCall = async (messages: Message[]): Promise<void> => {\n await runChatCompletionRef.current!(messages);\n };\n\n const append = async (message: Message): Promise<void> => {\n if (isLoading) {\n return;\n }\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.isTextMessage() && lastMessage.role === \"assistant\") {\n newMessages = newMessages.slice(0, -1);\n }\n\n setMessages(newMessages);\n\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const stop = (): void => {\n abortControllerRef.current?.abort();\n };\n\n return {\n append,\n reload,\n stop,\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAS,cAAc;AACvB;AAAA,EAEE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAoGA,SAAS,QAAQ,SAAyC;AAC/D,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,QAAM,qBAAqB,OAAwB;AACnD,QAAM,cAAc,OAAsB,IAAI;AAC9C,QAAM,WAAW,OAAsB,IAAI;AAC3C,QAAM,EAAE,sBAAsB,IAAI,SAAS;AAE3C,QAAM,uBAAuB,OAA4D;AAIzF,QAAM,mBAAmB,OAAqC,aAAa;AAC3E,mBAAiB,UAAU;AAC3B,QAAM,kBAAkB,OAA4B,YAAY;AAChE,kBAAgB,UAAU;AAE1B,QAAM,eAAe,cAAc;AAEnC,QAAM,UAAU,kCACV,cAAc,WAAW,CAAC,IAC1B,eAAe,EAAE,CAAC,mCAAmC,GAAG,aAAa,IAAI,CAAC;AAGhF,QAAM,gBAAgB,wBAAwB;AAAA,IAC5C,KAAK,cAAc;AAAA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