langchain 1.0.0-alpha.8 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +260 -0
- package/LICENSE +6 -6
- package/README.md +29 -77
- package/dist/agents/ReactAgent.cjs +498 -104
- package/dist/agents/ReactAgent.cjs.map +1 -1
- package/dist/agents/ReactAgent.d.cts +140 -17
- package/dist/agents/ReactAgent.d.cts.map +1 -1
- package/dist/agents/ReactAgent.d.ts +140 -17
- package/dist/agents/ReactAgent.d.ts.map +1 -1
- package/dist/agents/ReactAgent.js +501 -107
- package/dist/agents/ReactAgent.js.map +1 -1
- package/dist/agents/annotation.cjs +34 -152
- package/dist/agents/annotation.cjs.map +1 -1
- package/dist/agents/annotation.js +36 -150
- package/dist/agents/annotation.js.map +1 -1
- package/dist/agents/constants.cjs.map +1 -1
- package/dist/agents/constants.d.cts +9 -0
- package/dist/agents/constants.d.cts.map +1 -0
- package/dist/agents/constants.d.ts +9 -0
- package/dist/agents/constants.d.ts.map +1 -0
- package/dist/agents/constants.js.map +1 -1
- package/dist/agents/errors.cjs +2 -1
- package/dist/agents/errors.cjs.map +1 -1
- package/dist/agents/errors.js +2 -1
- package/dist/agents/errors.js.map +1 -1
- package/dist/agents/index.cjs +5 -29
- package/dist/agents/index.cjs.map +1 -1
- package/dist/agents/index.d.cts +157 -128
- package/dist/agents/index.d.cts.map +1 -1
- package/dist/agents/index.d.ts +157 -128
- package/dist/agents/index.d.ts.map +1 -1
- package/dist/agents/index.js +5 -27
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/{middlewareAgent/middleware → middleware}/callLimit.cjs +31 -29
- package/dist/agents/middleware/callLimit.cjs.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/callLimit.d.cts +3 -3
- package/dist/agents/middleware/callLimit.d.cts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/callLimit.d.ts +3 -3
- package/dist/agents/middleware/callLimit.d.ts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/callLimit.js +30 -28
- package/dist/agents/middleware/callLimit.js.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/contextEditing.cjs +6 -6
- package/dist/agents/middleware/contextEditing.cjs.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/contextEditing.d.cts +2 -2
- package/dist/agents/middleware/contextEditing.d.cts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/contextEditing.d.ts +2 -2
- package/dist/agents/middleware/contextEditing.d.ts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/contextEditing.js +5 -5
- package/dist/agents/middleware/contextEditing.js.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/dynamicSystemPrompt.cjs +6 -6
- package/dist/agents/middleware/dynamicSystemPrompt.cjs.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/dynamicSystemPrompt.d.cts +3 -2
- package/dist/agents/middleware/dynamicSystemPrompt.d.cts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/dynamicSystemPrompt.d.ts +3 -2
- package/dist/agents/middleware/dynamicSystemPrompt.d.ts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/dynamicSystemPrompt.js +6 -6
- package/dist/agents/middleware/dynamicSystemPrompt.js.map +1 -0
- package/dist/agents/middleware/hitl.cjs +406 -0
- package/dist/agents/middleware/hitl.cjs.map +1 -0
- package/dist/agents/middleware/hitl.d.cts +611 -0
- package/dist/agents/middleware/hitl.d.cts.map +1 -0
- package/dist/agents/middleware/hitl.d.ts +611 -0
- package/dist/agents/middleware/hitl.d.ts.map +1 -0
- package/dist/agents/middleware/hitl.js +405 -0
- package/dist/agents/middleware/hitl.js.map +1 -0
- package/dist/agents/middleware/index.cjs +12 -0
- package/dist/agents/middleware/index.js +12 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/llmToolSelector.cjs +7 -7
- package/dist/agents/middleware/llmToolSelector.cjs.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/llmToolSelector.d.cts +2 -2
- package/dist/agents/middleware/llmToolSelector.d.cts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/llmToolSelector.d.ts +2 -2
- package/dist/agents/middleware/llmToolSelector.d.ts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/llmToolSelector.js +6 -6
- package/dist/agents/middleware/llmToolSelector.js.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/modelFallback.cjs +29 -22
- package/dist/agents/middleware/modelFallback.cjs.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/modelFallback.d.cts +3 -3
- package/dist/agents/middleware/modelFallback.d.cts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/modelFallback.d.ts +3 -3
- package/dist/agents/middleware/modelFallback.d.ts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/modelFallback.js +29 -22
- package/dist/agents/middleware/modelFallback.js.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/piiRedaction.cjs +12 -12
- package/dist/agents/middleware/piiRedaction.cjs.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/piiRedaction.d.cts +4 -4
- package/dist/agents/middleware/piiRedaction.d.cts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/piiRedaction.d.ts +4 -4
- package/dist/agents/middleware/piiRedaction.d.ts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/piiRedaction.js +10 -10
- package/dist/agents/middleware/piiRedaction.js.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/promptCaching.cjs +27 -24
- package/dist/agents/middleware/promptCaching.cjs.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/promptCaching.d.cts +3 -3
- package/dist/agents/middleware/promptCaching.d.cts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/promptCaching.d.ts +3 -3
- package/dist/agents/middleware/promptCaching.d.ts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/promptCaching.js +26 -23
- package/dist/agents/middleware/promptCaching.js.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/summarization.cjs +7 -12
- package/dist/agents/middleware/summarization.cjs.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/summarization.d.cts +3 -3
- package/dist/agents/middleware/summarization.d.cts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/summarization.d.ts +3 -3
- package/dist/agents/middleware/summarization.d.ts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/summarization.js +5 -10
- package/dist/agents/middleware/summarization.js.map +1 -0
- package/dist/agents/middleware/todoListMiddleware.cjs +314 -0
- package/dist/agents/middleware/todoListMiddleware.cjs.map +1 -0
- package/dist/agents/middleware/todoListMiddleware.d.cts +75 -0
- package/dist/agents/middleware/todoListMiddleware.d.cts.map +1 -0
- package/dist/agents/middleware/todoListMiddleware.d.ts +75 -0
- package/dist/agents/middleware/todoListMiddleware.d.ts.map +1 -0
- package/dist/agents/middleware/todoListMiddleware.js +312 -0
- package/dist/agents/middleware/todoListMiddleware.js.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/toolCallLimit.cjs +32 -30
- package/dist/agents/middleware/toolCallLimit.cjs.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/toolCallLimit.d.cts +3 -3
- package/dist/agents/middleware/toolCallLimit.d.cts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/toolCallLimit.d.ts +3 -3
- package/dist/agents/middleware/toolCallLimit.d.ts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/toolCallLimit.js +31 -29
- package/dist/agents/middleware/toolCallLimit.js.map +1 -0
- package/dist/agents/middleware/types.d.cts +354 -0
- package/dist/agents/middleware/types.d.cts.map +1 -0
- package/dist/agents/middleware/types.d.ts +354 -0
- package/dist/agents/middleware/types.d.ts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/utils.cjs +11 -1
- package/dist/agents/middleware/utils.cjs.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/utils.d.cts +1 -1
- package/dist/agents/middleware/utils.d.cts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/utils.d.ts +1 -1
- package/dist/agents/middleware/utils.d.ts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/utils.js +10 -2
- package/dist/agents/middleware/utils.js.map +1 -0
- package/dist/agents/{middlewareAgent/middleware.cjs → middleware.cjs} +11 -8
- package/dist/agents/middleware.cjs.map +1 -0
- package/dist/agents/middleware.d.cts +185 -0
- package/dist/agents/middleware.d.cts.map +1 -0
- package/dist/agents/middleware.d.ts +185 -0
- package/dist/agents/middleware.d.ts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware.js → middleware.js} +11 -8
- package/dist/agents/middleware.js.map +1 -0
- package/dist/agents/nodes/AfterAgentNode.cjs +29 -0
- package/dist/agents/nodes/AfterAgentNode.cjs.map +1 -0
- package/dist/agents/nodes/AfterAgentNode.js +29 -0
- package/dist/agents/nodes/AfterAgentNode.js.map +1 -0
- package/dist/agents/{middlewareAgent/nodes/AfterModalNode.cjs → nodes/AfterModelNode.cjs} +6 -6
- package/dist/agents/nodes/AfterModelNode.cjs.map +1 -0
- package/dist/agents/{middlewareAgent/nodes/AfterModalNode.js → nodes/AfterModelNode.js} +6 -6
- package/dist/agents/nodes/AfterModelNode.js.map +1 -0
- package/dist/agents/nodes/AgentNode.cjs +203 -71
- package/dist/agents/nodes/AgentNode.cjs.map +1 -1
- package/dist/agents/nodes/AgentNode.js +205 -73
- package/dist/agents/nodes/AgentNode.js.map +1 -1
- package/dist/agents/nodes/BeforeAgentNode.cjs +29 -0
- package/dist/agents/nodes/BeforeAgentNode.cjs.map +1 -0
- package/dist/agents/nodes/BeforeAgentNode.js +29 -0
- package/dist/agents/nodes/BeforeAgentNode.js.map +1 -0
- package/dist/agents/{middlewareAgent/nodes/BeforeModalNode.cjs → nodes/BeforeModelNode.cjs} +6 -4
- package/dist/agents/nodes/BeforeModelNode.cjs.map +1 -0
- package/dist/agents/{middlewareAgent/nodes/BeforeModalNode.js → nodes/BeforeModelNode.js} +6 -4
- package/dist/agents/nodes/BeforeModelNode.js.map +1 -0
- package/dist/agents/nodes/ToolNode.cjs +163 -52
- package/dist/agents/nodes/ToolNode.cjs.map +1 -1
- package/dist/agents/nodes/ToolNode.js +164 -53
- package/dist/agents/nodes/ToolNode.js.map +1 -1
- package/dist/agents/{middlewareAgent/nodes → nodes}/middleware.cjs +36 -10
- package/dist/agents/nodes/middleware.cjs.map +1 -0
- package/dist/agents/{middlewareAgent/nodes → nodes}/middleware.js +35 -9
- package/dist/agents/nodes/middleware.js.map +1 -0
- package/dist/agents/nodes/types.d.cts +72 -0
- package/dist/agents/nodes/types.d.cts.map +1 -0
- package/dist/agents/nodes/types.d.ts +72 -0
- package/dist/agents/nodes/types.d.ts.map +1 -0
- package/dist/agents/nodes/utils.cjs +64 -0
- package/dist/agents/nodes/utils.cjs.map +1 -1
- package/dist/agents/nodes/utils.js +62 -1
- package/dist/agents/nodes/utils.js.map +1 -1
- package/dist/agents/responses.cjs +1 -1
- package/dist/agents/responses.cjs.map +1 -1
- package/dist/agents/responses.d.cts +9 -2
- package/dist/agents/responses.d.cts.map +1 -1
- package/dist/agents/responses.d.ts +8 -1
- package/dist/agents/responses.d.ts.map +1 -1
- package/dist/agents/responses.js +1 -1
- package/dist/agents/responses.js.map +1 -1
- package/dist/agents/runtime.d.cts +123 -0
- package/dist/agents/runtime.d.cts.map +1 -0
- package/dist/agents/runtime.d.ts +123 -0
- package/dist/agents/runtime.d.ts.map +1 -0
- package/dist/agents/tests/utils.cjs +13 -5
- package/dist/agents/tests/utils.cjs.map +1 -1
- package/dist/agents/tests/utils.d.cts +17 -8
- package/dist/agents/tests/utils.d.cts.map +1 -1
- package/dist/agents/tests/utils.d.ts +14 -5
- package/dist/agents/tests/utils.d.ts.map +1 -1
- package/dist/agents/tests/utils.js +13 -5
- package/dist/agents/tests/utils.js.map +1 -1
- package/dist/agents/tools.d.cts +9 -0
- package/dist/agents/tools.d.cts.map +1 -0
- package/dist/agents/tools.d.ts +9 -0
- package/dist/agents/tools.d.ts.map +1 -0
- package/dist/agents/types.d.cts +163 -119
- package/dist/agents/types.d.cts.map +1 -1
- package/dist/agents/types.d.ts +163 -119
- package/dist/agents/types.d.ts.map +1 -1
- package/dist/agents/utils.cjs +141 -38
- package/dist/agents/utils.cjs.map +1 -1
- package/dist/agents/utils.js +142 -40
- package/dist/agents/utils.js.map +1 -1
- package/dist/chat_models/universal.cjs +4 -0
- package/dist/chat_models/universal.cjs.map +1 -1
- package/dist/chat_models/universal.d.cts +6 -2
- package/dist/chat_models/universal.d.cts.map +1 -1
- package/dist/chat_models/universal.d.ts +4 -0
- package/dist/chat_models/universal.d.ts.map +1 -1
- package/dist/chat_models/universal.js +4 -0
- package/dist/chat_models/universal.js.map +1 -1
- package/dist/hub/base.cjs +4 -3
- package/dist/hub/base.cjs.map +1 -1
- package/dist/hub/base.d.cts +0 -4
- package/dist/hub/base.d.cts.map +1 -1
- package/dist/hub/base.d.ts +0 -4
- package/dist/hub/base.d.ts.map +1 -1
- package/dist/hub/base.js +4 -3
- package/dist/hub/base.js.map +1 -1
- package/dist/index.cjs +23 -43
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +21 -21
- package/dist/index.d.ts +21 -21
- package/dist/index.js +17 -26
- package/dist/index.js.map +1 -1
- package/dist/load/import_map.cjs +1 -7
- package/dist/load/import_map.cjs.map +1 -1
- package/dist/load/import_map.js +1 -7
- package/dist/load/import_map.js.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/client.cjs +74 -18
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/client.cjs.map +1 -0
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/client.js +75 -19
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/client.js.map +1 -0
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/env.cjs +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/env.cjs.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/env.js +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/env.js.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/experimental/otel/constants.cjs +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/experimental/otel/constants.cjs.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/experimental/otel/constants.js +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/experimental/otel/constants.js.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/experimental/otel/translator.cjs +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/experimental/otel/translator.cjs.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/experimental/otel/translator.js +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/experimental/otel/translator.js.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/index.cjs +2 -2
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/index.cjs.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/index.js +2 -2
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/index.js.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/run_trees.cjs +7 -5
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/run_trees.cjs.map +1 -0
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/run_trees.js +7 -5
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/run_trees.js.map +1 -0
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/singletons/constants.cjs +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/singletons/constants.cjs.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/singletons/constants.js +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/singletons/constants.js.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/singletons/fetch.cjs +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/singletons/fetch.cjs.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/singletons/fetch.js +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/singletons/fetch.js.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/singletons/otel.cjs +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/singletons/otel.cjs.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/singletons/otel.js +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/singletons/otel.js.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/_uuid.cjs +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/_uuid.cjs.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/_uuid.js +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/_uuid.js.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/async_caller.cjs +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/async_caller.cjs.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/async_caller.js +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/async_caller.js.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/env.cjs +19 -23
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/env.cjs.map +1 -0
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/env.js +19 -23
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/env.js.map +1 -0
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/error.cjs +16 -3
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/error.cjs.map +1 -0
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/error.js +16 -3
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/error.js.map +1 -0
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/fast-safe-stringify/index.cjs +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/fast-safe-stringify/index.cjs.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/fast-safe-stringify/index.js +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/fast-safe-stringify/index.js.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/messages.cjs +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/messages.cjs.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/messages.js +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/messages.js.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/project.cjs +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/project.cjs.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/project.js +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/project.js.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/prompts.cjs +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/prompts.cjs.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/prompts.js +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/prompts.js.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/warn.cjs +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/warn.cjs.map +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/warn.js +1 -1
- package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/dist/utils/warn.js.map +1 -1
- package/package.json +30 -63
- package/dist/agents/RunnableCallable.d.cts +0 -41
- package/dist/agents/RunnableCallable.d.cts.map +0 -1
- package/dist/agents/RunnableCallable.d.ts +0 -41
- package/dist/agents/RunnableCallable.d.ts.map +0 -1
- package/dist/agents/annotation.d.cts +0 -52
- package/dist/agents/annotation.d.cts.map +0 -1
- package/dist/agents/annotation.d.ts +0 -52
- package/dist/agents/annotation.d.ts.map +0 -1
- package/dist/agents/createAgent.cjs +0 -10
- package/dist/agents/createAgent.cjs.map +0 -1
- package/dist/agents/createAgent.js +0 -10
- package/dist/agents/createAgent.js.map +0 -1
- package/dist/agents/interrupt.cjs +0 -2
- package/dist/agents/interrupt.d.cts +0 -81
- package/dist/agents/interrupt.d.cts.map +0 -1
- package/dist/agents/interrupt.d.ts +0 -81
- package/dist/agents/interrupt.d.ts.map +0 -1
- package/dist/agents/interrupt.js +0 -3
- package/dist/agents/middlewareAgent/ReactAgent.cjs +0 -579
- package/dist/agents/middlewareAgent/ReactAgent.cjs.map +0 -1
- package/dist/agents/middlewareAgent/ReactAgent.d.cts +0 -234
- package/dist/agents/middlewareAgent/ReactAgent.d.cts.map +0 -1
- package/dist/agents/middlewareAgent/ReactAgent.d.ts +0 -234
- package/dist/agents/middlewareAgent/ReactAgent.d.ts.map +0 -1
- package/dist/agents/middlewareAgent/ReactAgent.js +0 -578
- package/dist/agents/middlewareAgent/ReactAgent.js.map +0 -1
- package/dist/agents/middlewareAgent/annotation.cjs +0 -45
- package/dist/agents/middlewareAgent/annotation.cjs.map +0 -1
- package/dist/agents/middlewareAgent/annotation.js +0 -44
- package/dist/agents/middlewareAgent/annotation.js.map +0 -1
- package/dist/agents/middlewareAgent/constants.d.cts +0 -5
- package/dist/agents/middlewareAgent/constants.d.cts.map +0 -1
- package/dist/agents/middlewareAgent/constants.d.ts +0 -5
- package/dist/agents/middlewareAgent/constants.d.ts.map +0 -1
- package/dist/agents/middlewareAgent/index.cjs +0 -11
- package/dist/agents/middlewareAgent/index.cjs.map +0 -1
- package/dist/agents/middlewareAgent/index.js +0 -11
- package/dist/agents/middlewareAgent/index.js.map +0 -1
- package/dist/agents/middlewareAgent/middleware/callLimit.cjs.map +0 -1
- package/dist/agents/middlewareAgent/middleware/callLimit.d.cts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/callLimit.d.ts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/callLimit.js.map +0 -1
- package/dist/agents/middlewareAgent/middleware/contextEditing.cjs.map +0 -1
- package/dist/agents/middlewareAgent/middleware/contextEditing.d.cts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/contextEditing.d.ts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/contextEditing.js.map +0 -1
- package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.cjs.map +0 -1
- package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.d.cts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.d.ts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.js.map +0 -1
- package/dist/agents/middlewareAgent/middleware/hitl.cjs +0 -341
- package/dist/agents/middlewareAgent/middleware/hitl.cjs.map +0 -1
- package/dist/agents/middlewareAgent/middleware/hitl.d.cts +0 -524
- package/dist/agents/middlewareAgent/middleware/hitl.d.cts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/hitl.d.ts +0 -524
- package/dist/agents/middlewareAgent/middleware/hitl.d.ts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/hitl.js +0 -340
- package/dist/agents/middlewareAgent/middleware/hitl.js.map +0 -1
- package/dist/agents/middlewareAgent/middleware/index.cjs +0 -52
- package/dist/agents/middlewareAgent/middleware/index.cjs.map +0 -1
- package/dist/agents/middlewareAgent/middleware/index.d.cts +0 -13
- package/dist/agents/middlewareAgent/middleware/index.d.ts +0 -13
- package/dist/agents/middlewareAgent/middleware/index.js +0 -34
- package/dist/agents/middlewareAgent/middleware/index.js.map +0 -1
- package/dist/agents/middlewareAgent/middleware/llmToolSelector.cjs.map +0 -1
- package/dist/agents/middlewareAgent/middleware/llmToolSelector.d.cts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/llmToolSelector.d.ts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/llmToolSelector.js.map +0 -1
- package/dist/agents/middlewareAgent/middleware/modelFallback.cjs.map +0 -1
- package/dist/agents/middlewareAgent/middleware/modelFallback.d.cts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/modelFallback.d.ts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/modelFallback.js.map +0 -1
- package/dist/agents/middlewareAgent/middleware/piiRedaction.cjs.map +0 -1
- package/dist/agents/middlewareAgent/middleware/piiRedaction.d.cts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/piiRedaction.d.ts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/piiRedaction.js.map +0 -1
- package/dist/agents/middlewareAgent/middleware/promptCaching.cjs.map +0 -1
- package/dist/agents/middlewareAgent/middleware/promptCaching.d.cts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/promptCaching.d.ts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/promptCaching.js.map +0 -1
- package/dist/agents/middlewareAgent/middleware/summarization.cjs.map +0 -1
- package/dist/agents/middlewareAgent/middleware/summarization.d.cts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/summarization.d.ts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/summarization.js.map +0 -1
- package/dist/agents/middlewareAgent/middleware/toolCallLimit.cjs.map +0 -1
- package/dist/agents/middlewareAgent/middleware/toolCallLimit.d.cts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/toolCallLimit.d.ts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/toolCallLimit.js.map +0 -1
- package/dist/agents/middlewareAgent/middleware/utils.cjs.map +0 -1
- package/dist/agents/middlewareAgent/middleware/utils.d.cts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/utils.d.ts.map +0 -1
- package/dist/agents/middlewareAgent/middleware/utils.js.map +0 -1
- package/dist/agents/middlewareAgent/middleware.cjs.map +0 -1
- package/dist/agents/middlewareAgent/middleware.d.cts +0 -117
- package/dist/agents/middlewareAgent/middleware.d.cts.map +0 -1
- package/dist/agents/middlewareAgent/middleware.d.ts +0 -117
- package/dist/agents/middlewareAgent/middleware.d.ts.map +0 -1
- package/dist/agents/middlewareAgent/middleware.js.map +0 -1
- package/dist/agents/middlewareAgent/nodes/AfterModalNode.cjs.map +0 -1
- package/dist/agents/middlewareAgent/nodes/AfterModalNode.js.map +0 -1
- package/dist/agents/middlewareAgent/nodes/AgentNode.cjs +0 -468
- package/dist/agents/middlewareAgent/nodes/AgentNode.cjs.map +0 -1
- package/dist/agents/middlewareAgent/nodes/AgentNode.js +0 -467
- package/dist/agents/middlewareAgent/nodes/AgentNode.js.map +0 -1
- package/dist/agents/middlewareAgent/nodes/BeforeModalNode.cjs.map +0 -1
- package/dist/agents/middlewareAgent/nodes/BeforeModalNode.js.map +0 -1
- package/dist/agents/middlewareAgent/nodes/middleware.cjs.map +0 -1
- package/dist/agents/middlewareAgent/nodes/middleware.js.map +0 -1
- package/dist/agents/middlewareAgent/nodes/utils.cjs +0 -66
- package/dist/agents/middlewareAgent/nodes/utils.cjs.map +0 -1
- package/dist/agents/middlewareAgent/nodes/utils.js +0 -63
- package/dist/agents/middlewareAgent/nodes/utils.js.map +0 -1
- package/dist/agents/middlewareAgent/types.d.cts +0 -472
- package/dist/agents/middlewareAgent/types.d.cts.map +0 -1
- package/dist/agents/middlewareAgent/types.d.ts +0 -472
- package/dist/agents/middlewareAgent/types.d.ts.map +0 -1
- package/dist/agents/nodes/ToolNode.d.cts +0 -97
- package/dist/agents/nodes/ToolNode.d.cts.map +0 -1
- package/dist/agents/nodes/ToolNode.d.ts +0 -97
- package/dist/agents/nodes/ToolNode.d.ts.map +0 -1
- package/dist/agents/types.cjs +0 -7
- package/dist/agents/types.cjs.map +0 -1
- package/dist/agents/types.js +0 -6
- package/dist/agents/types.js.map +0 -1
- package/dist/embeddings/cache_backed.cjs +0 -140
- package/dist/embeddings/cache_backed.cjs.map +0 -1
- package/dist/embeddings/cache_backed.d.cts +0 -107
- package/dist/embeddings/cache_backed.d.cts.map +0 -1
- package/dist/embeddings/cache_backed.d.ts +0 -107
- package/dist/embeddings/cache_backed.d.ts.map +0 -1
- package/dist/embeddings/cache_backed.js +0 -134
- package/dist/embeddings/cache_backed.js.map +0 -1
- package/dist/embeddings/fake.cjs +0 -22
- package/dist/embeddings/fake.cjs.map +0 -1
- package/dist/embeddings/fake.d.cts +0 -1
- package/dist/embeddings/fake.d.ts +0 -1
- package/dist/embeddings/fake.js +0 -12
- package/dist/embeddings/fake.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/client.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/client.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/run_trees.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/run_trees.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/env.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/env.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/error.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/error.js.map +0 -1
- /package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/index.cjs +0 -0
- /package/dist/node_modules/.pnpm/{langsmith@0.3.64_@opentelemetry_api@1.9.0_openai@5.11.0_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_ → langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_}/node_modules/langsmith/index.js +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"llmToolSelector.cjs","names":["tools: StructuredToolInterface[]","z","BaseLanguageModel","options: LLMToolSelectorConfig","createMiddleware","request: ModelRequest<TState, TContext>","runtime: Runtime<LLMToolSelectorConfig>","lastUserMessage: HumanMessage | undefined","HumanMessage","initChatModel","response: { tools: string[] }","availableTools: StructuredToolInterface[]","validToolNames: string[]","selectedToolNames: string[]","invalidToolSelections: string[]"],"sources":["../../../src/agents/middleware/llmToolSelector.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\nimport { HumanMessage } from \"@langchain/core/messages\";\nimport type { StructuredToolInterface } from \"@langchain/core/tools\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport type { Runtime } from \"../runtime.js\";\nimport type { ModelRequest } from \"../nodes/types.js\";\n\nconst DEFAULT_SYSTEM_PROMPT =\n \"Your goal is to select the most relevant tools for answering the user's query.\";\n\n/**\n * Prepared inputs for tool selection.\n */\ninterface SelectionRequest {\n availableTools: StructuredToolInterface[];\n systemMessage: string;\n lastUserMessage: HumanMessage;\n model: BaseLanguageModel;\n validToolNames: string[];\n}\n\n/**\n * Create a structured output schema for tool selection.\n *\n * @param tools - Available tools to include in the schema.\n * @returns Zod schema where each tool name is a literal with its description.\n */\nfunction createToolSelectionResponse(tools: StructuredToolInterface[]) {\n if (!tools || tools.length === 0) {\n throw new Error(\"Invalid usage: tools must be non-empty\");\n }\n\n // Create a union of literals for each tool name\n const toolLiterals = tools.map((tool) => z.literal(tool.name));\n const toolEnum = z.union(\n toolLiterals as [\n z.ZodLiteral<string>,\n z.ZodLiteral<string>,\n ...z.ZodLiteral<string>[]\n ]\n );\n\n return z.object({\n tools: z\n .array(toolEnum)\n .describe(\"Tools to use. Place the most relevant tools first.\"),\n });\n}\n\n/**\n * Options for configuring the LLM Tool Selector middleware.\n */\nexport const LLMToolSelectorOptionsSchema = z.object({\n /**\n * The language model to use for tool selection (default: the provided model from the agent options).\n */\n model: z.string().or(z.instanceof(BaseLanguageModel)).optional(),\n /**\n * System prompt for the tool selection model.\n */\n systemPrompt: z.string().optional(),\n /**\n * Maximum number of tools to select. If the model selects more,\n * only the first maxTools will be used. No limit if not specified.\n */\n maxTools: z.number().optional(),\n /**\n * Tool names to always include regardless of selection.\n * These do not count against the maxTools limit.\n */\n alwaysInclude: z.array(z.string()).optional(),\n});\nexport type LLMToolSelectorConfig = InferInteropZodInput<\n typeof LLMToolSelectorOptionsSchema\n>;\n\n/**\n * Middleware for selecting tools using an LLM-based strategy.\n *\n * When an agent has many tools available, this middleware filters them down\n * to only the most relevant ones for the user's query. This reduces token usage\n * and helps the main model focus on the right tools.\n *\n * @param options - Configuration options for the middleware\n * @param options.model - The language model to use for tool selection (default: the provided model from the agent options).\n * @param options.systemPrompt - Instructions for the selection model.\n * @param options.maxTools - Maximum number of tools to select. If the model selects more,\n * only the first maxTools will be used. No limit if not specified.\n * @param options.alwaysInclude - Tool names to always include regardless of selection.\n * These do not count against the maxTools limit.\n *\n * @example\n * Limit to 3 tools:\n * ```ts\n * import { llmToolSelectorMiddleware } from \"langchain/agents/middleware\";\n *\n * const middleware = llmToolSelectorMiddleware({ maxTools: 3 });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [tool1, tool2, tool3, tool4, tool5],\n * middleware: [middleware],\n * });\n * ```\n *\n * @example\n * Use a smaller model for selection:\n * ```ts\n * const middleware = llmToolSelectorMiddleware({\n * model: \"openai:gpt-4o-mini\",\n * maxTools: 2\n * });\n * ```\n */\nexport function llmToolSelectorMiddleware(\n options: LLMToolSelectorConfig\n): ReturnType<typeof createMiddleware> {\n return createMiddleware({\n name: \"LLMToolSelector\",\n contextSchema: LLMToolSelectorOptionsSchema,\n async wrapModelCall(request, handler) {\n const selectionRequest = await prepareSelectionRequest(\n request,\n options,\n request.runtime\n );\n if (!selectionRequest) {\n return handler(request);\n }\n\n // Create dynamic response model with union of literal tool names\n const toolSelectionSchema = createToolSelectionResponse(\n selectionRequest.availableTools\n );\n const structuredModel =\n await selectionRequest.model.withStructuredOutput?.(\n toolSelectionSchema\n );\n\n const response = await structuredModel?.invoke([\n { role: \"system\", content: selectionRequest.systemMessage },\n selectionRequest.lastUserMessage,\n ]);\n\n // Response should be an object with a tools array\n if (!response || typeof response !== \"object\" || !(\"tools\" in response)) {\n throw new Error(\n `Expected object response with tools array, got ${typeof response}`\n );\n }\n\n return handler(\n processSelectionResponse(\n response as { tools: string[] },\n selectionRequest.availableTools,\n selectionRequest.validToolNames,\n request,\n options\n )\n );\n },\n });\n}\n\n/**\n * Prepare inputs for tool selection.\n *\n * @param request - The model request to process.\n * @param options - Configuration options.\n * @param runtime - Runtime context.\n * @returns SelectionRequest with prepared inputs, or null if no selection is needed.\n */\nasync function prepareSelectionRequest<\n TState extends Record<string, unknown> = Record<string, unknown>,\n TContext = unknown\n>(\n request: ModelRequest<TState, TContext>,\n options: LLMToolSelectorConfig,\n runtime: Runtime<LLMToolSelectorConfig>\n): Promise<SelectionRequest | undefined> {\n const model = runtime.context.model ?? options.model;\n const maxTools = runtime.context.maxTools ?? options.maxTools;\n const alwaysInclude =\n runtime.context.alwaysInclude ?? options.alwaysInclude ?? [];\n const systemPrompt =\n runtime.context.systemPrompt ??\n options.systemPrompt ??\n DEFAULT_SYSTEM_PROMPT;\n\n /**\n * If no tools available, return null\n */\n if (!request.tools || request.tools.length === 0) {\n return undefined;\n }\n\n /**\n * Filter to only StructuredToolInterface instances (exclude provider-specific tool dicts)\n */\n const baseTools = request.tools.filter(\n (tool): tool is StructuredToolInterface =>\n typeof tool === \"object\" &&\n \"name\" in tool &&\n \"description\" in tool &&\n typeof tool.name === \"string\"\n );\n\n /**\n * Validate that alwaysInclude tools exist\n */\n if (alwaysInclude.length > 0) {\n const availableToolNames = new Set(baseTools.map((tool) => tool.name));\n const missingTools = alwaysInclude.filter(\n (name) => !availableToolNames.has(name)\n );\n if (missingTools.length > 0) {\n throw new Error(\n `Tools in alwaysInclude not found in request: ${missingTools.join(\n \", \"\n )}. ` +\n `Available tools: ${Array.from(availableToolNames).sort().join(\", \")}`\n );\n }\n }\n\n /**\n * Separate tools that are always included from those available for selection\n */\n const availableTools = baseTools.filter(\n (tool) => !alwaysInclude.includes(tool.name)\n );\n\n /**\n * If no tools available for selection, return null\n */\n if (availableTools.length === 0) {\n return undefined;\n }\n\n let systemMessage = systemPrompt;\n /**\n * If there's a maxTools limit, append instructions to the system prompt\n */\n if (maxTools !== undefined) {\n systemMessage +=\n `\\nIMPORTANT: List the tool names in order of relevance, ` +\n `with the most relevant first. ` +\n `If you exceed the maximum number of tools, ` +\n `only the first ${maxTools} will be used.`;\n }\n\n /**\n * Get the last user message from the conversation history\n */\n let lastUserMessage: HumanMessage | undefined;\n for (const message of request.messages) {\n if (HumanMessage.isInstance(message)) {\n lastUserMessage = message;\n }\n }\n\n if (!lastUserMessage) {\n throw new Error(\"No user message found in request messages\");\n }\n\n const modelInstance = !model\n ? (request.model as BaseLanguageModel)\n : typeof model === \"string\"\n ? await initChatModel(model)\n : model;\n\n const validToolNames = availableTools.map((tool) => tool.name);\n\n return {\n availableTools,\n systemMessage,\n lastUserMessage,\n model: modelInstance,\n validToolNames,\n };\n}\n\n/**\n * Process the selection response and return filtered ModelRequest.\n *\n * @param response - The structured output response from the model.\n * @param availableTools - Tools available for selection.\n * @param validToolNames - Valid tool names that can be selected.\n * @param request - Original model request.\n * @param options - Configuration options.\n * @returns Modified ModelRequest with filtered tools.\n */\nfunction processSelectionResponse<\n TState extends Record<string, unknown> = Record<string, unknown>,\n TContext = unknown\n>(\n response: { tools: string[] },\n availableTools: StructuredToolInterface[],\n validToolNames: string[],\n request: ModelRequest<TState, TContext>,\n options: LLMToolSelectorConfig\n): ModelRequest<TState, TContext> {\n const maxTools = options.maxTools;\n const alwaysInclude = options.alwaysInclude ?? [];\n\n const selectedToolNames: string[] = [];\n const invalidToolSelections: string[] = [];\n\n for (const toolName of response.tools) {\n if (!validToolNames.includes(toolName)) {\n invalidToolSelections.push(toolName);\n continue;\n }\n\n /**\n * Only add if not already selected and within maxTools limit\n */\n if (\n !selectedToolNames.includes(toolName) &&\n (maxTools === undefined || selectedToolNames.length < maxTools)\n ) {\n selectedToolNames.push(toolName);\n }\n }\n\n if (invalidToolSelections.length > 0) {\n throw new Error(\n `Model selected invalid tools: ${invalidToolSelections.join(\", \")}`\n );\n }\n\n /**\n * Filter tools based on selection\n */\n const selectedTools = availableTools.filter((tool) =>\n selectedToolNames.includes(tool.name)\n );\n\n /**\n * Append always-included tools\n */\n const alwaysIncludedTools = (request.tools ?? []).filter(\n (tool): tool is StructuredToolInterface =>\n typeof tool === \"object\" &&\n \"name\" in tool &&\n typeof tool.name === \"string\" &&\n alwaysInclude.includes(tool.name)\n );\n selectedTools.push(...alwaysIncludedTools);\n\n /**\n * Also preserve any provider-specific tool dicts from the original request\n */\n const providerTools = (request.tools ?? []).filter(\n (tool) =>\n !(\n typeof tool === \"object\" &&\n \"name\" in tool &&\n \"description\" in tool &&\n typeof tool.name === \"string\"\n )\n );\n\n return {\n ...request,\n tools: [...selectedTools, ...providerTools],\n };\n}\n"],"mappings":"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"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { createMiddleware } from "../middleware.cjs";
|
|
2
2
|
import * as _langchain_core_language_models_base7 from "@langchain/core/language_models/base";
|
|
3
3
|
import { BaseLanguageModel } from "@langchain/core/language_models/base";
|
|
4
|
-
import { z } from "zod/v3";
|
|
5
4
|
import { InferInteropZodInput } from "@langchain/core/utils/types";
|
|
5
|
+
import { z } from "zod/v3";
|
|
6
6
|
|
|
7
|
-
//#region src/agents/
|
|
7
|
+
//#region src/agents/middleware/llmToolSelector.d.ts
|
|
8
8
|
/**
|
|
9
9
|
* Options for configuring the LLM Tool Selector middleware.
|
|
10
10
|
*/
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"llmToolSelector.d.cts","names":["z","BaseLanguageModel","InferInteropZodInput","createMiddleware","LLMToolSelectorOptionsSchema","ZodString","_langchain_core_language_models_base7","BaseLanguageModelCallOptions","ZodTypeDef","ZodType","ZodUnion","ZodOptional","ZodNumber","ZodArray","ZodTypeAny","ZodObject","LLMToolSelectorConfig","llmToolSelectorMiddleware","ReturnType"],"sources":["../../../src/agents/middleware/llmToolSelector.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\nimport { createMiddleware } from \"../middleware.js\";\n/**\n * Options for configuring the LLM Tool Selector middleware.\n */\nexport declare const LLMToolSelectorOptionsSchema: z.ZodObject<{\n /**\n * The language model to use for tool selection (default: the provided model from the agent options).\n */\n model: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodType<BaseLanguageModel<unknown, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions>, z.ZodTypeDef, BaseLanguageModel<unknown, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions>>]>>;\n /**\n * System prompt for the tool selection model.\n */\n systemPrompt: z.ZodOptional<z.ZodString>;\n /**\n * Maximum number of tools to select. If the model selects more,\n * only the first maxTools will be used. No limit if not specified.\n */\n maxTools: z.ZodOptional<z.ZodNumber>;\n /**\n * Tool names to always include regardless of selection.\n * These do not count against the maxTools limit.\n */\n alwaysInclude: z.ZodOptional<z.ZodArray<z.ZodString, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n model?: string | BaseLanguageModel<unknown, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions> | undefined;\n systemPrompt?: string | undefined;\n maxTools?: number | undefined;\n alwaysInclude?: string[] | undefined;\n}, {\n model?: string | BaseLanguageModel<unknown, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions> | undefined;\n systemPrompt?: string | undefined;\n maxTools?: number | undefined;\n alwaysInclude?: string[] | undefined;\n}>;\nexport type LLMToolSelectorConfig = InferInteropZodInput<typeof LLMToolSelectorOptionsSchema>;\n/**\n * Middleware for selecting tools using an LLM-based strategy.\n *\n * When an agent has many tools available, this middleware filters them down\n * to only the most relevant ones for the user's query. This reduces token usage\n * and helps the main model focus on the right tools.\n *\n * @param options - Configuration options for the middleware\n * @param options.model - The language model to use for tool selection (default: the provided model from the agent options).\n * @param options.systemPrompt - Instructions for the selection model.\n * @param options.maxTools - Maximum number of tools to select. If the model selects more,\n * only the first maxTools will be used. No limit if not specified.\n * @param options.alwaysInclude - Tool names to always include regardless of selection.\n * These do not count against the maxTools limit.\n *\n * @example\n * Limit to 3 tools:\n * ```ts\n * import { llmToolSelectorMiddleware } from \"langchain/agents/middleware\";\n *\n * const middleware = llmToolSelectorMiddleware({ maxTools: 3 });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [tool1, tool2, tool3, tool4, tool5],\n * middleware: [middleware],\n * });\n * ```\n *\n * @example\n * Use a smaller model for selection:\n * ```ts\n * const middleware = llmToolSelectorMiddleware({\n * model: \"openai:gpt-4o-mini\",\n * maxTools: 2\n * });\n * ```\n */\nexport declare function llmToolSelectorMiddleware(options: LLMToolSelectorConfig): ReturnType<typeof createMiddleware>;\n"],"mappings":";;;;;;;;;;AAOqBI,cAAAA,4BA6BnB,EA7BiDJ,CAAAA,CAAEe,SA6BnD,CAAA;EAAA;;;EAzBgK,KAAtGd,EAAjDD,CAAAA,CAAEW,WAA+CV,CAAnCD,CAAAA,CAAEU,QAAiCT,CAAAA,CAAvBD,CAAAA,CAAEK,SAAqBJ,EAAVD,CAAAA,CAAES,OAAQR,CAAAA,iBAAAA,CAAAA,OAAAA,EAAZK,qCAAAA,CAAsFC,4BAAAA,CAA1EN,EAAyGD,CAAAA,CAAEQ,UAA3GP,EAAuHA,iBAAvHA,CAAAA,OAAAA,EAAqHK,qCAAAA,CAA4EC,4BAAAA,CAAjMN,CAAAA,CAAAA,CAAAA,CAAAA;EAAiB;;;EAAuH,YAAhJQ,EAIlCT,CAAAA,CAAEW,WAJgCF,CAIpBT,CAAAA,CAAEK,SAJkBI,CAAAA;EAAO;;;;EAI5B,QAKDG,EAAhBZ,CAAAA,CAAEW,WAAcC,CAAFZ,CAAAA,CAAEY,SAAAA,CAAAA;EAAS;;;;EAKP,aAClBE,EADKd,CAAAA,CAAEW,WACPG,CADmBd,CAAAA,CAAEa,QACrBC,CAD8Bd,CAAAA,CAAEK,SAChCS,EAAAA,MAAAA,CAAAA,CAAAA;CAAU,EAAA,OAAAR,EAAZN,CAAAA,CAAEc,UAAUR,EAAAA;EACmG,KAAtGL,CAAAA,EAAAA,MAAAA,GAAAA,iBAAAA,CAAAA,OAAAA,EADGK,qCAAAA,CACuEC,4BAAAA,CAA1EN,GAAAA,SAAAA;EAAiB,YAAAK,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAKqF,QAAtGL,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAiB,aAzBec,CAAAA,EAAAA,MAAAA,EAAAA,GAAAA,SAAAA;AAAS,CAAA,EAAA;EA8BlDC,KAAAA,CAAAA,EAAAA,MAAAA,GALSf,iBAKY,CAAA,OAAA,EAVKK,qCAAAA,CAKyDC,4BAAAA,CAK9D,GAAA,SAAA;EAAA,YAAA,CAAA,EAAA,MAAA,GAAA,SAAA;EAAA,QAA+BH,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAA4B,aAAxDF,CAAAA,EAAAA,MAAAA,EAAAA,GAAAA,SAAAA;AAAoB,CAAA,CAAA;AAuChCe,KAvCZD,qBAAAA,GAAwBd,oBAuCa,CAAA,OAvCeE,4BAuCf,CAAA;;;;;AAA4C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAArEa,yBAAAA,UAAmCD,wBAAwBE,kBAAkBf"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { createMiddleware } from "../middleware.js";
|
|
2
|
-
import { InferInteropZodInput } from "@langchain/core/utils/types";
|
|
3
2
|
import { z } from "zod/v3";
|
|
3
|
+
import { InferInteropZodInput } from "@langchain/core/utils/types";
|
|
4
4
|
import * as _langchain_core_language_models_base7 from "@langchain/core/language_models/base";
|
|
5
5
|
import { BaseLanguageModel } from "@langchain/core/language_models/base";
|
|
6
6
|
|
|
7
|
-
//#region src/agents/
|
|
7
|
+
//#region src/agents/middleware/llmToolSelector.d.ts
|
|
8
8
|
/**
|
|
9
9
|
* Options for configuring the LLM Tool Selector middleware.
|
|
10
10
|
*/
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"llmToolSelector.d.ts","names":["z","BaseLanguageModel","InferInteropZodInput","createMiddleware","LLMToolSelectorOptionsSchema","ZodString","_langchain_core_language_models_base7","BaseLanguageModelCallOptions","ZodTypeDef","ZodType","ZodUnion","ZodOptional","ZodNumber","ZodArray","ZodTypeAny","ZodObject","LLMToolSelectorConfig","llmToolSelectorMiddleware","ReturnType"],"sources":["../../../src/agents/middleware/llmToolSelector.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\nimport { createMiddleware } from \"../middleware.js\";\n/**\n * Options for configuring the LLM Tool Selector middleware.\n */\nexport declare const LLMToolSelectorOptionsSchema: z.ZodObject<{\n /**\n * The language model to use for tool selection (default: the provided model from the agent options).\n */\n model: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodType<BaseLanguageModel<unknown, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions>, z.ZodTypeDef, BaseLanguageModel<unknown, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions>>]>>;\n /**\n * System prompt for the tool selection model.\n */\n systemPrompt: z.ZodOptional<z.ZodString>;\n /**\n * Maximum number of tools to select. If the model selects more,\n * only the first maxTools will be used. No limit if not specified.\n */\n maxTools: z.ZodOptional<z.ZodNumber>;\n /**\n * Tool names to always include regardless of selection.\n * These do not count against the maxTools limit.\n */\n alwaysInclude: z.ZodOptional<z.ZodArray<z.ZodString, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n model?: string | BaseLanguageModel<unknown, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions> | undefined;\n systemPrompt?: string | undefined;\n maxTools?: number | undefined;\n alwaysInclude?: string[] | undefined;\n}, {\n model?: string | BaseLanguageModel<unknown, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions> | undefined;\n systemPrompt?: string | undefined;\n maxTools?: number | undefined;\n alwaysInclude?: string[] | undefined;\n}>;\nexport type LLMToolSelectorConfig = InferInteropZodInput<typeof LLMToolSelectorOptionsSchema>;\n/**\n * Middleware for selecting tools using an LLM-based strategy.\n *\n * When an agent has many tools available, this middleware filters them down\n * to only the most relevant ones for the user's query. This reduces token usage\n * and helps the main model focus on the right tools.\n *\n * @param options - Configuration options for the middleware\n * @param options.model - The language model to use for tool selection (default: the provided model from the agent options).\n * @param options.systemPrompt - Instructions for the selection model.\n * @param options.maxTools - Maximum number of tools to select. If the model selects more,\n * only the first maxTools will be used. No limit if not specified.\n * @param options.alwaysInclude - Tool names to always include regardless of selection.\n * These do not count against the maxTools limit.\n *\n * @example\n * Limit to 3 tools:\n * ```ts\n * import { llmToolSelectorMiddleware } from \"langchain/agents/middleware\";\n *\n * const middleware = llmToolSelectorMiddleware({ maxTools: 3 });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [tool1, tool2, tool3, tool4, tool5],\n * middleware: [middleware],\n * });\n * ```\n *\n * @example\n * Use a smaller model for selection:\n * ```ts\n * const middleware = llmToolSelectorMiddleware({\n * model: \"openai:gpt-4o-mini\",\n * maxTools: 2\n * });\n * ```\n */\nexport declare function llmToolSelectorMiddleware(options: LLMToolSelectorConfig): ReturnType<typeof createMiddleware>;\n"],"mappings":";;;;;;;;;;AAOqBI,cAAAA,4BA6BnB,EA7BiDJ,CAAAA,CAAEe,SA6BnD,CAAA;EAAA;;;EAzBgK,KAAtGd,EAAjDD,CAAAA,CAAEW,WAA+CV,CAAnCD,CAAAA,CAAEU,QAAiCT,CAAAA,CAAvBD,CAAAA,CAAEK,SAAqBJ,EAAVD,CAAAA,CAAES,OAAQR,CAAAA,iBAAAA,CAAAA,OAAAA,EAAZK,qCAAAA,CAAsFC,4BAAAA,CAA1EN,EAAyGD,CAAAA,CAAEQ,UAA3GP,EAAuHA,iBAAvHA,CAAAA,OAAAA,EAAqHK,qCAAAA,CAA4EC,4BAAAA,CAAjMN,CAAAA,CAAAA,CAAAA,CAAAA;EAAiB;;;EAAuH,YAAhJQ,EAIlCT,CAAAA,CAAEW,WAJgCF,CAIpBT,CAAAA,CAAEK,SAJkBI,CAAAA;EAAO;;;;EAI5B,QAKDG,EAAhBZ,CAAAA,CAAEW,WAAcC,CAAFZ,CAAAA,CAAEY,SAAAA,CAAAA;EAAS;;;;EAKP,aAClBE,EADKd,CAAAA,CAAEW,WACPG,CADmBd,CAAAA,CAAEa,QACrBC,CAD8Bd,CAAAA,CAAEK,SAChCS,EAAAA,MAAAA,CAAAA,CAAAA;CAAU,EAAA,OAAAR,EAAZN,CAAAA,CAAEc,UAAUR,EAAAA;EACmG,KAAtGL,CAAAA,EAAAA,MAAAA,GAAAA,iBAAAA,CAAAA,OAAAA,EADGK,qCAAAA,CACuEC,4BAAAA,CAA1EN,GAAAA,SAAAA;EAAiB,YAAAK,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAKqF,QAAtGL,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAiB,aAzBec,CAAAA,EAAAA,MAAAA,EAAAA,GAAAA,SAAAA;AAAS,CAAA,EAAA;EA8BlDC,KAAAA,CAAAA,EAAAA,MAAAA,GALSf,iBAKY,CAAA,OAAA,EAVKK,qCAAAA,CAKyDC,4BAAAA,CAK9D,GAAA,SAAA;EAAA,YAAA,CAAA,EAAA,MAAA,GAAA,SAAA;EAAA,QAA+BH,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAA4B,aAAxDF,CAAAA,EAAAA,MAAAA,EAAAA,GAAAA,SAAAA;AAAoB,CAAA,CAAA;AAuChCe,KAvCZD,qBAAAA,GAAwBd,oBAuCa,CAAA,OAvCeE,4BAuCf,CAAA;;;;;AAA4C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAArEa,yBAAAA,UAAmCD,wBAAwBE,kBAAkBf"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { initChatModel } from "
|
|
1
|
+
import { initChatModel } from "../../chat_models/universal.js";
|
|
2
2
|
import { createMiddleware } from "../middleware.js";
|
|
3
3
|
import { HumanMessage } from "@langchain/core/messages";
|
|
4
4
|
import { z } from "zod/v3";
|
|
5
5
|
import { BaseLanguageModel } from "@langchain/core/language_models/base";
|
|
6
6
|
|
|
7
|
-
//#region src/agents/
|
|
7
|
+
//#region src/agents/middleware/llmToolSelector.ts
|
|
8
8
|
const DEFAULT_SYSTEM_PROMPT = "Your goal is to select the most relevant tools for answering the user's query.";
|
|
9
9
|
/**
|
|
10
10
|
* Create a structured output schema for tool selection.
|
|
@@ -69,9 +69,9 @@ function llmToolSelectorMiddleware(options) {
|
|
|
69
69
|
return createMiddleware({
|
|
70
70
|
name: "LLMToolSelector",
|
|
71
71
|
contextSchema: LLMToolSelectorOptionsSchema,
|
|
72
|
-
async
|
|
73
|
-
const selectionRequest = await prepareSelectionRequest(request, options, runtime);
|
|
74
|
-
if (!selectionRequest) return request;
|
|
72
|
+
async wrapModelCall(request, handler) {
|
|
73
|
+
const selectionRequest = await prepareSelectionRequest(request, options, request.runtime);
|
|
74
|
+
if (!selectionRequest) return handler(request);
|
|
75
75
|
const toolSelectionSchema = createToolSelectionResponse(selectionRequest.availableTools);
|
|
76
76
|
const structuredModel = await selectionRequest.model.withStructuredOutput?.(toolSelectionSchema);
|
|
77
77
|
const response = await structuredModel?.invoke([{
|
|
@@ -79,7 +79,7 @@ function llmToolSelectorMiddleware(options) {
|
|
|
79
79
|
content: selectionRequest.systemMessage
|
|
80
80
|
}, selectionRequest.lastUserMessage]);
|
|
81
81
|
if (!response || typeof response !== "object" || !("tools" in response)) throw new Error(`Expected object response with tools array, got ${typeof response}`);
|
|
82
|
-
return processSelectionResponse(response, selectionRequest.availableTools, selectionRequest.validToolNames, request, options);
|
|
82
|
+
return handler(processSelectionResponse(response, selectionRequest.availableTools, selectionRequest.validToolNames, request, options));
|
|
83
83
|
}
|
|
84
84
|
});
|
|
85
85
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"llmToolSelector.js","names":["tools: StructuredToolInterface[]","options: LLMToolSelectorConfig","request: ModelRequest<TState, TContext>","runtime: Runtime<LLMToolSelectorConfig>","lastUserMessage: HumanMessage | undefined","response: { tools: string[] }","availableTools: StructuredToolInterface[]","validToolNames: string[]","selectedToolNames: string[]","invalidToolSelections: string[]"],"sources":["../../../src/agents/middleware/llmToolSelector.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\nimport { HumanMessage } from \"@langchain/core/messages\";\nimport type { StructuredToolInterface } from \"@langchain/core/tools\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport type { Runtime } from \"../runtime.js\";\nimport type { ModelRequest } from \"../nodes/types.js\";\n\nconst DEFAULT_SYSTEM_PROMPT =\n \"Your goal is to select the most relevant tools for answering the user's query.\";\n\n/**\n * Prepared inputs for tool selection.\n */\ninterface SelectionRequest {\n availableTools: StructuredToolInterface[];\n systemMessage: string;\n lastUserMessage: HumanMessage;\n model: BaseLanguageModel;\n validToolNames: string[];\n}\n\n/**\n * Create a structured output schema for tool selection.\n *\n * @param tools - Available tools to include in the schema.\n * @returns Zod schema where each tool name is a literal with its description.\n */\nfunction createToolSelectionResponse(tools: StructuredToolInterface[]) {\n if (!tools || tools.length === 0) {\n throw new Error(\"Invalid usage: tools must be non-empty\");\n }\n\n // Create a union of literals for each tool name\n const toolLiterals = tools.map((tool) => z.literal(tool.name));\n const toolEnum = z.union(\n toolLiterals as [\n z.ZodLiteral<string>,\n z.ZodLiteral<string>,\n ...z.ZodLiteral<string>[]\n ]\n );\n\n return z.object({\n tools: z\n .array(toolEnum)\n .describe(\"Tools to use. Place the most relevant tools first.\"),\n });\n}\n\n/**\n * Options for configuring the LLM Tool Selector middleware.\n */\nexport const LLMToolSelectorOptionsSchema = z.object({\n /**\n * The language model to use for tool selection (default: the provided model from the agent options).\n */\n model: z.string().or(z.instanceof(BaseLanguageModel)).optional(),\n /**\n * System prompt for the tool selection model.\n */\n systemPrompt: z.string().optional(),\n /**\n * Maximum number of tools to select. If the model selects more,\n * only the first maxTools will be used. No limit if not specified.\n */\n maxTools: z.number().optional(),\n /**\n * Tool names to always include regardless of selection.\n * These do not count against the maxTools limit.\n */\n alwaysInclude: z.array(z.string()).optional(),\n});\nexport type LLMToolSelectorConfig = InferInteropZodInput<\n typeof LLMToolSelectorOptionsSchema\n>;\n\n/**\n * Middleware for selecting tools using an LLM-based strategy.\n *\n * When an agent has many tools available, this middleware filters them down\n * to only the most relevant ones for the user's query. This reduces token usage\n * and helps the main model focus on the right tools.\n *\n * @param options - Configuration options for the middleware\n * @param options.model - The language model to use for tool selection (default: the provided model from the agent options).\n * @param options.systemPrompt - Instructions for the selection model.\n * @param options.maxTools - Maximum number of tools to select. If the model selects more,\n * only the first maxTools will be used. No limit if not specified.\n * @param options.alwaysInclude - Tool names to always include regardless of selection.\n * These do not count against the maxTools limit.\n *\n * @example\n * Limit to 3 tools:\n * ```ts\n * import { llmToolSelectorMiddleware } from \"langchain/agents/middleware\";\n *\n * const middleware = llmToolSelectorMiddleware({ maxTools: 3 });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [tool1, tool2, tool3, tool4, tool5],\n * middleware: [middleware],\n * });\n * ```\n *\n * @example\n * Use a smaller model for selection:\n * ```ts\n * const middleware = llmToolSelectorMiddleware({\n * model: \"openai:gpt-4o-mini\",\n * maxTools: 2\n * });\n * ```\n */\nexport function llmToolSelectorMiddleware(\n options: LLMToolSelectorConfig\n): ReturnType<typeof createMiddleware> {\n return createMiddleware({\n name: \"LLMToolSelector\",\n contextSchema: LLMToolSelectorOptionsSchema,\n async wrapModelCall(request, handler) {\n const selectionRequest = await prepareSelectionRequest(\n request,\n options,\n request.runtime\n );\n if (!selectionRequest) {\n return handler(request);\n }\n\n // Create dynamic response model with union of literal tool names\n const toolSelectionSchema = createToolSelectionResponse(\n selectionRequest.availableTools\n );\n const structuredModel =\n await selectionRequest.model.withStructuredOutput?.(\n toolSelectionSchema\n );\n\n const response = await structuredModel?.invoke([\n { role: \"system\", content: selectionRequest.systemMessage },\n selectionRequest.lastUserMessage,\n ]);\n\n // Response should be an object with a tools array\n if (!response || typeof response !== \"object\" || !(\"tools\" in response)) {\n throw new Error(\n `Expected object response with tools array, got ${typeof response}`\n );\n }\n\n return handler(\n processSelectionResponse(\n response as { tools: string[] },\n selectionRequest.availableTools,\n selectionRequest.validToolNames,\n request,\n options\n )\n );\n },\n });\n}\n\n/**\n * Prepare inputs for tool selection.\n *\n * @param request - The model request to process.\n * @param options - Configuration options.\n * @param runtime - Runtime context.\n * @returns SelectionRequest with prepared inputs, or null if no selection is needed.\n */\nasync function prepareSelectionRequest<\n TState extends Record<string, unknown> = Record<string, unknown>,\n TContext = unknown\n>(\n request: ModelRequest<TState, TContext>,\n options: LLMToolSelectorConfig,\n runtime: Runtime<LLMToolSelectorConfig>\n): Promise<SelectionRequest | undefined> {\n const model = runtime.context.model ?? options.model;\n const maxTools = runtime.context.maxTools ?? options.maxTools;\n const alwaysInclude =\n runtime.context.alwaysInclude ?? options.alwaysInclude ?? [];\n const systemPrompt =\n runtime.context.systemPrompt ??\n options.systemPrompt ??\n DEFAULT_SYSTEM_PROMPT;\n\n /**\n * If no tools available, return null\n */\n if (!request.tools || request.tools.length === 0) {\n return undefined;\n }\n\n /**\n * Filter to only StructuredToolInterface instances (exclude provider-specific tool dicts)\n */\n const baseTools = request.tools.filter(\n (tool): tool is StructuredToolInterface =>\n typeof tool === \"object\" &&\n \"name\" in tool &&\n \"description\" in tool &&\n typeof tool.name === \"string\"\n );\n\n /**\n * Validate that alwaysInclude tools exist\n */\n if (alwaysInclude.length > 0) {\n const availableToolNames = new Set(baseTools.map((tool) => tool.name));\n const missingTools = alwaysInclude.filter(\n (name) => !availableToolNames.has(name)\n );\n if (missingTools.length > 0) {\n throw new Error(\n `Tools in alwaysInclude not found in request: ${missingTools.join(\n \", \"\n )}. ` +\n `Available tools: ${Array.from(availableToolNames).sort().join(\", \")}`\n );\n }\n }\n\n /**\n * Separate tools that are always included from those available for selection\n */\n const availableTools = baseTools.filter(\n (tool) => !alwaysInclude.includes(tool.name)\n );\n\n /**\n * If no tools available for selection, return null\n */\n if (availableTools.length === 0) {\n return undefined;\n }\n\n let systemMessage = systemPrompt;\n /**\n * If there's a maxTools limit, append instructions to the system prompt\n */\n if (maxTools !== undefined) {\n systemMessage +=\n `\\nIMPORTANT: List the tool names in order of relevance, ` +\n `with the most relevant first. ` +\n `If you exceed the maximum number of tools, ` +\n `only the first ${maxTools} will be used.`;\n }\n\n /**\n * Get the last user message from the conversation history\n */\n let lastUserMessage: HumanMessage | undefined;\n for (const message of request.messages) {\n if (HumanMessage.isInstance(message)) {\n lastUserMessage = message;\n }\n }\n\n if (!lastUserMessage) {\n throw new Error(\"No user message found in request messages\");\n }\n\n const modelInstance = !model\n ? (request.model as BaseLanguageModel)\n : typeof model === \"string\"\n ? await initChatModel(model)\n : model;\n\n const validToolNames = availableTools.map((tool) => tool.name);\n\n return {\n availableTools,\n systemMessage,\n lastUserMessage,\n model: modelInstance,\n validToolNames,\n };\n}\n\n/**\n * Process the selection response and return filtered ModelRequest.\n *\n * @param response - The structured output response from the model.\n * @param availableTools - Tools available for selection.\n * @param validToolNames - Valid tool names that can be selected.\n * @param request - Original model request.\n * @param options - Configuration options.\n * @returns Modified ModelRequest with filtered tools.\n */\nfunction processSelectionResponse<\n TState extends Record<string, unknown> = Record<string, unknown>,\n TContext = unknown\n>(\n response: { tools: string[] },\n availableTools: StructuredToolInterface[],\n validToolNames: string[],\n request: ModelRequest<TState, TContext>,\n options: LLMToolSelectorConfig\n): ModelRequest<TState, TContext> {\n const maxTools = options.maxTools;\n const alwaysInclude = options.alwaysInclude ?? [];\n\n const selectedToolNames: string[] = [];\n const invalidToolSelections: string[] = [];\n\n for (const toolName of response.tools) {\n if (!validToolNames.includes(toolName)) {\n invalidToolSelections.push(toolName);\n continue;\n }\n\n /**\n * Only add if not already selected and within maxTools limit\n */\n if (\n !selectedToolNames.includes(toolName) &&\n (maxTools === undefined || selectedToolNames.length < maxTools)\n ) {\n selectedToolNames.push(toolName);\n }\n }\n\n if (invalidToolSelections.length > 0) {\n throw new Error(\n `Model selected invalid tools: ${invalidToolSelections.join(\", \")}`\n );\n }\n\n /**\n * Filter tools based on selection\n */\n const selectedTools = availableTools.filter((tool) =>\n selectedToolNames.includes(tool.name)\n );\n\n /**\n * Append always-included tools\n */\n const alwaysIncludedTools = (request.tools ?? []).filter(\n (tool): tool is StructuredToolInterface =>\n typeof tool === \"object\" &&\n \"name\" in tool &&\n typeof tool.name === \"string\" &&\n alwaysInclude.includes(tool.name)\n );\n selectedTools.push(...alwaysIncludedTools);\n\n /**\n * Also preserve any provider-specific tool dicts from the original request\n */\n const providerTools = (request.tools ?? []).filter(\n (tool) =>\n !(\n typeof tool === \"object\" &&\n \"name\" in tool &&\n \"description\" in tool &&\n typeof tool.name === \"string\"\n )\n );\n\n return {\n ...request,\n tools: [...selectedTools, ...providerTools],\n };\n}\n"],"mappings":"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"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
const require_chat_models_universal = require('
|
|
1
|
+
const require_chat_models_universal = require('../../chat_models/universal.cjs');
|
|
2
2
|
const require_middleware = require('../middleware.cjs');
|
|
3
3
|
|
|
4
|
-
//#region src/agents/
|
|
4
|
+
//#region src/agents/middleware/modelFallback.ts
|
|
5
5
|
/**
|
|
6
6
|
* Middleware that provides automatic model fallback on errors.
|
|
7
7
|
*
|
|
@@ -16,7 +16,7 @@ const require_middleware = require('../middleware.cjs');
|
|
|
16
16
|
* // Create middleware with fallback models (not including primary)
|
|
17
17
|
* const fallback = modelFallbackMiddleware({
|
|
18
18
|
* "openai:gpt-4o-mini", // First fallback
|
|
19
|
-
* "anthropic:claude-
|
|
19
|
+
* "anthropic:claude-sonnet-4-5-20250929", // Second fallback
|
|
20
20
|
* });
|
|
21
21
|
*
|
|
22
22
|
* const agent = createAgent({
|
|
@@ -37,27 +37,34 @@ const require_middleware = require('../middleware.cjs');
|
|
|
37
37
|
function modelFallbackMiddleware(...fallbackModels) {
|
|
38
38
|
return require_middleware.createMiddleware({
|
|
39
39
|
name: "modelFallbackMiddleware",
|
|
40
|
-
|
|
40
|
+
wrapModelCall: async (request, handler) => {
|
|
41
41
|
/**
|
|
42
|
-
*
|
|
42
|
+
* Try the primary model first
|
|
43
43
|
*/
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
44
|
+
try {
|
|
45
|
+
return await handler(request);
|
|
46
|
+
} catch (error) {
|
|
47
|
+
/**
|
|
48
|
+
* If primary model fails, try fallback models in sequence
|
|
49
|
+
*/
|
|
50
|
+
for (let i = 0; i < fallbackModels.length; i++) try {
|
|
51
|
+
const fallbackModel = fallbackModels[i];
|
|
52
|
+
const model = typeof fallbackModel === "string" ? await require_chat_models_universal.initChatModel(fallbackModel) : fallbackModel;
|
|
53
|
+
return await handler({
|
|
54
|
+
...request,
|
|
55
|
+
model
|
|
56
|
+
});
|
|
57
|
+
} catch (fallbackError) {
|
|
58
|
+
/**
|
|
59
|
+
* If this is the last fallback, throw the error
|
|
60
|
+
*/
|
|
61
|
+
if (i === fallbackModels.length - 1) throw fallbackError;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* If no fallbacks were provided, re-throw the original error
|
|
65
|
+
*/
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
61
68
|
}
|
|
62
69
|
});
|
|
63
70
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"modelFallback.cjs","names":["createMiddleware","initChatModel"],"sources":["../../../src/agents/middleware/modelFallback.ts"],"sourcesContent":["import type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport type { AgentMiddleware } from \"./types.js\";\nimport { createMiddleware } from \"../middleware.js\";\n\n/**\n * Middleware that provides automatic model fallback on errors.\n *\n * This middleware attempts to retry failed model calls with alternative models\n * in sequence. When a model call fails, it tries the next model in the fallback\n * list until either a call succeeds or all models have been exhausted.\n *\n * @example\n * ```ts\n * import { createAgent, modelFallbackMiddleware } from \"langchain\";\n *\n * // Create middleware with fallback models (not including primary)\n * const fallback = modelFallbackMiddleware({\n * \"openai:gpt-4o-mini\", // First fallback\n * \"anthropic:claude-sonnet-4-5-20250929\", // Second fallback\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\", // Primary model\n * middleware: [fallback],\n * tools: [],\n * });\n *\n * // If gpt-4o fails, automatically tries gpt-4o-mini, then claude\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Hello\" }]\n * });\n * ```\n *\n * @param fallbackModels - The fallback models to try, in order.\n * @returns A middleware instance that handles model failures with fallbacks\n */\nexport function modelFallbackMiddleware(\n /**\n * The fallback models to try, in order.\n */\n ...fallbackModels: (string | LanguageModelLike)[]\n): AgentMiddleware {\n return createMiddleware({\n name: \"modelFallbackMiddleware\",\n wrapModelCall: async (request, handler) => {\n /**\n * Try the primary model first\n */\n try {\n return await handler(request);\n } catch (error) {\n /**\n * If primary model fails, try fallback models in sequence\n */\n for (let i = 0; i < fallbackModels.length; i++) {\n try {\n const fallbackModel = fallbackModels[i];\n const model =\n typeof fallbackModel === \"string\"\n ? await initChatModel(fallbackModel)\n : fallbackModel;\n\n return await handler({\n ...request,\n model,\n });\n } catch (fallbackError) {\n /**\n * If this is the last fallback, throw the error\n */\n if (i === fallbackModels.length - 1) {\n throw fallbackError;\n }\n // Otherwise, continue to next fallback\n }\n }\n /**\n * If no fallbacks were provided, re-throw the original error\n */\n throw error;\n }\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,wBAId,GAAG,gBACc;AACjB,QAAOA,oCAAiB;EACtB,MAAM;EACN,eAAe,OAAO,SAAS,YAAY;;;;AAIzC,OAAI;AACF,WAAO,MAAM,QAAQ,QAAQ;GAC9B,SAAQ,OAAO;;;;AAId,SAAK,IAAI,IAAI,GAAG,IAAI,eAAe,QAAQ,IACzC,KAAI;KACF,MAAM,gBAAgB,eAAe;KACrC,MAAM,QACJ,OAAO,kBAAkB,WACrB,MAAMC,4CAAc,cAAc,GAClC;AAEN,YAAO,MAAM,QAAQ;MACnB,GAAG;MACH;KACD,EAAC;IACH,SAAQ,eAAe;;;;AAItB,SAAI,MAAM,eAAe,SAAS,EAChC,OAAM;IAGT;;;;AAKH,UAAM;GACP;EACF;CACF,EAAC;AACH"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { AgentMiddleware } from "
|
|
1
|
+
import { AgentMiddleware } from "./types.cjs";
|
|
2
2
|
import { LanguageModelLike } from "@langchain/core/language_models/base";
|
|
3
3
|
|
|
4
|
-
//#region src/agents/
|
|
4
|
+
//#region src/agents/middleware/modelFallback.d.ts
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Middleware that provides automatic model fallback on errors.
|
|
@@ -17,7 +17,7 @@ import { LanguageModelLike } from "@langchain/core/language_models/base";
|
|
|
17
17
|
* // Create middleware with fallback models (not including primary)
|
|
18
18
|
* const fallback = modelFallbackMiddleware({
|
|
19
19
|
* "openai:gpt-4o-mini", // First fallback
|
|
20
|
-
* "anthropic:claude-
|
|
20
|
+
* "anthropic:claude-sonnet-4-5-20250929", // Second fallback
|
|
21
21
|
* });
|
|
22
22
|
*
|
|
23
23
|
* const agent = createAgent({
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"modelFallback.d.cts","names":["LanguageModelLike","AgentMiddleware","modelFallbackMiddleware"],"sources":["../../../src/agents/middleware/modelFallback.d.ts"],"sourcesContent":["import type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { AgentMiddleware } from \"./types.js\";\n/**\n * Middleware that provides automatic model fallback on errors.\n *\n * This middleware attempts to retry failed model calls with alternative models\n * in sequence. When a model call fails, it tries the next model in the fallback\n * list until either a call succeeds or all models have been exhausted.\n *\n * @example\n * ```ts\n * import { createAgent, modelFallbackMiddleware } from \"langchain\";\n *\n * // Create middleware with fallback models (not including primary)\n * const fallback = modelFallbackMiddleware({\n * \"openai:gpt-4o-mini\", // First fallback\n * \"anthropic:claude-sonnet-4-5-20250929\", // Second fallback\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\", // Primary model\n * middleware: [fallback],\n * tools: [],\n * });\n *\n * // If gpt-4o fails, automatically tries gpt-4o-mini, then claude\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Hello\" }]\n * });\n * ```\n *\n * @param fallbackModels - The fallback models to try, in order.\n * @returns A middleware instance that handles model failures with fallbacks\n */\nexport declare function modelFallbackMiddleware(\n/**\n * The fallback models to try, in order.\n */\n...fallbackModels: (string | LanguageModelLike)[]): AgentMiddleware;\n"],"mappings":";;;;;;;AAkCA;;;;AAImE;;;;;;;;;;;;;;;;;;;;;;;;;;iBAJ3CE,uBAAAA;;;;6BAIKF,uBAAuBC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { AgentMiddleware } from "
|
|
1
|
+
import { AgentMiddleware } from "./types.js";
|
|
2
2
|
import { LanguageModelLike } from "@langchain/core/language_models/base";
|
|
3
3
|
|
|
4
|
-
//#region src/agents/
|
|
4
|
+
//#region src/agents/middleware/modelFallback.d.ts
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Middleware that provides automatic model fallback on errors.
|
|
@@ -17,7 +17,7 @@ import { LanguageModelLike } from "@langchain/core/language_models/base";
|
|
|
17
17
|
* // Create middleware with fallback models (not including primary)
|
|
18
18
|
* const fallback = modelFallbackMiddleware({
|
|
19
19
|
* "openai:gpt-4o-mini", // First fallback
|
|
20
|
-
* "anthropic:claude-
|
|
20
|
+
* "anthropic:claude-sonnet-4-5-20250929", // Second fallback
|
|
21
21
|
* });
|
|
22
22
|
*
|
|
23
23
|
* const agent = createAgent({
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"modelFallback.d.ts","names":["LanguageModelLike","AgentMiddleware","modelFallbackMiddleware"],"sources":["../../../src/agents/middleware/modelFallback.d.ts"],"sourcesContent":["import type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { AgentMiddleware } from \"./types.js\";\n/**\n * Middleware that provides automatic model fallback on errors.\n *\n * This middleware attempts to retry failed model calls with alternative models\n * in sequence. When a model call fails, it tries the next model in the fallback\n * list until either a call succeeds or all models have been exhausted.\n *\n * @example\n * ```ts\n * import { createAgent, modelFallbackMiddleware } from \"langchain\";\n *\n * // Create middleware with fallback models (not including primary)\n * const fallback = modelFallbackMiddleware({\n * \"openai:gpt-4o-mini\", // First fallback\n * \"anthropic:claude-sonnet-4-5-20250929\", // Second fallback\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\", // Primary model\n * middleware: [fallback],\n * tools: [],\n * });\n *\n * // If gpt-4o fails, automatically tries gpt-4o-mini, then claude\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Hello\" }]\n * });\n * ```\n *\n * @param fallbackModels - The fallback models to try, in order.\n * @returns A middleware instance that handles model failures with fallbacks\n */\nexport declare function modelFallbackMiddleware(\n/**\n * The fallback models to try, in order.\n */\n...fallbackModels: (string | LanguageModelLike)[]): AgentMiddleware;\n"],"mappings":";;;;;;;AAkCA;;;;AAImE;;;;;;;;;;;;;;;;;;;;;;;;;;iBAJ3CE,uBAAAA;;;;6BAIKF,uBAAuBC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { initChatModel } from "
|
|
1
|
+
import { initChatModel } from "../../chat_models/universal.js";
|
|
2
2
|
import { createMiddleware } from "../middleware.js";
|
|
3
3
|
|
|
4
|
-
//#region src/agents/
|
|
4
|
+
//#region src/agents/middleware/modelFallback.ts
|
|
5
5
|
/**
|
|
6
6
|
* Middleware that provides automatic model fallback on errors.
|
|
7
7
|
*
|
|
@@ -16,7 +16,7 @@ import { createMiddleware } from "../middleware.js";
|
|
|
16
16
|
* // Create middleware with fallback models (not including primary)
|
|
17
17
|
* const fallback = modelFallbackMiddleware({
|
|
18
18
|
* "openai:gpt-4o-mini", // First fallback
|
|
19
|
-
* "anthropic:claude-
|
|
19
|
+
* "anthropic:claude-sonnet-4-5-20250929", // Second fallback
|
|
20
20
|
* });
|
|
21
21
|
*
|
|
22
22
|
* const agent = createAgent({
|
|
@@ -37,27 +37,34 @@ import { createMiddleware } from "../middleware.js";
|
|
|
37
37
|
function modelFallbackMiddleware(...fallbackModels) {
|
|
38
38
|
return createMiddleware({
|
|
39
39
|
name: "modelFallbackMiddleware",
|
|
40
|
-
|
|
40
|
+
wrapModelCall: async (request, handler) => {
|
|
41
41
|
/**
|
|
42
|
-
*
|
|
42
|
+
* Try the primary model first
|
|
43
43
|
*/
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
44
|
+
try {
|
|
45
|
+
return await handler(request);
|
|
46
|
+
} catch (error) {
|
|
47
|
+
/**
|
|
48
|
+
* If primary model fails, try fallback models in sequence
|
|
49
|
+
*/
|
|
50
|
+
for (let i = 0; i < fallbackModels.length; i++) try {
|
|
51
|
+
const fallbackModel = fallbackModels[i];
|
|
52
|
+
const model = typeof fallbackModel === "string" ? await initChatModel(fallbackModel) : fallbackModel;
|
|
53
|
+
return await handler({
|
|
54
|
+
...request,
|
|
55
|
+
model
|
|
56
|
+
});
|
|
57
|
+
} catch (fallbackError) {
|
|
58
|
+
/**
|
|
59
|
+
* If this is the last fallback, throw the error
|
|
60
|
+
*/
|
|
61
|
+
if (i === fallbackModels.length - 1) throw fallbackError;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* If no fallbacks were provided, re-throw the original error
|
|
65
|
+
*/
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
61
68
|
}
|
|
62
69
|
});
|
|
63
70
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"modelFallback.js","names":[],"sources":["../../../src/agents/middleware/modelFallback.ts"],"sourcesContent":["import type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport type { AgentMiddleware } from \"./types.js\";\nimport { createMiddleware } from \"../middleware.js\";\n\n/**\n * Middleware that provides automatic model fallback on errors.\n *\n * This middleware attempts to retry failed model calls with alternative models\n * in sequence. When a model call fails, it tries the next model in the fallback\n * list until either a call succeeds or all models have been exhausted.\n *\n * @example\n * ```ts\n * import { createAgent, modelFallbackMiddleware } from \"langchain\";\n *\n * // Create middleware with fallback models (not including primary)\n * const fallback = modelFallbackMiddleware({\n * \"openai:gpt-4o-mini\", // First fallback\n * \"anthropic:claude-sonnet-4-5-20250929\", // Second fallback\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\", // Primary model\n * middleware: [fallback],\n * tools: [],\n * });\n *\n * // If gpt-4o fails, automatically tries gpt-4o-mini, then claude\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Hello\" }]\n * });\n * ```\n *\n * @param fallbackModels - The fallback models to try, in order.\n * @returns A middleware instance that handles model failures with fallbacks\n */\nexport function modelFallbackMiddleware(\n /**\n * The fallback models to try, in order.\n */\n ...fallbackModels: (string | LanguageModelLike)[]\n): AgentMiddleware {\n return createMiddleware({\n name: \"modelFallbackMiddleware\",\n wrapModelCall: async (request, handler) => {\n /**\n * Try the primary model first\n */\n try {\n return await handler(request);\n } catch (error) {\n /**\n * If primary model fails, try fallback models in sequence\n */\n for (let i = 0; i < fallbackModels.length; i++) {\n try {\n const fallbackModel = fallbackModels[i];\n const model =\n typeof fallbackModel === \"string\"\n ? await initChatModel(fallbackModel)\n : fallbackModel;\n\n return await handler({\n ...request,\n model,\n });\n } catch (fallbackError) {\n /**\n * If this is the last fallback, throw the error\n */\n if (i === fallbackModels.length - 1) {\n throw fallbackError;\n }\n // Otherwise, continue to next fallback\n }\n }\n /**\n * If no fallbacks were provided, re-throw the original error\n */\n throw error;\n }\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,wBAId,GAAG,gBACc;AACjB,QAAO,iBAAiB;EACtB,MAAM;EACN,eAAe,OAAO,SAAS,YAAY;;;;AAIzC,OAAI;AACF,WAAO,MAAM,QAAQ,QAAQ;GAC9B,SAAQ,OAAO;;;;AAId,SAAK,IAAI,IAAI,GAAG,IAAI,eAAe,QAAQ,IACzC,KAAI;KACF,MAAM,gBAAgB,eAAe;KACrC,MAAM,QACJ,OAAO,kBAAkB,WACrB,MAAM,cAAc,cAAc,GAClC;AAEN,YAAO,MAAM,QAAQ;MACnB,GAAG;MACH;KACD,EAAC;IACH,SAAQ,eAAe;;;;AAItB,SAAI,MAAM,eAAe,SAAS,EAChC,OAAM;IAGT;;;;AAKH,UAAM;GACP;EACF;CACF,EAAC;AACH"}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
const require_rolldown_runtime = require('
|
|
1
|
+
const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
|
|
2
2
|
const require_middleware = require('../middleware.cjs');
|
|
3
3
|
const __langchain_core_messages = require_rolldown_runtime.__toESM(require("@langchain/core/messages"));
|
|
4
|
-
const
|
|
4
|
+
const zod_v3 = require_rolldown_runtime.__toESM(require("zod/v3"));
|
|
5
5
|
|
|
6
|
-
//#region src/agents/
|
|
6
|
+
//#region src/agents/middleware/piiRedaction.ts
|
|
7
7
|
/**
|
|
8
8
|
* Configuration schema for the Input Guardrails middleware
|
|
9
9
|
*/
|
|
10
|
-
const contextSchema =
|
|
10
|
+
const contextSchema = zod_v3.z.object({ rules: zod_v3.z.record(zod_v3.z.string(), zod_v3.z.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional() });
|
|
11
11
|
/**
|
|
12
12
|
* Generate a unique ID for a redaction
|
|
13
13
|
*/
|
|
@@ -135,7 +135,7 @@ function restoreMessage(message, redactionMap) {
|
|
|
135
135
|
*
|
|
136
136
|
* The middleware intercepts agent execution at two points:
|
|
137
137
|
*
|
|
138
|
-
* ### Request Phase (`
|
|
138
|
+
* ### Request Phase (`wrapModelCall`)
|
|
139
139
|
* - Applies regex-based pattern matching to all message content (HumanMessage, ToolMessage, SystemMessage, AIMessage)
|
|
140
140
|
* - Processes both message text and AIMessage tool call arguments
|
|
141
141
|
* - Each matched pattern generates:
|
|
@@ -187,7 +187,7 @@ function restoreMessage(message, redactionMap) {
|
|
|
187
187
|
* import { piiRedactionMiddleware } from "langchain";
|
|
188
188
|
* import { createAgent } from "langchain";
|
|
189
189
|
* import { tool } from "@langchain/core/tools";
|
|
190
|
-
* import { z } from "zod";
|
|
190
|
+
* import { z } from "zod/v3";
|
|
191
191
|
*
|
|
192
192
|
* const PII_RULES = {
|
|
193
193
|
* ssn: /\b\d{3}-?\d{2}-?\d{4}\b/g,
|
|
@@ -261,23 +261,23 @@ function piiRedactionMiddleware(options = {}) {
|
|
|
261
261
|
return require_middleware.createMiddleware({
|
|
262
262
|
name: "PIIRedactionMiddleware",
|
|
263
263
|
contextSchema,
|
|
264
|
-
|
|
264
|
+
wrapModelCall: async (request, handler) => {
|
|
265
265
|
/**
|
|
266
266
|
* Merge options with context, following bigTool.ts pattern
|
|
267
267
|
*/
|
|
268
|
-
const rules = runtime.context.rules ?? options.rules ?? {};
|
|
268
|
+
const rules = request.runtime.context.rules ?? options.rules ?? {};
|
|
269
269
|
/**
|
|
270
270
|
* If no rules are provided, skip processing
|
|
271
271
|
*/
|
|
272
|
-
if (Object.keys(rules).length === 0) return;
|
|
273
|
-
const processedMessages = await Promise.all(state.messages.map((message) => processMessage(message, {
|
|
272
|
+
if (Object.keys(rules).length === 0) return handler(request);
|
|
273
|
+
const processedMessages = await Promise.all(request.state.messages.map((message) => processMessage(message, {
|
|
274
274
|
rules,
|
|
275
275
|
redactionMap
|
|
276
276
|
})));
|
|
277
|
-
return {
|
|
277
|
+
return handler({
|
|
278
278
|
...request,
|
|
279
279
|
messages: processedMessages
|
|
280
|
-
};
|
|
280
|
+
});
|
|
281
281
|
},
|
|
282
282
|
afterModel: async (state) => {
|
|
283
283
|
/**
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"piiRedaction.cjs","names":["z","text: string","rules: Record<string, RegExp>","redactionMap: RedactionMap","message: BaseMessage","config: ProcessHumanMessageConfig","HumanMessage","ToolMessage","SystemMessage","AIMessage","options: PIIRedactionMiddlewareConfig","createMiddleware","structuredResponse: Record<string, unknown> | undefined","structuredResponse","RemoveMessage"],"sources":["../../../src/agents/middleware/piiRedaction.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport {\n BaseMessage,\n AIMessage,\n HumanMessage,\n ToolMessage,\n RemoveMessage,\n SystemMessage,\n} from \"@langchain/core/messages\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\n\nimport { createMiddleware } from \"../middleware.js\";\n\n/**\n * Type for the redaction map that stores original values by ID\n */\ntype RedactionMap = Record<string, string>;\n\n/**\n * Configuration schema for the Input Guardrails middleware\n */\nconst contextSchema = z.object({\n /**\n * A record of PII detection rules to apply\n * @default DEFAULT_PII_RULES (with enabled rules only)\n */\n rules: z\n .record(\n z.string(),\n z.instanceof(RegExp).describe(\"Regular expression pattern to match PII\")\n )\n .optional(),\n});\n\nexport type PIIRedactionMiddlewareConfig = InferInteropZodInput<\n typeof contextSchema\n>;\n\n/**\n * Generate a unique ID for a redaction\n */\nfunction generateRedactionId(): string {\n return Math.random().toString(36).substring(2, 11);\n}\n\n/**\n * Apply PII detection rules to text with ID tracking\n */\nfunction applyPIIRules(\n text: string,\n rules: Record<string, RegExp>,\n redactionMap: RedactionMap\n): string {\n let processedText = text;\n\n for (const [name, pattern] of Object.entries(rules)) {\n const replacement = name.toUpperCase().replace(/[^a-zA-Z0-9_-]/g, \"\");\n processedText = processedText.replace(pattern, (match) => {\n const id = generateRedactionId();\n redactionMap[id] = match;\n // Create a trackable replacement like [REDACTED_SSN_abc123]\n return `[REDACTED_${replacement}_${id}]`;\n });\n }\n\n return processedText;\n}\n\ninterface ProcessHumanMessageConfig {\n rules: Record<string, RegExp>;\n redactionMap: RedactionMap;\n}\n\n/**\n * Process a single human message for PII detection and redaction\n */\nasync function processMessage(\n message: BaseMessage,\n config: ProcessHumanMessageConfig\n): Promise<BaseMessage> {\n /**\n * handle basic message types\n */\n if (\n HumanMessage.isInstance(message) ||\n ToolMessage.isInstance(message) ||\n SystemMessage.isInstance(message)\n ) {\n const content = message.content as string;\n const processedContent = await applyPIIRules(\n content,\n config.rules,\n config.redactionMap\n );\n\n if (processedContent !== content) {\n const MessageConstructor = Object.getPrototypeOf(message).constructor;\n return new MessageConstructor({\n ...message,\n content: processedContent,\n });\n }\n\n return message;\n }\n\n /**\n * Handle AI messages\n */\n if (AIMessage.isInstance(message)) {\n const content =\n typeof message.content === \"string\"\n ? message.content\n : JSON.stringify(message.content);\n const toolCalls = JSON.stringify(message.tool_calls);\n const processedContent = await applyPIIRules(\n content,\n config.rules,\n config.redactionMap\n );\n const processedToolCalls = await applyPIIRules(\n toolCalls,\n config.rules,\n config.redactionMap\n );\n\n if (processedContent !== content || processedToolCalls !== toolCalls) {\n return new AIMessage({\n ...message,\n content:\n typeof message.content === \"string\"\n ? processedContent\n : JSON.parse(processedContent),\n tool_calls: JSON.parse(processedToolCalls),\n });\n }\n\n return message;\n }\n\n throw new Error(`Unsupported message type: ${message.type}`);\n}\n\n/**\n * Restore original values from redacted text using the redaction map\n */\nfunction restoreRedactedValues(\n text: string,\n redactionMap: RedactionMap\n): string {\n let restoredText = text;\n\n // Pattern to match redacted values like [REDACTED_SSN_abc123]\n const redactionPattern = /\\[REDACTED_[A-Z_]+_(\\w+)\\]/g;\n\n restoredText = restoredText.replace(redactionPattern, (match, id) => {\n if (redactionMap[id]) {\n return redactionMap[id];\n }\n return match; // Keep original if no mapping found\n });\n\n return restoredText;\n}\n\n/**\n * Restore redacted values in a message (creates a new message object)\n */\nfunction restoreMessage(\n message: BaseMessage,\n redactionMap: RedactionMap\n): { message: BaseMessage; changed: boolean } {\n /**\n * handle basic message types\n */\n if (\n HumanMessage.isInstance(message) ||\n ToolMessage.isInstance(message) ||\n SystemMessage.isInstance(message)\n ) {\n const content = message.content as string;\n const restoredContent = restoreRedactedValues(content, redactionMap);\n if (restoredContent !== content) {\n const MessageConstructor = Object.getPrototypeOf(message).constructor;\n const newMessage = new MessageConstructor({\n ...message,\n content: restoredContent,\n });\n return { message: newMessage, changed: true };\n }\n return { message, changed: false };\n }\n\n /**\n * handle AI messages\n */\n if (AIMessage.isInstance(message)) {\n const content =\n typeof message.content === \"string\"\n ? message.content\n : JSON.stringify(message.content);\n const toolCalls = JSON.stringify(message.tool_calls);\n const processedContent = restoreRedactedValues(content, redactionMap);\n const processedToolCalls = restoreRedactedValues(toolCalls, redactionMap);\n if (processedContent !== content || processedToolCalls !== toolCalls) {\n return {\n message: new AIMessage({\n ...message,\n content:\n typeof message.content === \"string\"\n ? processedContent\n : JSON.parse(processedContent),\n tool_calls: JSON.parse(processedToolCalls),\n }),\n changed: true,\n };\n }\n\n return { message, changed: false };\n }\n\n throw new Error(`Unsupported message type: ${message.type}`);\n}\n\n/**\n * Creates a middleware that detects and redacts personally identifiable information (PII)\n * from messages before they are sent to model providers, and restores original values\n * in model responses for tool execution.\n *\n * ## Mechanism\n *\n * The middleware intercepts agent execution at two points:\n *\n * ### Request Phase (`wrapModelCall`)\n * - Applies regex-based pattern matching to all message content (HumanMessage, ToolMessage, SystemMessage, AIMessage)\n * - Processes both message text and AIMessage tool call arguments\n * - Each matched pattern generates:\n * - Unique identifier: `generateRedactionId()` → `\"abc123\"`\n * - Redaction marker: `[REDACTED_{RULE_NAME}_{ID}]` → `\"[REDACTED_SSN_abc123]\"`\n * - Redaction map entry: `{ \"abc123\": \"123-45-6789\" }`\n * - Returns modified request with redacted message content\n *\n * ### Response Phase (`afterModel`)\n * - Scans AIMessage responses for redaction markers matching pattern: `/\\[REDACTED_[A-Z_]+_(\\w+)\\]/g`\n * - Replaces markers with original values from redaction map\n * - Handles both standard responses and structured output (via tool calls or JSON content)\n * - For structured output, restores values in both the tool call arguments and the `structuredResponse` state field\n * - Returns new message instances via RemoveMessage/AIMessage to update state\n *\n * ## Data Flow\n *\n * ```\n * User Input: \"My SSN is 123-45-6789\"\n * ↓ [beforeModel]\n * Model Request: \"My SSN is [REDACTED_SSN_abc123]\"\n * ↓ [model invocation]\n * Model Response: tool_call({ \"ssn\": \"[REDACTED_SSN_abc123]\" })\n * ↓ [afterModel]\n * Tool Execution: tool({ \"ssn\": \"123-45-6789\" })\n * ```\n *\n * ## Limitations\n *\n * This middleware provides model provider isolation only. PII may still be present in:\n * - LangGraph state checkpoints (memory, databases)\n * - Network traffic between client and application server\n * - Application logs and trace data\n * - Tool execution arguments and responses\n * - Final agent output\n *\n * For comprehensive PII protection, implement additional controls at the application,\n * network, and storage layers.\n *\n * @param options - Configuration options\n * @param options.rules - Record of detection rules mapping rule names to regex patterns.\n * Rule names are normalized to uppercase and used in redaction markers.\n * Patterns must use the global flag (`/pattern/g`) to match all occurrences.\n *\n * @returns Middleware instance for use with `createAgent`\n *\n * @example Basic usage with custom rules\n * ```typescript\n * import { piiRedactionMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n * import { tool } from \"@langchain/core/tools\";\n * import { z } from \"zod/v3\";\n *\n * const PII_RULES = {\n * ssn: /\\b\\d{3}-?\\d{2}-?\\d{4}\\b/g,\n * email: /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g,\n * phone: /\\b\\d{3}[-.]?\\d{3}[-.]?\\d{4}\\b/g,\n * };\n *\n * const lookupUser = tool(async ({ ssn }) => {\n * // Receives original value: \"123-45-6789\"\n * return { name: \"John Doe\", account: \"active\" };\n * }, {\n * name: \"lookup_user\",\n * description: \"Look up user by SSN\",\n * schema: z.object({ ssn: z.string() })\n * });\n *\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4\" }),\n * tools: [lookupUser],\n * middleware: [piiRedactionMiddleware({ rules: PII_RULES })]\n * });\n *\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Look up SSN 123-45-6789\")]\n * });\n * // Model request: \"Look up SSN [REDACTED_SSN_abc123]\"\n * // Model response: tool_call({ \"ssn\": \"[REDACTED_SSN_abc123]\" })\n * // Tool receives: { \"ssn\": \"123-45-6789\" }\n * ```\n *\n * @example Runtime rule configuration via context\n * ```typescript\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4\" }),\n * tools: [someTool],\n * middleware: [piiRedactionMiddleware()]\n * });\n *\n * // Configure rules at runtime via middleware context\n * const result = await agent.invoke(\n * { messages: [new HumanMessage(\"...\")] },\n * {\n * configurable: {\n * PIIRedactionMiddleware: {\n * rules: {\n * ssn: /\\b\\d{3}-?\\d{2}-?\\d{4}\\b/g,\n * email: /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g,\n * }\n * }\n * }\n * }\n * );\n * ```\n *\n * @example Custom rule patterns\n * ```typescript\n * const customRules = {\n * employee_id: /EMP-\\d{6}/g,\n * api_key: /sk-[a-zA-Z0-9]{32}/g,\n * credit_card: /\\b\\d{4}[- ]?\\d{4}[- ]?\\d{4}[- ]?\\d{4}\\b/g,\n * };\n *\n * const middleware = piiRedactionMiddleware({ rules: customRules });\n * // Generates markers like: [REDACTED_EMPLOYEE_ID_xyz789]\n * ```\n *\n * @public\n */\nexport function piiRedactionMiddleware(\n options: PIIRedactionMiddlewareConfig = {}\n): ReturnType<typeof createMiddleware> {\n const redactionMap: RedactionMap = {};\n\n return createMiddleware({\n name: \"PIIRedactionMiddleware\",\n contextSchema,\n wrapModelCall: async (request, handler) => {\n /**\n * Merge options with context, following bigTool.ts pattern\n */\n const rules = request.runtime.context.rules ?? options.rules ?? {};\n\n /**\n * If no rules are provided, skip processing\n */\n if (Object.keys(rules).length === 0) {\n return handler(request);\n }\n\n const processedMessages = await Promise.all(\n request.state.messages.map((message: BaseMessage) =>\n processMessage(message, {\n rules,\n redactionMap,\n })\n )\n );\n\n return handler({\n ...request,\n messages: processedMessages,\n });\n },\n afterModel: async (state) => {\n /**\n * If no redactions were made, skip processing\n */\n if (Object.keys(redactionMap).length === 0) {\n return;\n }\n\n const lastMessage = state.messages.at(-1);\n if (!AIMessage.isInstance(lastMessage)) {\n return;\n }\n\n /**\n * In cases where we do structured output via tool calls, we also have to look at the second last message\n * as we add a custom last message to the messages array.\n */\n const secondLastMessage = state.messages.at(-2);\n\n const { message: restoredLastMessage, changed } = restoreMessage(\n lastMessage,\n redactionMap\n );\n\n if (!changed) {\n return;\n }\n\n /**\n * Identify if the last message is a structured response and restore the values if so\n */\n let structuredResponse: Record<string, unknown> | undefined;\n if (\n AIMessage.isInstance(lastMessage) &&\n lastMessage?.tool_calls?.length === 0 &&\n typeof lastMessage.content === \"string\" &&\n lastMessage.content.startsWith(\"{\") &&\n lastMessage.content.endsWith(\"}\")\n ) {\n try {\n structuredResponse = JSON.parse(\n restoreRedactedValues(lastMessage.content, redactionMap)\n );\n } catch {\n // ignore\n }\n }\n\n /**\n * Check if the second last message is a structured response tool call\n */\n const isStructuredResponseToolCall =\n AIMessage.isInstance(secondLastMessage) &&\n secondLastMessage?.tool_calls?.length !== 0 &&\n secondLastMessage?.tool_calls?.some((call) =>\n call.name.startsWith(\"extract-\")\n );\n if (isStructuredResponseToolCall) {\n const {\n message: restoredSecondLastMessage,\n changed: changedSecondLastMessage,\n } = restoreMessage(secondLastMessage, redactionMap);\n const structuredResponseRedacted = secondLastMessage.tool_calls?.find(\n (call) => call.name.startsWith(\"extract-\")\n )?.args;\n const structuredResponse = structuredResponseRedacted\n ? JSON.parse(\n restoreRedactedValues(\n JSON.stringify(structuredResponseRedacted),\n redactionMap\n )\n )\n : undefined;\n if (changed || changedSecondLastMessage) {\n return {\n ...state,\n ...(structuredResponse ? { structuredResponse } : {}),\n messages: [\n new RemoveMessage({ id: secondLastMessage.id as string }),\n new RemoveMessage({ id: lastMessage.id as string }),\n restoredSecondLastMessage,\n restoredLastMessage,\n ],\n };\n }\n }\n\n return {\n ...state,\n ...(structuredResponse ? { structuredResponse } : {}),\n messages: [\n new RemoveMessage({ id: lastMessage.id as string }),\n restoredLastMessage,\n ],\n };\n },\n });\n}\n"],"mappings":"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"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { createMiddleware } from "../middleware.cjs";
|
|
2
2
|
import { InferInteropZodInput } from "@langchain/core/utils/types";
|
|
3
|
-
import { z } from "zod";
|
|
3
|
+
import { z } from "zod/v3";
|
|
4
4
|
|
|
5
|
-
//#region src/agents/
|
|
5
|
+
//#region src/agents/middleware/piiRedaction.d.ts
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* Configuration schema for the Input Guardrails middleware
|
|
@@ -28,7 +28,7 @@ type PIIRedactionMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;
|
|
|
28
28
|
*
|
|
29
29
|
* The middleware intercepts agent execution at two points:
|
|
30
30
|
*
|
|
31
|
-
* ### Request Phase (`
|
|
31
|
+
* ### Request Phase (`wrapModelCall`)
|
|
32
32
|
* - Applies regex-based pattern matching to all message content (HumanMessage, ToolMessage, SystemMessage, AIMessage)
|
|
33
33
|
* - Processes both message text and AIMessage tool call arguments
|
|
34
34
|
* - Each matched pattern generates:
|
|
@@ -80,7 +80,7 @@ type PIIRedactionMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;
|
|
|
80
80
|
* import { piiRedactionMiddleware } from "langchain";
|
|
81
81
|
* import { createAgent } from "langchain";
|
|
82
82
|
* import { tool } from "@langchain/core/tools";
|
|
83
|
-
* import { z } from "zod";
|
|
83
|
+
* import { z } from "zod/v3";
|
|
84
84
|
*
|
|
85
85
|
* const PII_RULES = {
|
|
86
86
|
* ssn: /\b\d{3}-?\d{2}-?\d{4}\b/g,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"piiRedaction.d.cts","names":["z","InferInteropZodInput","createMiddleware","contextSchema","ZodString","RegExp","ZodTypeDef","ZodType","ZodRecord","ZodOptional","ZodTypeAny","Record","ZodObject","PIIRedactionMiddlewareConfig","piiRedactionMiddleware","ReturnType"],"sources":["../../../src/agents/middleware/piiRedaction.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\nimport { createMiddleware } from \"../middleware.js\";\n/**\n * Configuration schema for the Input Guardrails middleware\n */\ndeclare const contextSchema: z.ZodObject<{\n /**\n * A record of PII detection rules to apply\n * @default DEFAULT_PII_RULES (with enabled rules only)\n */\n rules: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodType<RegExp, z.ZodTypeDef, RegExp>>>;\n}, \"strip\", z.ZodTypeAny, {\n rules?: Record<string, RegExp> | undefined;\n}, {\n rules?: Record<string, RegExp> | undefined;\n}>;\nexport type PIIRedactionMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;\n/**\n * Creates a middleware that detects and redacts personally identifiable information (PII)\n * from messages before they are sent to model providers, and restores original values\n * in model responses for tool execution.\n *\n * ## Mechanism\n *\n * The middleware intercepts agent execution at two points:\n *\n * ### Request Phase (`wrapModelCall`)\n * - Applies regex-based pattern matching to all message content (HumanMessage, ToolMessage, SystemMessage, AIMessage)\n * - Processes both message text and AIMessage tool call arguments\n * - Each matched pattern generates:\n * - Unique identifier: `generateRedactionId()` → `\"abc123\"`\n * - Redaction marker: `[REDACTED_{RULE_NAME}_{ID}]` → `\"[REDACTED_SSN_abc123]\"`\n * - Redaction map entry: `{ \"abc123\": \"123-45-6789\" }`\n * - Returns modified request with redacted message content\n *\n * ### Response Phase (`afterModel`)\n * - Scans AIMessage responses for redaction markers matching pattern: `/\\[REDACTED_[A-Z_]+_(\\w+)\\]/g`\n * - Replaces markers with original values from redaction map\n * - Handles both standard responses and structured output (via tool calls or JSON content)\n * - For structured output, restores values in both the tool call arguments and the `structuredResponse` state field\n * - Returns new message instances via RemoveMessage/AIMessage to update state\n *\n * ## Data Flow\n *\n * ```\n * User Input: \"My SSN is 123-45-6789\"\n * ↓ [beforeModel]\n * Model Request: \"My SSN is [REDACTED_SSN_abc123]\"\n * ↓ [model invocation]\n * Model Response: tool_call({ \"ssn\": \"[REDACTED_SSN_abc123]\" })\n * ↓ [afterModel]\n * Tool Execution: tool({ \"ssn\": \"123-45-6789\" })\n * ```\n *\n * ## Limitations\n *\n * This middleware provides model provider isolation only. PII may still be present in:\n * - LangGraph state checkpoints (memory, databases)\n * - Network traffic between client and application server\n * - Application logs and trace data\n * - Tool execution arguments and responses\n * - Final agent output\n *\n * For comprehensive PII protection, implement additional controls at the application,\n * network, and storage layers.\n *\n * @param options - Configuration options\n * @param options.rules - Record of detection rules mapping rule names to regex patterns.\n * Rule names are normalized to uppercase and used in redaction markers.\n * Patterns must use the global flag (`/pattern/g`) to match all occurrences.\n *\n * @returns Middleware instance for use with `createAgent`\n *\n * @example Basic usage with custom rules\n * ```typescript\n * import { piiRedactionMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n * import { tool } from \"@langchain/core/tools\";\n * import { z } from \"zod/v3\";\n *\n * const PII_RULES = {\n * ssn: /\\b\\d{3}-?\\d{2}-?\\d{4}\\b/g,\n * email: /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g,\n * phone: /\\b\\d{3}[-.]?\\d{3}[-.]?\\d{4}\\b/g,\n * };\n *\n * const lookupUser = tool(async ({ ssn }) => {\n * // Receives original value: \"123-45-6789\"\n * return { name: \"John Doe\", account: \"active\" };\n * }, {\n * name: \"lookup_user\",\n * description: \"Look up user by SSN\",\n * schema: z.object({ ssn: z.string() })\n * });\n *\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4\" }),\n * tools: [lookupUser],\n * middleware: [piiRedactionMiddleware({ rules: PII_RULES })]\n * });\n *\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Look up SSN 123-45-6789\")]\n * });\n * // Model request: \"Look up SSN [REDACTED_SSN_abc123]\"\n * // Model response: tool_call({ \"ssn\": \"[REDACTED_SSN_abc123]\" })\n * // Tool receives: { \"ssn\": \"123-45-6789\" }\n * ```\n *\n * @example Runtime rule configuration via context\n * ```typescript\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4\" }),\n * tools: [someTool],\n * middleware: [piiRedactionMiddleware()]\n * });\n *\n * // Configure rules at runtime via middleware context\n * const result = await agent.invoke(\n * { messages: [new HumanMessage(\"...\")] },\n * {\n * configurable: {\n * PIIRedactionMiddleware: {\n * rules: {\n * ssn: /\\b\\d{3}-?\\d{2}-?\\d{4}\\b/g,\n * email: /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g,\n * }\n * }\n * }\n * }\n * );\n * ```\n *\n * @example Custom rule patterns\n * ```typescript\n * const customRules = {\n * employee_id: /EMP-\\d{6}/g,\n * api_key: /sk-[a-zA-Z0-9]{32}/g,\n * credit_card: /\\b\\d{4}[- ]?\\d{4}[- ]?\\d{4}[- ]?\\d{4}\\b/g,\n * };\n *\n * const middleware = piiRedactionMiddleware({ rules: customRules });\n * // Generates markers like: [REDACTED_EMPLOYEE_ID_xyz789]\n * ```\n *\n * @public\n */\nexport declare function piiRedactionMiddleware(options?: PIIRedactionMiddlewareConfig): ReturnType<typeof createMiddleware>;\nexport {};\n"],"mappings":";;;;;;;;AAEoD;cAItCG,aAUZ,EAV2BH,CAAAA,CAAEY,SAU7B,CAAA;EAAA;;;;EALsF,KAApCL,EAAzCP,CAAAA,CAAES,WAAuCF,CAA3BP,CAAAA,CAAEQ,SAAyBD,CAAfP,CAAAA,CAAEI,SAAaG,EAAFP,CAAAA,CAAEO,OAAAA,CAAQF,MAARE,EAAgBP,CAAAA,CAAEM,UAAlBC,EAA8BF,MAA9BE,CAAAA,CAAAA,CAAAA;CAAO,EAAA,OAAhCC,EACfR,CAAAA,CAAEU,UADaF,EAAAA;EAAS,KAAvBC,CAAAA,EAEDE,MAFCF,CAAAA,MAAAA,EAEcJ,MAFdI,CAAAA,GAAAA,SAAAA;CAAW,EAAA;EACA,KACGJ,CAAAA,EAEfM,MAFeN,CAAAA,MAAAA,EAEAA,MAFAA,CAAAA,GAAAA,SAAAA;CAAM,CAAA;AAENA,KAEfQ,4BAAAA,GAA+BZ,oBAFhBI,CAAAA,OAE4CF,aAF5CE,CAAAA;;;AATa;AAWxC;;;;AAA+D;AAmI/D;;;;;AAAkG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAA1ES,sBAAAA,WAAiCD,+BAA+BE,kBAAkBb"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { createMiddleware } from "../middleware.js";
|
|
2
|
+
import { z } from "zod/v3";
|
|
2
3
|
import { InferInteropZodInput } from "@langchain/core/utils/types";
|
|
3
|
-
import { z } from "zod";
|
|
4
4
|
|
|
5
|
-
//#region src/agents/
|
|
5
|
+
//#region src/agents/middleware/piiRedaction.d.ts
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* Configuration schema for the Input Guardrails middleware
|
|
@@ -28,7 +28,7 @@ type PIIRedactionMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;
|
|
|
28
28
|
*
|
|
29
29
|
* The middleware intercepts agent execution at two points:
|
|
30
30
|
*
|
|
31
|
-
* ### Request Phase (`
|
|
31
|
+
* ### Request Phase (`wrapModelCall`)
|
|
32
32
|
* - Applies regex-based pattern matching to all message content (HumanMessage, ToolMessage, SystemMessage, AIMessage)
|
|
33
33
|
* - Processes both message text and AIMessage tool call arguments
|
|
34
34
|
* - Each matched pattern generates:
|
|
@@ -80,7 +80,7 @@ type PIIRedactionMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;
|
|
|
80
80
|
* import { piiRedactionMiddleware } from "langchain";
|
|
81
81
|
* import { createAgent } from "langchain";
|
|
82
82
|
* import { tool } from "@langchain/core/tools";
|
|
83
|
-
* import { z } from "zod";
|
|
83
|
+
* import { z } from "zod/v3";
|
|
84
84
|
*
|
|
85
85
|
* const PII_RULES = {
|
|
86
86
|
* ssn: /\b\d{3}-?\d{2}-?\d{4}\b/g,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"piiRedaction.d.ts","names":["z","InferInteropZodInput","createMiddleware","contextSchema","ZodString","RegExp","ZodTypeDef","ZodType","ZodRecord","ZodOptional","ZodTypeAny","Record","ZodObject","PIIRedactionMiddlewareConfig","piiRedactionMiddleware","ReturnType"],"sources":["../../../src/agents/middleware/piiRedaction.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\nimport { createMiddleware } from \"../middleware.js\";\n/**\n * Configuration schema for the Input Guardrails middleware\n */\ndeclare const contextSchema: z.ZodObject<{\n /**\n * A record of PII detection rules to apply\n * @default DEFAULT_PII_RULES (with enabled rules only)\n */\n rules: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodType<RegExp, z.ZodTypeDef, RegExp>>>;\n}, \"strip\", z.ZodTypeAny, {\n rules?: Record<string, RegExp> | undefined;\n}, {\n rules?: Record<string, RegExp> | undefined;\n}>;\nexport type PIIRedactionMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;\n/**\n * Creates a middleware that detects and redacts personally identifiable information (PII)\n * from messages before they are sent to model providers, and restores original values\n * in model responses for tool execution.\n *\n * ## Mechanism\n *\n * The middleware intercepts agent execution at two points:\n *\n * ### Request Phase (`wrapModelCall`)\n * - Applies regex-based pattern matching to all message content (HumanMessage, ToolMessage, SystemMessage, AIMessage)\n * - Processes both message text and AIMessage tool call arguments\n * - Each matched pattern generates:\n * - Unique identifier: `generateRedactionId()` → `\"abc123\"`\n * - Redaction marker: `[REDACTED_{RULE_NAME}_{ID}]` → `\"[REDACTED_SSN_abc123]\"`\n * - Redaction map entry: `{ \"abc123\": \"123-45-6789\" }`\n * - Returns modified request with redacted message content\n *\n * ### Response Phase (`afterModel`)\n * - Scans AIMessage responses for redaction markers matching pattern: `/\\[REDACTED_[A-Z_]+_(\\w+)\\]/g`\n * - Replaces markers with original values from redaction map\n * - Handles both standard responses and structured output (via tool calls or JSON content)\n * - For structured output, restores values in both the tool call arguments and the `structuredResponse` state field\n * - Returns new message instances via RemoveMessage/AIMessage to update state\n *\n * ## Data Flow\n *\n * ```\n * User Input: \"My SSN is 123-45-6789\"\n * ↓ [beforeModel]\n * Model Request: \"My SSN is [REDACTED_SSN_abc123]\"\n * ↓ [model invocation]\n * Model Response: tool_call({ \"ssn\": \"[REDACTED_SSN_abc123]\" })\n * ↓ [afterModel]\n * Tool Execution: tool({ \"ssn\": \"123-45-6789\" })\n * ```\n *\n * ## Limitations\n *\n * This middleware provides model provider isolation only. PII may still be present in:\n * - LangGraph state checkpoints (memory, databases)\n * - Network traffic between client and application server\n * - Application logs and trace data\n * - Tool execution arguments and responses\n * - Final agent output\n *\n * For comprehensive PII protection, implement additional controls at the application,\n * network, and storage layers.\n *\n * @param options - Configuration options\n * @param options.rules - Record of detection rules mapping rule names to regex patterns.\n * Rule names are normalized to uppercase and used in redaction markers.\n * Patterns must use the global flag (`/pattern/g`) to match all occurrences.\n *\n * @returns Middleware instance for use with `createAgent`\n *\n * @example Basic usage with custom rules\n * ```typescript\n * import { piiRedactionMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n * import { tool } from \"@langchain/core/tools\";\n * import { z } from \"zod/v3\";\n *\n * const PII_RULES = {\n * ssn: /\\b\\d{3}-?\\d{2}-?\\d{4}\\b/g,\n * email: /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g,\n * phone: /\\b\\d{3}[-.]?\\d{3}[-.]?\\d{4}\\b/g,\n * };\n *\n * const lookupUser = tool(async ({ ssn }) => {\n * // Receives original value: \"123-45-6789\"\n * return { name: \"John Doe\", account: \"active\" };\n * }, {\n * name: \"lookup_user\",\n * description: \"Look up user by SSN\",\n * schema: z.object({ ssn: z.string() })\n * });\n *\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4\" }),\n * tools: [lookupUser],\n * middleware: [piiRedactionMiddleware({ rules: PII_RULES })]\n * });\n *\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Look up SSN 123-45-6789\")]\n * });\n * // Model request: \"Look up SSN [REDACTED_SSN_abc123]\"\n * // Model response: tool_call({ \"ssn\": \"[REDACTED_SSN_abc123]\" })\n * // Tool receives: { \"ssn\": \"123-45-6789\" }\n * ```\n *\n * @example Runtime rule configuration via context\n * ```typescript\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4\" }),\n * tools: [someTool],\n * middleware: [piiRedactionMiddleware()]\n * });\n *\n * // Configure rules at runtime via middleware context\n * const result = await agent.invoke(\n * { messages: [new HumanMessage(\"...\")] },\n * {\n * configurable: {\n * PIIRedactionMiddleware: {\n * rules: {\n * ssn: /\\b\\d{3}-?\\d{2}-?\\d{4}\\b/g,\n * email: /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g,\n * }\n * }\n * }\n * }\n * );\n * ```\n *\n * @example Custom rule patterns\n * ```typescript\n * const customRules = {\n * employee_id: /EMP-\\d{6}/g,\n * api_key: /sk-[a-zA-Z0-9]{32}/g,\n * credit_card: /\\b\\d{4}[- ]?\\d{4}[- ]?\\d{4}[- ]?\\d{4}\\b/g,\n * };\n *\n * const middleware = piiRedactionMiddleware({ rules: customRules });\n * // Generates markers like: [REDACTED_EMPLOYEE_ID_xyz789]\n * ```\n *\n * @public\n */\nexport declare function piiRedactionMiddleware(options?: PIIRedactionMiddlewareConfig): ReturnType<typeof createMiddleware>;\nexport {};\n"],"mappings":";;;;;;;;AAEoD;cAItCG,aAUZ,EAV2BH,CAAAA,CAAEY,SAU7B,CAAA;EAAA;;;;EALsF,KAApCL,EAAzCP,CAAAA,CAAES,WAAuCF,CAA3BP,CAAAA,CAAEQ,SAAyBD,CAAfP,CAAAA,CAAEI,SAAaG,EAAFP,CAAAA,CAAEO,OAAAA,CAAQF,MAARE,EAAgBP,CAAAA,CAAEM,UAAlBC,EAA8BF,MAA9BE,CAAAA,CAAAA,CAAAA;CAAO,EAAA,OAAhCC,EACfR,CAAAA,CAAEU,UADaF,EAAAA;EAAS,KAAvBC,CAAAA,EAEDE,MAFCF,CAAAA,MAAAA,EAEcJ,MAFdI,CAAAA,GAAAA,SAAAA;CAAW,EAAA;EACA,KACGJ,CAAAA,EAEfM,MAFeN,CAAAA,MAAAA,EAEAA,MAFAA,CAAAA,GAAAA,SAAAA;CAAM,CAAA;AAENA,KAEfQ,4BAAAA,GAA+BZ,oBAFhBI,CAAAA,OAE4CF,aAF5CE,CAAAA;;;AATa;AAWxC;;;;AAA+D;AAmI/D;;;;;AAAkG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAA1ES,sBAAAA,WAAiCD,+BAA+BE,kBAAkBb"}
|