@copilotkit/react-core 0.37.0 → 0.38.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +187 -234
- package/CHANGELOG.md +12 -0
- package/dist/{chunk-HUKLBIUK.mjs → chunk-5CKW6KE7.mjs} +13 -22
- package/dist/chunk-5CKW6KE7.mjs.map +1 -0
- package/dist/{chunk-S5LWO5V3.mjs → chunk-7GPIOOXB.mjs} +2 -2
- package/dist/{chunk-LLU5URI5.mjs → chunk-DDHJCFFV.mjs} +18 -33
- package/dist/chunk-DDHJCFFV.mjs.map +1 -0
- package/dist/{chunk-SR4RW4CU.mjs → chunk-IQCLNCGL.mjs} +6 -6
- package/dist/chunk-IQCLNCGL.mjs.map +1 -0
- package/dist/{chunk-DY63PD22.mjs → chunk-K6EV2CNB.mjs} +4 -5
- package/dist/chunk-K6EV2CNB.mjs.map +1 -0
- package/dist/{chunk-NSUYO6TP.mjs → chunk-LZVHW3T3.mjs} +9 -9
- package/dist/chunk-LZVHW3T3.mjs.map +1 -0
- package/dist/{chunk-Z5FB4WBL.mjs → chunk-NY6QSOU7.mjs} +43 -40
- package/dist/chunk-NY6QSOU7.mjs.map +1 -0
- package/dist/chunk-PHMHNAYC.mjs +192 -0
- package/dist/chunk-PHMHNAYC.mjs.map +1 -0
- package/dist/{chunk-B244LK6F.mjs → chunk-QNJQKKD4.mjs} +2 -2
- package/dist/{chunk-4OIVQMEM.mjs → chunk-WU3I3G3G.mjs} +60 -42
- package/dist/chunk-WU3I3G3G.mjs.map +1 -0
- package/dist/chunk-YJLRG5U3.mjs +1 -0
- package/dist/{chunk-MNZXQ6UH.mjs → chunk-YM2JV2YQ.mjs} +2 -2
- package/dist/components/copilot-provider/copilotkit-props.d.ts +2 -2
- package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.js +18 -33
- package/dist/components/copilot-provider/copilotkit.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.mjs +2 -2
- package/dist/components/copilot-provider/index.js +18 -33
- package/dist/components/copilot-provider/index.js.map +1 -1
- package/dist/components/copilot-provider/index.mjs +2 -2
- package/dist/components/index.js +18 -33
- package/dist/components/index.js.map +1 -1
- package/dist/components/index.mjs +2 -2
- package/dist/context/copilot-context.d.ts +7 -18
- package/dist/context/copilot-context.js +3 -4
- package/dist/context/copilot-context.js.map +1 -1
- package/dist/context/copilot-context.mjs +1 -1
- package/dist/context/index.d.ts +1 -0
- package/dist/context/index.js +3 -4
- package/dist/context/index.js.map +1 -1
- package/dist/context/index.mjs +1 -1
- package/dist/hooks/index.d.ts +2 -1
- package/dist/hooks/index.js +140 -229
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +9 -10
- package/dist/hooks/use-chat.d.ts +25 -51
- package/dist/hooks/use-chat.js +109 -203
- package/dist/hooks/use-chat.js.map +1 -1
- package/dist/hooks/use-chat.mjs +1 -2
- package/dist/hooks/use-copilot-action.js +10 -11
- package/dist/hooks/use-copilot-action.js.map +1 -1
- package/dist/hooks/use-copilot-action.mjs +2 -2
- package/dist/hooks/use-copilot-chat.d.ts +1 -1
- package/dist/hooks/use-copilot-chat.js +123 -212
- package/dist/hooks/use-copilot-chat.js.map +1 -1
- package/dist/hooks/use-copilot-chat.mjs +4 -5
- package/dist/hooks/use-copilot-readable.js +3 -4
- package/dist/hooks/use-copilot-readable.js.map +1 -1
- package/dist/hooks/use-copilot-readable.mjs +2 -2
- package/dist/hooks/use-make-copilot-actionable.js +7 -8
- package/dist/hooks/use-make-copilot-actionable.js.map +1 -1
- package/dist/hooks/use-make-copilot-actionable.mjs +2 -2
- package/dist/hooks/use-make-copilot-document-readable.js +3 -4
- 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/hooks/use-make-copilot-readable.js +3 -4
- package/dist/hooks/use-make-copilot-readable.js.map +1 -1
- package/dist/hooks/use-make-copilot-readable.mjs +2 -2
- package/dist/index.d.ts +1 -3
- package/dist/index.js +239 -497
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +12 -31
- package/dist/lib/copilot-task.d.ts +1 -0
- package/dist/lib/copilot-task.js +34 -110
- package/dist/lib/copilot-task.js.map +1 -1
- package/dist/lib/copilot-task.mjs +3 -4
- package/dist/lib/index.d.ts +1 -0
- package/dist/lib/index.js +36 -110
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/index.mjs +3 -4
- package/dist/utils/extract.d.ts +1 -0
- package/dist/utils/extract.js +53 -109
- package/dist/utils/extract.js.map +1 -1
- package/dist/utils/extract.mjs +3 -4
- package/dist/utils/index.d.ts +1 -1
- package/dist/utils/index.js +56 -132
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/index.mjs +5 -13
- package/package.json +6 -5
- package/src/components/copilot-provider/copilotkit-props.tsx +2 -2
- package/src/components/copilot-provider/copilotkit.tsx +16 -37
- package/src/context/copilot-context.tsx +11 -30
- package/src/hooks/use-chat.ts +179 -208
- package/src/hooks/use-copilot-action.ts +7 -8
- package/src/hooks/use-copilot-chat.ts +9 -23
- package/src/hooks/use-make-copilot-actionable.ts +4 -4
- package/src/index.tsx +0 -1
- package/src/lib/copilot-task.ts +45 -42
- package/src/utils/extract.ts +64 -36
- package/src/utils/index.ts +0 -7
- package/dist/chunk-2EQGN5QK.mjs +0 -137
- package/dist/chunk-2EQGN5QK.mjs.map +0 -1
- package/dist/chunk-4OIVQMEM.mjs.map +0 -1
- package/dist/chunk-7GFKOIO7.mjs +0 -1
- package/dist/chunk-B2H3NC4E.mjs +0 -204
- package/dist/chunk-B2H3NC4E.mjs.map +0 -1
- package/dist/chunk-BABVSMJR.mjs +0 -1
- package/dist/chunk-BABVSMJR.mjs.map +0 -1
- package/dist/chunk-CYDWEPFL.mjs +0 -1
- package/dist/chunk-CYDWEPFL.mjs.map +0 -1
- package/dist/chunk-DY63PD22.mjs.map +0 -1
- package/dist/chunk-FRAKUJWH.mjs +0 -1
- package/dist/chunk-FRAKUJWH.mjs.map +0 -1
- package/dist/chunk-HUKLBIUK.mjs.map +0 -1
- package/dist/chunk-LLU5URI5.mjs.map +0 -1
- package/dist/chunk-MJKBCG4U.mjs +0 -91
- package/dist/chunk-MJKBCG4U.mjs.map +0 -1
- package/dist/chunk-NSUYO6TP.mjs.map +0 -1
- package/dist/chunk-SR4RW4CU.mjs.map +0 -1
- package/dist/chunk-Z5FB4WBL.mjs.map +0 -1
- package/dist/chunk-ZFS5SQUT.mjs +0 -31
- package/dist/chunk-ZFS5SQUT.mjs.map +0 -1
- package/dist/openai-assistants/hooks/index.d.ts +0 -2
- package/dist/openai-assistants/hooks/index.js +0 -277
- package/dist/openai-assistants/hooks/index.js.map +0 -1
- package/dist/openai-assistants/hooks/index.mjs +0 -18
- package/dist/openai-assistants/hooks/index.mjs.map +0 -1
- package/dist/openai-assistants/hooks/use-assistants.d.ts +0 -17
- package/dist/openai-assistants/hooks/use-assistants.js +0 -154
- package/dist/openai-assistants/hooks/use-assistants.js.map +0 -1
- package/dist/openai-assistants/hooks/use-assistants.mjs +0 -92
- package/dist/openai-assistants/hooks/use-assistants.mjs.map +0 -1
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.d.ts +0 -44
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.js +0 -277
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.js.map +0 -1
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs +0 -19
- package/dist/openai-assistants/hooks/use-copilot-chat-v2.mjs.map +0 -1
- package/dist/openai-assistants/index.d.ts +0 -3
- package/dist/openai-assistants/index.js +0 -279
- package/dist/openai-assistants/index.js.map +0 -1
- package/dist/openai-assistants/index.mjs +0 -22
- package/dist/openai-assistants/index.mjs.map +0 -1
- package/dist/openai-assistants/utils/index.d.ts +0 -1
- package/dist/openai-assistants/utils/index.js +0 -73
- package/dist/openai-assistants/utils/index.js.map +0 -1
- package/dist/openai-assistants/utils/index.mjs +0 -9
- package/dist/openai-assistants/utils/index.mjs.map +0 -1
- package/dist/openai-assistants/utils/process-message-stream.d.ts +0 -3
- package/dist/openai-assistants/utils/process-message-stream.js +0 -71
- package/dist/openai-assistants/utils/process-message-stream.js.map +0 -1
- package/dist/openai-assistants/utils/process-message-stream.mjs +0 -8
- package/dist/openai-assistants/utils/process-message-stream.mjs.map +0 -1
- package/dist/utils/fetch-chat-completion.d.ts +0 -36
- package/dist/utils/fetch-chat-completion.js +0 -141
- package/dist/utils/fetch-chat-completion.js.map +0 -1
- package/dist/utils/fetch-chat-completion.mjs +0 -12
- package/dist/utils/fetch-chat-completion.mjs.map +0 -1
- package/src/openai-assistants/hooks/index.ts +0 -9
- package/src/openai-assistants/hooks/use-assistants.ts +0 -112
- package/src/openai-assistants/hooks/use-copilot-chat-v2.ts +0 -189
- package/src/openai-assistants/index.ts +0 -2
- package/src/openai-assistants/utils/index.ts +0 -1
- package/src/openai-assistants/utils/process-message-stream.ts +0 -25
- package/src/utils/fetch-chat-completion.ts +0 -120
- /package/dist/{chunk-S5LWO5V3.mjs.map → chunk-7GPIOOXB.mjs.map} +0 -0
- /package/dist/{chunk-B244LK6F.mjs.map → chunk-QNJQKKD4.mjs.map} +0 -0
- /package/dist/{chunk-7GFKOIO7.mjs.map → chunk-YJLRG5U3.mjs.map} +0 -0
- /package/dist/{chunk-MNZXQ6UH.mjs.map → chunk-YM2JV2YQ.mjs.map} +0 -0
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import {
|
|
2
|
+
__async,
|
|
3
|
+
__spreadValues
|
|
4
|
+
} from "./chunk-SKC7AJIV.mjs";
|
|
5
|
+
|
|
6
|
+
// src/hooks/use-chat.ts
|
|
7
|
+
import { useRef } from "react";
|
|
8
|
+
import {
|
|
9
|
+
COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,
|
|
10
|
+
actionParametersToJsonSchema
|
|
11
|
+
} from "@copilotkit/shared";
|
|
12
|
+
import {
|
|
13
|
+
TextMessage,
|
|
14
|
+
ActionExecutionMessage,
|
|
15
|
+
ResultMessage,
|
|
16
|
+
CopilotRuntimeClient,
|
|
17
|
+
convertMessagesToGqlInput,
|
|
18
|
+
convertGqlOutputToMessages,
|
|
19
|
+
MessageStatusCode,
|
|
20
|
+
MessageRole,
|
|
21
|
+
Role
|
|
22
|
+
} from "@copilotkit/runtime-client-gql";
|
|
23
|
+
function useChat(options) {
|
|
24
|
+
const {
|
|
25
|
+
messages,
|
|
26
|
+
setMessages,
|
|
27
|
+
makeSystemMessageCallback,
|
|
28
|
+
copilotConfig,
|
|
29
|
+
setIsLoading,
|
|
30
|
+
initialMessages,
|
|
31
|
+
isLoading,
|
|
32
|
+
actions,
|
|
33
|
+
onFunctionCall
|
|
34
|
+
} = options;
|
|
35
|
+
const abortControllerRef = useRef();
|
|
36
|
+
const threadIdRef = useRef(null);
|
|
37
|
+
const runIdRef = useRef(null);
|
|
38
|
+
const publicApiKey = copilotConfig.publicApiKey;
|
|
39
|
+
const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
|
|
40
|
+
const runtimeClient = new CopilotRuntimeClient({
|
|
41
|
+
url: copilotConfig.chatApiEndpoint,
|
|
42
|
+
publicApiKey: copilotConfig.publicApiKey,
|
|
43
|
+
headers
|
|
44
|
+
});
|
|
45
|
+
const runChatCompletion = (previousMessages) => __async(this, null, function* () {
|
|
46
|
+
var _a, _b, _c, _d, _e, _f;
|
|
47
|
+
setIsLoading(true);
|
|
48
|
+
let newMessages = [
|
|
49
|
+
new TextMessage({
|
|
50
|
+
content: "",
|
|
51
|
+
role: Role.Assistant
|
|
52
|
+
})
|
|
53
|
+
];
|
|
54
|
+
const abortController = new AbortController();
|
|
55
|
+
abortControllerRef.current = abortController;
|
|
56
|
+
setMessages([...previousMessages, ...newMessages]);
|
|
57
|
+
const systemMessage = makeSystemMessageCallback();
|
|
58
|
+
const messagesWithContext = [systemMessage, ...initialMessages || [], ...previousMessages];
|
|
59
|
+
const stream = CopilotRuntimeClient.asStream(
|
|
60
|
+
runtimeClient.generateCopilotResponse(
|
|
61
|
+
__spreadValues({
|
|
62
|
+
frontend: {
|
|
63
|
+
actions: actions.map((action) => ({
|
|
64
|
+
name: action.name,
|
|
65
|
+
description: action.description || "",
|
|
66
|
+
jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || []))
|
|
67
|
+
}))
|
|
68
|
+
},
|
|
69
|
+
threadId: threadIdRef.current,
|
|
70
|
+
runId: runIdRef.current,
|
|
71
|
+
messages: convertMessagesToGqlInput(messagesWithContext)
|
|
72
|
+
}, copilotConfig.cloud ? {
|
|
73
|
+
cloud: {
|
|
74
|
+
guardrails: {
|
|
75
|
+
inputValidationRules: {
|
|
76
|
+
allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,
|
|
77
|
+
denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
} : {}),
|
|
82
|
+
copilotConfig.properties,
|
|
83
|
+
(_a = abortControllerRef.current) == null ? void 0 : _a.signal
|
|
84
|
+
)
|
|
85
|
+
);
|
|
86
|
+
const guardrailsEnabled = ((_d = (_c = (_b = copilotConfig.cloud) == null ? void 0 : _b.guardrails) == null ? void 0 : _c.input) == null ? void 0 : _d.restrictToTopic.enabled) || false;
|
|
87
|
+
const reader = stream.getReader();
|
|
88
|
+
let results = {};
|
|
89
|
+
try {
|
|
90
|
+
while (true) {
|
|
91
|
+
const { done, value } = yield reader.read();
|
|
92
|
+
if (done) {
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
if (!(value == null ? void 0 : value.generateCopilotResponse)) {
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
threadIdRef.current = value.generateCopilotResponse.threadId || null;
|
|
99
|
+
runIdRef.current = value.generateCopilotResponse.runId || null;
|
|
100
|
+
const messages2 = convertGqlOutputToMessages(value.generateCopilotResponse.messages);
|
|
101
|
+
if (messages2.length === 0) {
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
newMessages = [];
|
|
105
|
+
if (((_e = value.generateCopilotResponse.status) == null ? void 0 : _e.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
|
|
106
|
+
newMessages = [
|
|
107
|
+
new TextMessage({
|
|
108
|
+
role: MessageRole.Assistant,
|
|
109
|
+
content: ((_f = value.generateCopilotResponse.status.details) == null ? void 0 : _f.guardrailsReason) || ""
|
|
110
|
+
})
|
|
111
|
+
];
|
|
112
|
+
} else {
|
|
113
|
+
for (const message of messages2) {
|
|
114
|
+
newMessages.push(message);
|
|
115
|
+
if (message instanceof ActionExecutionMessage && message.status.code !== MessageStatusCode.Pending && message.scope === "client" && onFunctionCall) {
|
|
116
|
+
if (!(message.id in results)) {
|
|
117
|
+
if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
|
|
118
|
+
break;
|
|
119
|
+
}
|
|
120
|
+
const result = yield onFunctionCall({
|
|
121
|
+
messages: previousMessages,
|
|
122
|
+
name: message.name,
|
|
123
|
+
args: message.arguments
|
|
124
|
+
});
|
|
125
|
+
results[message.id] = result;
|
|
126
|
+
}
|
|
127
|
+
newMessages.push(
|
|
128
|
+
new ResultMessage({
|
|
129
|
+
result: ResultMessage.encodeResult(results[message.id]),
|
|
130
|
+
actionExecutionId: message.id,
|
|
131
|
+
actionName: message.name
|
|
132
|
+
})
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (newMessages.length > 0) {
|
|
138
|
+
setMessages([...previousMessages, ...newMessages]);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (
|
|
142
|
+
// if we have client side results
|
|
143
|
+
Object.values(results).length || // or the last message we received is a result
|
|
144
|
+
newMessages.length && newMessages[newMessages.length - 1] instanceof ResultMessage
|
|
145
|
+
) {
|
|
146
|
+
yield new Promise((resolve) => setTimeout(resolve, 10));
|
|
147
|
+
return yield runChatCompletion([...previousMessages, ...newMessages]);
|
|
148
|
+
} else {
|
|
149
|
+
return newMessages.slice();
|
|
150
|
+
}
|
|
151
|
+
} finally {
|
|
152
|
+
setIsLoading(false);
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
const runChatCompletionAndHandleFunctionCall = (messages2) => __async(this, null, function* () {
|
|
156
|
+
yield runChatCompletion(messages2);
|
|
157
|
+
});
|
|
158
|
+
const append = (message) => __async(this, null, function* () {
|
|
159
|
+
if (isLoading) {
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
const newMessages = [...messages, message];
|
|
163
|
+
setMessages(newMessages);
|
|
164
|
+
return runChatCompletionAndHandleFunctionCall(newMessages);
|
|
165
|
+
});
|
|
166
|
+
const reload = () => __async(this, null, function* () {
|
|
167
|
+
if (isLoading || messages.length === 0) {
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
let newMessages = [...messages];
|
|
171
|
+
const lastMessage = messages[messages.length - 1];
|
|
172
|
+
if (lastMessage instanceof TextMessage && lastMessage.role === "assistant") {
|
|
173
|
+
newMessages = newMessages.slice(0, -1);
|
|
174
|
+
}
|
|
175
|
+
setMessages(newMessages);
|
|
176
|
+
return runChatCompletionAndHandleFunctionCall(newMessages);
|
|
177
|
+
});
|
|
178
|
+
const stop = () => {
|
|
179
|
+
var _a;
|
|
180
|
+
(_a = abortControllerRef.current) == null ? void 0 : _a.abort();
|
|
181
|
+
};
|
|
182
|
+
return {
|
|
183
|
+
append,
|
|
184
|
+
reload,
|
|
185
|
+
stop
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export {
|
|
190
|
+
useChat
|
|
191
|
+
};
|
|
192
|
+
//# sourceMappingURL=chunk-PHMHNAYC.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 Action,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport {\n Message,\n TextMessage,\n ActionExecutionMessage,\n ResultMessage,\n CopilotRuntimeClient,\n convertMessagesToGqlInput,\n convertGqlOutputToMessages,\n MessageStatusCode,\n MessageRole,\n Role,\n} from \"@copilotkit/runtime-client-gql\";\n\nimport { CopilotApiConfig } from \"../context\";\n\nexport type UseChatOptions = {\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n /**\n * Callback function to be called when a function call is received.\n * If the function returns a `ChatRequest` object, the request will be sent\n * automatically to the API and will be used to update the chat.\n */\n onFunctionCall?: FunctionCallHandler;\n /**\n * Function definitions to be sent to the API.\n */\n actions: Action[];\n\n /**\n * The CopilotKit API configuration.\n */\n copilotConfig: CopilotApiConfig;\n\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * A callback to get the latest system message.\n */\n makeSystemMessageCallback: () => TextMessage;\n\n /**\n * Whether the API request is in progress\n */\n isLoading: boolean;\n\n /**\n * setState-powered method to update the isChatLoading value\n */\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: () => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n};\n\nexport function useChat(options: UseChatOptions): UseChatHelpers {\n const {\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n } = options;\n const abortControllerRef = useRef<AbortController>();\n const threadIdRef = useRef<string | null>(null);\n const runIdRef = useRef<string | null>(null);\n const publicApiKey = copilotConfig.publicApiKey;\n const headers = {\n ...(copilotConfig.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const runtimeClient = new CopilotRuntimeClient({\n url: copilotConfig.chatApiEndpoint,\n publicApiKey: copilotConfig.publicApiKey,\n headers,\n });\n\n const runChatCompletion = async (previousMessages: Message[]): Promise<Message[]> => {\n setIsLoading(true);\n\n // this message is just a placeholder. It will disappear once the first real message\n // is received\n let newMessages: Message[] = [\n new TextMessage({\n content: \"\",\n role: Role.Assistant,\n }),\n ];\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setMessages([...previousMessages, ...newMessages]);\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(initialMessages || []), ...previousMessages];\n\n const stream = CopilotRuntimeClient.asStream(\n runtimeClient.generateCopilotResponse(\n {\n frontend: {\n actions: actions.map((action) => ({\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n })),\n },\n threadId: threadIdRef.current,\n runId: runIdRef.current,\n messages: convertMessagesToGqlInput(messagesWithContext),\n ...(copilotConfig.cloud\n ? {\n cloud: {\n guardrails: {\n inputValidationRules: {\n allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,\n denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics,\n },\n },\n },\n }\n : {}),\n },\n copilotConfig.properties,\n abortControllerRef.current?.signal,\n ),\n );\n\n const guardrailsEnabled =\n copilotConfig.cloud?.guardrails?.input?.restrictToTopic.enabled || false;\n\n const reader = stream.getReader();\n\n let results: { [id: string]: string } = {};\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n if (!value?.generateCopilotResponse) {\n continue;\n }\n\n threadIdRef.current = value.generateCopilotResponse.threadId || null;\n runIdRef.current = value.generateCopilotResponse.runId || null;\n\n const messages = convertGqlOutputToMessages(value.generateCopilotResponse.messages);\n\n if (messages.length === 0) {\n continue;\n }\n\n newMessages = [];\n\n // request failed, display error message\n if (\n value.generateCopilotResponse.status?.__typename === \"FailedResponseStatus\" &&\n value.generateCopilotResponse.status.reason === \"GUARDRAILS_VALIDATION_FAILED\"\n ) {\n newMessages = [\n new TextMessage({\n role: MessageRole.Assistant,\n content: value.generateCopilotResponse.status.details?.guardrailsReason || \"\",\n }),\n ];\n }\n\n // add messages to the chat\n else {\n for (const message of messages) {\n newMessages.push(message);\n\n if (\n message instanceof ActionExecutionMessage &&\n message.status.code !== MessageStatusCode.Pending &&\n message.scope === \"client\" &&\n onFunctionCall\n ) {\n if (!(message.id in results)) {\n // Do not execute a function call if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute action\n const result = await onFunctionCall({\n messages: previousMessages,\n name: message.name,\n args: message.arguments,\n });\n results[message.id] = result;\n }\n\n // add the result message\n newMessages.push(\n new ResultMessage({\n result: ResultMessage.encodeResult(results[message.id]),\n actionExecutionId: message.id,\n actionName: message.name,\n }),\n );\n }\n }\n }\n\n if (newMessages.length > 0) {\n setMessages([...previousMessages, ...newMessages]);\n }\n }\n\n if (\n // if we have client side results\n Object.values(results).length ||\n // or the last message we received is a result\n (newMessages.length && newMessages[newMessages.length - 1] instanceof ResultMessage)\n ) {\n // run the completion again and return the result\n\n // wait for next tick to make sure all the react state updates\n // - tried using react-dom's flushSync, but it did not work\n await new Promise((resolve) => setTimeout(resolve, 10));\n\n return await runChatCompletion([...previousMessages, ...newMessages]);\n } else {\n return newMessages.slice();\n }\n } finally {\n setIsLoading(false);\n }\n };\n\n const runChatCompletionAndHandleFunctionCall = async (messages: Message[]): Promise<void> => {\n await runChatCompletion(messages);\n };\n\n const append = async (message: Message): Promise<void> => {\n if (isLoading) {\n return;\n }\n const newMessages = [...messages, message];\n setMessages(newMessages);\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const reload = async (): Promise<void> => {\n if (isLoading || messages.length === 0) {\n return;\n }\n let newMessages = [...messages];\n const lastMessage = messages[messages.length - 1];\n\n if (lastMessage instanceof TextMessage && lastMessage.role === \"assistant\") {\n newMessages = newMessages.slice(0, -1);\n }\n\n setMessages(newMessages);\n\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const stop = (): void => {\n abortControllerRef.current?.abort();\n };\n\n return {\n append,\n reload,\n stop,\n };\n}\n"],"mappings":";;;;;;AAAA,SAAS,cAAc;AACvB;AAAA,EAEE;AAAA,EAEA;AAAA,OACK;AACP;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAqEA,SAAS,QAAQ,SAAyC;AAC/D,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AACJ,QAAM,qBAAqB,OAAwB;AACnD,QAAM,cAAc,OAAsB,IAAI;AAC9C,QAAM,WAAW,OAAsB,IAAI;AAC3C,QAAM,eAAe,cAAc;AACnC,QAAM,UAAU,kCACV,cAAc,WAAW,CAAC,IAC1B,eAAe,EAAE,CAAC,mCAAmC,GAAG,aAAa,IAAI,CAAC;AAGhF,QAAM,gBAAgB,IAAI,qBAAqB;AAAA,IAC7C,KAAK,cAAc;AAAA,IACnB,cAAc,cAAc;AAAA,IAC5B;AAAA,EACF,CAAC;AAED,QAAM,oBAAoB,CAAO,qBAAoD;AAlHvF;AAmHI,iBAAa,IAAI;AAIjB,QAAI,cAAyB;AAAA,MAC3B,IAAI,YAAY;AAAA,QACd,SAAS;AAAA,QACT,MAAM,KAAK;AAAA,MACb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AY,YAAY,SAAS,CAAC,aAAa;AAAA,QACtE;AAKA,cAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AAEtD,eAAO,MAAM,kBAAkB,CAAC,GAAG,kBAAkB,GAAG,WAAW,CAAC;AAAA,MACtE,OAAO;AACL,eAAO,YAAY,MAAM;AAAA,MAC3B;AAAA,IACF,UAAE;AACA,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF;AAEA,QAAM,yCAAyC,CAAOA,cAAuC;AAC3F,UAAM,kBAAkBA,SAAQ;AAAA,EAClC;AAEA,QAAM,SAAS,CAAO,YAAoC;AACxD,QAAI,WAAW;AACb;AAAA,IACF;AACA,UAAM,cAAc,CAAC,GAAG,UAAU,OAAO;AACzC,gBAAY,WAAW;AACvB,WAAO,uCAAuC,WAAW;AAAA,EAC3D;AAEA,QAAM,SAAS,MAA2B;AACxC,QAAI,aAAa,SAAS,WAAW,GAAG;AACtC;AAAA,IACF;AACA,QAAI,cAAc,CAAC,GAAG,QAAQ;AAC9B,UAAM,cAAc,SAAS,SAAS,SAAS,CAAC;AAEhD,QAAI,uBAAuB,eAAe,YAAY,SAAS,aAAa;AAC1E,oBAAc,YAAY,MAAM,GAAG,EAAE;AAAA,IACvC;AAEA,gBAAY,WAAW;AAEvB,WAAO,uCAAuC,WAAW;AAAA,EAC3D;AAEA,QAAM,OAAO,MAAY;AA5S3B;AA6SI,6BAAmB,YAAnB,mBAA4B;AAAA,EAC9B;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["messages"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
CopilotContext
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-K6EV2CNB.mjs";
|
|
4
4
|
|
|
5
5
|
// src/hooks/use-make-copilot-readable.ts
|
|
6
6
|
import { useContext, useEffect, useRef } from "react";
|
|
@@ -20,4 +20,4 @@ function useMakeCopilotReadable(information, parentId, categories) {
|
|
|
20
20
|
export {
|
|
21
21
|
useMakeCopilotReadable
|
|
22
22
|
};
|
|
23
|
-
//# sourceMappingURL=chunk-
|
|
23
|
+
//# sourceMappingURL=chunk-QNJQKKD4.mjs.map
|
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
defaultCopilotContextCategories
|
|
3
|
-
} from "./chunk-
|
|
4
|
-
import {
|
|
5
|
-
fetchAndDecodeChatCompletion
|
|
6
|
-
} from "./chunk-MJKBCG4U.mjs";
|
|
3
|
+
} from "./chunk-DDHJCFFV.mjs";
|
|
7
4
|
import {
|
|
8
5
|
__async,
|
|
9
6
|
__spreadValues
|
|
@@ -11,9 +8,17 @@ import {
|
|
|
11
8
|
|
|
12
9
|
// src/utils/extract.ts
|
|
13
10
|
import {
|
|
14
|
-
COPILOT_CLOUD_PUBLIC_API_KEY_HEADER
|
|
11
|
+
COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,
|
|
12
|
+
actionParametersToJsonSchema
|
|
15
13
|
} from "@copilotkit/shared";
|
|
16
|
-
import
|
|
14
|
+
import {
|
|
15
|
+
ActionExecutionMessage,
|
|
16
|
+
Role,
|
|
17
|
+
TextMessage,
|
|
18
|
+
convertGqlOutputToMessages
|
|
19
|
+
} from "@copilotkit/runtime-client-gql";
|
|
20
|
+
import { CopilotRuntimeClient } from "@copilotkit/runtime-client-gql";
|
|
21
|
+
import { convertMessagesToGqlInput } from "@copilotkit/runtime-client-gql";
|
|
17
22
|
function extract(_0) {
|
|
18
23
|
return __async(this, arguments, function* ({
|
|
19
24
|
context,
|
|
@@ -41,51 +46,64 @@ function extract(_0) {
|
|
|
41
46
|
if (includeReadable) {
|
|
42
47
|
contextString += context.getContextString([], defaultCopilotContextCategories);
|
|
43
48
|
}
|
|
44
|
-
const systemMessage = {
|
|
45
|
-
id: "system",
|
|
49
|
+
const systemMessage = new TextMessage({
|
|
46
50
|
content: makeSystemMessage(contextString, instructions),
|
|
47
|
-
role:
|
|
48
|
-
};
|
|
51
|
+
role: Role.System
|
|
52
|
+
});
|
|
49
53
|
const headers = __spreadValues(__spreadValues({}, context.copilotApiConfig.headers || {}), context.copilotApiConfig.publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: context.copilotApiConfig.publicApiKey } : {});
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
headers,
|
|
55
|
-
body: context.copilotApiConfig.body,
|
|
56
|
-
toolChoice: { type: "function", function: { name: "extract" } },
|
|
57
|
-
signal: abortSignal
|
|
54
|
+
const runtimeClient = new CopilotRuntimeClient({
|
|
55
|
+
url: context.copilotApiConfig.chatApiEndpoint,
|
|
56
|
+
publicApiKey: context.copilotApiConfig.publicApiKey,
|
|
57
|
+
headers
|
|
58
58
|
});
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
59
|
+
const response = CopilotRuntimeClient.asStream(
|
|
60
|
+
runtimeClient.generateCopilotResponse(
|
|
61
|
+
{
|
|
62
|
+
frontend: {
|
|
63
|
+
actions: [
|
|
64
|
+
{
|
|
65
|
+
name: action.name,
|
|
66
|
+
description: action.description || "",
|
|
67
|
+
jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || []))
|
|
68
|
+
}
|
|
69
|
+
]
|
|
70
|
+
},
|
|
71
|
+
messages: convertMessagesToGqlInput(
|
|
72
|
+
includeMessages ? [systemMessage, ...messages] : [systemMessage]
|
|
73
|
+
)
|
|
74
|
+
},
|
|
75
|
+
context.copilotApiConfig.properties,
|
|
76
|
+
abortSignal
|
|
77
|
+
)
|
|
78
|
+
);
|
|
79
|
+
const reader = response.getReader();
|
|
63
80
|
let isInitial = true;
|
|
81
|
+
let actionExecutionMessage = void 0;
|
|
64
82
|
while (true) {
|
|
65
83
|
const { done, value } = yield reader.read();
|
|
66
84
|
if (done) {
|
|
67
85
|
break;
|
|
68
86
|
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
args: partialArguments
|
|
75
|
-
});
|
|
76
|
-
isInitial = false;
|
|
77
|
-
} catch (e) {
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
if (value.type === "function") {
|
|
81
|
-
stream == null ? void 0 : stream({
|
|
82
|
-
status: "complete",
|
|
83
|
-
args: value.arguments
|
|
84
|
-
});
|
|
85
|
-
return value.arguments;
|
|
87
|
+
actionExecutionMessage = convertGqlOutputToMessages(
|
|
88
|
+
value.generateCopilotResponse.messages
|
|
89
|
+
).find((msg) => msg instanceof ActionExecutionMessage);
|
|
90
|
+
if (!actionExecutionMessage) {
|
|
91
|
+
continue;
|
|
86
92
|
}
|
|
93
|
+
stream == null ? void 0 : stream({
|
|
94
|
+
status: isInitial ? "initial" : "inProgress",
|
|
95
|
+
args: actionExecutionMessage.arguments
|
|
96
|
+
});
|
|
97
|
+
isInitial = false;
|
|
87
98
|
}
|
|
88
|
-
|
|
99
|
+
if (!actionExecutionMessage) {
|
|
100
|
+
throw new Error("extract() failed: No function call occurred");
|
|
101
|
+
}
|
|
102
|
+
stream == null ? void 0 : stream({
|
|
103
|
+
status: "complete",
|
|
104
|
+
args: actionExecutionMessage.arguments
|
|
105
|
+
});
|
|
106
|
+
return actionExecutionMessage.arguments;
|
|
89
107
|
});
|
|
90
108
|
}
|
|
91
109
|
function makeSystemMessage(contextString, instructions) {
|
|
@@ -100,7 +118,7 @@ The user has provided you with the following context:
|
|
|
100
118
|
${contextString}
|
|
101
119
|
\`\`\`
|
|
102
120
|
|
|
103
|
-
They have also provided you with a function you MUST call to initiate actions on their behalf.
|
|
121
|
+
They have also provided you with a function called extract you MUST call to initiate actions on their behalf.
|
|
104
122
|
|
|
105
123
|
Please assist them as best you can.
|
|
106
124
|
|
|
@@ -119,4 +137,4 @@ Any additional messages provided are for providing context only and should not b
|
|
|
119
137
|
export {
|
|
120
138
|
extract
|
|
121
139
|
};
|
|
122
|
-
//# sourceMappingURL=chunk-
|
|
140
|
+
//# sourceMappingURL=chunk-WU3I3G3G.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/extract.ts"],"sourcesContent":["import {\n Action,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n MappedParameterTypes,\n Parameter,\n actionParametersToJsonSchema,\n} from \"@copilotkit/shared\";\nimport {\n ActionExecutionMessage,\n Message,\n Role,\n TextMessage,\n convertGqlOutputToMessages,\n} from \"@copilotkit/runtime-client-gql\";\nimport { CopilotContextParams } from \"../context\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { CopilotRuntimeClient } from \"@copilotkit/runtime-client-gql\";\nimport { convertMessagesToGqlInput } from \"@copilotkit/runtime-client-gql\";\n\ninterface InitialState<T extends Parameter[] | [] = []> {\n status: \"initial\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface InProgressState<T extends Parameter[] | [] = []> {\n status: \"inProgress\";\n args: Partial<MappedParameterTypes<T>>;\n}\n\ninterface CompleteState<T extends Parameter[] | [] = []> {\n status: \"complete\";\n args: MappedParameterTypes<T>;\n}\n\ntype StreamHandlerArgs<T extends Parameter[] | [] = []> =\n | InitialState<T>\n | InProgressState<T>\n | CompleteState<T>;\n\ninterface ExtractOptions<T extends Parameter[]> {\n context: CopilotContextParams;\n instructions: string;\n parameters: T;\n include?: IncludeOptions;\n data?: any;\n abortSignal?: AbortSignal;\n stream?: (args: StreamHandlerArgs<T>) => void;\n}\n\ninterface IncludeOptions {\n readable?: boolean;\n messages?: boolean;\n}\n\nexport async function extract<const T extends Parameter[]>({\n context,\n instructions,\n parameters,\n include,\n data,\n abortSignal,\n stream,\n}: ExtractOptions<T>): Promise<MappedParameterTypes<T>> {\n const { messages } = context;\n\n const action: Action<any> = {\n name: \"extract\",\n parameters,\n handler: (args: any) => {},\n };\n\n const includeReadable = include?.readable ?? false;\n const includeMessages = include?.messages ?? false;\n\n let contextString = \"\";\n\n if (data) {\n contextString = (typeof data === \"string\" ? data : JSON.stringify(data)) + \"\\n\\n\";\n }\n\n if (includeReadable) {\n contextString += context.getContextString([], defaultCopilotContextCategories);\n }\n\n const systemMessage: Message = new TextMessage({\n content: makeSystemMessage(contextString, instructions),\n role: Role.System,\n });\n\n const headers = {\n ...(context.copilotApiConfig.headers || {}),\n ...(context.copilotApiConfig.publicApiKey\n ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: context.copilotApiConfig.publicApiKey }\n : {}),\n };\n\n const runtimeClient = new CopilotRuntimeClient({\n url: context.copilotApiConfig.chatApiEndpoint,\n publicApiKey: context.copilotApiConfig.publicApiKey,\n headers,\n });\n\n const response = CopilotRuntimeClient.asStream(\n runtimeClient.generateCopilotResponse(\n {\n frontend: {\n actions: [\n {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n },\n ],\n },\n\n messages: convertMessagesToGqlInput(\n includeMessages ? [systemMessage, ...messages] : [systemMessage],\n ),\n },\n context.copilotApiConfig.properties,\n abortSignal,\n ),\n );\n\n const reader = response.getReader();\n\n let isInitial = true;\n\n let actionExecutionMessage: ActionExecutionMessage | undefined = undefined;\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n actionExecutionMessage = convertGqlOutputToMessages(\n value.generateCopilotResponse.messages,\n ).find((msg) => msg instanceof ActionExecutionMessage) as ActionExecutionMessage | undefined;\n\n if (!actionExecutionMessage) {\n continue;\n }\n\n stream?.({\n status: isInitial ? \"initial\" : \"inProgress\",\n args: actionExecutionMessage.arguments as Partial<MappedParameterTypes<T>>,\n });\n\n isInitial = false;\n }\n\n if (!actionExecutionMessage) {\n throw new Error(\"extract() failed: No function call occurred\");\n }\n\n stream?.({\n status: \"complete\",\n args: actionExecutionMessage.arguments as MappedParameterTypes<T>,\n });\n\n return actionExecutionMessage.arguments as MappedParameterTypes<T>;\n}\n\nfunction makeSystemMessage(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 a function called extract you MUST 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 the function without saying anything else.\n\nThe user has given you the following task to complete:\n\n\\`\\`\\`\n${instructions}\n\\`\\`\\`\n\nAny additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.\n`;\n}\n"],"mappings":";;;;;;;;;AAAA;AAAA,EAEE;AAAA,EAGA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,SAAS,4BAA4B;AACrC,SAAS,iCAAiC;AAqC1C,SAAsB,QAAqC,IAQH;AAAA,6CARG;AAAA,IACzD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAAwD;AA9DxD;AA+DE,UAAM,EAAE,SAAS,IAAI;AAErB,UAAM,SAAsB;AAAA,MAC1B,MAAM;AAAA,MACN;AAAA,MACA,SAAS,CAAC,SAAc;AAAA,MAAC;AAAA,IAC3B;AAEA,UAAM,mBAAkB,wCAAS,aAAT,YAAqB;AAC7C,UAAM,mBAAkB,wCAAS,aAAT,YAAqB;AAE7C,QAAI,gBAAgB;AAEpB,QAAI,MAAM;AACR,uBAAiB,OAAO,SAAS,WAAW,OAAO,KAAK,UAAU,IAAI,KAAK;AAAA,IAC7E;AAEA,QAAI,iBAAiB;AACnB,uBAAiB,QAAQ,iBAAiB,CAAC,GAAG,+BAA+B;AAAA,IAC/E;AAEA,UAAM,gBAAyB,IAAI,YAAY;AAAA,MAC7C,SAAS,kBAAkB,eAAe,YAAY;AAAA,MACtD,MAAM,KAAK;AAAA,IACb,C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ACR,MAAM,uBAAuB;AAAA,IAC/B;AAEA,WAAO,uBAAuB;AAAA,EAChC;AAAA;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;AAAA;AAAA;AAKF;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
//# sourceMappingURL=chunk-YJLRG5U3.mjs.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
CopilotContext
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-K6EV2CNB.mjs";
|
|
4
4
|
|
|
5
5
|
// src/hooks/use-copilot-readable.ts
|
|
6
6
|
import { useContext, useEffect, useRef } from "react";
|
|
@@ -25,4 +25,4 @@ function useCopilotReadable({ description, value, parentId, categories, convert
|
|
|
25
25
|
export {
|
|
26
26
|
useCopilotReadable
|
|
27
27
|
};
|
|
28
|
-
//# sourceMappingURL=chunk-
|
|
28
|
+
//# sourceMappingURL=chunk-YM2JV2YQ.mjs.map
|
|
@@ -57,7 +57,7 @@ interface CopilotKitProps {
|
|
|
57
57
|
*/
|
|
58
58
|
children: ReactNode;
|
|
59
59
|
/**
|
|
60
|
-
*
|
|
60
|
+
* Custom properties to be sent with the request
|
|
61
61
|
* For example:
|
|
62
62
|
* ```js
|
|
63
63
|
* {
|
|
@@ -65,7 +65,7 @@ interface CopilotKitProps {
|
|
|
65
65
|
* }
|
|
66
66
|
* ```
|
|
67
67
|
*/
|
|
68
|
-
|
|
68
|
+
properties?: Record<string, any>;
|
|
69
69
|
/**
|
|
70
70
|
* Indicates whether the user agent should send or receive cookies from the other domain
|
|
71
71
|
* in the case of cross-origin requests.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/components/copilot-provider/copilotkit-props.tsx"],"sourcesContent":["import { ReactNode } from \"react\";\n\n/**\n * Props for CopilotKit.\n */\n\nexport interface CopilotKitProps {\n /**\n * Your Copilot Cloud API key.\n */\n publicApiKey?: string;\n\n /**\n * Cloud feature: Restrict input to a specific topic.\n */\n cloudRestrictToTopic?: {\n validTopics?: string[];\n invalidTopics?: string[];\n };\n\n /**\n * the endpoint for the Copilot Runtime instance.\n */\n runtimeUrl?: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * @deprecated use runtimeUrl instead\n */\n url?: string;\n\n /**\n * Additional headers to be sent with the request.\n *\n * For example:\n * ```js\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 * For example:\n * ```js\n * {\n * 'message': 'Hello, world!'\n * }\n * ```\n */\n body?: Record<string, any>;\n\n /**\n * The children to be rendered within the CopilotKit.\n */\n children: ReactNode;\n\n /**\n *
|
|
1
|
+
{"version":3,"sources":["../../../src/components/copilot-provider/copilotkit-props.tsx"],"sourcesContent":["import { ReactNode } from \"react\";\n\n/**\n * Props for CopilotKit.\n */\n\nexport interface CopilotKitProps {\n /**\n * Your Copilot Cloud API key.\n */\n publicApiKey?: string;\n\n /**\n * Cloud feature: Restrict input to a specific topic.\n */\n cloudRestrictToTopic?: {\n validTopics?: string[];\n invalidTopics?: string[];\n };\n\n /**\n * the endpoint for the Copilot Runtime instance.\n */\n runtimeUrl?: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * @deprecated use runtimeUrl instead\n */\n url?: string;\n\n /**\n * Additional headers to be sent with the request.\n *\n * For example:\n * ```js\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 * For example:\n * ```js\n * {\n * 'message': 'Hello, world!'\n * }\n * ```\n */\n body?: Record<string, any>;\n\n /**\n * The children to be rendered within the CopilotKit.\n */\n children: ReactNode;\n\n /**\n * Custom properties to be sent with the request\n * For example:\n * ```js\n * {\n * 'user_id': 'users_id',\n * }\n * ```\n */\n properties?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
|
|
@@ -89,17 +89,16 @@ var import_react4 = require("react");
|
|
|
89
89
|
// src/context/copilot-context.tsx
|
|
90
90
|
var import_react = __toESM(require("react"));
|
|
91
91
|
var emptyCopilotContext = {
|
|
92
|
-
|
|
93
|
-
|
|
92
|
+
actions: {},
|
|
93
|
+
setAction: () => {
|
|
94
94
|
},
|
|
95
|
-
|
|
95
|
+
removeAction: () => {
|
|
96
96
|
},
|
|
97
97
|
chatComponentsCache: { current: {} },
|
|
98
98
|
getContextString: (documents, categories) => returnAndThrowInDebug(""),
|
|
99
99
|
addContext: () => "",
|
|
100
100
|
removeContext: () => {
|
|
101
101
|
},
|
|
102
|
-
getChatCompletionFunctionDescriptions: () => returnAndThrowInDebug([]),
|
|
103
102
|
getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
|
|
104
103
|
})),
|
|
105
104
|
messages: [],
|
|
@@ -347,7 +346,7 @@ function CopilotKit(_a) {
|
|
|
347
346
|
throw new Error("Please provide either a url or a publicApiKey to the CopilotKit component.");
|
|
348
347
|
}
|
|
349
348
|
const chatApiEndpoint = props.runtimeUrl || props.url || import_shared.COPILOT_CLOUD_CHAT_URL;
|
|
350
|
-
const [
|
|
349
|
+
const [actions, setActions] = (0, import_react4.useState)({});
|
|
351
350
|
const chatComponentsCache = (0, import_react4.useRef)({});
|
|
352
351
|
const { addElement, removeElement, printTree } = use_tree_default();
|
|
353
352
|
const [messages, setMessages] = (0, import_react4.useState)([]);
|
|
@@ -358,15 +357,15 @@ function CopilotKit(_a) {
|
|
|
358
357
|
removeElement: removeDocument,
|
|
359
358
|
allElements: allDocuments
|
|
360
359
|
} = use_flat_category_store_default();
|
|
361
|
-
const
|
|
362
|
-
|
|
360
|
+
const setAction = (0, import_react4.useCallback)((id, action) => {
|
|
361
|
+
setActions((prevPoints) => {
|
|
363
362
|
return __spreadProps(__spreadValues({}, prevPoints), {
|
|
364
|
-
[id]:
|
|
363
|
+
[id]: action
|
|
365
364
|
});
|
|
366
365
|
});
|
|
367
366
|
}, []);
|
|
368
|
-
const
|
|
369
|
-
|
|
367
|
+
const removeAction = (0, import_react4.useCallback)((id) => {
|
|
368
|
+
setActions((prevPoints) => {
|
|
370
369
|
const newPoints = __spreadValues({}, prevPoints);
|
|
371
370
|
delete newPoints[id];
|
|
372
371
|
return newPoints;
|
|
@@ -397,17 +396,11 @@ ${nonDocumentStrings}`;
|
|
|
397
396
|
},
|
|
398
397
|
[removeElement]
|
|
399
398
|
);
|
|
400
|
-
const getChatCompletionFunctionDescriptions = (0, import_react4.useCallback)(
|
|
401
|
-
(customEntryPoints) => {
|
|
402
|
-
return entryPointsToChatCompletionFunctions(Object.values(customEntryPoints || entryPoints));
|
|
403
|
-
},
|
|
404
|
-
[entryPoints]
|
|
405
|
-
);
|
|
406
399
|
const getFunctionCallHandler = (0, import_react4.useCallback)(
|
|
407
400
|
(customEntryPoints) => {
|
|
408
|
-
return entryPointsToFunctionCallHandler(Object.values(customEntryPoints ||
|
|
401
|
+
return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));
|
|
409
402
|
},
|
|
410
|
-
[
|
|
403
|
+
[actions]
|
|
411
404
|
);
|
|
412
405
|
const getDocumentsContext = (0, import_react4.useCallback)(
|
|
413
406
|
(categories) => {
|
|
@@ -454,7 +447,7 @@ ${nonDocumentStrings}`;
|
|
|
454
447
|
chatApiEndpoint,
|
|
455
448
|
chatApiEndpointV2: `${props.url}/v2`,
|
|
456
449
|
headers: props.headers || {},
|
|
457
|
-
|
|
450
|
+
properties: props.properties || {},
|
|
458
451
|
transcribeAudioUrl: props.transcribeAudioUrl,
|
|
459
452
|
textToSpeechUrl: props.textToSpeechUrl,
|
|
460
453
|
credentials: props.credentials
|
|
@@ -473,12 +466,11 @@ ${nonDocumentStrings}`;
|
|
|
473
466
|
CopilotContext.Provider,
|
|
474
467
|
{
|
|
475
468
|
value: {
|
|
476
|
-
|
|
469
|
+
actions,
|
|
477
470
|
chatComponentsCache,
|
|
478
|
-
getChatCompletionFunctionDescriptions,
|
|
479
471
|
getFunctionCallHandler,
|
|
480
|
-
|
|
481
|
-
|
|
472
|
+
setAction,
|
|
473
|
+
removeAction,
|
|
482
474
|
getContextString,
|
|
483
475
|
addContext,
|
|
484
476
|
removeContext,
|
|
@@ -501,22 +493,15 @@ ${nonDocumentStrings}`;
|
|
|
501
493
|
);
|
|
502
494
|
}
|
|
503
495
|
var defaultCopilotContextCategories = ["global"];
|
|
504
|
-
function entryPointsToChatCompletionFunctions(actions) {
|
|
505
|
-
return actions.map(import_shared.actionToChatCompletionFunction);
|
|
506
|
-
}
|
|
507
496
|
function entryPointsToFunctionCallHandler(actions) {
|
|
508
|
-
return (
|
|
497
|
+
return (_0) => __async(this, [_0], function* ({ messages, name, args }) {
|
|
509
498
|
let actionsByFunctionName = {};
|
|
510
499
|
for (let action2 of actions) {
|
|
511
500
|
actionsByFunctionName[action2.name] = action2;
|
|
512
501
|
}
|
|
513
|
-
const action = actionsByFunctionName[
|
|
502
|
+
const action = actionsByFunctionName[name];
|
|
514
503
|
if (action) {
|
|
515
|
-
|
|
516
|
-
if (functionCall.arguments) {
|
|
517
|
-
functionCallArguments = JSON.parse(functionCall.arguments);
|
|
518
|
-
}
|
|
519
|
-
return yield action.handler(functionCallArguments);
|
|
504
|
+
return yield action.handler(args);
|
|
520
505
|
}
|
|
521
506
|
});
|
|
522
507
|
}
|