forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-copilot-chat_internal.ts
More file actions
875 lines (784 loc) · 25.3 KB
/
Copy pathuse-copilot-chat_internal.ts
File metadata and controls
875 lines (784 loc) · 25.3 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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
import React, {
useRef,
useEffect,
useCallback,
useMemo,
useState,
createElement,
} from "react";
import { useCopilotContext } from "../context/copilot-context";
import { SystemMessageFunction } from "../types";
import { useAsyncCallback } from "../components/error-boundary/error-utils";
import { Message } from "@copilotkit/shared";
import {
gqlToAGUI,
Message as DeprecatedGqlMessage,
} from "@copilotkit/runtime-client-gql";
import {
useAgent,
useCopilotChatConfiguration,
useCopilotKit,
useRenderCustomMessages,
useSuggestions,
} from "../v2";
import {
Suggestion,
CopilotKitCoreRuntimeConnectionStatus,
} from "@copilotkit/core";
import { useLazyToolRenderer } from "./use-lazy-tool-renderer";
import {
AbstractAgent,
AGUIConnectNotImplementedError,
HttpAgent,
} from "@ag-ui/client";
import {
CoAgentStateRenderBridge,
type CoAgentStateRenderBridgeProps,
} from "./use-coagent-state-render-bridge";
/**
* The type of suggestions to use in the chat.
*
* `auto` - Suggestions are generated automatically.
* `manual` - Suggestions are controlled programmatically.
* `SuggestionItem[]` - Static suggestions array.
*/
export type ChatSuggestions =
| "auto"
| "manual"
| Omit<Suggestion, "isLoading">[];
export interface AppendMessageOptions {
/**
* Whether to run the chat completion after appending the message. Defaults to `true`.
*/
followUp?: boolean;
/**
* Whether to clear the suggestions after appending the message. Defaults to `true`.
*/
clearSuggestions?: boolean;
}
export interface OnStopGenerationArguments {
/**
* The name of the currently executing agent.
*/
currentAgentName: string | undefined;
/**
* The messages in the chat.
*/
messages: Message[];
}
export type OnReloadMessagesArguments = OnStopGenerationArguments & {
/**
* The message on which "regenerate" was pressed
*/
messageId: string;
};
export type OnStopGeneration = (args: OnStopGenerationArguments) => void;
export type OnReloadMessages = (args: OnReloadMessagesArguments) => void;
export interface UseCopilotChatOptions {
/**
* A unique identifier for the chat. If not provided, a random one will be
* generated. When provided, the `useChat` hook with the same `id` will
* have shared states across components.
*/
id?: string;
/**
* HTTP headers to be sent with the API request.
*/
headers?: Record<string, string> | Headers;
/**
* Initial messages to populate the chat with.
*/
initialMessages?: Message[];
/**
* A function to generate the system message. Defaults to `defaultSystemMessage`.
*/
makeSystemMessage?: SystemMessageFunction;
/**
* Disables inclusion of CopilotKit’s default system message. When true, no system message is sent (this also suppresses any custom message from <code>makeSystemMessage</code>).
*/
disableSystemMessage?: boolean;
/**
* Controls the behavior of suggestions in the chat interface.
*
* `auto` (default) - Suggestions are generated automatically:
* - When the chat is first opened (empty state)
* - After each message exchange completes
* - Uses configuration from `useCopilotChatSuggestions` hooks
*
* `manual` - Suggestions are controlled programmatically:
* - Use `setSuggestions()` to set custom suggestions
* - Use `generateSuggestions()` to trigger AI generation
* - Access via `useCopilotChat` hook
*
* `SuggestionItem[]` - Static suggestions array:
* - Always shows the same suggestions
* - No AI generation involved
*/
suggestions?: ChatSuggestions;
onInProgress?: (isLoading: boolean) => void;
onSubmitMessage?: (messageContent: string) => Promise<void> | void;
onStopGeneration?: OnStopGeneration;
onReloadMessages?: OnReloadMessages;
}
export interface MCPServerConfig {
endpoint: string;
apiKey?: string;
}
// Old suggestion item interface, for returning from useCopilotChatInternal
interface SuggestionItem {
title: string;
message: string;
partial?: boolean;
className?: string;
}
export interface UseCopilotChatReturn {
/**
* @deprecated use `messages` instead, this is an old non ag-ui version of the messages
* Array of messages currently visible in the chat interface
*
* This is the visible messages, not the raw messages from the runtime client.
*/
visibleMessages: DeprecatedGqlMessage[];
/**
* The messages that are currently in the chat in AG-UI format.
*/
messages: Message[];
/** @deprecated use `sendMessage` in `useCopilotChatHeadless_c` instead. This will be removed in a future major version. */
appendMessage: (
message: DeprecatedGqlMessage,
options?: AppendMessageOptions,
) => Promise<void>;
/**
* Send a new message to the chat
*
* ```tsx
* await sendMessage({
* id: "123",
* role: "user",
* content: "Hello, process this request",
* });
* ```
*/
sendMessage: (
message: Message,
options?: AppendMessageOptions,
) => Promise<void>;
/**
* Replace all messages in the chat
*
* ```tsx
* setMessages([
* { id: "123", role: "user", content: "Hello, process this request" },
* { id: "456", role: "assistant", content: "Hello, I'm the assistant" },
* ]);
* ```
*
* **Deprecated** non-ag-ui version:
*
* ```tsx
* setMessages([
* new TextMessage({
* content: "Hello, process this request",
* role: gqlRole.User,
* }),
* new TextMessage({
* content: "Hello, I'm the assistant",
* role: gqlRole.Assistant,
* ]);
* ```
*
*/
setMessages: (messages: Message[] | DeprecatedGqlMessage[]) => void;
/**
* Remove a specific message by ID
*
* ```tsx
* deleteMessage("123");
* ```
*/
deleteMessage: (messageId: string) => void;
/**
* Regenerate the response for a specific message
*
* ```tsx
* reloadMessages("123");
* ```
*/
reloadMessages: (messageId: string) => Promise<void>;
/**
* Stop the current message generation
*
* ```tsx
* if (isLoading) {
* stopGeneration();
* }
* ```
*/
stopGeneration: () => void;
/**
* Clear all messages and reset chat state
*
* ```tsx
* reset();
* console.log(messages); // []
* ```
*/
reset: () => void;
/**
* Whether the chat is currently generating a response
*
* ```tsx
* if (isLoading) {
* console.log("Loading...");
* } else {
* console.log("Not loading");
* }
*/
isLoading: boolean;
/**
* Whether the chat agent is available to generate responses
*
* ```tsx
* if (isAvailable) {
* console.log("Loading...");
* } else {
* console.log("Not loading");
* }
*/
isAvailable: boolean;
/** Manually trigger chat completion (advanced usage) */
runChatCompletion: () => Promise<Message[]>;
/** MCP (Model Context Protocol) server configurations */
mcpServers: MCPServerConfig[];
/** Update MCP server configurations */
setMcpServers: (mcpServers: MCPServerConfig[]) => void;
/**
* Current suggestions array
* Use this to read the current suggestions or in conjunction with setSuggestions for manual control
*/
suggestions: Suggestion[];
/**
* Manually set suggestions
* Useful for manual mode or custom suggestion workflows
*/
setSuggestions: (suggestions: Omit<Suggestion, "isLoading">[]) => void;
/**
* Trigger AI-powered suggestion generation
* Uses configurations from useCopilotChatSuggestions hooks
* Respects global debouncing - only one generation can run at a time
*
* ```tsx
* generateSuggestions();
* console.log(suggestions); // [suggestion1, suggestion2, suggestion3]
* ```
*/
generateSuggestions: () => Promise<void>;
/**
* Clear all current suggestions
* Also resets suggestion generation state
*/
resetSuggestions: () => void;
/** Whether suggestions are currently being generated */
isLoadingSuggestions: boolean;
/** Interrupt content for human-in-the-loop workflows */
interrupt: string | React.ReactElement | null;
agent?: ReturnType<typeof useAgent>["agent"];
threadId?: string;
}
export function useCopilotChatInternal({
suggestions,
onInProgress,
onSubmitMessage,
onStopGeneration,
onReloadMessages,
}: UseCopilotChatOptions = {}): UseCopilotChatReturn {
const { copilotkit } = useCopilotKit();
const { threadId, agentSession } = useCopilotContext();
const existingConfig = useCopilotChatConfiguration();
const [agentAvailable, setAgentAvailable] = useState(false);
// Apply priority: props > existing config > defaults
const resolvedAgentId = existingConfig?.agentId ?? "default";
const { agent } = useAgent({
agentId: resolvedAgentId,
});
// Track the last agent instance we called connect() on. Without this,
// connect() fires on every render where status is Connected — including
// unrelated context re-renders and StrictMode double-invocations.
// The ref is reset in the cleanup so that remounts (StrictMode, real
// unmount/remount) always trigger a fresh connect.
const lastConnectedAgentRef = useRef<AbstractAgent | null>(null);
useEffect(() => {
let detached = false;
// Create a fresh AbortController so we can cancel the HTTP request on cleanup.
// Mirrors the V2 CopilotChat pattern: HttpAgent uses abortController.signal in
// its fetch config. connectAgent() does NOT create a new AbortController
// automatically, so we must set one before connecting.
const connectAbortController = new AbortController();
if (agent instanceof HttpAgent) {
agent.abortController = connectAbortController;
}
const connect = async (agent: AbstractAgent) => {
setAgentAvailable(false);
try {
await copilotkit.connectAgent({ agent });
// Guard against setting state after cleanup (e.g. React StrictMode unmount)
if (!detached) {
setAgentAvailable(true);
}
} catch (error) {
// Ignore errors from aborted connections (e.g. React StrictMode cleanup)
if (detached) return;
if (error instanceof AGUIConnectNotImplementedError) {
// connect not implemented, ignore
} else {
console.error("CopilotChat: connectAgent failed", error);
// Error will be reported through subscription
}
}
};
if (
agent &&
agent !== lastConnectedAgentRef.current &&
copilotkit.runtimeConnectionStatus ===
CopilotKitCoreRuntimeConnectionStatus.Connected
) {
lastConnectedAgentRef.current = agent;
connect(agent);
}
return () => {
// Abort the HTTP request and detach the active run.
// This is critical for React StrictMode which unmounts+remounts in dev,
// preventing duplicate /connect requests from reaching the server.
// Reset the ref so remounts always trigger a fresh connect.
lastConnectedAgentRef.current = null;
detached = true;
connectAbortController.abort();
agent?.detachActiveRun();
};
}, [
existingConfig?.threadId,
agent,
copilotkit,
copilotkit.runtimeConnectionStatus,
resolvedAgentId,
]);
useEffect(() => {
onInProgress?.(Boolean(agent?.isRunning));
}, [agent?.isRunning, onInProgress]);
// Subscribe to copilotkit.interruptElement so the v1 return type stays
// reactive. The element is published by useInterrupt (v2) when user code
// calls useLangGraphInterrupt({ render, ... }).
const [interrupt, setInterrupt] = useState<React.ReactElement | null>(null);
useEffect(() => {
setInterrupt(copilotkit.interruptElement);
const subscription = copilotkit.subscribe({
onInterruptElementChanged: ({ interruptElement }) => {
setInterrupt(interruptElement);
},
});
return () => subscription.unsubscribe();
}, [copilotkit]);
const reset = () => {
agent?.setMessages([]);
agent?.setState(null);
};
const deleteMessage = useCallback(
(messageId: string) => {
const filteredMessages = (agent?.messages ?? []).filter(
(message) => message.id !== messageId,
);
agent?.setMessages(filteredMessages);
},
[agent?.setMessages, agent?.messages],
);
const latestDelete = useUpdatedRef(deleteMessage);
const latestDeleteFunc = useCallback(
(messageId: string) => {
return latestDelete.current(messageId);
},
[latestDelete],
);
const currentSuggestions = useSuggestions({ agentId: resolvedAgentId });
const reload = useAsyncCallback(
async (reloadMessageId: string): Promise<void> => {
if (!agent) return;
const messages = agent?.messages ?? [];
const isLoading = agent.isRunning;
if (isLoading || messages.length === 0) {
return;
}
const reloadMessageIndex = messages.findIndex(
(msg) => msg.id === reloadMessageId,
);
if (reloadMessageIndex === -1) {
console.warn(`Message with id ${reloadMessageId} not found`);
return;
}
const reloadMessageRole = messages[reloadMessageIndex].role;
if (reloadMessageRole !== "assistant") {
console.warn(
`Regenerate cannot be performed on ${reloadMessageRole} role`,
);
return;
}
let historyCutoff: Message[] = [messages[0]];
if (messages.length > 2 && reloadMessageIndex !== 0) {
// message to regenerate from is now first.
// Work backwards to find the first the closest user message
const lastUserMessageBeforeRegenerate = messages
.slice(0, reloadMessageIndex)
.toReversed()
.find((msg) => msg.role === "user");
if (!lastUserMessageBeforeRegenerate) {
historyCutoff = [messages[0]];
} else {
const indexOfLastUserMessageBeforeRegenerate = messages.findIndex(
(msg) => msg.id === lastUserMessageBeforeRegenerate.id,
);
// Include the user message, remove everything after it
historyCutoff = messages.slice(
0,
indexOfLastUserMessageBeforeRegenerate + 1,
);
}
} else if (messages.length > 2 && reloadMessageIndex === 0) {
historyCutoff = [messages[0], messages[1]];
}
agent?.setMessages(historyCutoff);
if (agent) {
try {
await copilotkit.runAgent({ agent });
} catch (error) {
console.error("CopilotChat: runAgent failed during reload", error);
// Error will be reported through subscription
}
}
return;
},
[
agent?.messages.length,
agent?.isRunning,
agent?.setMessages,
copilotkit?.runAgent,
],
);
const latestSendMessageFunc = useAsyncCallback(
async (message: Message, options?: AppendMessageOptions) => {
if (!agent) return;
const followUp = options?.followUp ?? true;
if (options?.clearSuggestions) {
copilotkit.clearSuggestions(resolvedAgentId);
}
// Call onSubmitMessage BEFORE adding message and running agent
// This allows users to perform actions (e.g., open chat window) before agent starts processing
if (onSubmitMessage) {
const content =
typeof message.content === "string"
? message.content
: message.content && "text" in message.content
? message.content.text
: message.content && "filename" in message.content
? message.content.filename
: "";
try {
await onSubmitMessage(content);
} catch (error) {
console.error("Error in onSubmitMessage:", error);
}
}
agent?.addMessage(message);
if (followUp) {
try {
await copilotkit.runAgent({ agent });
} catch (error) {
console.error("CopilotChat: runAgent failed", error);
// Error will be reported through subscription
}
}
},
[agent, copilotkit, resolvedAgentId, onSubmitMessage],
);
const latestAppendFunc = useAsyncCallback(
async (message: DeprecatedGqlMessage, options?: AppendMessageOptions) => {
return latestSendMessageFunc(gqlToAGUI([message])[0], options);
},
[latestSendMessageFunc],
);
const latestSetMessagesFunc = useCallback(
(messages: Message[] | DeprecatedGqlMessage[]) => {
if (
messages.every((message) => message instanceof DeprecatedGqlMessage)
) {
return agent?.setMessages?.(gqlToAGUI(messages));
}
return agent?.setMessages?.(messages);
},
[agent?.setMessages, agent],
);
const latestReload = useUpdatedRef(reload);
const latestReloadFunc = useAsyncCallback(
async (messageId: string) => {
onReloadMessages?.({
messageId,
currentAgentName: agent?.agentId,
messages: agent?.messages ?? [],
});
return await latestReload.current(messageId);
},
[latestReload, agent, onReloadMessages],
);
const latestStopFunc = useCallback(() => {
onStopGeneration?.({
currentAgentName: agent?.agentId,
messages: agent?.messages ?? [],
});
return agent?.abortRun?.();
}, [onStopGeneration, agent]);
const latestReset = useUpdatedRef(reset);
const latestResetFunc = useCallback(() => {
return latestReset.current();
}, [latestReset]);
const lazyToolRendered = useLazyToolRenderer();
const renderCustomMessage = useRenderCustomMessages();
const legacyCustomMessageRenderer = useLegacyCoagentRenderer({
copilotkit,
agent,
agentId: resolvedAgentId,
threadId: existingConfig?.threadId ?? threadId,
});
const allMessages = agent?.messages ?? [];
const resolvedMessages = useMemo(() => {
let processedMessages = allMessages.map((message) => {
if (message.role !== "assistant") {
return message;
}
const lazyRendered = lazyToolRendered(message, allMessages);
if (lazyRendered) {
const renderedGenUi = lazyRendered();
if (renderedGenUi) {
return { ...message, generativeUI: () => renderedGenUi };
}
}
const bridgeRenderer =
legacyCustomMessageRenderer || renderCustomMessage
? () => {
if (legacyCustomMessageRenderer) {
return legacyCustomMessageRenderer({
message,
position: "before",
});
}
try {
return (
renderCustomMessage?.({ message, position: "before" }) ?? null
);
} catch (error) {
console.warn(
"[CopilotKit] renderCustomMessages failed, falling back to legacy renderer",
error,
);
return null;
}
}
: null;
if (bridgeRenderer) {
// Attach a position so react-ui can render the custom UI above the assistant content.
return {
...message,
generativeUI: bridgeRenderer,
generativeUIPosition: "before" as const,
};
}
return message;
});
const hasAssistantMessages = processedMessages.some(
(msg) => msg.role === "assistant",
);
const canUseCustomRenderer = Boolean(
renderCustomMessage && copilotkit?.getAgent?.(resolvedAgentId),
);
const placeholderRenderer = legacyCustomMessageRenderer
? legacyCustomMessageRenderer
: canUseCustomRenderer
? renderCustomMessage
: null;
const shouldRenderPlaceholder =
Boolean(agent?.isRunning) ||
Boolean(agent?.state && Object.keys(agent.state).length);
const effectiveThreadId = threadId ?? agent?.threadId ?? "default";
let latestUserIndex = -1;
for (let i = processedMessages.length - 1; i >= 0; i -= 1) {
if (processedMessages[i].role === "user") {
latestUserIndex = i;
break;
}
}
const latestUserMessageId =
latestUserIndex >= 0 ? processedMessages[latestUserIndex].id : undefined;
const currentRunId = latestUserMessageId
? copilotkit.getRunIdForMessage(
resolvedAgentId,
effectiveThreadId,
latestUserMessageId,
) || `pending:${latestUserMessageId}`
: undefined;
const hasAssistantForCurrentRun =
latestUserIndex >= 0
? processedMessages
.slice(latestUserIndex + 1)
.some((msg) => msg.role === "assistant")
: hasAssistantMessages;
// Insert a placeholder assistant message so state snapshots can render before any
// assistant text exists for the current run.
if (
placeholderRenderer &&
shouldRenderPlaceholder &&
!hasAssistantForCurrentRun
) {
const placeholderId = currentRunId
? `coagent-state-render-${resolvedAgentId}-${currentRunId}`
: `coagent-state-render-${resolvedAgentId}`;
const placeholderMessage: Message = {
id: placeholderId,
role: "assistant",
content: "",
name: "coagent-state-render",
runId: currentRunId,
};
processedMessages = [
...processedMessages,
{
...placeholderMessage,
generativeUIPosition: "before" as const,
generativeUI: () =>
placeholderRenderer({
message: placeholderMessage,
position: "before",
}),
} as Message,
];
}
return processedMessages;
}, [
agent?.messages,
lazyToolRendered,
allMessages,
renderCustomMessage,
legacyCustomMessageRenderer,
resolvedAgentId,
copilotkit,
agent?.isRunning,
agent?.state,
]);
const renderedSuggestions = useMemo(() => {
if (Array.isArray(suggestions)) {
return {
suggestions: suggestions.map((s) => ({ ...s, isLoading: false })),
isLoading: false,
};
}
return currentSuggestions;
}, [suggestions, currentSuggestions]);
// @ts-ignore
return {
messages: resolvedMessages,
sendMessage: latestSendMessageFunc,
appendMessage: latestAppendFunc,
setMessages: latestSetMessagesFunc,
reloadMessages: latestReloadFunc,
stopGeneration: latestStopFunc,
reset: latestResetFunc,
deleteMessage: latestDeleteFunc,
isAvailable: agentAvailable,
isLoading: Boolean(agent?.isRunning),
// mcpServers,
// setMcpServers,
suggestions: renderedSuggestions.suggestions,
setSuggestions: (suggestions: Omit<Suggestion, "isLoading">[]) =>
copilotkit.addSuggestionsConfig({ suggestions }),
generateSuggestions: async () =>
copilotkit.reloadSuggestions(resolvedAgentId),
resetSuggestions: () => copilotkit.clearSuggestions(resolvedAgentId),
isLoadingSuggestions: renderedSuggestions.isLoading,
interrupt,
agent,
threadId,
};
}
// store `value` in a ref and update
// it whenever it changes.
function useUpdatedRef<T>(value: T) {
const ref = useRef(value);
useEffect(() => {
ref.current = value;
}, [value]);
return ref;
}
type LegacyRenderParams = {
message: Message;
position: "before" | "after";
};
type LegacyRenderer = ((args: LegacyRenderParams) => any) | null;
function useLegacyCoagentRenderer({
copilotkit,
agent,
agentId,
threadId,
}: {
copilotkit: ReturnType<typeof useCopilotKit>["copilotkit"];
agent?: AbstractAgent;
agentId: string;
threadId?: string;
}): LegacyRenderer {
return useMemo(() => {
if (!copilotkit || !agent) {
return null;
}
return ({ message, position }: LegacyRenderParams) => {
const effectiveThreadId = threadId ?? agent.threadId ?? "default";
const providedRunId = (message as any).runId as string | undefined;
const existingRunId = providedRunId
? providedRunId
: copilotkit.getRunIdForMessage(agentId, effectiveThreadId, message.id);
const runId = existingRunId || `pending:${message.id}`;
const messageIndex = Math.max(
agent.messages.findIndex((msg) => msg.id === message.id),
0,
);
const bridgeProps: CoAgentStateRenderBridgeProps = {
message: message as any,
position,
runId,
messageIndex,
messageIndexInRun: 0,
numberOfMessagesInRun: 1,
agentId,
stateSnapshot: (message as any).state,
};
return createElement(CoAgentStateRenderBridge, bridgeProps) as any;
};
}, [agent, agentId, copilotkit, threadId]);
}
export function defaultSystemMessage(
contextString: string,
additionalInstructions?: string,
): string {
return (
`
Please act as an efficient, competent, conscientious, and industrious professional assistant.
Help the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.
Always be polite and respectful, and prefer brevity over verbosity.
The user has provided you with the following context:
\`\`\`
${contextString}
\`\`\`
They have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.
Please assist them as best you can.
You can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.
If you would like to call a function, call it without saying anything else.
In case of a function error:
- If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.
- If the error's source is unclear or seems unrelated to your input, do not attempt further retries.
` + (additionalInstructions ? `\n\n${additionalInstructions}` : "")
);
}