forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopilot-context.tsx
More file actions
365 lines (313 loc) · 10.1 KB
/
Copy pathcopilot-context.tsx
File metadata and controls
365 lines (313 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
import {
CopilotCloudConfig,
FunctionCallHandler,
CopilotErrorHandler,
CopilotKitError,
} from "@copilotkit/shared";
import {
ActionRenderProps,
CatchAllActionRenderProps,
FrontendAction,
} from "../types/frontend-action";
import React from "react";
import { TreeNodeId, Tree } from "../hooks/use-tree";
import { DocumentPointer } from "../types";
import { CopilotChatSuggestionConfiguration } from "../types/chat-suggestion-configuration";
import {
CoAgentStateRender,
CoAgentStateRenderProps,
} from "../types/coagent-action";
import { CoagentState } from "../types/coagent-state";
import {
CopilotRuntimeClient,
ExtensionsInput,
ForwardedParametersInput,
} from "@copilotkit/runtime-client-gql";
import { Agent } from "@copilotkit/runtime-client-gql";
import {
LangGraphInterruptRender,
LangGraphInterruptActionSetter,
QueuedInterruptEvent,
} from "../types/interrupt-action";
/**
* Interface for the configuration of the Copilot API.
*/
export interface CopilotApiConfig {
/**
* The public API key for Copilot Cloud.
*/
publicApiKey?: string;
/**
* The configuration for Copilot Cloud.
*/
cloud?: CopilotCloudConfig;
/**
* The endpoint for the chat API.
*/
chatApiEndpoint: string;
/**
* The endpoint for the Copilot transcribe audio service.
*/
transcribeAudioUrl?: string;
/**
* The endpoint for the Copilot text to speech service.
*/
textToSpeechUrl?: string;
/**
* additional headers to be sent with the request
* @default {}
* @example
* ```
* {
* 'Authorization': 'Bearer your_token_here'
* }
* ```
*/
headers: Record<string, string>;
/**
* Custom properties to be sent with the request
* @default {}
* @example
* ```
* {
* 'user_id': 'user_id'
* }
* ```
*/
properties?: Record<string, any>;
/**
* Indicates whether the user agent should send or receive cookies from the other domain
* in the case of cross-origin requests.
*/
credentials?: RequestCredentials;
/**
* Optional configuration for connecting to Model Context Protocol (MCP) servers.
* This is typically derived from the CopilotKitProps and used internally.
* @experimental
*/
mcpServers?: Array<{ endpoint: string; apiKey?: string }>;
}
export type InChatRenderFunction<
TProps = ActionRenderProps<any> | CatchAllActionRenderProps<any>,
> = (props: TProps) => string | React.JSX.Element;
export type CoagentInChatRenderFunction = (
props: CoAgentStateRenderProps<any>,
) => string | React.JSX.Element | undefined | null;
export interface ChatComponentsCache {
actions: Record<string, InChatRenderFunction | string>;
coAgentStateRenders: Record<string, CoagentInChatRenderFunction | string>;
}
export interface AgentSession {
agentName: string;
threadId?: string;
nodeName?: string;
}
export interface AuthState {
status: "authenticated" | "unauthenticated";
authHeaders: Record<string, string>;
userId?: string;
metadata?: Record<string, any>;
}
export type ActionName = string;
export type ContextTree = Tree;
export interface CopilotContextParams {
// function-calling
actions: Record<string, FrontendAction<any>>;
setAction: (id: string, action: FrontendAction<any>) => void;
removeAction: (id: string) => void;
// registered actions for component-based rendering
setRegisteredActions: (actionConfig: any) => string;
removeRegisteredAction: (actionKey: string) => void;
chatComponentsCache: React.RefObject<ChatComponentsCache>;
getFunctionCallHandler: (
customEntryPoints?: Record<string, FrontendAction<any>>,
) => FunctionCallHandler;
// text context
addContext: (
context: string,
parentId?: string,
categories?: string[],
) => TreeNodeId;
removeContext: (id: TreeNodeId) => void;
getAllContext: () => Tree;
getContextString: (
documents: DocumentPointer[],
categories: string[],
) => string;
// document context
addDocumentContext: (
documentPointer: DocumentPointer,
categories?: string[],
) => TreeNodeId;
removeDocumentContext: (documentId: string) => void;
getDocumentsContext: (categories: string[]) => DocumentPointer[];
isLoading: boolean;
setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;
chatSuggestionConfiguration: {
[key: string]: CopilotChatSuggestionConfiguration;
};
addChatSuggestionConfiguration: (
id: string,
suggestion: CopilotChatSuggestionConfiguration,
) => void;
removeChatSuggestionConfiguration: (id: string) => void;
chatInstructions: string;
setChatInstructions: React.Dispatch<React.SetStateAction<string>>;
additionalInstructions?: string[];
setAdditionalInstructions: React.Dispatch<React.SetStateAction<string[]>>;
// api endpoints
copilotApiConfig: CopilotApiConfig;
showDevConsole: boolean;
// agents
coagentStates: Record<string, CoagentState>;
setCoagentStates: React.Dispatch<
React.SetStateAction<Record<string, CoagentState>>
>;
coagentStatesRef: React.RefObject<Record<string, CoagentState>>;
setCoagentStatesWithRef: (
value:
| Record<string, CoagentState>
| ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),
) => void;
agentSession: AgentSession | null;
setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;
agentLock: string | null;
threadId: string;
setThreadId: React.Dispatch<React.SetStateAction<string>>;
runId: string | null;
setRunId: React.Dispatch<React.SetStateAction<string | null>>;
// The chat abort controller can be used to stop generation globally,
// i.e. when using `stop()` from `useChat`
chatAbortControllerRef: React.MutableRefObject<AbortController | null>;
/**
* The forwarded parameters to use for the task.
*/
forwardedParameters?: Partial<Pick<ForwardedParametersInput, "temperature">>;
availableAgents: Agent[];
/**
* The auth states for the CopilotKit.
*/
authStates_c?: Record<ActionName, AuthState>;
setAuthStates_c?: React.Dispatch<
React.SetStateAction<Record<ActionName, AuthState>>
>;
/**
* The auth config for the CopilotKit.
*/
authConfig_c?: {
SignInComponent: React.ComponentType<{
onSignInComplete: (authState: AuthState) => void;
}>;
};
extensions: ExtensionsInput;
setExtensions: React.Dispatch<React.SetStateAction<ExtensionsInput>>;
interruptActions: Record<string, LangGraphInterruptRender>;
setInterruptAction: LangGraphInterruptActionSetter;
removeInterruptAction: (actionId: string) => void;
interruptEventQueue: Record<string, QueuedInterruptEvent[]>;
addInterruptEvent: (queuedEvent: QueuedInterruptEvent) => void;
resolveInterruptEvent: (
threadId: string,
eventId: string,
response: string,
) => void;
/**
* Optional trace handler for comprehensive debugging and observability.
*/
onError: CopilotErrorHandler;
// banner error state
bannerError: CopilotKitError | null;
setBannerError: React.Dispatch<React.SetStateAction<CopilotKitError | null>>;
// Internal error handlers
// These are used to handle errors that occur during the execution of the chat.
// They are not intended for use by the developer. A component can register itself an error listener to be activated somewhere else as needed
internalErrorHandlers: Record<string, CopilotErrorHandler>;
setInternalErrorHandler: (
handler: Record<string, CopilotErrorHandler>,
) => void;
removeInternalErrorHandler: (id: string) => void;
}
const emptyCopilotContext: CopilotContextParams = {
actions: {},
setAction: () => {},
removeAction: () => {},
setRegisteredActions: () => "",
removeRegisteredAction: () => {},
chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },
getContextString: (documents: DocumentPointer[], categories: string[]) =>
returnAndThrowInDebug(""),
addContext: () => "",
removeContext: () => {},
getAllContext: () => [],
getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),
isLoading: false,
setIsLoading: () => returnAndThrowInDebug(false),
chatInstructions: "",
setChatInstructions: () => returnAndThrowInDebug(""),
additionalInstructions: [],
setAdditionalInstructions: () => returnAndThrowInDebug([]),
getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),
addDocumentContext: () => returnAndThrowInDebug(""),
removeDocumentContext: () => {},
copilotApiConfig: new (class implements CopilotApiConfig {
get chatApiEndpoint(): string {
throw new Error(
"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!",
);
}
get headers(): Record<string, string> {
return {};
}
get body(): Record<string, any> {
return {};
}
})(),
chatSuggestionConfiguration: {},
addChatSuggestionConfiguration: () => {},
removeChatSuggestionConfiguration: () => {},
showDevConsole: false,
coagentStates: {},
setCoagentStates: () => {},
coagentStatesRef: { current: {} },
setCoagentStatesWithRef: () => {},
agentSession: null,
setAgentSession: () => {},
forwardedParameters: {},
agentLock: null,
threadId: "",
setThreadId: () => {},
runId: null,
setRunId: () => {},
chatAbortControllerRef: { current: null },
availableAgents: [],
extensions: {},
setExtensions: () => {},
interruptActions: {},
setInterruptAction: () => {},
removeInterruptAction: () => {},
interruptEventQueue: {},
addInterruptEvent: () => {},
resolveInterruptEvent: () => {},
onError: () => {},
bannerError: null,
setBannerError: () => {},
internalErrorHandlers: {},
setInternalErrorHandler: () => {},
removeInternalErrorHandler: () => {},
};
export const CopilotContext =
React.createContext<CopilotContextParams>(emptyCopilotContext);
export function useCopilotContext(): CopilotContextParams {
const context = React.useContext(CopilotContext);
if (context === emptyCopilotContext) {
throw new Error(
"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!",
);
}
return context;
}
function returnAndThrowInDebug<T>(_value: T): T {
throw new Error(
"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!",
);
}