forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
548 lines (509 loc) · 14.8 KB
/
Copy pathutils.ts
File metadata and controls
548 lines (509 loc) · 14.8 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
import type { RunnableConfig } from "@langchain/core/runnables";
import { dispatchCustomEvent } from "@langchain/core/callbacks/dispatch";
import {
convertJsonSchemaToZodSchema,
randomId,
randomUUID,
CopilotKitMisuseError,
} from "@copilotkit/shared";
import { interrupt } from "@langchain/langgraph";
import { DynamicStructuredTool } from "@langchain/core/tools";
import { AIMessage } from "@langchain/core/messages";
import type { OptionsConfig } from "./types";
/**
* Customize the LangGraph configuration for use in CopilotKit.
*
* To the CopilotKit SDK, run:
*
* ```bash
* npm install @copilotkit/sdk-js
* ```
*
* ### Examples
*
* Disable emitting messages and tool calls:
*
* ```typescript
* import { copilotkitCustomizeConfig } from "@copilotkit/sdk-js";
*
* config = copilotkitCustomizeConfig(
* config,
* emitMessages=false,
* emitToolCalls=false
* )
* ```
*
* To emit a tool call as streaming LangGraph state, pass the destination key in state,
* the tool name and optionally the tool argument. (If you don't pass the argument name,
* all arguments are emitted under the state key.)
*
* ```typescript
* import { copilotkitCustomizeConfig } from "@copilotkit/sdk-js";
*
* config = copilotkitCustomizeConfig(
* config,
* emitIntermediateState=[
* {
* "stateKey": "steps",
* "tool": "SearchTool",
* "toolArgument": "steps",
* },
* ],
* )
* ```
*/
export function copilotkitCustomizeConfig(
/**
* The LangChain/LangGraph configuration to customize.
*/
baseConfig: RunnableConfig,
/**
* Configuration options:
* - `emitMessages: boolean?`
* Configure how messages are emitted. By default, all messages are emitted. Pass false to
* disable emitting messages.
* - `emitToolCalls: boolean | string | string[]?`
* Configure how tool calls are emitted. By default, all tool calls are emitted. Pass false to
* disable emitting tool calls. Pass a string or list of strings to emit only specific tool calls.
* - `emitIntermediateState: IntermediateStateConfig[]?`
* Lets you emit tool calls as streaming LangGraph state.
*/
options?: OptionsConfig,
): RunnableConfig {
if (baseConfig && typeof baseConfig !== "object") {
throw new CopilotKitMisuseError({
message: "baseConfig must be an object or null/undefined",
});
}
if (options && typeof options !== "object") {
throw new CopilotKitMisuseError({
message: "options must be an object when provided",
});
}
// Validate emitIntermediateState structure
if (options?.emitIntermediateState) {
if (!Array.isArray(options.emitIntermediateState)) {
throw new CopilotKitMisuseError({
message: "emitIntermediateState must be an array when provided",
});
}
options.emitIntermediateState.forEach((state, index) => {
if (!state || typeof state !== "object") {
throw new CopilotKitMisuseError({
message: `emitIntermediateState[${index}] must be an object`,
});
}
if (!state.stateKey || typeof state.stateKey !== "string") {
throw new CopilotKitMisuseError({
message: `emitIntermediateState[${index}] must have a valid 'stateKey' string property`,
});
}
if (!state.tool || typeof state.tool !== "string") {
throw new CopilotKitMisuseError({
message: `emitIntermediateState[${index}] must have a valid 'tool' string property`,
});
}
if (state.toolArgument && typeof state.toolArgument !== "string") {
throw new CopilotKitMisuseError({
message: `emitIntermediateState[${index}].toolArgument must be a string when provided`,
});
}
});
}
try {
const metadata = baseConfig?.metadata || {};
if (options?.emitAll) {
metadata["copilotkit:emit-tool-calls"] = true;
metadata["copilotkit:emit-messages"] = true;
} else {
if (options?.emitToolCalls !== undefined) {
metadata["copilotkit:emit-tool-calls"] = options.emitToolCalls;
}
if (options?.emitMessages !== undefined) {
metadata["copilotkit:emit-messages"] = options.emitMessages;
}
}
if (options?.emitIntermediateState) {
const snakeCaseIntermediateState = options.emitIntermediateState.map(
(state) => ({
tool: state.tool,
tool_argument: state.toolArgument,
state_key: state.stateKey,
}),
);
metadata["copilotkit:emit-intermediate-state"] =
snakeCaseIntermediateState;
}
baseConfig = baseConfig || {};
return {
...baseConfig,
metadata: metadata,
};
} catch (error) {
throw new CopilotKitMisuseError({
message: `Failed to customize config: ${error instanceof Error ? error.message : String(error)}`,
});
}
}
/**
* Exits the current agent after the run completes. Calling copilotkit_exit() will
* not immediately stop the agent. Instead, it signals to CopilotKit to stop the agent after
* the run completes.
*
* ### Examples
*
* ```typescript
* import { copilotkitExit } from "@copilotkit/sdk-js";
*
* async function myNode(state: Any):
* await copilotkitExit(config)
* return state
* ```
*/
export async function copilotkitExit(
/**
* The LangChain/LangGraph configuration.
*/
config: RunnableConfig,
) {
if (!config) {
throw new CopilotKitMisuseError({
message: "LangGraph configuration is required for copilotkitExit",
});
}
try {
await dispatchCustomEvent("copilotkit_exit", {}, config);
} catch (error) {
throw new CopilotKitMisuseError({
message: `Failed to dispatch exit event: ${error instanceof Error ? error.message : String(error)}`,
});
}
}
/**
* Emits intermediate state to CopilotKit. Useful if you have a longer running node and you want to
* update the user with the current state of the node.
*
* ### Examples
*
* ```typescript
* import { copilotkitEmitState } from "@copilotkit/sdk-js";
*
* for (let i = 0; i < 10; i++) {
* await someLongRunningOperation(i);
* await copilotkitEmitState(config, { progress: i });
* }
* ```
*/
export async function copilotkitEmitState(
/**
* The LangChain/LangGraph configuration.
*/
config: RunnableConfig,
/**
* The state to emit.
*/
state: any,
) {
if (!config) {
throw new CopilotKitMisuseError({
message: "LangGraph configuration is required for copilotkitEmitState",
});
}
if (state === undefined) {
throw new CopilotKitMisuseError({
message: "State is required for copilotkitEmitState",
});
}
try {
await dispatchCustomEvent(
"copilotkit_manually_emit_intermediate_state",
state,
config,
);
} catch (error) {
throw new CopilotKitMisuseError({
message: `Failed to emit state: ${error instanceof Error ? error.message : String(error)}`,
});
}
}
/**
* Manually emits a message to CopilotKit. Useful in longer running nodes to update the user.
* Important: You still need to return the messages from the node.
*
* ### Examples
*
* ```typescript
* import { copilotkitEmitMessage } from "@copilotkit/sdk-js";
*
* const message = "Step 1 of 10 complete";
* await copilotkitEmitMessage(config, message);
*
* // Return the message from the node
* return {
* "messages": [AIMessage(content=message)]
* }
* ```
*/
export async function copilotkitEmitMessage(
/**
* The LangChain/LangGraph configuration.
*/
config: RunnableConfig,
/**
* The message to emit.
*/
message: string,
) {
if (!config) {
throw new CopilotKitMisuseError({
message: "LangGraph configuration is required for copilotkitEmitMessage",
});
}
if (!message || typeof message !== "string") {
throw new CopilotKitMisuseError({
message: "Message must be a non-empty string for copilotkitEmitMessage",
});
}
try {
await dispatchCustomEvent(
"copilotkit_manually_emit_message",
{ message, message_id: randomId(), role: "assistant" },
config,
);
} catch (error) {
throw new CopilotKitMisuseError({
message: `Failed to emit message: ${error instanceof Error ? error.message : String(error)}`,
});
}
}
/**
* Manually emits a tool call to CopilotKit.
*
* ### Examples
*
* ```typescript
* import { copilotkitEmitToolCall } from "@copilotkit/sdk-js";
*
* const autoId = await copilotkitEmitToolCall(config, "SearchTool", { steps: 10 });
*
* // With a custom ID for correlation/idempotency:
* const customId = await copilotkitEmitToolCall(config, "SearchTool", { steps: 10 }, { toolCallId: "my-custom-id" });
* ```
*
* @returns The tool call ID used for the emitted call — equals `options.toolCallId`
* when provided, otherwise a randomly generated ID.
*/
export async function copilotkitEmitToolCall(
/**
* The LangChain/LangGraph configuration.
*/
config: RunnableConfig,
/**
* The name of the tool to emit.
*/
name: string,
/**
* The arguments to emit.
*/
args: any,
/**
* Options for the tool call emission.
*/
options?: {
/**
* Optional tool call ID. If not provided, a random ID is generated.
* When provided, this ID is used as the toolCallId and parentMessageId
* in AG-UI protocol events. The caller is responsible for ensuring uniqueness.
*/
toolCallId?: string;
},
): Promise<string> {
if (!config) {
throw new CopilotKitMisuseError({
message: "LangGraph configuration is required for copilotkitEmitToolCall",
});
}
if (typeof name !== "string" || name.trim().length === 0) {
throw new CopilotKitMisuseError({
message:
"Tool name must be a non-empty string for copilotkitEmitToolCall",
});
}
if (
options?.toolCallId !== undefined &&
(typeof options.toolCallId !== "string" ||
options.toolCallId.trim().length === 0)
) {
throw new CopilotKitMisuseError({
message:
"Tool call id must be a non-empty string when provided for copilotkitEmitToolCall",
});
}
if (args === undefined) {
throw new CopilotKitMisuseError({
message: "Tool arguments are required for copilotkitEmitToolCall",
});
}
try {
JSON.stringify(args);
} catch (error) {
throw new CopilotKitMisuseError({
message: `Tool arguments for '${name}' are not JSON-serializable: ${error instanceof Error ? error.message : String(error)}`,
});
}
const toolCallId = options?.toolCallId ?? randomUUID();
try {
await dispatchCustomEvent(
"copilotkit_manually_emit_tool_call",
{ name, args, id: toolCallId },
config,
);
} catch (error) {
const wrapped = new Error(
`copilotkitEmitToolCall dispatch failed for tool="${name}" id="${toolCallId}": ${error instanceof Error ? error.message : String(error)}`,
);
(wrapped as any).cause = error;
throw wrapped;
}
return toolCallId;
}
export function convertActionToDynamicStructuredTool(
actionInput: any,
): DynamicStructuredTool<any> {
if (!actionInput) {
throw new CopilotKitMisuseError({
message: "Action input is required but was not provided",
});
}
if (!actionInput.name || typeof actionInput.name !== "string") {
throw new CopilotKitMisuseError({
message: "Action must have a valid 'name' property of type string",
});
}
if (
actionInput.description == undefined ||
actionInput.description == null ||
typeof actionInput.description !== "string"
) {
throw new CopilotKitMisuseError({
message: `Action '${actionInput.name}' must have a valid 'description' property of type string`,
});
}
if (!actionInput.parameters) {
throw new CopilotKitMisuseError({
message: `Action '${actionInput.name}' must have a 'parameters' property`,
});
}
try {
return new DynamicStructuredTool({
name: actionInput.name,
description: actionInput.description,
schema: convertJsonSchemaToZodSchema(actionInput.parameters, true),
func: async () => {
return "";
},
});
} catch (error) {
throw new CopilotKitMisuseError({
message: `Failed to convert action '${actionInput.name}' to DynamicStructuredTool: ${error instanceof Error ? error.message : String(error)}`,
});
}
}
/**
* Use this function to convert a list of actions you get from state
* to a list of dynamic structured tools.
*
* ### Examples
*
* ```typescript
* import { convertActionsToDynamicStructuredTools } from "@copilotkit/sdk-js";
*
* const tools = convertActionsToDynamicStructuredTools(state.copilotkit.actions);
* ```
*/
export function convertActionsToDynamicStructuredTools(
/**
* The list of actions to convert.
*/
actions: any[],
): DynamicStructuredTool<any>[] {
if (!Array.isArray(actions)) {
throw new CopilotKitMisuseError({
message: "Actions must be an array",
});
}
return actions.map((action, index) => {
try {
return convertActionToDynamicStructuredTool(
action.type === "function" ? action.function : action,
);
} catch (error) {
throw new CopilotKitMisuseError({
message: `Failed to convert action at index ${index}: ${error instanceof Error ? error.message : String(error)}`,
});
}
});
}
export function copilotKitInterrupt({
message,
action,
args,
}: {
message?: string;
action?: string;
args?: Record<string, any>;
}) {
if (!message && !action) {
throw new CopilotKitMisuseError({
message:
"Either message or action (and optional arguments) must be provided for copilotKitInterrupt",
});
}
if (action && typeof action !== "string") {
throw new CopilotKitMisuseError({
message: "Action must be a string when provided to copilotKitInterrupt",
});
}
if (message && typeof message !== "string") {
throw new CopilotKitMisuseError({
message: "Message must be a string when provided to copilotKitInterrupt",
});
}
if (args && typeof args !== "object") {
throw new CopilotKitMisuseError({
message: "Args must be an object when provided to copilotKitInterrupt",
});
}
let interruptValues = null;
let interruptMessage = null;
let answer = null;
try {
if (message) {
interruptValues = message;
interruptMessage = new AIMessage({ content: message, id: randomId() });
} else {
const toolId = randomId();
interruptMessage = new AIMessage({
content: "",
tool_calls: [{ id: toolId, name: action, args: args ?? {} }],
});
interruptValues = {
action,
args: args ?? {},
};
}
const response = interrupt({
__copilotkit_interrupt_value__: interruptValues,
__copilotkit_messages__: [interruptMessage],
});
answer = response[response.length - 1].content;
return {
answer,
messages: response,
};
} catch (error) {
throw new CopilotKitMisuseError({
message: `Failed to create interrupt: ${error instanceof Error ? error.message : String(error)}`,
});
}
}