langchain 1.2.24 → 1.2.25
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 +11 -0
- package/dist/_virtual/{rolldown_runtime.cjs → _rolldown/runtime.cjs} +24 -13
- package/dist/_virtual/_rolldown/runtime.js +36 -0
- package/dist/agents/ReactAgent.cjs +52 -65
- package/dist/agents/ReactAgent.cjs.map +1 -1
- package/dist/agents/ReactAgent.d.cts.map +1 -1
- package/dist/agents/ReactAgent.d.ts.map +1 -1
- package/dist/agents/ReactAgent.js +11 -24
- package/dist/agents/ReactAgent.js.map +1 -1
- package/dist/agents/RunnableCallable.cjs +7 -7
- package/dist/agents/RunnableCallable.cjs.map +1 -1
- package/dist/agents/RunnableCallable.js.map +1 -1
- package/dist/agents/annotation.cjs +41 -37
- package/dist/agents/annotation.cjs.map +1 -1
- package/dist/agents/annotation.js +21 -17
- package/dist/agents/annotation.js.map +1 -1
- package/dist/agents/constants.d.cts.map +1 -1
- package/dist/agents/constants.d.ts.map +1 -1
- package/dist/agents/errors.cjs +3 -3
- package/dist/agents/errors.cjs.map +1 -1
- package/dist/agents/errors.d.cts.map +1 -1
- package/dist/agents/errors.d.ts.map +1 -1
- package/dist/agents/errors.js.map +1 -1
- package/dist/agents/index.cjs.map +1 -1
- package/dist/agents/index.d.cts +2 -2
- package/dist/agents/index.d.cts.map +1 -1
- package/dist/agents/index.d.ts +2 -2
- package/dist/agents/index.d.ts.map +1 -1
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/middleware/constants.cjs +2 -2
- package/dist/agents/middleware/constants.cjs.map +1 -1
- package/dist/agents/middleware/constants.js.map +1 -1
- package/dist/agents/middleware/contextEditing.cjs +14 -27
- package/dist/agents/middleware/contextEditing.cjs.map +1 -1
- package/dist/agents/middleware/contextEditing.d.cts +2 -3
- package/dist/agents/middleware/contextEditing.d.cts.map +1 -1
- package/dist/agents/middleware/contextEditing.d.ts +2 -3
- package/dist/agents/middleware/contextEditing.d.ts.map +1 -1
- package/dist/agents/middleware/contextEditing.js +5 -18
- package/dist/agents/middleware/contextEditing.js.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.cjs +3 -4
- package/dist/agents/middleware/dynamicSystemPrompt.cjs.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.cts +2 -2
- package/dist/agents/middleware/dynamicSystemPrompt.d.cts.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.ts +2 -2
- package/dist/agents/middleware/dynamicSystemPrompt.d.ts.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.js +1 -2
- package/dist/agents/middleware/dynamicSystemPrompt.js.map +1 -1
- package/dist/agents/middleware/error.cjs +2 -2
- package/dist/agents/middleware/error.cjs.map +1 -1
- package/dist/agents/middleware/error.js.map +1 -1
- package/dist/agents/middleware/hitl.cjs +16 -26
- package/dist/agents/middleware/hitl.cjs.map +1 -1
- package/dist/agents/middleware/hitl.d.cts.map +1 -1
- package/dist/agents/middleware/hitl.d.ts.map +1 -1
- package/dist/agents/middleware/hitl.js +8 -18
- package/dist/agents/middleware/hitl.js.map +1 -1
- package/dist/agents/middleware/index.js +2 -0
- package/dist/agents/middleware/llmToolSelector.cjs +9 -10
- package/dist/agents/middleware/llmToolSelector.cjs.map +1 -1
- package/dist/agents/middleware/llmToolSelector.d.cts +4 -4
- package/dist/agents/middleware/llmToolSelector.d.cts.map +1 -1
- package/dist/agents/middleware/llmToolSelector.d.ts +4 -4
- package/dist/agents/middleware/llmToolSelector.d.ts.map +1 -1
- package/dist/agents/middleware/llmToolSelector.js +3 -4
- package/dist/agents/middleware/llmToolSelector.js.map +1 -1
- package/dist/agents/middleware/modelCallLimit.cjs +5 -5
- package/dist/agents/middleware/modelCallLimit.cjs.map +1 -1
- package/dist/agents/middleware/modelCallLimit.d.cts +2 -2
- package/dist/agents/middleware/modelCallLimit.d.cts.map +1 -1
- package/dist/agents/middleware/modelCallLimit.d.ts +2 -2
- package/dist/agents/middleware/modelCallLimit.d.ts.map +1 -1
- package/dist/agents/middleware/modelCallLimit.js.map +1 -1
- package/dist/agents/middleware/modelFallback.cjs.map +1 -1
- package/dist/agents/middleware/modelFallback.d.cts +0 -1
- package/dist/agents/middleware/modelFallback.d.cts.map +1 -1
- package/dist/agents/middleware/modelFallback.d.ts +0 -1
- package/dist/agents/middleware/modelFallback.d.ts.map +1 -1
- package/dist/agents/middleware/modelFallback.js.map +1 -1
- package/dist/agents/middleware/modelRetry.cjs +19 -17
- package/dist/agents/middleware/modelRetry.cjs.map +1 -1
- package/dist/agents/middleware/modelRetry.d.cts +0 -1
- package/dist/agents/middleware/modelRetry.d.cts.map +1 -1
- package/dist/agents/middleware/modelRetry.d.ts +0 -1
- package/dist/agents/middleware/modelRetry.d.ts.map +1 -1
- package/dist/agents/middleware/modelRetry.js +15 -13
- package/dist/agents/middleware/modelRetry.js.map +1 -1
- package/dist/agents/middleware/pii.cjs +21 -32
- package/dist/agents/middleware/pii.cjs.map +1 -1
- package/dist/agents/middleware/pii.d.cts +0 -1
- package/dist/agents/middleware/pii.d.cts.map +1 -1
- package/dist/agents/middleware/pii.d.ts +0 -1
- package/dist/agents/middleware/pii.d.ts.map +1 -1
- package/dist/agents/middleware/pii.js +10 -21
- package/dist/agents/middleware/pii.js.map +1 -1
- package/dist/agents/middleware/piiRedaction.cjs +22 -28
- package/dist/agents/middleware/piiRedaction.cjs.map +1 -1
- package/dist/agents/middleware/piiRedaction.d.cts +0 -1
- package/dist/agents/middleware/piiRedaction.d.cts.map +1 -1
- package/dist/agents/middleware/piiRedaction.d.ts +0 -1
- package/dist/agents/middleware/piiRedaction.d.ts.map +1 -1
- package/dist/agents/middleware/piiRedaction.js +8 -14
- package/dist/agents/middleware/piiRedaction.js.map +1 -1
- package/dist/agents/middleware/provider/anthropic/promptCaching.cjs +5 -8
- package/dist/agents/middleware/provider/anthropic/promptCaching.cjs.map +1 -1
- package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts +2 -2
- package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts.map +1 -1
- package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts +2 -2
- package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts.map +1 -1
- package/dist/agents/middleware/provider/anthropic/promptCaching.js +3 -6
- package/dist/agents/middleware/provider/anthropic/promptCaching.js.map +1 -1
- package/dist/agents/middleware/provider/openai/moderation.cjs +17 -22
- package/dist/agents/middleware/provider/openai/moderation.cjs.map +1 -1
- package/dist/agents/middleware/provider/openai/moderation.d.cts +0 -2
- package/dist/agents/middleware/provider/openai/moderation.d.cts.map +1 -1
- package/dist/agents/middleware/provider/openai/moderation.d.ts +0 -2
- package/dist/agents/middleware/provider/openai/moderation.d.ts.map +1 -1
- package/dist/agents/middleware/provider/openai/moderation.js +10 -15
- package/dist/agents/middleware/provider/openai/moderation.js.map +1 -1
- package/dist/agents/middleware/summarization.cjs +39 -62
- package/dist/agents/middleware/summarization.cjs.map +1 -1
- package/dist/agents/middleware/summarization.d.cts +2 -2
- package/dist/agents/middleware/summarization.d.cts.map +1 -1
- package/dist/agents/middleware/summarization.d.ts +2 -2
- package/dist/agents/middleware/summarization.d.ts.map +1 -1
- package/dist/agents/middleware/summarization.js +17 -40
- package/dist/agents/middleware/summarization.js.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.cjs +21 -27
- package/dist/agents/middleware/todoListMiddleware.cjs.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.d.cts +4 -4
- package/dist/agents/middleware/todoListMiddleware.d.cts.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.d.ts +4 -4
- package/dist/agents/middleware/todoListMiddleware.d.ts.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.js +12 -18
- package/dist/agents/middleware/todoListMiddleware.js.map +1 -1
- package/dist/agents/middleware/toolCallLimit.cjs +24 -46
- package/dist/agents/middleware/toolCallLimit.cjs.map +1 -1
- package/dist/agents/middleware/toolCallLimit.d.cts +2 -3
- package/dist/agents/middleware/toolCallLimit.d.cts.map +1 -1
- package/dist/agents/middleware/toolCallLimit.d.ts +2 -3
- package/dist/agents/middleware/toolCallLimit.d.ts.map +1 -1
- package/dist/agents/middleware/toolCallLimit.js +17 -39
- package/dist/agents/middleware/toolCallLimit.js.map +1 -1
- package/dist/agents/middleware/toolEmulator.cjs +8 -13
- package/dist/agents/middleware/toolEmulator.cjs.map +1 -1
- package/dist/agents/middleware/toolEmulator.d.cts +0 -1
- package/dist/agents/middleware/toolEmulator.d.cts.map +1 -1
- package/dist/agents/middleware/toolEmulator.d.ts +0 -1
- package/dist/agents/middleware/toolEmulator.d.ts.map +1 -1
- package/dist/agents/middleware/toolEmulator.js +5 -10
- package/dist/agents/middleware/toolEmulator.js.map +1 -1
- package/dist/agents/middleware/toolRetry.cjs +19 -17
- package/dist/agents/middleware/toolRetry.cjs.map +1 -1
- package/dist/agents/middleware/toolRetry.d.cts +0 -1
- package/dist/agents/middleware/toolRetry.d.cts.map +1 -1
- package/dist/agents/middleware/toolRetry.d.ts +0 -1
- package/dist/agents/middleware/toolRetry.d.ts.map +1 -1
- package/dist/agents/middleware/toolRetry.js +15 -13
- package/dist/agents/middleware/toolRetry.js.map +1 -1
- package/dist/agents/middleware/types.cjs.map +1 -1
- package/dist/agents/middleware/types.d.cts +33 -33
- package/dist/agents/middleware/types.d.cts.map +1 -1
- package/dist/agents/middleware/types.d.ts +33 -33
- package/dist/agents/middleware/types.d.ts.map +1 -1
- package/dist/agents/middleware/types.js.map +1 -1
- package/dist/agents/middleware/utils.cjs +8 -8
- package/dist/agents/middleware/utils.cjs.map +1 -1
- package/dist/agents/middleware/utils.d.cts +0 -1
- package/dist/agents/middleware/utils.d.cts.map +1 -1
- package/dist/agents/middleware/utils.d.ts +0 -1
- package/dist/agents/middleware/utils.d.ts.map +1 -1
- package/dist/agents/middleware/utils.js +3 -3
- package/dist/agents/middleware/utils.js.map +1 -1
- package/dist/agents/middleware.cjs +1 -2
- package/dist/agents/middleware.cjs.map +1 -1
- package/dist/agents/middleware.d.cts +0 -1
- package/dist/agents/middleware.d.cts.map +1 -1
- package/dist/agents/middleware.d.ts +0 -1
- package/dist/agents/middleware.d.ts.map +1 -1
- package/dist/agents/middleware.js +1 -2
- package/dist/agents/middleware.js.map +1 -1
- package/dist/agents/model.cjs.map +1 -1
- package/dist/agents/model.js.map +1 -1
- package/dist/agents/nodes/AfterAgentNode.cjs +1 -2
- package/dist/agents/nodes/AfterAgentNode.cjs.map +1 -1
- package/dist/agents/nodes/AfterAgentNode.js +1 -2
- package/dist/agents/nodes/AfterAgentNode.js.map +1 -1
- package/dist/agents/nodes/AfterModelNode.cjs +1 -2
- package/dist/agents/nodes/AfterModelNode.cjs.map +1 -1
- package/dist/agents/nodes/AfterModelNode.js +1 -2
- package/dist/agents/nodes/AfterModelNode.js.map +1 -1
- package/dist/agents/nodes/AgentNode.cjs +46 -58
- package/dist/agents/nodes/AgentNode.cjs.map +1 -1
- package/dist/agents/nodes/AgentNode.js +16 -28
- package/dist/agents/nodes/AgentNode.js.map +1 -1
- package/dist/agents/nodes/BeforeAgentNode.cjs +1 -2
- package/dist/agents/nodes/BeforeAgentNode.cjs.map +1 -1
- package/dist/agents/nodes/BeforeAgentNode.js +1 -2
- package/dist/agents/nodes/BeforeAgentNode.js.map +1 -1
- package/dist/agents/nodes/BeforeModelNode.cjs +1 -2
- package/dist/agents/nodes/BeforeModelNode.cjs.map +1 -1
- package/dist/agents/nodes/BeforeModelNode.js +1 -2
- package/dist/agents/nodes/BeforeModelNode.js.map +1 -1
- package/dist/agents/nodes/ToolNode.cjs +25 -25
- package/dist/agents/nodes/ToolNode.cjs.map +1 -1
- package/dist/agents/nodes/ToolNode.js +6 -6
- package/dist/agents/nodes/ToolNode.js.map +1 -1
- package/dist/agents/nodes/middleware.cjs +3 -3
- package/dist/agents/nodes/middleware.cjs.map +1 -1
- package/dist/agents/nodes/middleware.js.map +1 -1
- package/dist/agents/nodes/types.d.cts +0 -1
- package/dist/agents/nodes/types.d.cts.map +1 -1
- package/dist/agents/nodes/types.d.ts +0 -1
- package/dist/agents/nodes/types.d.ts.map +1 -1
- package/dist/agents/nodes/utils.cjs +16 -17
- package/dist/agents/nodes/utils.cjs.map +1 -1
- package/dist/agents/nodes/utils.js +2 -3
- package/dist/agents/nodes/utils.js.map +1 -1
- package/dist/agents/responses.cjs +20 -30
- package/dist/agents/responses.cjs.map +1 -1
- package/dist/agents/responses.d.cts +0 -1
- package/dist/agents/responses.d.cts.map +1 -1
- package/dist/agents/responses.d.ts +0 -1
- package/dist/agents/responses.d.ts.map +1 -1
- package/dist/agents/responses.js +12 -22
- package/dist/agents/responses.js.map +1 -1
- package/dist/agents/runtime.d.cts +0 -1
- package/dist/agents/runtime.d.cts.map +1 -1
- package/dist/agents/runtime.d.ts +0 -1
- package/dist/agents/runtime.d.ts.map +1 -1
- package/dist/agents/state.cjs +1 -2
- package/dist/agents/state.cjs.map +1 -1
- package/dist/agents/state.js +1 -2
- package/dist/agents/state.js.map +1 -1
- package/dist/agents/tests/utils.cjs +21 -26
- package/dist/agents/tests/utils.cjs.map +1 -1
- package/dist/agents/tests/utils.d.cts +0 -1
- package/dist/agents/tests/utils.d.cts.map +1 -1
- package/dist/agents/tests/utils.d.ts +0 -1
- package/dist/agents/tests/utils.d.ts.map +1 -1
- package/dist/agents/tests/utils.js +12 -17
- package/dist/agents/tests/utils.js.map +1 -1
- package/dist/agents/types.d.cts +4 -5
- package/dist/agents/types.d.cts.map +1 -1
- package/dist/agents/types.d.ts +4 -5
- package/dist/agents/types.d.ts.map +1 -1
- package/dist/agents/utils.cjs +32 -32
- package/dist/agents/utils.cjs.map +1 -1
- package/dist/agents/utils.js +6 -6
- package/dist/agents/utils.js.map +1 -1
- package/dist/agents/withAgentName.cjs +5 -5
- package/dist/agents/withAgentName.cjs.map +1 -1
- package/dist/agents/withAgentName.js.map +1 -1
- package/dist/chat_models/universal.cjs +34 -41
- package/dist/chat_models/universal.cjs.map +1 -1
- package/dist/chat_models/universal.d.cts.map +1 -1
- package/dist/chat_models/universal.d.ts.map +1 -1
- package/dist/chat_models/universal.js +21 -29
- package/dist/chat_models/universal.js.map +1 -1
- package/dist/hub/base.cjs +3 -4
- package/dist/hub/base.cjs.map +1 -1
- package/dist/hub/base.d.cts +0 -1
- package/dist/hub/base.d.cts.map +1 -1
- package/dist/hub/base.d.ts +0 -1
- package/dist/hub/base.d.ts.map +1 -1
- package/dist/hub/base.js +1 -2
- package/dist/hub/base.js.map +1 -1
- package/dist/hub/index.cjs +2 -2
- package/dist/hub/index.cjs.map +1 -1
- package/dist/hub/index.d.cts +0 -1
- package/dist/hub/index.d.cts.map +1 -1
- package/dist/hub/index.d.ts +0 -1
- package/dist/hub/index.d.ts.map +1 -1
- package/dist/hub/index.js +1 -2
- package/dist/hub/index.js.map +1 -1
- package/dist/hub/node.cjs +7 -13
- package/dist/hub/node.cjs.map +1 -1
- package/dist/hub/node.d.cts +0 -1
- package/dist/hub/node.d.cts.map +1 -1
- package/dist/hub/node.d.ts +0 -1
- package/dist/hub/node.d.ts.map +1 -1
- package/dist/hub/node.js +6 -13
- package/dist/hub/node.js.map +1 -1
- package/dist/index.cjs +48 -48
- package/dist/index.d.cts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -3
- package/dist/load/import_constants.cjs.map +1 -1
- package/dist/load/import_constants.js.map +1 -1
- package/dist/load/import_map.cjs +46 -47
- package/dist/load/import_map.cjs.map +1 -1
- package/dist/load/import_map.js +2 -3
- package/dist/load/import_map.js.map +1 -1
- package/dist/load/import_type.d.cts.map +1 -1
- package/dist/load/import_type.d.ts.map +1 -1
- package/dist/load/index.cjs +13 -3
- package/dist/load/index.cjs.map +1 -1
- package/dist/load/index.d.cts +9 -1
- package/dist/load/index.d.cts.map +1 -1
- package/dist/load/index.d.ts +9 -1
- package/dist/load/index.d.ts.map +1 -1
- package/dist/load/index.js +9 -0
- package/dist/load/index.js.map +1 -1
- package/dist/load/serializable.cjs +7 -6
- package/dist/load/serializable.js +4 -4
- package/dist/storage/encoder_backed.cjs +9 -10
- package/dist/storage/encoder_backed.cjs.map +1 -1
- package/dist/storage/encoder_backed.d.cts +0 -1
- package/dist/storage/encoder_backed.d.cts.map +1 -1
- package/dist/storage/encoder_backed.d.ts +0 -1
- package/dist/storage/encoder_backed.d.ts.map +1 -1
- package/dist/storage/encoder_backed.js +4 -6
- package/dist/storage/encoder_backed.js.map +1 -1
- package/dist/storage/file_system.cjs +12 -11
- package/dist/storage/file_system.cjs.map +1 -1
- package/dist/storage/file_system.d.cts +0 -1
- package/dist/storage/file_system.d.cts.map +1 -1
- package/dist/storage/file_system.d.ts +0 -1
- package/dist/storage/file_system.d.ts.map +1 -1
- package/dist/storage/file_system.js +5 -7
- package/dist/storage/file_system.js.map +1 -1
- package/dist/storage/in_memory.cjs +5 -5
- package/dist/storage/in_memory.js +2 -3
- package/package.json +6 -6
- package/dist/_virtual/rolldown_runtime.js +0 -25
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","names":[
|
|
1
|
+
{"version":3,"file":"utils.d.ts","names":[],"sources":["../../../src/agents/middleware/utils.ts"],"mappings":";;;;;;;AA0BA;;;;;;;;;iBAAgB,wBAAA,CACd,QAAA,EAAU,WAAA,IAEV,KAAA,GAAQ,KAAA,CAAM,MAAA"}
|
|
@@ -19,8 +19,8 @@ function countTokensApproximately(messages, tools) {
|
|
|
19
19
|
let totalChars = 0;
|
|
20
20
|
if (tools && tools.length > 0) {
|
|
21
21
|
let toolsChars = 0;
|
|
22
|
-
for (const tool
|
|
23
|
-
const toolDict = isLangChainTool(tool
|
|
22
|
+
for (const tool of tools) {
|
|
23
|
+
const toolDict = isLangChainTool(tool) ? convertToOpenAITool(tool) : tool;
|
|
24
24
|
toolsChars += JSON.stringify(toolDict).length;
|
|
25
25
|
}
|
|
26
26
|
totalChars += toolsChars;
|
|
@@ -41,7 +41,7 @@ function countTokensApproximately(messages, tools) {
|
|
|
41
41
|
return Math.ceil(totalChars / charsPerToken);
|
|
42
42
|
}
|
|
43
43
|
function getHookConstraint(hook) {
|
|
44
|
-
if (!hook || typeof hook === "function") return
|
|
44
|
+
if (!hook || typeof hook === "function") return;
|
|
45
45
|
return hook.canJumpTo;
|
|
46
46
|
}
|
|
47
47
|
function getHookFunction(arg) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":[
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../../../src/agents/middleware/utils.ts"],"sourcesContent":["import {\n AIMessage,\n ToolMessage,\n type BaseMessage,\n} from \"@langchain/core/messages\";\nimport { isLangChainTool } from \"@langchain/core/tools\";\nimport { convertToOpenAITool } from \"@langchain/core/utils/function_calling\";\nimport {\n AfterModelHook,\n AfterAgentHook,\n BeforeAgentHook,\n BeforeModelHook,\n} from \"./types.js\";\nimport { JumpToTarget } from \"../constants.js\";\n\n/**\n * Default token counter that approximates based on character count.\n *\n * If tools are provided, the token count also includes stringified tool schemas.\n *\n * @param messages Messages to count tokens for\n * @param tools Optional list of tools to include in the token count. Each tool\n * can be either a LangChain tool instance or a dict representing a tool schema.\n * LangChain tool instances are converted to OpenAI tool format before counting.\n * @returns Approximate token count\n */\nexport function countTokensApproximately(\n messages: BaseMessage[],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n tools?: Array<Record<string, any>> | null\n): number {\n const charsPerToken = 4;\n let totalChars = 0;\n\n // Count tokens for tools if provided\n if (tools && tools.length > 0) {\n let toolsChars = 0;\n for (const tool of tools) {\n const toolDict = isLangChainTool(tool) ? convertToOpenAITool(tool) : tool;\n toolsChars += JSON.stringify(toolDict).length;\n }\n totalChars += toolsChars;\n }\n\n for (const msg of messages) {\n let textContent: string;\n if (typeof msg.content === \"string\") {\n textContent = msg.content;\n } else if (Array.isArray(msg.content)) {\n textContent = msg.content\n .map((item) => {\n if (typeof item === \"string\") return item;\n if (item.type === \"text\" && \"text\" in item) return item.text;\n return \"\";\n })\n .join(\"\");\n } else {\n textContent = \"\";\n }\n\n if (\n AIMessage.isInstance(msg) &&\n Array.isArray(msg.tool_calls) &&\n msg.tool_calls.length > 0\n ) {\n textContent += JSON.stringify(msg.tool_calls);\n }\n\n if (ToolMessage.isInstance(msg)) {\n textContent += msg.tool_call_id ?? \"\";\n }\n\n totalChars += textContent.length;\n }\n // Approximate 1 token = 4 characters\n return Math.ceil(totalChars / charsPerToken);\n}\n\nexport function getHookConstraint(\n hook:\n | BeforeAgentHook\n | BeforeModelHook\n | AfterAgentHook\n | AfterModelHook\n | undefined\n): JumpToTarget[] | undefined {\n if (!hook || typeof hook === \"function\") {\n return undefined;\n }\n return hook.canJumpTo;\n}\n\nexport function getHookFunction(\n arg: BeforeAgentHook | BeforeModelHook | AfterAgentHook | AfterModelHook\n) {\n if (typeof arg === \"function\") {\n return arg;\n }\n return arg.hook;\n}\n\n/**\n * Sleep for the specified number of milliseconds.\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Calculate delay for a retry attempt with exponential backoff and jitter.\n *\n * @param retryNumber - The retry attempt number (0-indexed)\n * @param config - Configuration for backoff calculation\n * @returns Delay in milliseconds before next retry\n *\n * @internal Exported for testing purposes\n */\nexport function calculateRetryDelay(\n config: {\n backoffFactor: number;\n initialDelayMs: number;\n maxDelayMs: number;\n jitter: boolean;\n },\n retryNumber: number\n): number {\n const { backoffFactor, initialDelayMs, maxDelayMs, jitter } = config;\n\n let delay: number;\n if (backoffFactor === 0.0) {\n delay = initialDelayMs;\n } else {\n delay = initialDelayMs * backoffFactor ** retryNumber;\n }\n\n // Cap at maxDelayMs\n delay = Math.min(delay, maxDelayMs);\n\n if (jitter && delay > 0) {\n const jitterAmount = delay * 0.25;\n delay = delay + (Math.random() * 2 - 1) * jitterAmount;\n // Ensure delay is not negative after jitter\n delay = Math.max(0, delay);\n }\n\n return delay;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA0BA,SAAgB,yBACd,UAEA,OACQ;CACR,MAAM,gBAAgB;CACtB,IAAI,aAAa;AAGjB,KAAI,SAAS,MAAM,SAAS,GAAG;EAC7B,IAAI,aAAa;AACjB,OAAK,MAAM,QAAQ,OAAO;GACxB,MAAM,WAAW,gBAAgB,KAAK,GAAG,oBAAoB,KAAK,GAAG;AACrE,iBAAc,KAAK,UAAU,SAAS,CAAC;;AAEzC,gBAAc;;AAGhB,MAAK,MAAM,OAAO,UAAU;EAC1B,IAAI;AACJ,MAAI,OAAO,IAAI,YAAY,SACzB,eAAc,IAAI;WACT,MAAM,QAAQ,IAAI,QAAQ,CACnC,eAAc,IAAI,QACf,KAAK,SAAS;AACb,OAAI,OAAO,SAAS,SAAU,QAAO;AACrC,OAAI,KAAK,SAAS,UAAU,UAAU,KAAM,QAAO,KAAK;AACxD,UAAO;IACP,CACD,KAAK,GAAG;MAEX,eAAc;AAGhB,MACE,UAAU,WAAW,IAAI,IACzB,MAAM,QAAQ,IAAI,WAAW,IAC7B,IAAI,WAAW,SAAS,EAExB,gBAAe,KAAK,UAAU,IAAI,WAAW;AAG/C,MAAI,YAAY,WAAW,IAAI,CAC7B,gBAAe,IAAI,gBAAgB;AAGrC,gBAAc,YAAY;;AAG5B,QAAO,KAAK,KAAK,aAAa,cAAc;;AAG9C,SAAgB,kBACd,MAM4B;AAC5B,KAAI,CAAC,QAAQ,OAAO,SAAS,WAC3B;AAEF,QAAO,KAAK;;AAGd,SAAgB,gBACd,KACA;AACA,KAAI,OAAO,QAAQ,WACjB,QAAO;AAET,QAAO,IAAI;;;;;AAMb,SAAgB,MAAM,IAA2B;AAC/C,QAAO,IAAI,SAAS,YAAY,WAAW,SAAS,GAAG,CAAC;;;;;;;;;;;AAY1D,SAAgB,oBACd,QAMA,aACQ;CACR,MAAM,EAAE,eAAe,gBAAgB,YAAY,WAAW;CAE9D,IAAI;AACJ,KAAI,kBAAkB,EACpB,SAAQ;KAER,SAAQ,iBAAiB,iBAAiB;AAI5C,SAAQ,KAAK,IAAI,OAAO,WAAW;AAEnC,KAAI,UAAU,QAAQ,GAAG;EACvB,MAAM,eAAe,QAAQ;AAC7B,UAAQ,SAAS,KAAK,QAAQ,GAAG,IAAI,KAAK;AAE1C,UAAQ,KAAK,IAAI,GAAG,MAAM;;AAG5B,QAAO"}
|
|
@@ -54,7 +54,7 @@ const require_types = require('./middleware/types.cjs');
|
|
|
54
54
|
* ```
|
|
55
55
|
*/
|
|
56
56
|
function createMiddleware(config) {
|
|
57
|
-
|
|
57
|
+
return {
|
|
58
58
|
[require_types.MIDDLEWARE_BRAND]: true,
|
|
59
59
|
name: config.name,
|
|
60
60
|
stateSchema: config.stateSchema,
|
|
@@ -67,7 +67,6 @@ function createMiddleware(config) {
|
|
|
67
67
|
afterAgent: config.afterAgent,
|
|
68
68
|
tools: config.tools
|
|
69
69
|
};
|
|
70
|
-
return middleware;
|
|
71
70
|
}
|
|
72
71
|
|
|
73
72
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.cjs","names":["config: {\n /**\n * The name of the middleware\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object (InteropZodObject)\n * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n * - An AnnotationRoot\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: TTools;\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * The request parameter contains: model, messages, systemPrompt, tools, state, and runtime.\n *\n * @param request - The model request containing all the parameters needed.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n}","middleware: AgentMiddleware<\n TSchema,\n TContextSchema,\n NormalizeContextSchema<TContextSchema>,\n TTools\n >","MIDDLEWARE_BRAND"],"sources":["../../src/agents/middleware.ts"],"sourcesContent":["import type {\n InteropZodObject,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport type { StateDefinitionInit } from \"@langchain/langgraph\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport {\n MIDDLEWARE_BRAND,\n type AgentMiddleware,\n type WrapToolCallHook,\n type WrapModelCallHook,\n type BeforeAgentHook,\n type BeforeModelHook,\n type AfterModelHook,\n type AfterAgentHook,\n} from \"./middleware/types.js\";\n\n/**\n * Creates a middleware instance with automatic schema inference.\n *\n * @param config - Middleware configuration\n * @param config.name - The name of the middleware\n * @param config.stateSchema - The schema of the middleware state\n * @param config.contextSchema - The schema of the middleware context\n * @param config.wrapModelCall - The function to wrap model invocation\n * @param config.wrapToolCall - The function to wrap tool invocation\n * @param config.beforeModel - The function to run before the model call\n * @param config.afterModel - The function to run after the model call\n * @param config.beforeAgent - The function to run before the agent execution starts\n * @param config.afterAgent - The function to run after the agent execution completes\n * @returns A middleware instance\n *\n * @example Using Zod schema\n * ```ts\n * const authMiddleware = createMiddleware({\n * name: \"AuthMiddleware\",\n * stateSchema: z.object({\n * isAuthenticated: z.boolean().default(false),\n * }),\n * contextSchema: z.object({\n * userId: z.string(),\n * }),\n * beforeModel: async (state, runtime, controls) => {\n * if (!state.isAuthenticated) {\n * return controls.terminate(new Error(\"Not authenticated\"));\n * }\n * },\n * });\n * ```\n *\n * @example Using StateSchema\n * ```ts\n * import { StateSchema, ReducedValue } from \"@langchain/langgraph\";\n *\n * const historyMiddleware = createMiddleware({\n * name: \"HistoryMiddleware\",\n * stateSchema: new StateSchema({\n * count: z.number().default(0),\n * history: new ReducedValue(\n * z.array(z.string()).default(() => []),\n * { inputSchema: z.string(), reducer: (current, next) => [...current, next] }\n * ),\n * }),\n * beforeModel: async (state, runtime) => {\n * return { count: state.count + 1 };\n * },\n * });\n * ```\n */\nexport function createMiddleware<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContextSchema extends InteropZodObject | undefined = undefined,\n const TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[],\n>(config: {\n /**\n * The name of the middleware\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object (InteropZodObject)\n * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n * - An AnnotationRoot\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: TTools;\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * The request parameter contains: model, messages, systemPrompt, tools, state, and runtime.\n *\n * @param request - The model request containing all the parameters needed.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n}): AgentMiddleware<\n TSchema,\n TContextSchema,\n NormalizeContextSchema<TContextSchema>,\n TTools\n> {\n const middleware: AgentMiddleware<\n TSchema,\n TContextSchema,\n NormalizeContextSchema<TContextSchema>,\n TTools\n > = {\n [MIDDLEWARE_BRAND]: true as const,\n name: config.name,\n stateSchema: config.stateSchema,\n contextSchema: config.contextSchema,\n wrapToolCall: config.wrapToolCall,\n wrapModelCall: config.wrapModelCall,\n beforeAgent: config.beforeAgent,\n beforeModel: config.beforeModel,\n afterModel: config.afterModel,\n afterAgent: config.afterAgent,\n tools: config.tools,\n };\n\n return middleware;\n}\n\ntype NormalizeContextSchema<\n TContextSchema extends InteropZodObject | undefined = undefined,\n> = TContextSchema extends InteropZodObject\n ? InferInteropZodOutput<TContextSchema>\n : unknown;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,SAAgB,iBAOdA,QAkKA;CACA,MAAMC,aAKF;GACDC,iCAAmB;EACpB,MAAM,OAAO;EACb,aAAa,OAAO;EACpB,eAAe,OAAO;EACtB,cAAc,OAAO;EACrB,eAAe,OAAO;EACtB,aAAa,OAAO;EACpB,aAAa,OAAO;EACpB,YAAY,OAAO;EACnB,YAAY,OAAO;EACnB,OAAO,OAAO;CACf;AAED,QAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"middleware.cjs","names":["MIDDLEWARE_BRAND"],"sources":["../../src/agents/middleware.ts"],"sourcesContent":["import type {\n InteropZodObject,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport type { StateDefinitionInit } from \"@langchain/langgraph\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport {\n MIDDLEWARE_BRAND,\n type AgentMiddleware,\n type WrapToolCallHook,\n type WrapModelCallHook,\n type BeforeAgentHook,\n type BeforeModelHook,\n type AfterModelHook,\n type AfterAgentHook,\n} from \"./middleware/types.js\";\n\n/**\n * Creates a middleware instance with automatic schema inference.\n *\n * @param config - Middleware configuration\n * @param config.name - The name of the middleware\n * @param config.stateSchema - The schema of the middleware state\n * @param config.contextSchema - The schema of the middleware context\n * @param config.wrapModelCall - The function to wrap model invocation\n * @param config.wrapToolCall - The function to wrap tool invocation\n * @param config.beforeModel - The function to run before the model call\n * @param config.afterModel - The function to run after the model call\n * @param config.beforeAgent - The function to run before the agent execution starts\n * @param config.afterAgent - The function to run after the agent execution completes\n * @returns A middleware instance\n *\n * @example Using Zod schema\n * ```ts\n * const authMiddleware = createMiddleware({\n * name: \"AuthMiddleware\",\n * stateSchema: z.object({\n * isAuthenticated: z.boolean().default(false),\n * }),\n * contextSchema: z.object({\n * userId: z.string(),\n * }),\n * beforeModel: async (state, runtime, controls) => {\n * if (!state.isAuthenticated) {\n * return controls.terminate(new Error(\"Not authenticated\"));\n * }\n * },\n * });\n * ```\n *\n * @example Using StateSchema\n * ```ts\n * import { StateSchema, ReducedValue } from \"@langchain/langgraph\";\n *\n * const historyMiddleware = createMiddleware({\n * name: \"HistoryMiddleware\",\n * stateSchema: new StateSchema({\n * count: z.number().default(0),\n * history: new ReducedValue(\n * z.array(z.string()).default(() => []),\n * { inputSchema: z.string(), reducer: (current, next) => [...current, next] }\n * ),\n * }),\n * beforeModel: async (state, runtime) => {\n * return { count: state.count + 1 };\n * },\n * });\n * ```\n */\nexport function createMiddleware<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContextSchema extends InteropZodObject | undefined = undefined,\n const TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[],\n>(config: {\n /**\n * The name of the middleware\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object (InteropZodObject)\n * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n * - An AnnotationRoot\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: TTools;\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * The request parameter contains: model, messages, systemPrompt, tools, state, and runtime.\n *\n * @param request - The model request containing all the parameters needed.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n}): AgentMiddleware<\n TSchema,\n TContextSchema,\n NormalizeContextSchema<TContextSchema>,\n TTools\n> {\n const middleware: AgentMiddleware<\n TSchema,\n TContextSchema,\n NormalizeContextSchema<TContextSchema>,\n TTools\n > = {\n [MIDDLEWARE_BRAND]: true as const,\n name: config.name,\n stateSchema: config.stateSchema,\n contextSchema: config.contextSchema,\n wrapToolCall: config.wrapToolCall,\n wrapModelCall: config.wrapModelCall,\n beforeAgent: config.beforeAgent,\n beforeModel: config.beforeModel,\n afterModel: config.afterModel,\n afterAgent: config.afterAgent,\n tools: config.tools,\n };\n\n return middleware;\n}\n\ntype NormalizeContextSchema<\n TContextSchema extends InteropZodObject | undefined = undefined,\n> = TContextSchema extends InteropZodObject\n ? InferInteropZodOutput<TContextSchema>\n : unknown;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,SAAgB,iBAOd,QAkKA;AAoBA,QAdI;GACDA,iCAAmB;EACpB,MAAM,OAAO;EACb,aAAa,OAAO;EACpB,eAAe,OAAO;EACtB,cAAc,OAAO;EACrB,eAAe,OAAO;EACtB,aAAa,OAAO;EACpB,aAAa,OAAO;EACpB,YAAY,OAAO;EACnB,YAAY,OAAO;EACnB,OAAO,OAAO;EACf"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.d.cts","names":["InteropZodObject","InferInteropZodOutput","StateDefinitionInit","ClientTool","ServerTool","AgentMiddleware","WrapToolCallHook","WrapModelCallHook","BeforeAgentHook","BeforeModelHook","AfterModelHook","AfterAgentHook","createMiddleware","TSchema","TContextSchema","TTools","NormalizeContextSchema"],"sources":["../../src/agents/middleware.d.ts"],"sourcesContent":["import type { InteropZodObject, InferInteropZodOutput } from \"@langchain/core/utils/types\";\nimport type { StateDefinitionInit } from \"@langchain/langgraph\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport { type AgentMiddleware, type WrapToolCallHook, type WrapModelCallHook, type BeforeAgentHook, type BeforeModelHook, type AfterModelHook, type AfterAgentHook } from \"./middleware/types.js\";\n/**\n * Creates a middleware instance with automatic schema inference.\n *\n * @param config - Middleware configuration\n * @param config.name - The name of the middleware\n * @param config.stateSchema - The schema of the middleware state\n * @param config.contextSchema - The schema of the middleware context\n * @param config.wrapModelCall - The function to wrap model invocation\n * @param config.wrapToolCall - The function to wrap tool invocation\n * @param config.beforeModel - The function to run before the model call\n * @param config.afterModel - The function to run after the model call\n * @param config.beforeAgent - The function to run before the agent execution starts\n * @param config.afterAgent - The function to run after the agent execution completes\n * @returns A middleware instance\n *\n * @example Using Zod schema\n * ```ts\n * const authMiddleware = createMiddleware({\n * name: \"AuthMiddleware\",\n * stateSchema: z.object({\n * isAuthenticated: z.boolean().default(false),\n * }),\n * contextSchema: z.object({\n * userId: z.string(),\n * }),\n * beforeModel: async (state, runtime, controls) => {\n * if (!state.isAuthenticated) {\n * return controls.terminate(new Error(\"Not authenticated\"));\n * }\n * },\n * });\n * ```\n *\n * @example Using StateSchema\n * ```ts\n * import { StateSchema, ReducedValue } from \"@langchain/langgraph\";\n *\n * const historyMiddleware = createMiddleware({\n * name: \"HistoryMiddleware\",\n * stateSchema: new StateSchema({\n * count: z.number().default(0),\n * history: new ReducedValue(\n * z.array(z.string()).default(() => []),\n * { inputSchema: z.string(), reducer: (current, next) => [...current, next] }\n * ),\n * }),\n * beforeModel: async (state, runtime) => {\n * return { count: state.count + 1 };\n * },\n * });\n * ```\n */\nexport declare function createMiddleware<TSchema extends StateDefinitionInit | undefined = undefined, TContextSchema extends InteropZodObject | undefined = undefined, const TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[]>(config: {\n /**\n * The name of the middleware\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object (InteropZodObject)\n * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n * - An AnnotationRoot\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: TTools;\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * The request parameter contains: model, messages, systemPrompt, tools, state, and runtime.\n *\n * @param request - The model request containing all the parameters needed.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n}): AgentMiddleware<TSchema, TContextSchema, NormalizeContextSchema<TContextSchema>, TTools>;\ntype NormalizeContextSchema<TContextSchema extends InteropZodObject | undefined = undefined> = TContextSchema extends InteropZodObject ? InferInteropZodOutput<TContextSchema> : unknown;\nexport {};\n//# sourceMappingURL=middleware.d.ts.map"],"mappings":";;;;;;;;;AAwDA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6ImB;AAA0E;;;;;;AACiE;;;iBA9ItIY,iCAAiCV,oEAAoEF,yEAAyEG,aAAaC,0BAA0BD,aAAaC;;;;;;;;;;;;gBAYxOS;;;;;;;;kBAQEC;;;;UAIRC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiDOT,iBAAiBO,SAASG,uBAAuBF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBA+BhDP,kBAAkBM,SAASG,uBAAuBF;;;;;;;;;gBASpDN,gBAAgBK,SAASG,uBAAuBF;;;;;;;;;gBAShDL,gBAAgBI,SAASG,uBAAuBF;;;;;;;;;eASjDJ,eAAeG,SAASG,uBAAuBF;;;;;;;;;eAS/CH,eAAeE,SAASG,uBAAuBF;IAC5DT,gBAAgBQ,SAASC,gBAAgBE,uBAAuBF,iBAAiBC;KAChFC,8CAA8ChB,4CAA4Cc,uBAAuBd,mBAAmBC,sBAAsBa"}
|
|
1
|
+
{"version":3,"file":"middleware.d.cts","names":[],"sources":["../../src/agents/middleware.ts"],"mappings":";;;;;;;;AAsEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,gBAAA,iBACE,mBAAA,iDACO,gBAAA,yDACQ,UAAA,GAAa,UAAA,gBACxC,UAAA,GACA,UAAA,IAAA,CAEJ,MAAA;EAHI;;;EAOJ,IAAA;EAQc;;;;;;;EAAd,WAAA,GAAc,OAAA;EA+DZ;;;;;;;EAvDF,aAAA,GAAgB,cAAA;EAoGF;;;EAhGd,KAAA,GAAQ,MAAA;EA6GR;;;;;;;;;;;;;;;;;;;;;;;;AAkDD;;;;;;;;;;;;;;;;;;;;;;;;EA9GC,YAAA,GAAe,gBAAA,CACb,OAAA,EACA,sBAAA,CAAuB,cAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAiCzB,aAAA,GAAgB,iBAAA,CACd,OAAA,EACA,sBAAA,CAAuB,cAAA;;;;;;;;;EAUzB,WAAA,GAAc,eAAA,CACZ,OAAA,EACA,sBAAA,CAAuB,cAAA;;;;;;;;;EAWzB,WAAA,GAAc,eAAA,CACZ,OAAA,EACA,sBAAA,CAAuB,cAAA;;;;;;;;;EAWzB,UAAA,GAAa,cAAA,CAAe,OAAA,EAAS,sBAAA,CAAuB,cAAA;;;;;;;;;EAU5D,UAAA,GAAa,cAAA,CAAe,OAAA,EAAS,sBAAA,CAAuB,cAAA;AAAA,IAC1D,eAAA,CACF,OAAA,EACA,cAAA,EACA,sBAAA,CAAuB,cAAA,GACvB,MAAA;AAAA,KAwBG,sBAAA,wBACoB,gBAAA,4BACrB,cAAA,SAAuB,gBAAA,GACvB,qBAAA,CAAsB,cAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.d.ts","names":["InteropZodObject","InferInteropZodOutput","StateDefinitionInit","ClientTool","ServerTool","AgentMiddleware","WrapToolCallHook","WrapModelCallHook","BeforeAgentHook","BeforeModelHook","AfterModelHook","AfterAgentHook","createMiddleware","TSchema","TContextSchema","TTools","NormalizeContextSchema"],"sources":["../../src/agents/middleware.d.ts"],"sourcesContent":["import type { InteropZodObject, InferInteropZodOutput } from \"@langchain/core/utils/types\";\nimport type { StateDefinitionInit } from \"@langchain/langgraph\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport { type AgentMiddleware, type WrapToolCallHook, type WrapModelCallHook, type BeforeAgentHook, type BeforeModelHook, type AfterModelHook, type AfterAgentHook } from \"./middleware/types.js\";\n/**\n * Creates a middleware instance with automatic schema inference.\n *\n * @param config - Middleware configuration\n * @param config.name - The name of the middleware\n * @param config.stateSchema - The schema of the middleware state\n * @param config.contextSchema - The schema of the middleware context\n * @param config.wrapModelCall - The function to wrap model invocation\n * @param config.wrapToolCall - The function to wrap tool invocation\n * @param config.beforeModel - The function to run before the model call\n * @param config.afterModel - The function to run after the model call\n * @param config.beforeAgent - The function to run before the agent execution starts\n * @param config.afterAgent - The function to run after the agent execution completes\n * @returns A middleware instance\n *\n * @example Using Zod schema\n * ```ts\n * const authMiddleware = createMiddleware({\n * name: \"AuthMiddleware\",\n * stateSchema: z.object({\n * isAuthenticated: z.boolean().default(false),\n * }),\n * contextSchema: z.object({\n * userId: z.string(),\n * }),\n * beforeModel: async (state, runtime, controls) => {\n * if (!state.isAuthenticated) {\n * return controls.terminate(new Error(\"Not authenticated\"));\n * }\n * },\n * });\n * ```\n *\n * @example Using StateSchema\n * ```ts\n * import { StateSchema, ReducedValue } from \"@langchain/langgraph\";\n *\n * const historyMiddleware = createMiddleware({\n * name: \"HistoryMiddleware\",\n * stateSchema: new StateSchema({\n * count: z.number().default(0),\n * history: new ReducedValue(\n * z.array(z.string()).default(() => []),\n * { inputSchema: z.string(), reducer: (current, next) => [...current, next] }\n * ),\n * }),\n * beforeModel: async (state, runtime) => {\n * return { count: state.count + 1 };\n * },\n * });\n * ```\n */\nexport declare function createMiddleware<TSchema extends StateDefinitionInit | undefined = undefined, TContextSchema extends InteropZodObject | undefined = undefined, const TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[]>(config: {\n /**\n * The name of the middleware\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object (InteropZodObject)\n * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n * - An AnnotationRoot\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: TTools;\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * The request parameter contains: model, messages, systemPrompt, tools, state, and runtime.\n *\n * @param request - The model request containing all the parameters needed.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n}): AgentMiddleware<TSchema, TContextSchema, NormalizeContextSchema<TContextSchema>, TTools>;\ntype NormalizeContextSchema<TContextSchema extends InteropZodObject | undefined = undefined> = TContextSchema extends InteropZodObject ? InferInteropZodOutput<TContextSchema> : unknown;\nexport {};\n//# sourceMappingURL=middleware.d.ts.map"],"mappings":";;;;;;;;;AAwDA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6ImB;AAA0E;;;;;;AACiE;;;iBA9ItIY,iCAAiCV,oEAAoEF,yEAAyEG,aAAaC,0BAA0BD,aAAaC;;;;;;;;;;;;gBAYxOS;;;;;;;;kBAQEC;;;;UAIRC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiDOT,iBAAiBO,SAASG,uBAAuBF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBA+BhDP,kBAAkBM,SAASG,uBAAuBF;;;;;;;;;gBASpDN,gBAAgBK,SAASG,uBAAuBF;;;;;;;;;gBAShDL,gBAAgBI,SAASG,uBAAuBF;;;;;;;;;eASjDJ,eAAeG,SAASG,uBAAuBF;;;;;;;;;eAS/CH,eAAeE,SAASG,uBAAuBF;IAC5DT,gBAAgBQ,SAASC,gBAAgBE,uBAAuBF,iBAAiBC;KAChFC,8CAA8ChB,4CAA4Cc,uBAAuBd,mBAAmBC,sBAAsBa"}
|
|
1
|
+
{"version":3,"file":"middleware.d.ts","names":[],"sources":["../../src/agents/middleware.ts"],"mappings":";;;;;;;;AAsEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,gBAAA,iBACE,mBAAA,iDACO,gBAAA,yDACQ,UAAA,GAAa,UAAA,gBACxC,UAAA,GACA,UAAA,IAAA,CAEJ,MAAA;EAHI;;;EAOJ,IAAA;EAQc;;;;;;;EAAd,WAAA,GAAc,OAAA;EA+DZ;;;;;;;EAvDF,aAAA,GAAgB,cAAA;EAoGF;;;EAhGd,KAAA,GAAQ,MAAA;EA6GR;;;;;;;;;;;;;;;;;;;;;;;;AAkDD;;;;;;;;;;;;;;;;;;;;;;;;EA9GC,YAAA,GAAe,gBAAA,CACb,OAAA,EACA,sBAAA,CAAuB,cAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAiCzB,aAAA,GAAgB,iBAAA,CACd,OAAA,EACA,sBAAA,CAAuB,cAAA;;;;;;;;;EAUzB,WAAA,GAAc,eAAA,CACZ,OAAA,EACA,sBAAA,CAAuB,cAAA;;;;;;;;;EAWzB,WAAA,GAAc,eAAA,CACZ,OAAA,EACA,sBAAA,CAAuB,cAAA;;;;;;;;;EAWzB,UAAA,GAAa,cAAA,CAAe,OAAA,EAAS,sBAAA,CAAuB,cAAA;;;;;;;;;EAU5D,UAAA,GAAa,cAAA,CAAe,OAAA,EAAS,sBAAA,CAAuB,cAAA;AAAA,IAC1D,eAAA,CACF,OAAA,EACA,cAAA,EACA,sBAAA,CAAuB,cAAA,GACvB,MAAA;AAAA,KAwBG,sBAAA,wBACoB,gBAAA,4BACrB,cAAA,SAAuB,gBAAA,GACvB,qBAAA,CAAsB,cAAA"}
|
|
@@ -54,7 +54,7 @@ import { MIDDLEWARE_BRAND } from "./middleware/types.js";
|
|
|
54
54
|
* ```
|
|
55
55
|
*/
|
|
56
56
|
function createMiddleware(config) {
|
|
57
|
-
|
|
57
|
+
return {
|
|
58
58
|
[MIDDLEWARE_BRAND]: true,
|
|
59
59
|
name: config.name,
|
|
60
60
|
stateSchema: config.stateSchema,
|
|
@@ -67,7 +67,6 @@ function createMiddleware(config) {
|
|
|
67
67
|
afterAgent: config.afterAgent,
|
|
68
68
|
tools: config.tools
|
|
69
69
|
};
|
|
70
|
-
return middleware;
|
|
71
70
|
}
|
|
72
71
|
|
|
73
72
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.js","names":["config: {\n /**\n * The name of the middleware\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object (InteropZodObject)\n * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n * - An AnnotationRoot\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: TTools;\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * The request parameter contains: model, messages, systemPrompt, tools, state, and runtime.\n *\n * @param request - The model request containing all the parameters needed.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n}","middleware: AgentMiddleware<\n TSchema,\n TContextSchema,\n NormalizeContextSchema<TContextSchema>,\n TTools\n >"],"sources":["../../src/agents/middleware.ts"],"sourcesContent":["import type {\n InteropZodObject,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport type { StateDefinitionInit } from \"@langchain/langgraph\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport {\n MIDDLEWARE_BRAND,\n type AgentMiddleware,\n type WrapToolCallHook,\n type WrapModelCallHook,\n type BeforeAgentHook,\n type BeforeModelHook,\n type AfterModelHook,\n type AfterAgentHook,\n} from \"./middleware/types.js\";\n\n/**\n * Creates a middleware instance with automatic schema inference.\n *\n * @param config - Middleware configuration\n * @param config.name - The name of the middleware\n * @param config.stateSchema - The schema of the middleware state\n * @param config.contextSchema - The schema of the middleware context\n * @param config.wrapModelCall - The function to wrap model invocation\n * @param config.wrapToolCall - The function to wrap tool invocation\n * @param config.beforeModel - The function to run before the model call\n * @param config.afterModel - The function to run after the model call\n * @param config.beforeAgent - The function to run before the agent execution starts\n * @param config.afterAgent - The function to run after the agent execution completes\n * @returns A middleware instance\n *\n * @example Using Zod schema\n * ```ts\n * const authMiddleware = createMiddleware({\n * name: \"AuthMiddleware\",\n * stateSchema: z.object({\n * isAuthenticated: z.boolean().default(false),\n * }),\n * contextSchema: z.object({\n * userId: z.string(),\n * }),\n * beforeModel: async (state, runtime, controls) => {\n * if (!state.isAuthenticated) {\n * return controls.terminate(new Error(\"Not authenticated\"));\n * }\n * },\n * });\n * ```\n *\n * @example Using StateSchema\n * ```ts\n * import { StateSchema, ReducedValue } from \"@langchain/langgraph\";\n *\n * const historyMiddleware = createMiddleware({\n * name: \"HistoryMiddleware\",\n * stateSchema: new StateSchema({\n * count: z.number().default(0),\n * history: new ReducedValue(\n * z.array(z.string()).default(() => []),\n * { inputSchema: z.string(), reducer: (current, next) => [...current, next] }\n * ),\n * }),\n * beforeModel: async (state, runtime) => {\n * return { count: state.count + 1 };\n * },\n * });\n * ```\n */\nexport function createMiddleware<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContextSchema extends InteropZodObject | undefined = undefined,\n const TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[],\n>(config: {\n /**\n * The name of the middleware\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object (InteropZodObject)\n * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n * - An AnnotationRoot\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: TTools;\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * The request parameter contains: model, messages, systemPrompt, tools, state, and runtime.\n *\n * @param request - The model request containing all the parameters needed.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n}): AgentMiddleware<\n TSchema,\n TContextSchema,\n NormalizeContextSchema<TContextSchema>,\n TTools\n> {\n const middleware: AgentMiddleware<\n TSchema,\n TContextSchema,\n NormalizeContextSchema<TContextSchema>,\n TTools\n > = {\n [MIDDLEWARE_BRAND]: true as const,\n name: config.name,\n stateSchema: config.stateSchema,\n contextSchema: config.contextSchema,\n wrapToolCall: config.wrapToolCall,\n wrapModelCall: config.wrapModelCall,\n beforeAgent: config.beforeAgent,\n beforeModel: config.beforeModel,\n afterModel: config.afterModel,\n afterAgent: config.afterAgent,\n tools: config.tools,\n };\n\n return middleware;\n}\n\ntype NormalizeContextSchema<\n TContextSchema extends InteropZodObject | undefined = undefined,\n> = TContextSchema extends InteropZodObject\n ? InferInteropZodOutput<TContextSchema>\n : unknown;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,SAAgB,iBAOdA,QAkKA;CACA,MAAMC,aAKF;GACD,mBAAmB;EACpB,MAAM,OAAO;EACb,aAAa,OAAO;EACpB,eAAe,OAAO;EACtB,cAAc,OAAO;EACrB,eAAe,OAAO;EACtB,aAAa,OAAO;EACpB,aAAa,OAAO;EACpB,YAAY,OAAO;EACnB,YAAY,OAAO;EACnB,OAAO,OAAO;CACf;AAED,QAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"middleware.js","names":[],"sources":["../../src/agents/middleware.ts"],"sourcesContent":["import type {\n InteropZodObject,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport type { StateDefinitionInit } from \"@langchain/langgraph\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport {\n MIDDLEWARE_BRAND,\n type AgentMiddleware,\n type WrapToolCallHook,\n type WrapModelCallHook,\n type BeforeAgentHook,\n type BeforeModelHook,\n type AfterModelHook,\n type AfterAgentHook,\n} from \"./middleware/types.js\";\n\n/**\n * Creates a middleware instance with automatic schema inference.\n *\n * @param config - Middleware configuration\n * @param config.name - The name of the middleware\n * @param config.stateSchema - The schema of the middleware state\n * @param config.contextSchema - The schema of the middleware context\n * @param config.wrapModelCall - The function to wrap model invocation\n * @param config.wrapToolCall - The function to wrap tool invocation\n * @param config.beforeModel - The function to run before the model call\n * @param config.afterModel - The function to run after the model call\n * @param config.beforeAgent - The function to run before the agent execution starts\n * @param config.afterAgent - The function to run after the agent execution completes\n * @returns A middleware instance\n *\n * @example Using Zod schema\n * ```ts\n * const authMiddleware = createMiddleware({\n * name: \"AuthMiddleware\",\n * stateSchema: z.object({\n * isAuthenticated: z.boolean().default(false),\n * }),\n * contextSchema: z.object({\n * userId: z.string(),\n * }),\n * beforeModel: async (state, runtime, controls) => {\n * if (!state.isAuthenticated) {\n * return controls.terminate(new Error(\"Not authenticated\"));\n * }\n * },\n * });\n * ```\n *\n * @example Using StateSchema\n * ```ts\n * import { StateSchema, ReducedValue } from \"@langchain/langgraph\";\n *\n * const historyMiddleware = createMiddleware({\n * name: \"HistoryMiddleware\",\n * stateSchema: new StateSchema({\n * count: z.number().default(0),\n * history: new ReducedValue(\n * z.array(z.string()).default(() => []),\n * { inputSchema: z.string(), reducer: (current, next) => [...current, next] }\n * ),\n * }),\n * beforeModel: async (state, runtime) => {\n * return { count: state.count + 1 };\n * },\n * });\n * ```\n */\nexport function createMiddleware<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContextSchema extends InteropZodObject | undefined = undefined,\n const TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[],\n>(config: {\n /**\n * The name of the middleware\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object (InteropZodObject)\n * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n * - An AnnotationRoot\n * - Undefined\n */\n stateSchema?: TSchema;\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n /**\n * Additional tools registered by the middleware.\n */\n tools?: TTools;\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * The request parameter contains: model, messages, systemPrompt, tools, state, and runtime.\n *\n * @param request - The model request containing all the parameters needed.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<\n TSchema,\n NormalizeContextSchema<TContextSchema>\n >;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, NormalizeContextSchema<TContextSchema>>;\n}): AgentMiddleware<\n TSchema,\n TContextSchema,\n NormalizeContextSchema<TContextSchema>,\n TTools\n> {\n const middleware: AgentMiddleware<\n TSchema,\n TContextSchema,\n NormalizeContextSchema<TContextSchema>,\n TTools\n > = {\n [MIDDLEWARE_BRAND]: true as const,\n name: config.name,\n stateSchema: config.stateSchema,\n contextSchema: config.contextSchema,\n wrapToolCall: config.wrapToolCall,\n wrapModelCall: config.wrapModelCall,\n beforeAgent: config.beforeAgent,\n beforeModel: config.beforeModel,\n afterModel: config.afterModel,\n afterAgent: config.afterAgent,\n tools: config.tools,\n };\n\n return middleware;\n}\n\ntype NormalizeContextSchema<\n TContextSchema extends InteropZodObject | undefined = undefined,\n> = TContextSchema extends InteropZodObject\n ? InferInteropZodOutput<TContextSchema>\n : unknown;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,SAAgB,iBAOd,QAkKA;AAoBA,QAdI;GACD,mBAAmB;EACpB,MAAM,OAAO;EACb,aAAa,OAAO;EACpB,eAAe,OAAO;EACtB,cAAc,OAAO;EACrB,eAAe,OAAO;EACtB,aAAa,OAAO;EACpB,aAAa,OAAO;EACpB,YAAY,OAAO;EACnB,YAAY,OAAO;EACnB,OAAO,OAAO;EACf"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.cjs","names":[
|
|
1
|
+
{"version":3,"file":"model.cjs","names":[],"sources":["../../src/agents/model.ts"],"sourcesContent":["import type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\n\nexport interface ConfigurableModelInterface {\n _queuedMethodOperations: Record<string, unknown>;\n _getModelInstance: () => Promise<BaseChatModel>;\n}\n\nexport function isBaseChatModel(\n model: LanguageModelLike\n): model is BaseChatModel {\n return (\n \"invoke\" in model &&\n typeof model.invoke === \"function\" &&\n \"_streamResponseChunks\" in model\n );\n}\n\nexport function isConfigurableModel(\n model: unknown\n): model is ConfigurableModelInterface {\n return (\n typeof model === \"object\" &&\n model != null &&\n \"_queuedMethodOperations\" in model &&\n \"_getModelInstance\" in model &&\n typeof (model as { _getModelInstance: unknown })._getModelInstance ===\n \"function\"\n );\n}\n"],"mappings":";;AAQA,SAAgB,gBACd,OACwB;AACxB,QACE,YAAY,SACZ,OAAO,MAAM,WAAW,cACxB,2BAA2B;;AAI/B,SAAgB,oBACd,OACqC;AACrC,QACE,OAAO,UAAU,YACjB,SAAS,QACT,6BAA6B,SAC7B,uBAAuB,SACvB,OAAQ,MAAyC,sBAC/C"}
|
package/dist/agents/model.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.js","names":[
|
|
1
|
+
{"version":3,"file":"model.js","names":[],"sources":["../../src/agents/model.ts"],"sourcesContent":["import type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\n\nexport interface ConfigurableModelInterface {\n _queuedMethodOperations: Record<string, unknown>;\n _getModelInstance: () => Promise<BaseChatModel>;\n}\n\nexport function isBaseChatModel(\n model: LanguageModelLike\n): model is BaseChatModel {\n return (\n \"invoke\" in model &&\n typeof model.invoke === \"function\" &&\n \"_streamResponseChunks\" in model\n );\n}\n\nexport function isConfigurableModel(\n model: unknown\n): model is ConfigurableModelInterface {\n return (\n typeof model === \"object\" &&\n model != null &&\n \"_queuedMethodOperations\" in model &&\n \"_getModelInstance\" in model &&\n typeof (model as { _getModelInstance: unknown })._getModelInstance ===\n \"function\"\n );\n}\n"],"mappings":";AAQA,SAAgB,gBACd,OACwB;AACxB,QACE,YAAY,SACZ,OAAO,MAAM,WAAW,cACxB,2BAA2B;;AAI/B,SAAgB,oBACd,OACqC;AACrC,QACE,OAAO,UAAU,YACjB,SAAS,QACT,6BAA6B,SAC7B,uBAAuB,SACvB,OAAQ,MAAyC,sBAC/C"}
|
|
@@ -19,8 +19,7 @@ var AfterAgentNode = class extends require_middleware.MiddlewareNode {
|
|
|
19
19
|
this.middleware = middleware;
|
|
20
20
|
}
|
|
21
21
|
runHook(state, runtime) {
|
|
22
|
-
|
|
23
|
-
return fn(state, runtime);
|
|
22
|
+
return require_utils.getHookFunction(this.middleware.afterAgent)(state, runtime);
|
|
24
23
|
}
|
|
25
24
|
};
|
|
26
25
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AfterAgentNode.cjs","names":["MiddlewareNode","
|
|
1
|
+
{"version":3,"file":"AfterAgentNode.cjs","names":["MiddlewareNode","getHookFunction"],"sources":["../../../src/agents/nodes/AfterAgentNode.ts"],"sourcesContent":["import { z } from \"zod/v4\";\nimport { RunnableConfig } from \"@langchain/core/runnables\";\nimport { MiddlewareNode, MiddlewareNodeOptions } from \"./middleware.js\";\nimport type { AgentMiddleware, MiddlewareResult } from \"../middleware/types.js\";\nimport type { AgentBuiltInState, Runtime } from \"../runtime.js\";\nimport { getHookFunction } from \"../middleware/utils.js\";\n\n/**\n * Node for executing a single middleware's afterAgent hook.\n */\nexport class AfterAgentNode<\n TStateSchema extends Record<string, unknown> = Record<string, unknown>,\n TContextSchema extends Record<string, unknown> = Record<string, unknown>,\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"afterAgentNodes\"];\n\n constructor(\n public middleware: AgentMiddleware<\n z.ZodObject<z.ZodRawShape>,\n z.ZodObject<z.ZodRawShape>\n >,\n options: MiddlewareNodeOptions\n ) {\n super(\n {\n name: `AfterAgentNode_${middleware.name}`,\n func: async (\n state: TStateSchema,\n config?: RunnableConfig<TContextSchema>\n ) => this.invokeMiddleware(state, config),\n },\n options\n );\n }\n\n runHook(state: TStateSchema, runtime: Runtime<TContextSchema>) {\n const fn = getHookFunction(this.middleware.afterAgent!);\n return fn(\n state as Record<string, unknown> & AgentBuiltInState,\n runtime as Runtime<unknown>\n ) as Promise<MiddlewareResult<TStateSchema>>;\n }\n}\n"],"mappings":";;;;;;;AAUA,IAAa,iBAAb,cAGUA,kCAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;EAAkB;CAEzD,YACE,AAAO,YAIP,SACA;AACA,QACE;GACE,MAAM,kBAAkB,WAAW;GACnC,MAAM,OACJ,OACA,WACG,KAAK,iBAAiB,OAAO,OAAO;GAC1C,EACD,QACD;EAfM;;CAkBT,QAAQ,OAAqB,SAAkC;AAE7D,SADWC,8BAAgB,KAAK,WAAW,WAAY,CAErD,OACA,QACD"}
|
|
@@ -19,8 +19,7 @@ var AfterAgentNode = class extends MiddlewareNode {
|
|
|
19
19
|
this.middleware = middleware;
|
|
20
20
|
}
|
|
21
21
|
runHook(state, runtime) {
|
|
22
|
-
|
|
23
|
-
return fn(state, runtime);
|
|
22
|
+
return getHookFunction(this.middleware.afterAgent)(state, runtime);
|
|
24
23
|
}
|
|
25
24
|
};
|
|
26
25
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AfterAgentNode.js","names":[
|
|
1
|
+
{"version":3,"file":"AfterAgentNode.js","names":[],"sources":["../../../src/agents/nodes/AfterAgentNode.ts"],"sourcesContent":["import { z } from \"zod/v4\";\nimport { RunnableConfig } from \"@langchain/core/runnables\";\nimport { MiddlewareNode, MiddlewareNodeOptions } from \"./middleware.js\";\nimport type { AgentMiddleware, MiddlewareResult } from \"../middleware/types.js\";\nimport type { AgentBuiltInState, Runtime } from \"../runtime.js\";\nimport { getHookFunction } from \"../middleware/utils.js\";\n\n/**\n * Node for executing a single middleware's afterAgent hook.\n */\nexport class AfterAgentNode<\n TStateSchema extends Record<string, unknown> = Record<string, unknown>,\n TContextSchema extends Record<string, unknown> = Record<string, unknown>,\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"afterAgentNodes\"];\n\n constructor(\n public middleware: AgentMiddleware<\n z.ZodObject<z.ZodRawShape>,\n z.ZodObject<z.ZodRawShape>\n >,\n options: MiddlewareNodeOptions\n ) {\n super(\n {\n name: `AfterAgentNode_${middleware.name}`,\n func: async (\n state: TStateSchema,\n config?: RunnableConfig<TContextSchema>\n ) => this.invokeMiddleware(state, config),\n },\n options\n );\n }\n\n runHook(state: TStateSchema, runtime: Runtime<TContextSchema>) {\n const fn = getHookFunction(this.middleware.afterAgent!);\n return fn(\n state as Record<string, unknown> & AgentBuiltInState,\n runtime as Runtime<unknown>\n ) as Promise<MiddlewareResult<TStateSchema>>;\n }\n}\n"],"mappings":";;;;;;;AAUA,IAAa,iBAAb,cAGU,eAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;EAAkB;CAEzD,YACE,AAAO,YAIP,SACA;AACA,QACE;GACE,MAAM,kBAAkB,WAAW;GACnC,MAAM,OACJ,OACA,WACG,KAAK,iBAAiB,OAAO,OAAO;GAC1C,EACD,QACD;EAfM;;CAkBT,QAAQ,OAAqB,SAAkC;AAE7D,SADW,gBAAgB,KAAK,WAAW,WAAY,CAErD,OACA,QACD"}
|
|
@@ -19,8 +19,7 @@ var AfterModelNode = class extends require_middleware.MiddlewareNode {
|
|
|
19
19
|
this.middleware = middleware;
|
|
20
20
|
}
|
|
21
21
|
runHook(state, runtime) {
|
|
22
|
-
|
|
23
|
-
return fn(state, runtime);
|
|
22
|
+
return require_utils.getHookFunction(this.middleware.afterModel)(state, runtime);
|
|
24
23
|
}
|
|
25
24
|
};
|
|
26
25
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AfterModelNode.cjs","names":["MiddlewareNode","
|
|
1
|
+
{"version":3,"file":"AfterModelNode.cjs","names":["MiddlewareNode","getHookFunction"],"sources":["../../../src/agents/nodes/AfterModelNode.ts"],"sourcesContent":["import { z } from \"zod/v4\";\nimport { RunnableConfig } from \"@langchain/core/runnables\";\nimport { MiddlewareNode, MiddlewareNodeOptions } from \"./middleware.js\";\nimport type { AgentMiddleware, MiddlewareResult } from \"../middleware/types.js\";\nimport type { AgentBuiltInState, Runtime } from \"../runtime.js\";\nimport { getHookFunction } from \"../middleware/utils.js\";\n\n/**\n * Node for executing a single middleware's afterModel hook.\n */\nexport class AfterModelNode<\n TStateSchema extends Record<string, unknown> = Record<string, unknown>,\n TContextSchema extends Record<string, unknown> = Record<string, unknown>,\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"afterModelNodes\"];\n\n constructor(\n public middleware: AgentMiddleware<\n z.ZodObject<z.ZodRawShape>,\n z.ZodObject<z.ZodRawShape>\n >,\n options: MiddlewareNodeOptions\n ) {\n super(\n {\n name: `AfterModelNode_${middleware.name}`,\n func: async (\n state: TStateSchema,\n config?: RunnableConfig<TContextSchema>\n ) => this.invokeMiddleware(state, config),\n },\n options\n );\n }\n\n runHook(state: TStateSchema, runtime: Runtime<TContextSchema>) {\n const fn = getHookFunction(this.middleware.afterModel!);\n return fn(\n state as Record<string, unknown> & AgentBuiltInState,\n runtime as Runtime<unknown>\n ) as Promise<MiddlewareResult<TStateSchema>>;\n }\n}\n"],"mappings":";;;;;;;AAUA,IAAa,iBAAb,cAGUA,kCAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;EAAkB;CAEzD,YACE,AAAO,YAIP,SACA;AACA,QACE;GACE,MAAM,kBAAkB,WAAW;GACnC,MAAM,OACJ,OACA,WACG,KAAK,iBAAiB,OAAO,OAAO;GAC1C,EACD,QACD;EAfM;;CAkBT,QAAQ,OAAqB,SAAkC;AAE7D,SADWC,8BAAgB,KAAK,WAAW,WAAY,CAErD,OACA,QACD"}
|
|
@@ -19,8 +19,7 @@ var AfterModelNode = class extends MiddlewareNode {
|
|
|
19
19
|
this.middleware = middleware;
|
|
20
20
|
}
|
|
21
21
|
runHook(state, runtime) {
|
|
22
|
-
|
|
23
|
-
return fn(state, runtime);
|
|
22
|
+
return getHookFunction(this.middleware.afterModel)(state, runtime);
|
|
24
23
|
}
|
|
25
24
|
};
|
|
26
25
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AfterModelNode.js","names":[
|
|
1
|
+
{"version":3,"file":"AfterModelNode.js","names":[],"sources":["../../../src/agents/nodes/AfterModelNode.ts"],"sourcesContent":["import { z } from \"zod/v4\";\nimport { RunnableConfig } from \"@langchain/core/runnables\";\nimport { MiddlewareNode, MiddlewareNodeOptions } from \"./middleware.js\";\nimport type { AgentMiddleware, MiddlewareResult } from \"../middleware/types.js\";\nimport type { AgentBuiltInState, Runtime } from \"../runtime.js\";\nimport { getHookFunction } from \"../middleware/utils.js\";\n\n/**\n * Node for executing a single middleware's afterModel hook.\n */\nexport class AfterModelNode<\n TStateSchema extends Record<string, unknown> = Record<string, unknown>,\n TContextSchema extends Record<string, unknown> = Record<string, unknown>,\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"afterModelNodes\"];\n\n constructor(\n public middleware: AgentMiddleware<\n z.ZodObject<z.ZodRawShape>,\n z.ZodObject<z.ZodRawShape>\n >,\n options: MiddlewareNodeOptions\n ) {\n super(\n {\n name: `AfterModelNode_${middleware.name}`,\n func: async (\n state: TStateSchema,\n config?: RunnableConfig<TContextSchema>\n ) => this.invokeMiddleware(state, config),\n },\n options\n );\n }\n\n runHook(state: TStateSchema, runtime: Runtime<TContextSchema>) {\n const fn = getHookFunction(this.middleware.afterModel!);\n return fn(\n state as Record<string, unknown> & AgentBuiltInState,\n runtime as Runtime<unknown>\n ) as Promise<MiddlewareResult<TStateSchema>>;\n }\n}\n"],"mappings":";;;;;;;AAUA,IAAa,iBAAb,cAGU,eAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;EAAkB;CAEzD,YACE,AAAO,YAIP,SACA;AACA,QACE;GACE,MAAM,kBAAkB,WAAW;GACnC,MAAM,OACJ,OACA,WACG,KAAK,iBAAiB,OAAO,OAAO;GAC1C,EACD,QACD;EAfM;;CAkBT,QAAQ,OAAqB,SAAkC;AAE7D,SADW,gBAAgB,KAAK,WAAW,WAAY,CAErD,OACA,QACD"}
|