@copilotkit/sdk-js 1.50.1 → 2.0.0-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/dist/{chunk-RPSUO5FS.mjs → chunk-JLGOQLGS.mjs} +130 -9
- package/dist/chunk-JLGOQLGS.mjs.map +1 -0
- package/dist/{langgraph.d.ts → langchain-2645763d.d.ts} +75 -13
- package/dist/langchain.d.ts +2 -1
- package/dist/langchain.js +11 -6
- package/dist/langchain.js.map +1 -1
- package/dist/langchain.mjs +1 -1
- package/dist/langgraph/index.d.ts +11 -0
- package/dist/langgraph.js +143 -9
- package/dist/langgraph.js.map +1 -1
- package/dist/langgraph.mjs +5 -3
- package/package.json +6 -4
- package/src/langgraph/index.ts +3 -0
- package/src/langgraph/middleware.ts +144 -0
- package/src/langgraph/types.ts +29 -0
- package/src/{langgraph.ts → langgraph/utils.ts} +2 -27
- package/tsup.config.ts +2 -2
- package/dist/chunk-RPSUO5FS.mjs.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# @copilotkit/sdk-js
|
|
2
2
|
|
|
3
|
+
## 2.0.0-next.1
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 5a24f28: create copilotkit langgraph middleware
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- @copilotkit/shared@2.0.0-next.1
|
|
12
|
+
|
|
13
|
+
## 1.50.2-next.0
|
|
14
|
+
|
|
15
|
+
### Patch Changes
|
|
16
|
+
|
|
17
|
+
- @copilotkit/shared@1.50.2-next.0
|
|
18
|
+
|
|
3
19
|
## 1.50.1
|
|
4
20
|
|
|
5
21
|
### Patch Changes
|
|
@@ -1,20 +1,25 @@
|
|
|
1
1
|
var __defProp = Object.defineProperty;
|
|
2
2
|
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
3
3
|
|
|
4
|
-
// src/langgraph.ts
|
|
5
|
-
import {
|
|
6
|
-
import { convertJsonSchemaToZodSchema, randomId, CopilotKitMisuseError } from "@copilotkit/shared";
|
|
7
|
-
import { Annotation, MessagesAnnotation, interrupt } from "@langchain/langgraph";
|
|
8
|
-
import { DynamicStructuredTool } from "@langchain/core/tools";
|
|
9
|
-
import { AIMessage } from "@langchain/core/messages";
|
|
4
|
+
// src/langgraph/types.ts
|
|
5
|
+
import { Annotation, MessagesAnnotation } from "@langchain/langgraph";
|
|
10
6
|
var CopilotKitPropertiesAnnotation = Annotation.Root({
|
|
11
7
|
actions: Annotation,
|
|
12
|
-
context: Annotation
|
|
8
|
+
context: Annotation,
|
|
9
|
+
interceptedToolCalls: Annotation,
|
|
10
|
+
originalAIMessageId: Annotation
|
|
13
11
|
});
|
|
14
12
|
var CopilotKitStateAnnotation = Annotation.Root({
|
|
15
13
|
copilotkit: Annotation,
|
|
16
14
|
...MessagesAnnotation.spec
|
|
17
15
|
});
|
|
16
|
+
|
|
17
|
+
// src/langgraph/utils.ts
|
|
18
|
+
import { dispatchCustomEvent } from "@langchain/core/callbacks/dispatch";
|
|
19
|
+
import { convertJsonSchemaToZodSchema, randomId, CopilotKitMisuseError } from "@copilotkit/shared";
|
|
20
|
+
import { interrupt } from "@langchain/langgraph";
|
|
21
|
+
import { DynamicStructuredTool } from "@langchain/core/tools";
|
|
22
|
+
import { AIMessage } from "@langchain/core/messages";
|
|
18
23
|
function copilotkitCustomizeConfig(baseConfig, options) {
|
|
19
24
|
if (baseConfig && typeof baseConfig !== "object") {
|
|
20
25
|
throw new CopilotKitMisuseError({
|
|
@@ -297,6 +302,121 @@ function copilotKitInterrupt({ message, action, args }) {
|
|
|
297
302
|
}
|
|
298
303
|
__name(copilotKitInterrupt, "copilotKitInterrupt");
|
|
299
304
|
|
|
305
|
+
// src/langgraph/middleware.ts
|
|
306
|
+
import { createMiddleware, AIMessage as AIMessage2 } from "langchain";
|
|
307
|
+
import * as z from "zod";
|
|
308
|
+
var copilotKitStateSchema = z.object({
|
|
309
|
+
copilotkit: z.object({
|
|
310
|
+
actions: z.array(z.any()),
|
|
311
|
+
context: z.any().optional(),
|
|
312
|
+
interceptedToolCalls: z.array(z.any()).optional(),
|
|
313
|
+
originalAIMessageId: z.string().optional()
|
|
314
|
+
}).optional()
|
|
315
|
+
});
|
|
316
|
+
var createCopilotKitMiddleware = /* @__PURE__ */ __name(() => {
|
|
317
|
+
return createMiddleware({
|
|
318
|
+
name: "CopilotKitMiddleware",
|
|
319
|
+
stateSchema: copilotKitStateSchema,
|
|
320
|
+
// Inject frontend tools before model call
|
|
321
|
+
wrapModelCall: async (request, handler) => {
|
|
322
|
+
var _a;
|
|
323
|
+
const frontendTools = ((_a = request.state["copilotkit"]) == null ? void 0 : _a.actions) ?? [];
|
|
324
|
+
if (frontendTools.length === 0) {
|
|
325
|
+
return handler(request);
|
|
326
|
+
}
|
|
327
|
+
const existingTools = request.tools || [];
|
|
328
|
+
const mergedTools = [
|
|
329
|
+
...existingTools,
|
|
330
|
+
...frontendTools
|
|
331
|
+
];
|
|
332
|
+
return handler({
|
|
333
|
+
...request,
|
|
334
|
+
tools: mergedTools
|
|
335
|
+
});
|
|
336
|
+
},
|
|
337
|
+
// Restore frontend tool calls to AIMessage before agent exits
|
|
338
|
+
afterAgent: (state) => {
|
|
339
|
+
var _a, _b;
|
|
340
|
+
const interceptedToolCalls = (_a = state["copilotkit"]) == null ? void 0 : _a.interceptedToolCalls;
|
|
341
|
+
const originalMessageId = (_b = state["copilotkit"]) == null ? void 0 : _b.originalAIMessageId;
|
|
342
|
+
if (!(interceptedToolCalls == null ? void 0 : interceptedToolCalls.length) || !originalMessageId) {
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
let messageFound = false;
|
|
346
|
+
const updatedMessages = state.messages.map((msg) => {
|
|
347
|
+
if (AIMessage2.isInstance(msg) && msg.id === originalMessageId) {
|
|
348
|
+
messageFound = true;
|
|
349
|
+
const existingToolCalls = msg.tool_calls || [];
|
|
350
|
+
return new AIMessage2({
|
|
351
|
+
content: msg.content,
|
|
352
|
+
tool_calls: [
|
|
353
|
+
...existingToolCalls,
|
|
354
|
+
...interceptedToolCalls
|
|
355
|
+
],
|
|
356
|
+
id: msg.id
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
return msg;
|
|
360
|
+
});
|
|
361
|
+
if (!messageFound) {
|
|
362
|
+
console.warn(`CopilotKit: Could not find message with id ${originalMessageId} to restore tool calls`);
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
return {
|
|
366
|
+
messages: updatedMessages,
|
|
367
|
+
copilotkit: {
|
|
368
|
+
...state["copilotkit"] ?? {},
|
|
369
|
+
interceptedToolCalls: void 0,
|
|
370
|
+
originalAIMessageId: void 0
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
},
|
|
374
|
+
// Intercept frontend tool calls after model returns, before ToolNode executes
|
|
375
|
+
afterModel: (state) => {
|
|
376
|
+
var _a, _b;
|
|
377
|
+
const frontendTools = ((_a = state["copilotkit"]) == null ? void 0 : _a.actions) ?? [];
|
|
378
|
+
if (frontendTools.length === 0)
|
|
379
|
+
return;
|
|
380
|
+
const frontendToolNames = new Set(frontendTools.map((t) => {
|
|
381
|
+
var _a2;
|
|
382
|
+
return ((_a2 = t.function) == null ? void 0 : _a2.name) || t.name;
|
|
383
|
+
}));
|
|
384
|
+
const lastMessage = state.messages[state.messages.length - 1];
|
|
385
|
+
if (!AIMessage2.isInstance(lastMessage) || !((_b = lastMessage.tool_calls) == null ? void 0 : _b.length)) {
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
const backendToolCalls = [];
|
|
389
|
+
const frontendToolCalls = [];
|
|
390
|
+
for (const call of lastMessage.tool_calls) {
|
|
391
|
+
if (frontendToolNames.has(call.name)) {
|
|
392
|
+
frontendToolCalls.push(call);
|
|
393
|
+
} else {
|
|
394
|
+
backendToolCalls.push(call);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
if (frontendToolCalls.length === 0)
|
|
398
|
+
return;
|
|
399
|
+
const updatedAIMessage = new AIMessage2({
|
|
400
|
+
content: lastMessage.content,
|
|
401
|
+
tool_calls: backendToolCalls,
|
|
402
|
+
id: lastMessage.id
|
|
403
|
+
});
|
|
404
|
+
return {
|
|
405
|
+
messages: [
|
|
406
|
+
...state.messages.slice(0, -1),
|
|
407
|
+
updatedAIMessage
|
|
408
|
+
],
|
|
409
|
+
copilotkit: {
|
|
410
|
+
...state["copilotkit"] ?? {},
|
|
411
|
+
interceptedToolCalls: frontendToolCalls,
|
|
412
|
+
originalAIMessageId: lastMessage.id
|
|
413
|
+
}
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
});
|
|
417
|
+
}, "createCopilotKitMiddleware");
|
|
418
|
+
var copilotkitMiddleware = createCopilotKitMiddleware();
|
|
419
|
+
|
|
300
420
|
export {
|
|
301
421
|
CopilotKitPropertiesAnnotation,
|
|
302
422
|
CopilotKitStateAnnotation,
|
|
@@ -307,6 +427,7 @@ export {
|
|
|
307
427
|
copilotkitEmitToolCall,
|
|
308
428
|
convertActionToDynamicStructuredTool,
|
|
309
429
|
convertActionsToDynamicStructuredTools,
|
|
310
|
-
copilotKitInterrupt
|
|
430
|
+
copilotKitInterrupt,
|
|
431
|
+
copilotkitMiddleware
|
|
311
432
|
};
|
|
312
|
-
//# sourceMappingURL=chunk-
|
|
433
|
+
//# sourceMappingURL=chunk-JLGOQLGS.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/langgraph/types.ts","../src/langgraph/utils.ts","../src/langgraph/middleware.ts"],"sourcesContent":["import { Annotation, MessagesAnnotation } from \"@langchain/langgraph\";\n\nexport const CopilotKitPropertiesAnnotation = Annotation.Root({\n actions: Annotation<any[]>,\n context: Annotation<{ description: string; value: string }[]>,\n interceptedToolCalls: Annotation<any[]>,\n originalAIMessageId: Annotation<string>,\n});\n\nexport const CopilotKitStateAnnotation = Annotation.Root({\n copilotkit: Annotation<typeof CopilotKitPropertiesAnnotation.State>,\n ...MessagesAnnotation.spec,\n});\n\nexport interface IntermediateStateConfig {\n stateKey: string;\n tool: string;\n toolArgument?: string;\n}\n\nexport interface OptionsConfig {\n emitToolCalls?: boolean | string | string[];\n emitMessages?: boolean;\n emitAll?: boolean;\n emitIntermediateState?: IntermediateStateConfig[];\n}\n\nexport type CopilotKitState = typeof CopilotKitStateAnnotation.State;\nexport type CopilotKitProperties = typeof CopilotKitPropertiesAnnotation.State;\n","import { RunnableConfig } from \"@langchain/core/runnables\";\nimport { dispatchCustomEvent } from \"@langchain/core/callbacks/dispatch\";\nimport { convertJsonSchemaToZodSchema, randomId, CopilotKitMisuseError } from \"@copilotkit/shared\";\nimport { interrupt } from \"@langchain/langgraph\";\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { AIMessage } from \"@langchain/core/messages\";\nimport { OptionsConfig } from \"./types\";\n\n/**\n * Customize the LangGraph configuration for use in CopilotKit.\n *\n * To the CopilotKit SDK, run:\n *\n * ```bash\n * npm install @copilotkit/sdk-js\n * ```\n *\n * ### Examples\n *\n * Disable emitting messages and tool calls:\n *\n * ```typescript\n * import { copilotkitCustomizeConfig } from \"@copilotkit/sdk-js\";\n *\n * config = copilotkitCustomizeConfig(\n * config,\n * emitMessages=false,\n * emitToolCalls=false\n * )\n * ```\n *\n * To emit a tool call as streaming LangGraph state, pass the destination key in state,\n * the tool name and optionally the tool argument. (If you don't pass the argument name,\n * all arguments are emitted under the state key.)\n *\n * ```typescript\n * import { copilotkitCustomizeConfig } from \"@copilotkit/sdk-js\";\n *\n * config = copilotkitCustomizeConfig(\n * config,\n * emitIntermediateState=[\n * {\n * \"stateKey\": \"steps\",\n * \"tool\": \"SearchTool\",\n * \"toolArgument\": \"steps\",\n * },\n * ],\n * )\n * ```\n */\nexport function copilotkitCustomizeConfig(\n /**\n * The LangChain/LangGraph configuration to customize.\n */\n baseConfig: RunnableConfig,\n /**\n * Configuration options:\n * - `emitMessages: boolean?`\n * Configure how messages are emitted. By default, all messages are emitted. Pass false to\n * disable emitting messages.\n * - `emitToolCalls: boolean | string | string[]?`\n * Configure how tool calls are emitted. By default, all tool calls are emitted. Pass false to\n * disable emitting tool calls. Pass a string or list of strings to emit only specific tool calls.\n * - `emitIntermediateState: IntermediateStateConfig[]?`\n * Lets you emit tool calls as streaming LangGraph state.\n */\n options?: OptionsConfig,\n): RunnableConfig {\n if (baseConfig && typeof baseConfig !== \"object\") {\n throw new CopilotKitMisuseError({\n message: \"baseConfig must be an object or null/undefined\",\n });\n }\n\n if (options && typeof options !== \"object\") {\n throw new CopilotKitMisuseError({\n message: \"options must be an object when provided\",\n });\n }\n\n // Validate emitIntermediateState structure\n if (options?.emitIntermediateState) {\n if (!Array.isArray(options.emitIntermediateState)) {\n throw new CopilotKitMisuseError({\n message: \"emitIntermediateState must be an array when provided\",\n });\n }\n\n options.emitIntermediateState.forEach((state, index) => {\n if (!state || typeof state !== \"object\") {\n throw new CopilotKitMisuseError({\n message: `emitIntermediateState[${index}] must be an object`,\n });\n }\n\n if (!state.stateKey || typeof state.stateKey !== \"string\") {\n throw new CopilotKitMisuseError({\n message: `emitIntermediateState[${index}] must have a valid 'stateKey' string property`,\n });\n }\n\n if (!state.tool || typeof state.tool !== \"string\") {\n throw new CopilotKitMisuseError({\n message: `emitIntermediateState[${index}] must have a valid 'tool' string property`,\n });\n }\n\n if (state.toolArgument && typeof state.toolArgument !== \"string\") {\n throw new CopilotKitMisuseError({\n message: `emitIntermediateState[${index}].toolArgument must be a string when provided`,\n });\n }\n });\n }\n\n try {\n const metadata = baseConfig?.metadata || {};\n\n if (options?.emitAll) {\n metadata[\"copilotkit:emit-tool-calls\"] = true;\n metadata[\"copilotkit:emit-messages\"] = true;\n } else {\n if (options?.emitToolCalls !== undefined) {\n metadata[\"copilotkit:emit-tool-calls\"] = options.emitToolCalls;\n }\n if (options?.emitMessages !== undefined) {\n metadata[\"copilotkit:emit-messages\"] = options.emitMessages;\n }\n }\n\n if (options?.emitIntermediateState) {\n const snakeCaseIntermediateState = options.emitIntermediateState.map((state) => ({\n tool: state.tool,\n tool_argument: state.toolArgument,\n state_key: state.stateKey,\n }));\n\n metadata[\"copilotkit:emit-intermediate-state\"] = snakeCaseIntermediateState;\n }\n\n baseConfig = baseConfig || {};\n\n return {\n ...baseConfig,\n metadata: metadata,\n };\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to customize config: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Exits the current agent after the run completes. Calling copilotkit_exit() will\n * not immediately stop the agent. Instead, it signals to CopilotKit to stop the agent after\n * the run completes.\n *\n * ### Examples\n *\n * ```typescript\n * import { copilotkitExit } from \"@copilotkit/sdk-js\";\n *\n * async function myNode(state: Any):\n * await copilotkitExit(config)\n * return state\n * ```\n */\nexport async function copilotkitExit(\n /**\n * The LangChain/LangGraph configuration.\n */\n config: RunnableConfig,\n) {\n if (!config) {\n throw new CopilotKitMisuseError({\n message: \"LangGraph configuration is required for copilotkitExit\",\n });\n }\n\n try {\n await dispatchCustomEvent(\"copilotkit_exit\", {}, config);\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to dispatch exit event: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Emits intermediate state to CopilotKit. Useful if you have a longer running node and you want to\n * update the user with the current state of the node.\n *\n * ### Examples\n *\n * ```typescript\n * import { copilotkitEmitState } from \"@copilotkit/sdk-js\";\n *\n * for (let i = 0; i < 10; i++) {\n * await someLongRunningOperation(i);\n * await copilotkitEmitState(config, { progress: i });\n * }\n * ```\n */\nexport async function copilotkitEmitState(\n /**\n * The LangChain/LangGraph configuration.\n */\n config: RunnableConfig,\n /**\n * The state to emit.\n */\n state: any,\n) {\n if (!config) {\n throw new CopilotKitMisuseError({\n message: \"LangGraph configuration is required for copilotkitEmitState\",\n });\n }\n\n if (state === undefined) {\n throw new CopilotKitMisuseError({\n message: \"State is required for copilotkitEmitState\",\n });\n }\n\n try {\n await dispatchCustomEvent(\"copilotkit_manually_emit_intermediate_state\", state, config);\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to emit state: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Manually emits a message to CopilotKit. Useful in longer running nodes to update the user.\n * Important: You still need to return the messages from the node.\n *\n * ### Examples\n *\n * ```typescript\n * import { copilotkitEmitMessage } from \"@copilotkit/sdk-js\";\n *\n * const message = \"Step 1 of 10 complete\";\n * await copilotkitEmitMessage(config, message);\n *\n * // Return the message from the node\n * return {\n * \"messages\": [AIMessage(content=message)]\n * }\n * ```\n */\nexport async function copilotkitEmitMessage(\n /**\n * The LangChain/LangGraph configuration.\n */\n config: RunnableConfig,\n /**\n * The message to emit.\n */\n message: string,\n) {\n if (!config) {\n throw new CopilotKitMisuseError({\n message: \"LangGraph configuration is required for copilotkitEmitMessage\",\n });\n }\n\n if (!message || typeof message !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Message must be a non-empty string for copilotkitEmitMessage\",\n });\n }\n\n try {\n await dispatchCustomEvent(\n \"copilotkit_manually_emit_message\",\n { message, message_id: randomId(), role: \"assistant\" },\n config,\n );\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to emit message: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Manually emits a tool call to CopilotKit.\n *\n * ### Examples\n *\n * ```typescript\n * import { copilotkitEmitToolCall } from \"@copilotkit/sdk-js\";\n *\n * await copilotkitEmitToolCall(config, name=\"SearchTool\", args={\"steps\": 10})\n * ```\n */\nexport async function copilotkitEmitToolCall(\n /**\n * The LangChain/LangGraph configuration.\n */\n config: RunnableConfig,\n /**\n * The name of the tool to emit.\n */\n name: string,\n /**\n * The arguments to emit.\n */\n args: any,\n) {\n if (!config) {\n throw new CopilotKitMisuseError({\n message: \"LangGraph configuration is required for copilotkitEmitToolCall\",\n });\n }\n\n if (!name || typeof name !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Tool name must be a non-empty string for copilotkitEmitToolCall\",\n });\n }\n\n if (args === undefined) {\n throw new CopilotKitMisuseError({\n message: \"Tool arguments are required for copilotkitEmitToolCall\",\n });\n }\n\n try {\n await dispatchCustomEvent(\n \"copilotkit_manually_emit_tool_call\",\n { name, args, id: randomId() },\n config,\n );\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to emit tool call '${name}': ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n\nexport function convertActionToDynamicStructuredTool(actionInput: any): DynamicStructuredTool<any> {\n if (!actionInput) {\n throw new CopilotKitMisuseError({\n message: \"Action input is required but was not provided\",\n });\n }\n\n if (!actionInput.name || typeof actionInput.name !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Action must have a valid 'name' property of type string\",\n });\n }\n\n if (\n actionInput.description == undefined ||\n actionInput.description == null ||\n typeof actionInput.description !== \"string\"\n ) {\n throw new CopilotKitMisuseError({\n message: `Action '${actionInput.name}' must have a valid 'description' property of type string`,\n });\n }\n\n if (!actionInput.parameters) {\n throw new CopilotKitMisuseError({\n message: `Action '${actionInput.name}' must have a 'parameters' property`,\n });\n }\n\n try {\n return new DynamicStructuredTool({\n name: actionInput.name,\n description: actionInput.description,\n schema: convertJsonSchemaToZodSchema(actionInput.parameters, true),\n func: async () => {\n return \"\";\n },\n });\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to convert action '${actionInput.name}' to DynamicStructuredTool: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Use this function to convert a list of actions you get from state\n * to a list of dynamic structured tools.\n *\n * ### Examples\n *\n * ```typescript\n * import { convertActionsToDynamicStructuredTools } from \"@copilotkit/sdk-js\";\n *\n * const tools = convertActionsToDynamicStructuredTools(state.copilotkit.actions);\n * ```\n */\nexport function convertActionsToDynamicStructuredTools(\n /**\n * The list of actions to convert.\n */\n actions: any[],\n): DynamicStructuredTool<any>[] {\n if (!Array.isArray(actions)) {\n throw new CopilotKitMisuseError({\n message: \"Actions must be an array\",\n });\n }\n\n return actions.map((action, index) => {\n try {\n return convertActionToDynamicStructuredTool(\n action.type === \"function\" ? action.function : action,\n );\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to convert action at index ${index}: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n });\n}\n\nexport function copilotKitInterrupt({\n message,\n action,\n args,\n}: {\n message?: string;\n action?: string;\n args?: Record<string, any>;\n}) {\n if (!message && !action) {\n throw new CopilotKitMisuseError({\n message:\n \"Either message or action (and optional arguments) must be provided for copilotKitInterrupt\",\n });\n }\n\n if (action && typeof action !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Action must be a string when provided to copilotKitInterrupt\",\n });\n }\n\n if (message && typeof message !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Message must be a string when provided to copilotKitInterrupt\",\n });\n }\n\n if (args && typeof args !== \"object\") {\n throw new CopilotKitMisuseError({\n message: \"Args must be an object when provided to copilotKitInterrupt\",\n });\n }\n\n let interruptValues = null;\n let interruptMessage = null;\n let answer = null;\n\n try {\n if (message) {\n interruptValues = message;\n interruptMessage = new AIMessage({ content: message, id: randomId() });\n } else {\n const toolId = randomId();\n interruptMessage = new AIMessage({\n content: \"\",\n tool_calls: [{ id: toolId, name: action, args: args ?? {} }],\n });\n interruptValues = {\n action,\n args: args ?? {},\n };\n }\n\n const response = interrupt({\n __copilotkit_interrupt_value__: interruptValues,\n __copilotkit_messages__: [interruptMessage],\n });\n answer = response[response.length - 1].content;\n\n return {\n answer,\n messages: response,\n };\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to create interrupt: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n","import { createMiddleware, AIMessage } from \"langchain\";\nimport type { InteropZodObject } from \"@langchain/core/utils/types\";\nimport * as z from \"zod\";\n\n/**\n * CopilotKit Middleware for LangGraph agents.\n *\n * Enables:\n * - Dynamic frontend tools from state.tools\n * - Context provided from CopilotKit useCopilotReadable\n *\n * Works with any agent (prebuilt or custom).\n *\n * @example\n * ```typescript\n * import { createAgent } from \"langchain\";\n * import { copilotkitMiddleware } from \"@copilotkit/sdk-js/langgraph\";\n *\n * const agent = createAgent({\n * model: \"gpt-4o\",\n * tools: [backendTool],\n * middleware: [copilotkitMiddleware],\n * });\n * ```\n */\nconst copilotKitStateSchema = z.object({\n copilotkit: z\n .object({\n actions: z.array(z.any()),\n context: z.any().optional(),\n interceptedToolCalls: z.array(z.any()).optional(),\n originalAIMessageId: z.string().optional(),\n })\n .optional(),\n});\n\nconst createCopilotKitMiddleware = () => {\n return createMiddleware({\n name: \"CopilotKitMiddleware\",\n\n stateSchema: copilotKitStateSchema as unknown as InteropZodObject,\n\n // Inject frontend tools before model call\n wrapModelCall: async (request, handler) => {\n const frontendTools = request.state[\"copilotkit\"]?.actions ?? [];\n\n if (frontendTools.length === 0) {\n return handler(request);\n }\n\n const existingTools = request.tools || [];\n const mergedTools = [...existingTools, ...frontendTools];\n\n return handler({\n ...request,\n tools: mergedTools,\n });\n },\n\n // Restore frontend tool calls to AIMessage before agent exits\n afterAgent: (state) => {\n const interceptedToolCalls = state[\"copilotkit\"]?.interceptedToolCalls;\n const originalMessageId = state[\"copilotkit\"]?.originalAIMessageId;\n\n if (!interceptedToolCalls?.length || !originalMessageId) {\n return;\n }\n\n let messageFound = false;\n const updatedMessages = state.messages.map((msg: any) => {\n if (AIMessage.isInstance(msg) && msg.id === originalMessageId) {\n messageFound = true;\n const existingToolCalls = msg.tool_calls || [];\n return new AIMessage({\n content: msg.content,\n tool_calls: [...existingToolCalls, ...interceptedToolCalls],\n id: msg.id,\n });\n }\n return msg;\n });\n\n // Only clear intercepted state if we successfully restored the tool calls\n if (!messageFound) {\n console.warn(\n `CopilotKit: Could not find message with id ${originalMessageId} to restore tool calls`,\n );\n return;\n }\n\n return {\n messages: updatedMessages,\n copilotkit: {\n ...(state[\"copilotkit\"] ?? {}),\n interceptedToolCalls: undefined,\n originalAIMessageId: undefined,\n },\n };\n },\n\n // Intercept frontend tool calls after model returns, before ToolNode executes\n afterModel: (state) => {\n const frontendTools = state[\"copilotkit\"]?.actions ?? [];\n if (frontendTools.length === 0) return;\n\n const frontendToolNames = new Set(frontendTools.map((t: any) => t.function?.name || t.name));\n\n const lastMessage = state.messages[state.messages.length - 1];\n if (!AIMessage.isInstance(lastMessage) || !lastMessage.tool_calls?.length) {\n return;\n }\n\n const backendToolCalls: any[] = [];\n const frontendToolCalls: any[] = [];\n\n for (const call of lastMessage.tool_calls) {\n if (frontendToolNames.has(call.name)) {\n frontendToolCalls.push(call);\n } else {\n backendToolCalls.push(call);\n }\n }\n\n if (frontendToolCalls.length === 0) return;\n\n const updatedAIMessage = new AIMessage({\n content: lastMessage.content,\n tool_calls: backendToolCalls,\n id: lastMessage.id,\n });\n\n return {\n messages: [...state.messages.slice(0, -1), updatedAIMessage],\n copilotkit: {\n ...(state[\"copilotkit\"] ?? {}),\n interceptedToolCalls: frontendToolCalls,\n originalAIMessageId: lastMessage.id,\n },\n };\n },\n });\n};\n\nexport const copilotkitMiddleware = createCopilotKitMiddleware();\n"],"mappings":";;;;AAAA,SAASA,YAAYC,0BAA0B;AAExC,IAAMC,iCAAiCF,WAAWG,KAAK;EAC5DC,SAASJ;EACTK,SAASL;EACTM,sBAAsBN;EACtBO,qBAAqBP;AACvB,CAAA;AAEO,IAAMQ,4BAA4BR,WAAWG,KAAK;EACvDM,YAAYT;EACZ,GAAGC,mBAAmBS;AACxB,CAAA;;;ACXA,SAASC,2BAA2B;AACpC,SAASC,8BAA8BC,UAAUC,6BAA6B;AAC9E,SAASC,iBAAiB;AAC1B,SAASC,6BAA6B;AACtC,SAASC,iBAAiB;AA6CnB,SAASC,0BAIdC,YAYAC,SAAuB;AAEvB,MAAID,cAAc,OAAOA,eAAe,UAAU;AAChD,UAAM,IAAIE,sBAAsB;MAC9BC,SAAS;IACX,CAAA;EACF;AAEA,MAAIF,WAAW,OAA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AW;AAAG;AAEhC,YAAMqB,oBAAoB,IAAIC,IAAIxB,cAAcW,IAAI,CAACc,MAAAA;AAzG3D,YAAAC;AAyGsED,iBAAAA,MAAAA,EAAEE,aAAFF,gBAAAA,IAAY9B,SAAQ8B,EAAE9B;OAAI,CAAA;AAE1F,YAAMiC,cAAc3B,MAAMS,SAAST,MAAMS,SAASR,SAAS,CAAA;AAC3D,UAAI,CAACW,WAAUC,WAAWc,WAAAA,KAAgB,GAACA,iBAAYX,eAAZW,mBAAwB1B,SAAQ;AACzE;MACF;AAEA,YAAM2B,mBAA0B,CAAA;AAChC,YAAMC,oBAA2B,CAAA;AAEjC,iBAAWC,QAAQH,YAAYX,YAAY;AACzC,YAAIM,kBAAkBS,IAAID,KAAKpC,IAAI,GAAG;AACpCmC,4BAAkBG,KAAKF,IAAAA;QACzB,OAAO;AACLF,2BAAiBI,KAAKF,IAAAA;QACxB;MACF;AAEA,UAAID,kBAAkB5B,WAAW;AAAG;AAEpC,YAAMgC,mBAAmB,IAAIrB,WAAU;QACrCK,SAASU,YAAYV;QACrBD,YAAYY;QACZd,IAAIa,YAAYb;MAClB,CAAA;AAEA,aAAO;QACLL,UAAU;aAAIT,MAAMS,SAASyB,MAAM,GAAG,EAAC;UAAID;;QAC3ClD,YAAY;UACV,GAAIiB,MAAM,YAAA,KAAiB,CAAC;UAC5BX,sBAAsBwC;UACtBvC,qBAAqBqC,YAAYb;QACnC;MACF;IACF;EACF,CAAA;AACF,GAzGmC;AA2G5B,IAAMqB,uBAAuB3C,2BAAAA;","names":["Annotation","MessagesAnnotation","CopilotKitPropertiesAnnotation","Root","actions","context","interceptedToolCalls","originalAIMessageId","CopilotKitStateAnnotation","copilotkit","spec","dispatchCustomEvent","convertJsonSchemaToZodSchema","randomId","CopilotKitMisuseError","interrupt","DynamicStructuredTool","AIMessage","copilotkitCustomizeConfig","baseConfig","options","CopilotKitMisuseError","message","emitIntermediateState","Array","isArray","forEach","state","index","stateKey","tool","toolArgument","metadata","emitAll","emitToolCalls","undefined","emitMessages","snakeCaseIntermediateState","map","tool_argument","state_key","error","Error","String","copilotkitExit","config","dispatchCustomEvent","copilotkitEmitState","copilotkitEmitMessage","message_id","randomId","role","copilotkitEmitToolCall","name","args","id","convertActionToDynamicStructuredTool","actionInput","description","parameters","DynamicStructuredTool","schema","convertJsonSchemaToZodSchema","func","convertActionsToDynamicStructuredTools","actions","action","type","function","copilotKitInterrupt","interruptValues","interruptMessage","answer","AIMessage","content","toolId","tool_calls","response","interrupt","__copilotkit_interrupt_value__","__copilotkit_messages__","length","messages","createMiddleware","AIMessage","z","copilotKitStateSchema","object","copilotkit","actions","array","any","context","optional","interceptedToolCalls","originalAIMessageId","string","createCopilotKitMiddleware","createMiddleware","name","stateSchema","wrapModelCall","request","handler","frontendTools","state","length","existingTools","tools","mergedTools","afterAgent","originalMessageId","messageFound","updatedMessages","messages","map","msg","AIMessage","isInstance","id","existingToolCalls","tool_calls","content","console","warn","undefined","afterModel","frontendToolNames","Set","t","_a","function","lastMessage","backendToolCalls","frontendToolCalls","call","has","push","updatedAIMessage","slice","copilotkitMiddleware"]}
|
|
@@ -1,19 +1,9 @@
|
|
|
1
|
+
import * as langchain from 'langchain';
|
|
1
2
|
import * as _langchain_core_messages from '@langchain/core/messages';
|
|
2
3
|
import * as _langchain_langgraph from '@langchain/langgraph';
|
|
3
4
|
import { RunnableConfig } from '@langchain/core/runnables';
|
|
4
5
|
import { DynamicStructuredTool } from '@langchain/core/tools';
|
|
5
6
|
|
|
6
|
-
interface IntermediateStateConfig {
|
|
7
|
-
stateKey: string;
|
|
8
|
-
tool: string;
|
|
9
|
-
toolArgument?: string;
|
|
10
|
-
}
|
|
11
|
-
interface OptionsConfig {
|
|
12
|
-
emitToolCalls?: boolean | string | string[];
|
|
13
|
-
emitMessages?: boolean;
|
|
14
|
-
emitAll?: boolean;
|
|
15
|
-
emitIntermediateState?: IntermediateStateConfig[];
|
|
16
|
-
}
|
|
17
7
|
declare const CopilotKitPropertiesAnnotation: _langchain_langgraph.AnnotationRoot<{
|
|
18
8
|
actions: {
|
|
19
9
|
(): _langchain_langgraph.LastValue<any[]>;
|
|
@@ -40,9 +30,19 @@ declare const CopilotKitPropertiesAnnotation: _langchain_langgraph.AnnotationRoo
|
|
|
40
30
|
}[]>;
|
|
41
31
|
Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
|
|
42
32
|
};
|
|
33
|
+
interceptedToolCalls: {
|
|
34
|
+
(): _langchain_langgraph.LastValue<any[]>;
|
|
35
|
+
(annotation: _langchain_langgraph.SingleReducer<any[], any[]>): _langchain_langgraph.BinaryOperatorAggregate<any[], any[]>;
|
|
36
|
+
Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
|
|
37
|
+
};
|
|
38
|
+
originalAIMessageId: {
|
|
39
|
+
(): _langchain_langgraph.LastValue<string>;
|
|
40
|
+
(annotation: _langchain_langgraph.SingleReducer<string, string>): _langchain_langgraph.BinaryOperatorAggregate<string, string>;
|
|
41
|
+
Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
|
|
42
|
+
};
|
|
43
43
|
}>;
|
|
44
44
|
declare const CopilotKitStateAnnotation: _langchain_langgraph.AnnotationRoot<{
|
|
45
|
-
messages: _langchain_langgraph.BinaryOperatorAggregate<_langchain_core_messages.
|
|
45
|
+
messages: _langchain_langgraph.BinaryOperatorAggregate<langchain.BaseMessage<_langchain_core_messages.MessageStructure, _langchain_core_messages.MessageType>[], _langchain_langgraph.Messages>;
|
|
46
46
|
copilotkit: {
|
|
47
47
|
(): _langchain_langgraph.LastValue<_langchain_langgraph.StateType<{
|
|
48
48
|
actions: {
|
|
@@ -70,6 +70,16 @@ declare const CopilotKitStateAnnotation: _langchain_langgraph.AnnotationRoot<{
|
|
|
70
70
|
}[]>;
|
|
71
71
|
Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
|
|
72
72
|
};
|
|
73
|
+
interceptedToolCalls: {
|
|
74
|
+
(): _langchain_langgraph.LastValue<any[]>;
|
|
75
|
+
(annotation: _langchain_langgraph.SingleReducer<any[], any[]>): _langchain_langgraph.BinaryOperatorAggregate<any[], any[]>;
|
|
76
|
+
Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
|
|
77
|
+
};
|
|
78
|
+
originalAIMessageId: {
|
|
79
|
+
(): _langchain_langgraph.LastValue<string>;
|
|
80
|
+
(annotation: _langchain_langgraph.SingleReducer<string, string>): _langchain_langgraph.BinaryOperatorAggregate<string, string>;
|
|
81
|
+
Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
|
|
82
|
+
};
|
|
73
83
|
}>>;
|
|
74
84
|
(annotation: _langchain_langgraph.SingleReducer<_langchain_langgraph.StateType<{
|
|
75
85
|
actions: {
|
|
@@ -97,6 +107,16 @@ declare const CopilotKitStateAnnotation: _langchain_langgraph.AnnotationRoot<{
|
|
|
97
107
|
}[]>;
|
|
98
108
|
Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
|
|
99
109
|
};
|
|
110
|
+
interceptedToolCalls: {
|
|
111
|
+
(): _langchain_langgraph.LastValue<any[]>;
|
|
112
|
+
(annotation: _langchain_langgraph.SingleReducer<any[], any[]>): _langchain_langgraph.BinaryOperatorAggregate<any[], any[]>;
|
|
113
|
+
Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
|
|
114
|
+
};
|
|
115
|
+
originalAIMessageId: {
|
|
116
|
+
(): _langchain_langgraph.LastValue<string>;
|
|
117
|
+
(annotation: _langchain_langgraph.SingleReducer<string, string>): _langchain_langgraph.BinaryOperatorAggregate<string, string>;
|
|
118
|
+
Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
|
|
119
|
+
};
|
|
100
120
|
}>, _langchain_langgraph.StateType<{
|
|
101
121
|
actions: {
|
|
102
122
|
(): _langchain_langgraph.LastValue<any[]>;
|
|
@@ -123,6 +143,16 @@ declare const CopilotKitStateAnnotation: _langchain_langgraph.AnnotationRoot<{
|
|
|
123
143
|
}[]>;
|
|
124
144
|
Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
|
|
125
145
|
};
|
|
146
|
+
interceptedToolCalls: {
|
|
147
|
+
(): _langchain_langgraph.LastValue<any[]>;
|
|
148
|
+
(annotation: _langchain_langgraph.SingleReducer<any[], any[]>): _langchain_langgraph.BinaryOperatorAggregate<any[], any[]>;
|
|
149
|
+
Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
|
|
150
|
+
};
|
|
151
|
+
originalAIMessageId: {
|
|
152
|
+
(): _langchain_langgraph.LastValue<string>;
|
|
153
|
+
(annotation: _langchain_langgraph.SingleReducer<string, string>): _langchain_langgraph.BinaryOperatorAggregate<string, string>;
|
|
154
|
+
Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
|
|
155
|
+
};
|
|
126
156
|
}>>): _langchain_langgraph.BinaryOperatorAggregate<_langchain_langgraph.StateType<{
|
|
127
157
|
actions: {
|
|
128
158
|
(): _langchain_langgraph.LastValue<any[]>;
|
|
@@ -149,6 +179,16 @@ declare const CopilotKitStateAnnotation: _langchain_langgraph.AnnotationRoot<{
|
|
|
149
179
|
}[]>;
|
|
150
180
|
Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
|
|
151
181
|
};
|
|
182
|
+
interceptedToolCalls: {
|
|
183
|
+
(): _langchain_langgraph.LastValue<any[]>;
|
|
184
|
+
(annotation: _langchain_langgraph.SingleReducer<any[], any[]>): _langchain_langgraph.BinaryOperatorAggregate<any[], any[]>;
|
|
185
|
+
Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
|
|
186
|
+
};
|
|
187
|
+
originalAIMessageId: {
|
|
188
|
+
(): _langchain_langgraph.LastValue<string>;
|
|
189
|
+
(annotation: _langchain_langgraph.SingleReducer<string, string>): _langchain_langgraph.BinaryOperatorAggregate<string, string>;
|
|
190
|
+
Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
|
|
191
|
+
};
|
|
152
192
|
}>, _langchain_langgraph.StateType<{
|
|
153
193
|
actions: {
|
|
154
194
|
(): _langchain_langgraph.LastValue<any[]>;
|
|
@@ -175,12 +215,34 @@ declare const CopilotKitStateAnnotation: _langchain_langgraph.AnnotationRoot<{
|
|
|
175
215
|
}[]>;
|
|
176
216
|
Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
|
|
177
217
|
};
|
|
218
|
+
interceptedToolCalls: {
|
|
219
|
+
(): _langchain_langgraph.LastValue<any[]>;
|
|
220
|
+
(annotation: _langchain_langgraph.SingleReducer<any[], any[]>): _langchain_langgraph.BinaryOperatorAggregate<any[], any[]>;
|
|
221
|
+
Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
|
|
222
|
+
};
|
|
223
|
+
originalAIMessageId: {
|
|
224
|
+
(): _langchain_langgraph.LastValue<string>;
|
|
225
|
+
(annotation: _langchain_langgraph.SingleReducer<string, string>): _langchain_langgraph.BinaryOperatorAggregate<string, string>;
|
|
226
|
+
Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
|
|
227
|
+
};
|
|
178
228
|
}>>;
|
|
179
229
|
Root: <S extends _langchain_langgraph.StateDefinition>(sd: S) => _langchain_langgraph.AnnotationRoot<S>;
|
|
180
230
|
};
|
|
181
231
|
}>;
|
|
232
|
+
interface IntermediateStateConfig {
|
|
233
|
+
stateKey: string;
|
|
234
|
+
tool: string;
|
|
235
|
+
toolArgument?: string;
|
|
236
|
+
}
|
|
237
|
+
interface OptionsConfig {
|
|
238
|
+
emitToolCalls?: boolean | string | string[];
|
|
239
|
+
emitMessages?: boolean;
|
|
240
|
+
emitAll?: boolean;
|
|
241
|
+
emitIntermediateState?: IntermediateStateConfig[];
|
|
242
|
+
}
|
|
182
243
|
type CopilotKitState = typeof CopilotKitStateAnnotation.State;
|
|
183
244
|
type CopilotKitProperties = typeof CopilotKitPropertiesAnnotation.State;
|
|
245
|
+
|
|
184
246
|
/**
|
|
185
247
|
* Customize the LangGraph configuration for use in CopilotKit.
|
|
186
248
|
*
|
|
@@ -362,4 +424,4 @@ declare function copilotKitInterrupt({ message, action, args, }: {
|
|
|
362
424
|
messages: any;
|
|
363
425
|
};
|
|
364
426
|
|
|
365
|
-
export {
|
|
427
|
+
export { CopilotKitPropertiesAnnotation as C, IntermediateStateConfig as I, OptionsConfig as O, CopilotKitStateAnnotation as a, CopilotKitState as b, CopilotKitProperties as c, copilotkitCustomizeConfig as d, copilotkitExit as e, copilotkitEmitState as f, copilotkitEmitMessage as g, copilotkitEmitToolCall as h, convertActionToDynamicStructuredTool as i, convertActionsToDynamicStructuredTools as j, copilotKitInterrupt as k };
|
package/dist/langchain.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
export { CopilotKitProperties, CopilotKitPropertiesAnnotation, CopilotKitState, CopilotKitStateAnnotation, convertActionToDynamicStructuredTool, convertActionsToDynamicStructuredTools,
|
|
1
|
+
export { c as CopilotKitProperties, C as CopilotKitPropertiesAnnotation, b as CopilotKitState, a as CopilotKitStateAnnotation, i as convertActionToDynamicStructuredTool, j as convertActionsToDynamicStructuredTools, d as copilotKitCustomizeConfig, g as copilotKitEmitMessage, f as copilotKitEmitState, h as copilotKitEmitToolCall, e as copilotKitExit } from './langchain-2645763d.js';
|
|
2
|
+
import 'langchain';
|
|
2
3
|
import '@langchain/core/messages';
|
|
3
4
|
import '@langchain/langgraph';
|
|
4
5
|
import '@langchain/core/runnables';
|
package/dist/langchain.js
CHANGED
|
@@ -32,20 +32,25 @@ __export(langchain_exports, {
|
|
|
32
32
|
});
|
|
33
33
|
module.exports = __toCommonJS(langchain_exports);
|
|
34
34
|
|
|
35
|
-
// src/langgraph.ts
|
|
36
|
-
var import_dispatch = require("@langchain/core/callbacks/dispatch");
|
|
37
|
-
var import_shared = require("@copilotkit/shared");
|
|
35
|
+
// src/langgraph/types.ts
|
|
38
36
|
var import_langgraph = require("@langchain/langgraph");
|
|
39
|
-
var import_tools = require("@langchain/core/tools");
|
|
40
|
-
var import_messages = require("@langchain/core/messages");
|
|
41
37
|
var CopilotKitPropertiesAnnotation = import_langgraph.Annotation.Root({
|
|
42
38
|
actions: import_langgraph.Annotation,
|
|
43
|
-
context: import_langgraph.Annotation
|
|
39
|
+
context: import_langgraph.Annotation,
|
|
40
|
+
interceptedToolCalls: import_langgraph.Annotation,
|
|
41
|
+
originalAIMessageId: import_langgraph.Annotation
|
|
44
42
|
});
|
|
45
43
|
var CopilotKitStateAnnotation = import_langgraph.Annotation.Root({
|
|
46
44
|
copilotkit: import_langgraph.Annotation,
|
|
47
45
|
...import_langgraph.MessagesAnnotation.spec
|
|
48
46
|
});
|
|
47
|
+
|
|
48
|
+
// src/langgraph/utils.ts
|
|
49
|
+
var import_dispatch = require("@langchain/core/callbacks/dispatch");
|
|
50
|
+
var import_shared = require("@copilotkit/shared");
|
|
51
|
+
var import_langgraph2 = require("@langchain/langgraph");
|
|
52
|
+
var import_tools = require("@langchain/core/tools");
|
|
53
|
+
var import_messages = require("@langchain/core/messages");
|
|
49
54
|
function copilotkitCustomizeConfig(baseConfig, options) {
|
|
50
55
|
if (baseConfig && typeof baseConfig !== "object") {
|
|
51
56
|
throw new import_shared.CopilotKitMisuseError({
|
package/dist/langchain.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/langchain.ts","../src/langgraph.ts"],"sourcesContent":["console.warn(\n \"Warning: '@copilotkit/sdk-js/langchain' is deprecated and will be removed in a future release. Please use '@copilotkit/sdk-js/langgraph' instead.\",\n);\n\nexport {\n CopilotKitPropertiesAnnotation,\n CopilotKitStateAnnotation,\n type CopilotKitState,\n type CopilotKitProperties,\n copilotkitCustomizeConfig as copilotKitCustomizeConfig,\n copilotkitExit as copilotKitExit,\n copilotkitEmitState as copilotKitEmitState,\n copilotkitEmitMessage as copilotKitEmitMessage,\n copilotkitEmitToolCall as copilotKitEmitToolCall,\n convertActionToDynamicStructuredTool,\n convertActionsToDynamicStructuredTools,\n} from \"./langgraph\";\n","import { RunnableConfig } from \"@langchain/core/runnables\";\nimport { dispatchCustomEvent } from \"@langchain/core/callbacks/dispatch\";\nimport { convertJsonSchemaToZodSchema, randomId, CopilotKitMisuseError } from \"@copilotkit/shared\";\nimport { Annotation, MessagesAnnotation, interrupt } from \"@langchain/langgraph\";\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { AIMessage } from \"@langchain/core/messages\";\n\ninterface IntermediateStateConfig {\n stateKey: string;\n tool: string;\n toolArgument?: string;\n}\n\ninterface OptionsConfig {\n emitToolCalls?: boolean | string | string[];\n emitMessages?: boolean;\n emitAll?: boolean;\n emitIntermediateState?: IntermediateStateConfig[];\n}\n\nexport const CopilotKitPropertiesAnnotation = Annotation.Root({\n actions: Annotation<any[]>,\n context: Annotation<{ description: string; value: string }[]>,\n});\n\nexport const CopilotKitStateAnnotation = Annotation.Root({\n copilotkit: Annotation<typeof CopilotKitPropertiesAnnotation.State>,\n ...MessagesAnnotation.spec,\n});\n\nexport type CopilotKitState = typeof CopilotKitStateAnnotation.State;\nexport type CopilotKitProperties = typeof CopilotKitPropertiesAnnotation.State;\n\n/**\n * Customize the LangGraph configuration for use in CopilotKit.\n *\n * To the CopilotKit SDK, run:\n *\n * ```bash\n * npm install @copilotkit/sdk-js\n * ```\n *\n * ### Examples\n *\n * Disable emitting messages and tool calls:\n *\n * ```typescript\n * import { copilotkitCustomizeConfig } from \"@copilotkit/sdk-js\";\n *\n * config = copilotkitCustomizeConfig(\n * config,\n * emitMessages=false,\n * emitToolCalls=false\n * )\n * ```\n *\n * To emit a tool call as streaming LangGraph state, pass the destination key in state,\n * the tool name and optionally the tool argument. (If you don't pass the argument name,\n * all arguments are emitted under the state key.)\n *\n * ```typescript\n * import { copilotkitCustomizeConfig } from \"@copilotkit/sdk-js\";\n *\n * config = copilotkitCustomizeConfig(\n * config,\n * emitIntermediateState=[\n * {\n * \"stateKey\": \"steps\",\n * \"tool\": \"SearchTool\",\n * \"toolArgument\": \"steps\",\n * },\n * ],\n * )\n * ```\n */\nexport function copilotkitCustomizeConfig(\n /**\n * The LangChain/LangGraph configuration to customize.\n */\n baseConfig: RunnableConfig,\n /**\n * Configuration options:\n * - `emitMessages: boolean?`\n * Configure how messages are emitted. By default, all messages are emitted. Pass false to\n * disable emitting messages.\n * - `emitToolCalls: boolean | string | string[]?`\n * Configure how tool calls are emitted. By default, all tool calls are emitted. Pass false to\n * disable emitting tool calls. Pass a string or list of strings to emit only specific tool calls.\n * - `emitIntermediateState: IntermediateStateConfig[]?`\n * Lets you emit tool calls as streaming LangGraph state.\n */\n options?: OptionsConfig,\n): RunnableConfig {\n if (baseConfig && typeof baseConfig !== \"object\") {\n throw new CopilotKitMisuseError({\n message: \"baseConfig must be an object or null/undefined\",\n });\n }\n\n if (options && typeof options !== \"object\") {\n throw new CopilotKitMisuseError({\n message: \"options must be an object when provided\",\n });\n }\n\n // Validate emitIntermediateState structure\n if (options?.emitIntermediateState) {\n if (!Array.isArray(options.emitIntermediateState)) {\n throw new CopilotKitMisuseError({\n message: \"emitIntermediateState must be an array when provided\",\n });\n }\n\n options.emitIntermediateState.forEach((state, index) => {\n if (!state || typeof state !== \"object\") {\n throw new CopilotKitMisuseError({\n message: `emitIntermediateState[${index}] must be an object`,\n });\n }\n\n if (!state.stateKey || typeof state.stateKey !== \"string\") {\n throw new CopilotKitMisuseError({\n message: `emitIntermediateState[${index}] must have a valid 'stateKey' string property`,\n });\n }\n\n if (!state.tool || typeof state.tool !== \"string\") {\n throw new CopilotKitMisuseError({\n message: `emitIntermediateState[${index}] must have a valid 'tool' string property`,\n });\n }\n\n if (state.toolArgument && typeof state.toolArgument !== \"string\") {\n throw new CopilotKitMisuseError({\n message: `emitIntermediateState[${index}].toolArgument must be a string when provided`,\n });\n }\n });\n }\n\n try {\n const metadata = baseConfig?.metadata || {};\n\n if (options?.emitAll) {\n metadata[\"copilotkit:emit-tool-calls\"] = true;\n metadata[\"copilotkit:emit-messages\"] = true;\n } else {\n if (options?.emitToolCalls !== undefined) {\n metadata[\"copilotkit:emit-tool-calls\"] = options.emitToolCalls;\n }\n if (options?.emitMessages !== undefined) {\n metadata[\"copilotkit:emit-messages\"] = options.emitMessages;\n }\n }\n\n if (options?.emitIntermediateState) {\n const snakeCaseIntermediateState = options.emitIntermediateState.map((state) => ({\n tool: state.tool,\n tool_argument: state.toolArgument,\n state_key: state.stateKey,\n }));\n\n metadata[\"copilotkit:emit-intermediate-state\"] = snakeCaseIntermediateState;\n }\n\n baseConfig = baseConfig || {};\n\n return {\n ...baseConfig,\n metadata: metadata,\n };\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to customize config: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Exits the current agent after the run completes. Calling copilotkit_exit() will\n * not immediately stop the agent. Instead, it signals to CopilotKit to stop the agent after\n * the run completes.\n *\n * ### Examples\n *\n * ```typescript\n * import { copilotkitExit } from \"@copilotkit/sdk-js\";\n *\n * async function myNode(state: Any):\n * await copilotkitExit(config)\n * return state\n * ```\n */\nexport async function copilotkitExit(\n /**\n * The LangChain/LangGraph configuration.\n */\n config: RunnableConfig,\n) {\n if (!config) {\n throw new CopilotKitMisuseError({\n message: \"LangGraph configuration is required for copilotkitExit\",\n });\n }\n\n try {\n await dispatchCustomEvent(\"copilotkit_exit\", {}, config);\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to dispatch exit event: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Emits intermediate state to CopilotKit. Useful if you have a longer running node and you want to\n * update the user with the current state of the node.\n *\n * ### Examples\n *\n * ```typescript\n * import { copilotkitEmitState } from \"@copilotkit/sdk-js\";\n *\n * for (let i = 0; i < 10; i++) {\n * await someLongRunningOperation(i);\n * await copilotkitEmitState(config, { progress: i });\n * }\n * ```\n */\nexport async function copilotkitEmitState(\n /**\n * The LangChain/LangGraph configuration.\n */\n config: RunnableConfig,\n /**\n * The state to emit.\n */\n state: any,\n) {\n if (!config) {\n throw new CopilotKitMisuseError({\n message: \"LangGraph configuration is required for copilotkitEmitState\",\n });\n }\n\n if (state === undefined) {\n throw new CopilotKitMisuseError({\n message: \"State is required for copilotkitEmitState\",\n });\n }\n\n try {\n await dispatchCustomEvent(\"copilotkit_manually_emit_intermediate_state\", state, config);\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to emit state: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Manually emits a message to CopilotKit. Useful in longer running nodes to update the user.\n * Important: You still need to return the messages from the node.\n *\n * ### Examples\n *\n * ```typescript\n * import { copilotkitEmitMessage } from \"@copilotkit/sdk-js\";\n *\n * const message = \"Step 1 of 10 complete\";\n * await copilotkitEmitMessage(config, message);\n *\n * // Return the message from the node\n * return {\n * \"messages\": [AIMessage(content=message)]\n * }\n * ```\n */\nexport async function copilotkitEmitMessage(\n /**\n * The LangChain/LangGraph configuration.\n */\n config: RunnableConfig,\n /**\n * The message to emit.\n */\n message: string,\n) {\n if (!config) {\n throw new CopilotKitMisuseError({\n message: \"LangGraph configuration is required for copilotkitEmitMessage\",\n });\n }\n\n if (!message || typeof message !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Message must be a non-empty string for copilotkitEmitMessage\",\n });\n }\n\n try {\n await dispatchCustomEvent(\n \"copilotkit_manually_emit_message\",\n { message, message_id: randomId(), role: \"assistant\" },\n config,\n );\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to emit message: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Manually emits a tool call to CopilotKit.\n *\n * ### Examples\n *\n * ```typescript\n * import { copilotkitEmitToolCall } from \"@copilotkit/sdk-js\";\n *\n * await copilotkitEmitToolCall(config, name=\"SearchTool\", args={\"steps\": 10})\n * ```\n */\nexport async function copilotkitEmitToolCall(\n /**\n * The LangChain/LangGraph configuration.\n */\n config: RunnableConfig,\n /**\n * The name of the tool to emit.\n */\n name: string,\n /**\n * The arguments to emit.\n */\n args: any,\n) {\n if (!config) {\n throw new CopilotKitMisuseError({\n message: \"LangGraph configuration is required for copilotkitEmitToolCall\",\n });\n }\n\n if (!name || typeof name !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Tool name must be a non-empty string for copilotkitEmitToolCall\",\n });\n }\n\n if (args === undefined) {\n throw new CopilotKitMisuseError({\n message: \"Tool arguments are required for copilotkitEmitToolCall\",\n });\n }\n\n try {\n await dispatchCustomEvent(\n \"copilotkit_manually_emit_tool_call\",\n { name, args, id: randomId() },\n config,\n );\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to emit tool call '${name}': ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n\nexport function convertActionToDynamicStructuredTool(actionInput: any): DynamicStructuredTool<any> {\n if (!actionInput) {\n throw new CopilotKitMisuseError({\n message: \"Action input is required but was not provided\",\n });\n }\n\n if (!actionInput.name || typeof actionInput.name !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Action must have a valid 'name' property of type string\",\n });\n }\n\n if (\n actionInput.description == undefined ||\n actionInput.description == null ||\n typeof actionInput.description !== \"string\"\n ) {\n throw new CopilotKitMisuseError({\n message: `Action '${actionInput.name}' must have a valid 'description' property of type string`,\n });\n }\n\n if (!actionInput.parameters) {\n throw new CopilotKitMisuseError({\n message: `Action '${actionInput.name}' must have a 'parameters' property`,\n });\n }\n\n try {\n return new DynamicStructuredTool({\n name: actionInput.name,\n description: actionInput.description,\n schema: convertJsonSchemaToZodSchema(actionInput.parameters, true),\n func: async () => {\n return \"\";\n },\n });\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to convert action '${actionInput.name}' to DynamicStructuredTool: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Use this function to convert a list of actions you get from state\n * to a list of dynamic structured tools.\n *\n * ### Examples\n *\n * ```typescript\n * import { convertActionsToDynamicStructuredTools } from \"@copilotkit/sdk-js\";\n *\n * const tools = convertActionsToDynamicStructuredTools(state.copilotkit.actions);\n * ```\n */\nexport function convertActionsToDynamicStructuredTools(\n /**\n * The list of actions to convert.\n */\n actions: any[],\n): DynamicStructuredTool<any>[] {\n if (!Array.isArray(actions)) {\n throw new CopilotKitMisuseError({\n message: \"Actions must be an array\",\n });\n }\n\n return actions.map((action, index) => {\n try {\n return convertActionToDynamicStructuredTool(\n action.type === \"function\" ? action.function : action,\n );\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to convert action at index ${index}: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n });\n}\n\nexport function copilotKitInterrupt({\n message,\n action,\n args,\n}: {\n message?: string;\n action?: string;\n args?: Record<string, any>;\n}) {\n if (!message && !action) {\n throw new CopilotKitMisuseError({\n message:\n \"Either message or action (and optional arguments) must be provided for copilotKitInterrupt\",\n });\n }\n\n if (action && typeof action !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Action must be a string when provided to copilotKitInterrupt\",\n });\n }\n\n if (message && typeof message !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Message must be a string when provided to copilotKitInterrupt\",\n });\n }\n\n if (args && typeof args !== \"object\") {\n throw new CopilotKitMisuseError({\n message: \"Args must be an object when provided to copilotKitInterrupt\",\n });\n }\n\n let interruptValues = null;\n let interruptMessage = null;\n let answer = null;\n\n try {\n if (message) {\n interruptValues = message;\n interruptMessage = new AIMessage({ content: message, id: randomId() });\n } else {\n const toolId = randomId();\n interruptMessage = new AIMessage({\n content: \"\",\n tool_calls: [{ id: toolId, name: action, args: args ?? {} }],\n });\n interruptValues = {\n action,\n args: args ?? {},\n };\n }\n\n const response = interrupt({\n __copilotkit_interrupt_value__: interruptValues,\n __copilotkit_messages__: [interruptMessage],\n });\n answer = response[response.length - 1].content;\n\n return {\n answer,\n messages: response,\n };\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to create interrupt: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAAA;;;;;;;;;;;;;;;ACCA,sBAAoC;AACpC,oBAA8E;AAC9E,uBAA0D;AAC1D,mBAAsC;AACtC,sBAA0B;AAenB,IAAMC,iCAAiCC,4BAAWC,KAAK;EAC5DC,SAASF;EACTG,SAASH;AACX,CAAA;AAEO,IAAMI,4BAA4BJ,4BAAWC,KAAK;EACvDI,YAAYL;EACZ,GAAGM,oCAAmBC;AACxB,CAAA;AA+CO,SAASC,0BAIdC,YAYAC,SAAuB;AAEvB,MAAID,cAAc,OAAOA,eAAe,UAAU;AAChD,UAAM,IAAIE,oCAAsB;MAC9BC,SAAS;IACX,CAAA;EACF;AAEA,MAAIF,WAAW,OAAOA,YAAY,UAAU;AAC1C,UAAM,IAAIC,oCAAsB;MAC9BC,SAAS;IACX,CAAA;EACF;AAGA,MAAIF,mCAASG,uBAAuB;AAClC,QAAI,CAACC,MAAMC,QAAQL,QAAQG,qBAAqB,GAAG;AACjD,YAAM,IAAIF,oCAAsB;QAC9BC,SAAS;MACX,CAAA;IACF;AAEAF,YAAQG,sBAAsBG,QAAQ,CAACC,OAAOC,UAAAA;AAC5C,UAAI,CAACD,SAAS,OAAOA,UAAU,UAAU;AACvC,cAAM,IAAIN,oCAAsB;UAC9BC,SAAS,yBAAyBM;QACpC,CAAA;MACF;AAEA,UAAI,CAACD,MAAME,YAAY,OAAOF,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AMnB,UAAUqB,OAAOF,KAAAA;IACvI,CAAA;EACF;AACF;AA3CgBe;AAwDT,SAASQ,uCAIdpD,SAAc;AAEd,MAAI,CAACY,MAAMC,QAAQb,OAAAA,GAAU;AAC3B,UAAM,IAAIS,oCAAsB;MAC9BC,SAAS;IACX,CAAA;EACF;AAEA,SAAOV,QAAQ0B,IAAI,CAAC2B,QAAQrC,UAAAA;AAC1B,QAAI;AACF,aAAO4B,qCACLS,OAAOC,SAAS,aAAaD,OAAOE,WAAWF,MAAAA;IAEnD,SAASxB,OAAP;AACA,YAAM,IAAIpB,oCAAsB;QAC9BC,SAAS,qCAAqCM,UAAUa,iBAAiBC,QAAQD,MAAMnB,UAAUqB,OAAOF,KAAAA;MAC1G,CAAA;IACF;EACF,CAAA;AACF;AAvBgBuB;;;ADrahBI,QAAQC,KACN,mJAAA;","names":["console","CopilotKitPropertiesAnnotation","Annotation","Root","actions","context","CopilotKitStateAnnotation","copilotkit","MessagesAnnotation","spec","copilotkitCustomizeConfig","baseConfig","options","CopilotKitMisuseError","message","emitIntermediateState","Array","isArray","forEach","state","index","stateKey","tool","toolArgument","metadata","emitAll","emitToolCalls","undefined","emitMessages","snakeCaseIntermediateState","map","tool_argument","state_key","error","Error","String","copilotkitExit","config","dispatchCustomEvent","copilotkitEmitState","copilotkitEmitMessage","message_id","randomId","role","copilotkitEmitToolCall","name","args","id","convertActionToDynamicStructuredTool","actionInput","description","parameters","DynamicStructuredTool","schema","convertJsonSchemaToZodSchema","func","convertActionsToDynamicStructuredTools","action","type","function","console","warn"]}
|
|
1
|
+
{"version":3,"sources":["../src/langchain.ts","../src/langgraph/types.ts","../src/langgraph/utils.ts"],"sourcesContent":["console.warn(\n \"Warning: '@copilotkit/sdk-js/langchain' is deprecated and will be removed in a future release. Please use '@copilotkit/sdk-js/langgraph' instead.\",\n);\n\nexport {\n CopilotKitPropertiesAnnotation,\n CopilotKitStateAnnotation,\n type CopilotKitState,\n type CopilotKitProperties,\n copilotkitCustomizeConfig as copilotKitCustomizeConfig,\n copilotkitExit as copilotKitExit,\n copilotkitEmitState as copilotKitEmitState,\n copilotkitEmitMessage as copilotKitEmitMessage,\n copilotkitEmitToolCall as copilotKitEmitToolCall,\n convertActionToDynamicStructuredTool,\n convertActionsToDynamicStructuredTools,\n} from \"./langgraph\";\n","import { Annotation, MessagesAnnotation } from \"@langchain/langgraph\";\n\nexport const CopilotKitPropertiesAnnotation = Annotation.Root({\n actions: Annotation<any[]>,\n context: Annotation<{ description: string; value: string }[]>,\n interceptedToolCalls: Annotation<any[]>,\n originalAIMessageId: Annotation<string>,\n});\n\nexport const CopilotKitStateAnnotation = Annotation.Root({\n copilotkit: Annotation<typeof CopilotKitPropertiesAnnotation.State>,\n ...MessagesAnnotation.spec,\n});\n\nexport interface IntermediateStateConfig {\n stateKey: string;\n tool: string;\n toolArgument?: string;\n}\n\nexport interface OptionsConfig {\n emitToolCalls?: boolean | string | string[];\n emitMessages?: boolean;\n emitAll?: boolean;\n emitIntermediateState?: IntermediateStateConfig[];\n}\n\nexport type CopilotKitState = typeof CopilotKitStateAnnotation.State;\nexport type CopilotKitProperties = typeof CopilotKitPropertiesAnnotation.State;\n","import { RunnableConfig } from \"@langchain/core/runnables\";\nimport { dispatchCustomEvent } from \"@langchain/core/callbacks/dispatch\";\nimport { convertJsonSchemaToZodSchema, randomId, CopilotKitMisuseError } from \"@copilotkit/shared\";\nimport { interrupt } from \"@langchain/langgraph\";\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { AIMessage } from \"@langchain/core/messages\";\nimport { OptionsConfig } from \"./types\";\n\n/**\n * Customize the LangGraph configuration for use in CopilotKit.\n *\n * To the CopilotKit SDK, run:\n *\n * ```bash\n * npm install @copilotkit/sdk-js\n * ```\n *\n * ### Examples\n *\n * Disable emitting messages and tool calls:\n *\n * ```typescript\n * import { copilotkitCustomizeConfig } from \"@copilotkit/sdk-js\";\n *\n * config = copilotkitCustomizeConfig(\n * config,\n * emitMessages=false,\n * emitToolCalls=false\n * )\n * ```\n *\n * To emit a tool call as streaming LangGraph state, pass the destination key in state,\n * the tool name and optionally the tool argument. (If you don't pass the argument name,\n * all arguments are emitted under the state key.)\n *\n * ```typescript\n * import { copilotkitCustomizeConfig } from \"@copilotkit/sdk-js\";\n *\n * config = copilotkitCustomizeConfig(\n * config,\n * emitIntermediateState=[\n * {\n * \"stateKey\": \"steps\",\n * \"tool\": \"SearchTool\",\n * \"toolArgument\": \"steps\",\n * },\n * ],\n * )\n * ```\n */\nexport function copilotkitCustomizeConfig(\n /**\n * The LangChain/LangGraph configuration to customize.\n */\n baseConfig: RunnableConfig,\n /**\n * Configuration options:\n * - `emitMessages: boolean?`\n * Configure how messages are emitted. By default, all messages are emitted. Pass false to\n * disable emitting messages.\n * - `emitToolCalls: boolean | string | string[]?`\n * Configure how tool calls are emitted. By default, all tool calls are emitted. Pass false to\n * disable emitting tool calls. Pass a string or list of strings to emit only specific tool calls.\n * - `emitIntermediateState: IntermediateStateConfig[]?`\n * Lets you emit tool calls as streaming LangGraph state.\n */\n options?: OptionsConfig,\n): RunnableConfig {\n if (baseConfig && typeof baseConfig !== \"object\") {\n throw new CopilotKitMisuseError({\n message: \"baseConfig must be an object or null/undefined\",\n });\n }\n\n if (options && typeof options !== \"object\") {\n throw new CopilotKitMisuseError({\n message: \"options must be an object when provided\",\n });\n }\n\n // Validate emitIntermediateState structure\n if (options?.emitIntermediateState) {\n if (!Array.isArray(options.emitIntermediateState)) {\n throw new CopilotKitMisuseError({\n message: \"emitIntermediateState must be an array when provided\",\n });\n }\n\n options.emitIntermediateState.forEach((state, index) => {\n if (!state || typeof state !== \"object\") {\n throw new CopilotKitMisuseError({\n message: `emitIntermediateState[${index}] must be an object`,\n });\n }\n\n if (!state.stateKey || typeof state.stateKey !== \"string\") {\n throw new CopilotKitMisuseError({\n message: `emitIntermediateState[${index}] must have a valid 'stateKey' string property`,\n });\n }\n\n if (!state.tool || typeof state.tool !== \"string\") {\n throw new CopilotKitMisuseError({\n message: `emitIntermediateState[${index}] must have a valid 'tool' string property`,\n });\n }\n\n if (state.toolArgument && typeof state.toolArgument !== \"string\") {\n throw new CopilotKitMisuseError({\n message: `emitIntermediateState[${index}].toolArgument must be a string when provided`,\n });\n }\n });\n }\n\n try {\n const metadata = baseConfig?.metadata || {};\n\n if (options?.emitAll) {\n metadata[\"copilotkit:emit-tool-calls\"] = true;\n metadata[\"copilotkit:emit-messages\"] = true;\n } else {\n if (options?.emitToolCalls !== undefined) {\n metadata[\"copilotkit:emit-tool-calls\"] = options.emitToolCalls;\n }\n if (options?.emitMessages !== undefined) {\n metadata[\"copilotkit:emit-messages\"] = options.emitMessages;\n }\n }\n\n if (options?.emitIntermediateState) {\n const snakeCaseIntermediateState = options.emitIntermediateState.map((state) => ({\n tool: state.tool,\n tool_argument: state.toolArgument,\n state_key: state.stateKey,\n }));\n\n metadata[\"copilotkit:emit-intermediate-state\"] = snakeCaseIntermediateState;\n }\n\n baseConfig = baseConfig || {};\n\n return {\n ...baseConfig,\n metadata: metadata,\n };\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to customize config: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Exits the current agent after the run completes. Calling copilotkit_exit() will\n * not immediately stop the agent. Instead, it signals to CopilotKit to stop the agent after\n * the run completes.\n *\n * ### Examples\n *\n * ```typescript\n * import { copilotkitExit } from \"@copilotkit/sdk-js\";\n *\n * async function myNode(state: Any):\n * await copilotkitExit(config)\n * return state\n * ```\n */\nexport async function copilotkitExit(\n /**\n * The LangChain/LangGraph configuration.\n */\n config: RunnableConfig,\n) {\n if (!config) {\n throw new CopilotKitMisuseError({\n message: \"LangGraph configuration is required for copilotkitExit\",\n });\n }\n\n try {\n await dispatchCustomEvent(\"copilotkit_exit\", {}, config);\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to dispatch exit event: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Emits intermediate state to CopilotKit. Useful if you have a longer running node and you want to\n * update the user with the current state of the node.\n *\n * ### Examples\n *\n * ```typescript\n * import { copilotkitEmitState } from \"@copilotkit/sdk-js\";\n *\n * for (let i = 0; i < 10; i++) {\n * await someLongRunningOperation(i);\n * await copilotkitEmitState(config, { progress: i });\n * }\n * ```\n */\nexport async function copilotkitEmitState(\n /**\n * The LangChain/LangGraph configuration.\n */\n config: RunnableConfig,\n /**\n * The state to emit.\n */\n state: any,\n) {\n if (!config) {\n throw new CopilotKitMisuseError({\n message: \"LangGraph configuration is required for copilotkitEmitState\",\n });\n }\n\n if (state === undefined) {\n throw new CopilotKitMisuseError({\n message: \"State is required for copilotkitEmitState\",\n });\n }\n\n try {\n await dispatchCustomEvent(\"copilotkit_manually_emit_intermediate_state\", state, config);\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to emit state: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Manually emits a message to CopilotKit. Useful in longer running nodes to update the user.\n * Important: You still need to return the messages from the node.\n *\n * ### Examples\n *\n * ```typescript\n * import { copilotkitEmitMessage } from \"@copilotkit/sdk-js\";\n *\n * const message = \"Step 1 of 10 complete\";\n * await copilotkitEmitMessage(config, message);\n *\n * // Return the message from the node\n * return {\n * \"messages\": [AIMessage(content=message)]\n * }\n * ```\n */\nexport async function copilotkitEmitMessage(\n /**\n * The LangChain/LangGraph configuration.\n */\n config: RunnableConfig,\n /**\n * The message to emit.\n */\n message: string,\n) {\n if (!config) {\n throw new CopilotKitMisuseError({\n message: \"LangGraph configuration is required for copilotkitEmitMessage\",\n });\n }\n\n if (!message || typeof message !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Message must be a non-empty string for copilotkitEmitMessage\",\n });\n }\n\n try {\n await dispatchCustomEvent(\n \"copilotkit_manually_emit_message\",\n { message, message_id: randomId(), role: \"assistant\" },\n config,\n );\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to emit message: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Manually emits a tool call to CopilotKit.\n *\n * ### Examples\n *\n * ```typescript\n * import { copilotkitEmitToolCall } from \"@copilotkit/sdk-js\";\n *\n * await copilotkitEmitToolCall(config, name=\"SearchTool\", args={\"steps\": 10})\n * ```\n */\nexport async function copilotkitEmitToolCall(\n /**\n * The LangChain/LangGraph configuration.\n */\n config: RunnableConfig,\n /**\n * The name of the tool to emit.\n */\n name: string,\n /**\n * The arguments to emit.\n */\n args: any,\n) {\n if (!config) {\n throw new CopilotKitMisuseError({\n message: \"LangGraph configuration is required for copilotkitEmitToolCall\",\n });\n }\n\n if (!name || typeof name !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Tool name must be a non-empty string for copilotkitEmitToolCall\",\n });\n }\n\n if (args === undefined) {\n throw new CopilotKitMisuseError({\n message: \"Tool arguments are required for copilotkitEmitToolCall\",\n });\n }\n\n try {\n await dispatchCustomEvent(\n \"copilotkit_manually_emit_tool_call\",\n { name, args, id: randomId() },\n config,\n );\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to emit tool call '${name}': ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n\nexport function convertActionToDynamicStructuredTool(actionInput: any): DynamicStructuredTool<any> {\n if (!actionInput) {\n throw new CopilotKitMisuseError({\n message: \"Action input is required but was not provided\",\n });\n }\n\n if (!actionInput.name || typeof actionInput.name !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Action must have a valid 'name' property of type string\",\n });\n }\n\n if (\n actionInput.description == undefined ||\n actionInput.description == null ||\n typeof actionInput.description !== \"string\"\n ) {\n throw new CopilotKitMisuseError({\n message: `Action '${actionInput.name}' must have a valid 'description' property of type string`,\n });\n }\n\n if (!actionInput.parameters) {\n throw new CopilotKitMisuseError({\n message: `Action '${actionInput.name}' must have a 'parameters' property`,\n });\n }\n\n try {\n return new DynamicStructuredTool({\n name: actionInput.name,\n description: actionInput.description,\n schema: convertJsonSchemaToZodSchema(actionInput.parameters, true),\n func: async () => {\n return \"\";\n },\n });\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to convert action '${actionInput.name}' to DynamicStructuredTool: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n/**\n * Use this function to convert a list of actions you get from state\n * to a list of dynamic structured tools.\n *\n * ### Examples\n *\n * ```typescript\n * import { convertActionsToDynamicStructuredTools } from \"@copilotkit/sdk-js\";\n *\n * const tools = convertActionsToDynamicStructuredTools(state.copilotkit.actions);\n * ```\n */\nexport function convertActionsToDynamicStructuredTools(\n /**\n * The list of actions to convert.\n */\n actions: any[],\n): DynamicStructuredTool<any>[] {\n if (!Array.isArray(actions)) {\n throw new CopilotKitMisuseError({\n message: \"Actions must be an array\",\n });\n }\n\n return actions.map((action, index) => {\n try {\n return convertActionToDynamicStructuredTool(\n action.type === \"function\" ? action.function : action,\n );\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to convert action at index ${index}: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n });\n}\n\nexport function copilotKitInterrupt({\n message,\n action,\n args,\n}: {\n message?: string;\n action?: string;\n args?: Record<string, any>;\n}) {\n if (!message && !action) {\n throw new CopilotKitMisuseError({\n message:\n \"Either message or action (and optional arguments) must be provided for copilotKitInterrupt\",\n });\n }\n\n if (action && typeof action !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Action must be a string when provided to copilotKitInterrupt\",\n });\n }\n\n if (message && typeof message !== \"string\") {\n throw new CopilotKitMisuseError({\n message: \"Message must be a string when provided to copilotKitInterrupt\",\n });\n }\n\n if (args && typeof args !== \"object\") {\n throw new CopilotKitMisuseError({\n message: \"Args must be an object when provided to copilotKitInterrupt\",\n });\n }\n\n let interruptValues = null;\n let interruptMessage = null;\n let answer = null;\n\n try {\n if (message) {\n interruptValues = message;\n interruptMessage = new AIMessage({ content: message, id: randomId() });\n } else {\n const toolId = randomId();\n interruptMessage = new AIMessage({\n content: \"\",\n tool_calls: [{ id: toolId, name: action, args: args ?? {} }],\n });\n interruptValues = {\n action,\n args: args ?? {},\n };\n }\n\n const response = interrupt({\n __copilotkit_interrupt_value__: interruptValues,\n __copilotkit_messages__: [interruptMessage],\n });\n answer = response[response.length - 1].content;\n\n return {\n answer,\n messages: response,\n };\n } catch (error) {\n throw new CopilotKitMisuseError({\n message: `Failed to create interrupt: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAAA;;;;;;;;;;;;;;;ACAA,uBAA+C;AAExC,IAAMC,iCAAiCC,4BAAWC,KAAK;EAC5DC,SAASF;EACTG,SAASH;EACTI,sBAAsBJ;EACtBK,qBAAqBL;AACvB,CAAA;AAEO,IAAMM,4BAA4BN,4BAAWC,KAAK;EACvDM,YAAYP;EACZ,GAAGQ,oCAAmBC;AACxB,CAAA;;;ACXA,sBAAoC;AACpC,oBAA8E;AAC9E,IAAAC,oBAA0B;AAC1B,mBAAsC;AACtC,sBAA0B;AA6CnB,SAASC,0BAIdC,YAYAC,SAAuB;AAEvB,MAAID,cAAc,OAAOA,eAAe,UAAU;AAChD,UAAM,IAAIE,oCAAsB;MAC9BC,SAAS;IACX,CAAA;EACF;AAEA,MAAIF,WAAW,OAAOA,YAAY,UAAU;AAC1C,UAAM,IAAIC,oCAAsB;MAC9BC,SAAS;IACX,CAAA;EACF;AAGA,MAAIF,mCAASG,uBAAuB;AAClC,QAAI,CAACC,MAAMC,QAAQL,QAAQG,qBAAqB,GAAG;AACjD,YAAM,IAAIF,oCAAsB;QAC9BC,SAAS;MACX,CAAA;IACF;AAEAF,YAAQG,sBAAsBG,QAAQ,CAACC,OAAOC,UAAAA;AAC5C,UAAI,CAACD,SAAS,OAAOA,UAAU,UAAU;AACvC,cAAM,IAAIN,oCAAsB;UAC9BC,SAAS,yBAAyBM;QACpC,CAAA;MACF;AAEA,UAAI,CAACD,MAAME,YAAY,OAAOF,MAAME,aAAa,UAAU;AACzD,cAAM,IAAIR,oCAAsB;UAC9BC,SAAS,yBAAyBM;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ASQ,uCAIdC,SAAc;AAEd,MAAI,CAACzC,MAAMC,QAAQwC,OAAAA,GAAU;AAC3B,UAAM,IAAI5C,oCAAsB;MAC9BC,SAAS;IACX,CAAA;EACF;AAEA,SAAO2C,QAAQ3B,IAAI,CAAC4B,QAAQtC,UAAAA;AAC1B,QAAI;AACF,aAAO4B,qCACLU,OAAOC,SAAS,aAAaD,OAAOE,WAAWF,MAAAA;IAEnD,SAASzB,OAAP;AACA,YAAM,IAAIpB,oCAAsB;QAC9BC,SAAS,qCAAqCM,UAAUa,iBAAiBC,QAAQD,MAAMnB,UAAUqB,OAAOF,KAAAA;MAC1G,CAAA;IACF;EACF,CAAA;AACF;AAvBgBuB;;;AF5YhBK,QAAQC,KACN,mJAAA;","names":["console","CopilotKitPropertiesAnnotation","Annotation","Root","actions","context","interceptedToolCalls","originalAIMessageId","CopilotKitStateAnnotation","copilotkit","MessagesAnnotation","spec","import_langgraph","copilotkitCustomizeConfig","baseConfig","options","CopilotKitMisuseError","message","emitIntermediateState","Array","isArray","forEach","state","index","stateKey","tool","toolArgument","metadata","emitAll","emitToolCalls","undefined","emitMessages","snakeCaseIntermediateState","map","tool_argument","state_key","error","Error","String","copilotkitExit","config","dispatchCustomEvent","copilotkitEmitState","copilotkitEmitMessage","message_id","randomId","role","copilotkitEmitToolCall","name","args","id","convertActionToDynamicStructuredTool","actionInput","description","parameters","DynamicStructuredTool","schema","convertJsonSchemaToZodSchema","func","convertActionsToDynamicStructuredTools","actions","action","type","function","console","warn"]}
|
package/dist/langchain.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
copilotkitEmitState,
|
|
9
9
|
copilotkitEmitToolCall,
|
|
10
10
|
copilotkitExit
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-JLGOQLGS.mjs";
|
|
12
12
|
|
|
13
13
|
// src/langchain.ts
|
|
14
14
|
console.warn("Warning: '@copilotkit/sdk-js/langchain' is deprecated and will be removed in a future release. Please use '@copilotkit/sdk-js/langgraph' instead.");
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { c as CopilotKitProperties, C as CopilotKitPropertiesAnnotation, b as CopilotKitState, a as CopilotKitStateAnnotation, I as IntermediateStateConfig, O as OptionsConfig, i as convertActionToDynamicStructuredTool, j as convertActionsToDynamicStructuredTools, k as copilotKitInterrupt, d as copilotkitCustomizeConfig, g as copilotkitEmitMessage, f as copilotkitEmitState, h as copilotkitEmitToolCall, e as copilotkitExit } from '../langchain-2645763d.js';
|
|
2
|
+
import * as langchain from 'langchain';
|
|
3
|
+
import { InteropZodObject } from '@langchain/core/utils/types';
|
|
4
|
+
import '@langchain/core/messages';
|
|
5
|
+
import '@langchain/langgraph';
|
|
6
|
+
import '@langchain/core/runnables';
|
|
7
|
+
import '@langchain/core/tools';
|
|
8
|
+
|
|
9
|
+
declare const copilotkitMiddleware: langchain.AgentMiddleware<InteropZodObject, undefined, any>;
|
|
10
|
+
|
|
11
|
+
export { copilotkitMiddleware };
|