langchain 1.0.0-alpha.8 → 1.0.0-alpha.9
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/LICENSE +6 -6
- package/dist/agents/ReactAgent.cjs +497 -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 +500 -107
- package/dist/agents/ReactAgent.js.map +1 -1
- package/dist/agents/annotation.cjs +32 -149
- package/dist/agents/annotation.cjs.map +1 -1
- package/dist/agents/annotation.js +34 -147
- 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 +2 -2
- 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 +1 -1
- package/dist/agents/middleware/callLimit.js.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/contextEditing.cjs +5 -5
- 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 +4 -4
- 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 +404 -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 +403 -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 +28 -21
- package/dist/agents/middleware/modelFallback.cjs.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/modelFallback.d.cts +2 -2
- package/dist/agents/middleware/modelFallback.d.cts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/modelFallback.d.ts +2 -2
- package/dist/agents/middleware/modelFallback.d.ts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/modelFallback.js +28 -21
- 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 +4 -9
- 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 +2 -2
- 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 +1 -1
- package/dist/agents/middleware/toolCallLimit.js.map +1 -0
- package/dist/agents/middleware/types.d.cts +208 -0
- package/dist/agents/middleware/types.d.cts.map +1 -0
- package/dist/agents/middleware/types.d.ts +208 -0
- package/dist/agents/middleware/types.d.ts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware → middleware}/utils.cjs +1 -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 +1 -1
- package/dist/agents/middleware/utils.js.map +1 -0
- package/dist/agents/{middlewareAgent/middleware.cjs → middleware.cjs} +11 -4
- package/dist/agents/middleware.cjs.map +1 -0
- package/dist/agents/middleware.d.cts +205 -0
- package/dist/agents/middleware.d.cts.map +1 -0
- package/dist/agents/middleware.d.ts +205 -0
- package/dist/agents/middleware.d.ts.map +1 -0
- package/dist/agents/{middlewareAgent/middleware.js → middleware.js} +11 -4
- package/dist/agents/middleware.js.map +1 -0
- package/dist/agents/nodes/AfterAgentNode.cjs +27 -0
- package/dist/agents/nodes/AfterAgentNode.cjs.map +1 -0
- package/dist/agents/nodes/AfterAgentNode.js +27 -0
- package/dist/agents/nodes/AfterAgentNode.js.map +1 -0
- package/dist/agents/{middlewareAgent/nodes/AfterModalNode.cjs → nodes/AfterModelNode.cjs} +3 -5
- package/dist/agents/nodes/AfterModelNode.cjs.map +1 -0
- package/dist/agents/{middlewareAgent/nodes/AfterModalNode.js → nodes/AfterModelNode.js} +3 -5
- package/dist/agents/nodes/AfterModelNode.js.map +1 -0
- package/dist/agents/nodes/AgentNode.cjs +202 -71
- package/dist/agents/nodes/AgentNode.cjs.map +1 -1
- package/dist/agents/nodes/AgentNode.js +204 -73
- package/dist/agents/nodes/AgentNode.js.map +1 -1
- package/dist/agents/nodes/BeforeAgentNode.cjs +27 -0
- package/dist/agents/nodes/BeforeAgentNode.cjs.map +1 -0
- package/dist/agents/nodes/BeforeAgentNode.js +27 -0
- package/dist/agents/nodes/BeforeAgentNode.js.map +1 -0
- package/dist/agents/{middlewareAgent/nodes/BeforeModalNode.cjs → nodes/BeforeModelNode.cjs} +3 -3
- package/dist/agents/nodes/BeforeModelNode.cjs.map +1 -0
- package/dist/agents/{middlewareAgent/nodes/BeforeModalNode.js → nodes/BeforeModelNode.js} +3 -3
- package/dist/agents/nodes/BeforeModelNode.js.map +1 -0
- package/dist/agents/nodes/ToolNode.cjs +157 -47
- package/dist/agents/nodes/ToolNode.cjs.map +1 -1
- package/dist/agents/nodes/ToolNode.js +158 -48
- package/dist/agents/nodes/ToolNode.js.map +1 -1
- package/dist/agents/{middlewareAgent/nodes → nodes}/middleware.cjs +35 -10
- package/dist/agents/nodes/middleware.cjs.map +1 -0
- package/dist/agents/{middlewareAgent/nodes → nodes}/middleware.js +34 -9
- package/dist/agents/nodes/middleware.js.map +1 -0
- package/dist/agents/nodes/types.d.cts +57 -0
- package/dist/agents/nodes/types.d.cts.map +1 -0
- package/dist/agents/nodes/types.d.ts +57 -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 +125 -126
- package/dist/agents/types.d.cts.map +1 -1
- package/dist/agents/types.d.ts +125 -126
- 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 +18 -38
- 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 +0 -2
- package/dist/load/import_map.cjs.map +1 -1
- package/dist/load/import_map.js +0 -2
- 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 +4 -18
- 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/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
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ReactAgent.js","names":["options: CreateAgentParams<StructuredResponseFormat, ContextSchema>","#toolBehaviorVersion","beforeModelNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[]","afterModelNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[]","modifyModelRequestHookMiddleware: [\n AgentMiddleware,\n /**\n * ToDo: better type to get the state of middleware\n */\n () => any\n ][]","retryModelRequestHookMiddleware: [\n AgentMiddleware,\n /**\n * ToDo: better type to get the state of middleware\n */\n () => any\n ][]","#agentNode","beforeModelNode: BeforeModelNode | undefined","afterModelNode: AfterModelNode | undefined","#createBeforeModelRouter","#getModelPaths","#createModelRouter","#createAfterModelSequenceRouter","#createAfterModelRouter","toolReturnTarget: string","#createToolsRouter","#graph","toolClasses: (ClientTool | ServerTool)[]","includeModelRequest: boolean","paths: (\"tools\" | \"model_request\" | typeof END)[]","shouldReturnDirect: Set<string>","state: any","state: BuiltInState","allowJump: boolean","state: Omit<BuiltInState, \"jumpTo\"> & { jumpTo?: JumpTo }","allowed: string[]","nextDefault: string","#initializeMiddlewareStates","state: InvokeStateParameter<TMiddleware>","#populatePrivateState","config?: RunnableConfig","config?: InvokeConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n >","config?: StreamConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n >","config?: StreamConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n > & { version?: \"v1\" | \"v2\" }","streamOptions?: any","params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }","config: RunnableConfig","options?: GetStateOptions","options?: CheckpointListOptions","namespace?: string","recurse?: boolean"],"sources":["../../../src/agents/middlewareAgent/ReactAgent.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\n\nimport {\n AnnotationRoot,\n StateGraph,\n END,\n START,\n Send,\n Command,\n CompiledStateGraph,\n type GetStateOptions,\n} from \"@langchain/langgraph\";\nimport type { CheckpointListOptions } from \"@langchain/langgraph-checkpoint\";\nimport { ToolMessage, AIMessage } from \"@langchain/core/messages\";\nimport { IterableReadableStream } from \"@langchain/core/utils/stream\";\nimport type { RunnableConfig } from \"@langchain/core/runnables\";\n\nimport { createAgentAnnotationConditional } from \"./annotation.js\";\nimport { isClientTool } from \"../utils.js\";\n\nimport { AgentNode } from \"./nodes/AgentNode.js\";\nimport { ToolNode } from \"../nodes/ToolNode.js\";\nimport { BeforeModelNode } from \"./nodes/BeforeModalNode.js\";\nimport { AfterModelNode } from \"./nodes/AfterModalNode.js\";\nimport {\n initializeMiddlewareStates,\n parseJumpToTarget,\n} from \"./nodes/utils.js\";\n\nimport type { ClientTool, ServerTool, WithStateGraphNodes } from \"../types.js\";\n\nimport type {\n CreateAgentParams,\n AgentMiddleware,\n InferMiddlewareStates,\n InferMiddlewareInputStates,\n BuiltInState,\n InferMiddlewareContextInputs,\n InferContextInput,\n InvokeConfiguration,\n StreamConfiguration,\n JumpTo,\n UserInput,\n PrivateState,\n} from \"./types.js\";\n\nimport {\n type AnyAnnotationRoot,\n type ToAnnotationRoot,\n type ResponseFormatUndefined,\n} from \"../annotation.js\";\n\n// Helper type to get the state definition with middleware states\ntype MergedAgentState<\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined,\n TMiddleware extends readonly AgentMiddleware<any, any, any>[]\n> = (StructuredResponseFormat extends ResponseFormatUndefined\n ? Omit<BuiltInState, \"jumpTo\">\n : Omit<BuiltInState, \"jumpTo\"> & {\n structuredResponse: StructuredResponseFormat;\n }) &\n InferMiddlewareStates<TMiddleware>;\n\ntype InvokeStateParameter<\n TMiddleware extends readonly AgentMiddleware<any, any, any>[]\n> =\n | (UserInput & InferMiddlewareInputStates<TMiddleware>)\n | Command<any, any, any>\n | null;\n\ntype AgentGraph<\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<any, any, any>[] = []\n> = CompiledStateGraph<\n any,\n any,\n any,\n any,\n MergedAgentState<StructuredResponseFormat, TMiddleware>,\n ToAnnotationRoot<ContextSchema>[\"spec\"],\n unknown\n>;\n\nexport class ReactAgent<\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n> {\n #graph: AgentGraph<StructuredResponseFormat, ContextSchema, TMiddleware>;\n\n #toolBehaviorVersion: \"v1\" | \"v2\" = \"v2\";\n\n #agentNode: AgentNode<any, AnyAnnotationRoot>;\n\n constructor(\n public options: CreateAgentParams<StructuredResponseFormat, ContextSchema>\n ) {\n this.#toolBehaviorVersion = options.version ?? this.#toolBehaviorVersion;\n\n /**\n * define complete list of tools based on options and middleware\n */\n const middlewareTools = (this.options.middleware\n ?.filter((m) => m.tools)\n .flatMap((m) => m.tools) ?? []) as (ClientTool | ServerTool)[];\n const toolClasses = [\n ...((Array.isArray(options.tools)\n ? options.tools\n : options.tools?.tools) ?? []),\n ...middlewareTools,\n ];\n\n /**\n * If any of the tools are configured to return_directly after running,\n * our graph needs to check if these were called\n */\n const shouldReturnDirect = new Set(\n toolClasses\n .filter(isClientTool)\n .filter((tool) => \"returnDirect\" in tool && tool.returnDirect)\n .map((tool) => tool.name)\n );\n\n // Create a schema that merges agent base schema with middleware state schemas\n const schema = createAgentAnnotationConditional<\n StructuredResponseFormat,\n TMiddleware\n >(\n this.options.responseFormat !== undefined,\n this.options.middleware as TMiddleware\n );\n\n const workflow = new StateGraph(\n schema as AnnotationRoot<any>,\n this.options.contextSchema\n );\n\n const allNodeWorkflows = workflow as WithStateGraphNodes<\n \"tools\" | \"model_request\" | string,\n typeof workflow\n >;\n\n // Generate node names for middleware nodes that have hooks\n const beforeModelNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[] = [];\n const afterModelNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[] = [];\n const modifyModelRequestHookMiddleware: [\n AgentMiddleware,\n /**\n * ToDo: better type to get the state of middleware\n */\n () => any\n ][] = [];\n const retryModelRequestHookMiddleware: [\n AgentMiddleware,\n /**\n * ToDo: better type to get the state of middleware\n */\n () => any\n ][] = [];\n\n this.#agentNode = new AgentNode({\n model: this.options.model,\n systemPrompt: this.options.systemPrompt,\n includeAgentName: this.options.includeAgentName,\n name: this.options.name,\n responseFormat: this.options.responseFormat,\n middleware: this.options.middleware,\n toolClasses,\n shouldReturnDirect,\n signal: this.options.signal,\n modifyModelRequestHookMiddleware,\n retryModelRequestHookMiddleware,\n });\n\n const middlewareNames = new Set<string>();\n const middleware = this.options.middleware ?? [];\n for (let i = 0; i < middleware.length; i++) {\n let beforeModelNode: BeforeModelNode | undefined;\n let afterModelNode: AfterModelNode | undefined;\n const m = middleware[i];\n if (middlewareNames.has(m.name)) {\n throw new Error(`Middleware ${m.name} is defined multiple times`);\n }\n\n middlewareNames.add(m.name);\n if (m.beforeModel) {\n beforeModelNode = new BeforeModelNode(m, {\n getPrivateState: () => this.#agentNode.getState()._privateState,\n });\n const name = `${m.name}.before_model`;\n beforeModelNodes.push({\n index: i,\n name,\n allowed: m.beforeModelJumpTo,\n });\n allNodeWorkflows.addNode(\n name,\n beforeModelNode,\n beforeModelNode.nodeOptions\n );\n }\n if (m.afterModel) {\n afterModelNode = new AfterModelNode(m, {\n getPrivateState: () => this.#agentNode.getState()._privateState,\n });\n const name = `${m.name}.after_model`;\n afterModelNodes.push({\n index: i,\n name,\n allowed: m.afterModelJumpTo,\n });\n allNodeWorkflows.addNode(\n name,\n afterModelNode,\n afterModelNode.nodeOptions\n );\n }\n\n if (m.modifyModelRequest) {\n modifyModelRequestHookMiddleware.push([\n m,\n () => ({\n ...beforeModelNode?.getState(),\n ...afterModelNode?.getState(),\n }),\n ]);\n }\n\n if (m.retryModelRequest) {\n retryModelRequestHookMiddleware.push([\n m,\n () => ({\n ...beforeModelNode?.getState(),\n ...afterModelNode?.getState(),\n }),\n ]);\n }\n }\n\n /**\n * Add Nodes\n */\n allNodeWorkflows.addNode(\n \"model_request\",\n this.#agentNode,\n AgentNode.nodeOptions\n );\n\n /**\n * add single tool node for all tools\n */\n if (toolClasses.filter(isClientTool).length > 0) {\n const toolNode = new ToolNode(toolClasses.filter(isClientTool), {\n signal: this.options.signal,\n });\n allNodeWorkflows.addNode(\"tools\", toolNode);\n }\n\n /**\n * Add Edges\n */\n // Determine starting point based on what nodes exist\n if (beforeModelNodes.length > 0) {\n // If we have beforeModel nodes, start with the first one\n allNodeWorkflows.addEdge(START, beforeModelNodes[0].name);\n } else {\n // If no beforeModel nodes, go directly to agent\n allNodeWorkflows.addEdge(START, \"model_request\");\n }\n\n // Connect beforeModel nodes; add conditional routing ONLY if allowed jumps are specified\n for (let i = 0; i < beforeModelNodes.length; i++) {\n const node = beforeModelNodes[i];\n const current = node.name;\n const isLast = i === beforeModelNodes.length - 1;\n const nextDefault = isLast\n ? \"model_request\"\n : beforeModelNodes[i + 1].name;\n\n if (node.allowed && node.allowed.length > 0) {\n const hasTools = toolClasses.filter(isClientTool).length > 0;\n const allowedMapped = node.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== \"tools\" || hasTools);\n const destinations = Array.from(\n new Set([nextDefault, ...allowedMapped])\n ) as (\"tools\" | \"model_request\" | typeof END)[];\n\n allNodeWorkflows.addConditionalEdges(\n current,\n this.#createBeforeModelRouter(\n toolClasses.filter(isClientTool),\n nextDefault\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(current, nextDefault);\n }\n }\n\n // Connect agent to last afterModel node (for reverse order execution)\n const lastAfterModelNode = afterModelNodes.at(-1);\n if (afterModelNodes.length > 0 && lastAfterModelNode) {\n allNodeWorkflows.addEdge(\"model_request\", lastAfterModelNode.name);\n } else {\n // If no afterModel nodes, connect model_request directly to model paths\n const modelPaths = this.#getModelPaths(toolClasses.filter(isClientTool));\n if (modelPaths.length === 1) {\n allNodeWorkflows.addEdge(\"model_request\", modelPaths[0]);\n } else {\n allNodeWorkflows.addConditionalEdges(\n \"model_request\",\n this.#createModelRouter(),\n modelPaths\n );\n }\n }\n\n // Connect afterModel nodes in reverse sequence; add conditional routing ONLY if allowed jumps are specified per node\n for (let i = afterModelNodes.length - 1; i > 0; i--) {\n const node = afterModelNodes[i];\n const current = node.name;\n const nextDefault = afterModelNodes[i - 1].name;\n\n if (node.allowed && node.allowed.length > 0) {\n const hasTools = toolClasses.filter(isClientTool).length > 0;\n const allowedMapped = node.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== \"tools\" || hasTools);\n const destinations = Array.from(\n new Set([nextDefault, ...allowedMapped])\n ) as (\"tools\" | \"model_request\" | typeof END)[];\n\n allNodeWorkflows.addConditionalEdges(\n current,\n this.#createAfterModelSequenceRouter(\n toolClasses.filter(isClientTool),\n node.allowed,\n nextDefault\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(current, nextDefault);\n }\n }\n\n // Connect first afterModel node (last to execute) to model paths with jumpTo support\n if (afterModelNodes.length > 0) {\n const firstAfterModel = afterModelNodes[0];\n const firstAfterModelNode = firstAfterModel.name;\n const modelPaths = this.#getModelPaths(\n toolClasses.filter(isClientTool),\n true\n ).filter(\n (p) => p !== \"tools\" || toolClasses.filter(isClientTool).length > 0\n );\n\n const allowJump = Boolean(\n firstAfterModel.allowed && firstAfterModel.allowed.length > 0\n );\n\n const destinations = modelPaths;\n\n allNodeWorkflows.addConditionalEdges(\n firstAfterModelNode,\n this.#createAfterModelRouter(\n toolClasses.filter(isClientTool),\n allowJump\n ),\n destinations\n );\n }\n\n /**\n * add edges for tools node\n */\n if (toolClasses.filter(isClientTool).length > 0) {\n // Tools should return to first beforeModel node or agent\n let toolReturnTarget: string;\n if (beforeModelNodes.length > 0) {\n toolReturnTarget = beforeModelNodes[0].name;\n } else {\n toolReturnTarget = \"model_request\";\n }\n\n if (shouldReturnDirect.size > 0) {\n allNodeWorkflows.addConditionalEdges(\n \"tools\",\n this.#createToolsRouter(shouldReturnDirect),\n [toolReturnTarget, END]\n );\n } else {\n allNodeWorkflows.addEdge(\"tools\", toolReturnTarget);\n }\n }\n\n /**\n * compile the graph\n */\n this.#graph = allNodeWorkflows.compile({\n checkpointer: this.options.checkpointer ?? this.options.checkpointSaver,\n store: this.options.store,\n name: this.options.name,\n description: this.options.description,\n }) as AgentGraph<StructuredResponseFormat, ContextSchema, TMiddleware>;\n }\n\n /**\n * Get the compiled {@link https://docs.langchain.com/oss/javascript/langgraph/use-graph-api | StateGraph}.\n */\n get graph(): AgentGraph<\n StructuredResponseFormat,\n ContextSchema,\n TMiddleware\n > {\n return this.#graph;\n }\n\n /**\n * Get possible edge destinations from model node.\n * @param toolClasses names of tools to call\n * @param includeModelRequest whether to include \"model_request\" as a valid path (for jumpTo routing)\n * @returns list of possible edge destinations\n */\n #getModelPaths(\n toolClasses: (ClientTool | ServerTool)[],\n includeModelRequest: boolean = false\n ): (\"tools\" | \"model_request\" | typeof END)[] {\n const paths: (\"tools\" | \"model_request\" | typeof END)[] = [];\n if (toolClasses.length > 0) {\n paths.push(\"tools\");\n }\n\n if (includeModelRequest) {\n paths.push(\"model_request\");\n }\n\n paths.push(END);\n\n return paths;\n }\n\n /**\n * Create routing function for tools node conditional edges.\n */\n #createToolsRouter(shouldReturnDirect: Set<string>) {\n /**\n * ToDo: fix type\n */\n return (state: any) => {\n const messages = state.messages;\n const lastMessage = messages[messages.length - 1];\n\n // Check if we just executed a returnDirect tool\n if (\n ToolMessage.isInstance(lastMessage) &&\n lastMessage.name &&\n shouldReturnDirect.has(lastMessage.name)\n ) {\n // If we have a response format, route to agent to generate structured response\n // Otherwise, return directly\n return this.options.responseFormat ? \"model_request\" : END;\n }\n\n // For non-returnDirect tools, always route back to agent\n return \"model_request\";\n };\n }\n\n /**\n * Create routing function for model node conditional edges.\n */\n #createModelRouter() {\n /**\n * determine if the agent should continue or not\n */\n return (state: BuiltInState) => {\n const messages = state.messages;\n const lastMessage = messages.at(-1);\n\n if (\n !AIMessage.isInstance(lastMessage) ||\n !lastMessage.tool_calls ||\n lastMessage.tool_calls.length === 0\n ) {\n return END;\n }\n\n // Check if all tool calls are for structured response extraction\n const hasOnlyStructuredResponseCalls = lastMessage.tool_calls.every(\n (toolCall) => toolCall.name.startsWith(\"extract-\")\n );\n\n if (hasOnlyStructuredResponseCalls) {\n // If all tool calls are for structured response extraction, go to END\n // The AgentNode will handle these internally and return the structured response\n return END;\n }\n\n /**\n * The tool node processes a single message.\n */\n if (this.#toolBehaviorVersion === \"v1\") {\n return \"tools\";\n }\n\n /**\n * Route to tools node (filter out any structured response tool calls)\n */\n const regularToolCalls = lastMessage.tool_calls.filter(\n (toolCall) => !toolCall.name.startsWith(\"extract-\")\n );\n\n if (regularToolCalls.length === 0) {\n return END;\n }\n\n return regularToolCalls.map(\n (toolCall) => new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n );\n };\n }\n\n /**\n * Create routing function for jumpTo functionality after afterModel hooks.\n *\n * This router checks if the `jumpTo` property is set in the state after afterModel middleware\n * execution. If set, it routes to the specified target (\"model_request\" or \"tools\").\n * If not set, it falls back to the normal model routing logic for afterModel context.\n *\n * The jumpTo property is automatically cleared after use to prevent infinite loops.\n *\n * @param toolClasses - Available tool classes for validation\n * @returns Router function that handles jumpTo logic and normal routing\n */\n #createAfterModelRouter(\n toolClasses: (ClientTool | ServerTool)[],\n allowJump: boolean\n ) {\n const hasStructuredResponse = Boolean(this.options.responseFormat);\n\n return (state: Omit<BuiltInState, \"jumpTo\"> & { jumpTo?: JumpTo }) => {\n // First, check if we just processed a structured response\n // If so, ignore any existing jumpTo and go to END\n const messages = state.messages;\n const lastMessage = messages.at(-1);\n if (\n AIMessage.isInstance(lastMessage) &&\n (!lastMessage.tool_calls || lastMessage.tool_calls.length === 0)\n ) {\n return END;\n }\n\n // Check if jumpTo is set in the state and allowed\n if (allowJump && state.jumpTo) {\n if (state.jumpTo === END) {\n return END;\n }\n if (state.jumpTo === \"tools\") {\n // If trying to jump to tools but no tools are available, go to END\n if (toolClasses.length === 0) {\n return END;\n }\n return new Send(\"tools\", { ...state, jumpTo: undefined });\n }\n // destination === \"model_request\"\n return new Send(\"model_request\", { ...state, jumpTo: undefined });\n }\n\n // check if there are pending tool calls\n const toolMessages = messages.filter(ToolMessage.isInstance);\n const lastAiMessage = messages.filter(AIMessage.isInstance).at(-1);\n const pendingToolCalls = lastAiMessage?.tool_calls?.filter(\n (call) => !toolMessages.some((m) => m.tool_call_id === call.id)\n );\n if (pendingToolCalls && pendingToolCalls.length > 0) {\n return pendingToolCalls.map(\n (toolCall) => new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n );\n }\n\n // if we exhausted all tool calls, but still have no structured response tool calls,\n // go back to model_request\n const hasStructuredResponseCalls = lastAiMessage?.tool_calls?.some(\n (toolCall) => toolCall.name.startsWith(\"extract-\")\n );\n\n if (\n pendingToolCalls &&\n pendingToolCalls.length === 0 &&\n !hasStructuredResponseCalls &&\n hasStructuredResponse\n ) {\n return \"model_request\";\n }\n\n if (\n !AIMessage.isInstance(lastMessage) ||\n !lastMessage.tool_calls ||\n lastMessage.tool_calls.length === 0\n ) {\n return END;\n }\n\n // Check if all tool calls are for structured response extraction\n const hasOnlyStructuredResponseCalls = lastMessage.tool_calls.every(\n (toolCall) => toolCall.name.startsWith(\"extract-\")\n );\n\n // Check if there are any regular tool calls (non-structured response)\n const hasRegularToolCalls = lastMessage.tool_calls.some(\n (toolCall) => !toolCall.name.startsWith(\"extract-\")\n );\n\n if (hasOnlyStructuredResponseCalls || !hasRegularToolCalls) {\n return END;\n }\n\n /**\n * For routing from afterModel nodes, always use simple string paths\n * The Send API is handled at the model_request node level\n */\n return \"tools\";\n };\n }\n\n /**\n * Router for afterModel sequence nodes (connecting later middlewares to earlier ones),\n * honoring allowed jump targets and defaulting to the next node.\n */\n #createAfterModelSequenceRouter(\n toolClasses: (ClientTool | ServerTool)[],\n allowed: string[],\n nextDefault: string\n ) {\n const allowedSet = new Set(allowed.map((t) => parseJumpToTarget(t)));\n return (state: BuiltInState) => {\n if (state.jumpTo) {\n const dest = parseJumpToTarget(state.jumpTo);\n if (dest === END && allowedSet.has(END)) {\n return END;\n }\n if (dest === \"tools\" && allowedSet.has(\"tools\")) {\n if (toolClasses.length === 0) return END;\n return new Send(\"tools\", { ...state, jumpTo: undefined });\n }\n if (dest === \"model_request\" && allowedSet.has(\"model_request\")) {\n return new Send(\"model_request\", { ...state, jumpTo: undefined });\n }\n }\n return nextDefault as any;\n };\n }\n\n /**\n * Create routing function for jumpTo functionality after beforeModel hooks.\n * Falls back to the default next node if no jumpTo is present.\n */\n #createBeforeModelRouter(\n toolClasses: (ClientTool | ServerTool)[],\n nextDefault: string\n ) {\n return (state: BuiltInState) => {\n if (!state.jumpTo) {\n return nextDefault;\n }\n const destination = parseJumpToTarget(state.jumpTo);\n if (destination === END) {\n return END;\n }\n if (destination === \"tools\") {\n if (toolClasses.length === 0) {\n return END;\n }\n return new Send(\"tools\", { ...state, jumpTo: undefined });\n }\n // destination === \"model_request\"\n return new Send(\"model_request\", { ...state, jumpTo: undefined });\n };\n }\n\n /**\n * Initialize middleware states if not already present in the input state.\n */\n async #initializeMiddlewareStates(\n state: InvokeStateParameter<TMiddleware>\n ): Promise<InvokeStateParameter<TMiddleware>> {\n if (\n !this.options.middleware ||\n this.options.middleware.length === 0 ||\n state instanceof Command ||\n !state\n ) {\n return state;\n }\n\n const defaultStates = await initializeMiddlewareStates(\n this.options.middleware,\n state\n );\n const updatedState = { ...state } as InvokeStateParameter<TMiddleware>;\n if (!updatedState) {\n return updatedState;\n }\n\n // Only add defaults for keys that don't exist in current state\n for (const [key, value] of Object.entries(defaultStates)) {\n if (!(key in updatedState)) {\n updatedState[key as keyof typeof updatedState] = value;\n }\n }\n\n return updatedState;\n }\n\n /**\n * Populate the private state of the agent node from the previous state.\n */\n async #populatePrivateState(config?: RunnableConfig) {\n /**\n * not needed if thread_id is not provided\n */\n if (!config?.configurable?.thread_id) {\n return;\n }\n const prevState = (await this.#graph.getState(config as any)) as {\n values: {\n _privateState: PrivateState;\n };\n };\n\n /**\n * not need if state is empty\n */\n if (!prevState.values._privateState) {\n return;\n }\n\n this.#agentNode.setState({\n structuredResponse: undefined,\n _privateState: prevState.values._privateState,\n });\n }\n\n /**\n * Executes the agent with the given state and returns the final state after all processing.\n *\n * This method runs the agent's entire workflow synchronously, including:\n * - Processing the input messages through any configured middleware\n * - Calling the language model to generate responses\n * - Executing any tool calls made by the model\n * - Running all middleware hooks (beforeModel, afterModel, etc.)\n *\n * @param state - The initial state for the agent execution. Can be:\n * - An object containing `messages` array and any middleware-specific state properties\n * - A Command object for more advanced control flow\n *\n * @param config - Optional runtime configuration including:\n * @param config.context - The context for the agent execution.\n * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc.\n * @param config.store - The store for the agent execution for persisting state, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Memory storage}.\n * @param config.signal - An optional {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} for the agent execution.\n * @param config.recursionLimit - The recursion limit for the agent execution.\n *\n * @returns A Promise that resolves to the final agent state after execution completes.\n * The returned state includes:\n * - a `messages` property containing an array with all messages (input, AI responses, tool calls/results)\n * - a `structuredResponse` property containing the structured response (if configured)\n * - all state values defined in the middleware\n *\n * @example\n * ```typescript\n * const agent = new ReactAgent({\n * llm: myModel,\n * tools: [calculator, webSearch],\n * responseFormat: z.object({\n * weather: z.string(),\n * }),\n * });\n *\n * const result = await agent.invoke({\n * messages: [{ role: \"human\", content: \"What's the weather in Paris?\" }]\n * });\n *\n * console.log(result.structuredResponse.weather); // outputs: \"It's sunny and 75°F.\"\n * ```\n */\n async invoke(\n state: InvokeStateParameter<TMiddleware>,\n config?: InvokeConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n >\n ) {\n type FullState = MergedAgentState<StructuredResponseFormat, TMiddleware>;\n const initializedState = await this.#initializeMiddlewareStates(state);\n await this.#populatePrivateState(config);\n\n return this.#graph.invoke(\n initializedState,\n config as unknown as InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n ) as Promise<FullState>;\n }\n\n /**\n * Executes the agent with streaming, returning an async iterable of state updates as they occur.\n *\n * This method runs the agent's workflow similar to `invoke`, but instead of waiting for\n * completion, it streams high-level state updates in real-time. This allows you to:\n * - Display intermediate results to users as they're generated\n * - Monitor the agent's progress through each step\n * - React to state changes as nodes complete\n *\n * For more granular event-level streaming (like individual LLM tokens), use `streamEvents` instead.\n *\n * @param state - The initial state for the agent execution. Can be:\n * - An object containing `messages` array and any middleware-specific state properties\n * - A Command object for more advanced control flow\n *\n * @param config - Optional runtime configuration including:\n * @param config.context - The context for the agent execution.\n * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc.\n * @param config.store - The store for the agent execution for persisting state, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Memory storage}.\n * @param config.signal - An optional {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} for the agent execution.\n * @param config.streamMode - The streaming mode for the agent execution, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/streaming#supported-stream-modes | Supported stream modes}.\n * @param config.recursionLimit - The recursion limit for the agent execution.\n *\n * @returns A Promise that resolves to an IterableReadableStream of state updates.\n * Each update contains the current state after a node completes.\n *\n * @example\n * ```typescript\n * const agent = new ReactAgent({\n * llm: myModel,\n * tools: [calculator, webSearch]\n * });\n *\n * const stream = await agent.stream({\n * messages: [{ role: \"human\", content: \"What's 2+2 and the weather in NYC?\" }]\n * });\n *\n * for await (const chunk of stream) {\n * console.log(chunk); // State update from each node\n * }\n * ```\n */\n async stream(\n state: InvokeStateParameter<TMiddleware>,\n config?: StreamConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n >\n ): Promise<IterableReadableStream<any>> {\n const initializedState = await this.#initializeMiddlewareStates(state);\n return this.#graph.stream(initializedState, config as Record<string, any>);\n }\n\n /**\n * Executes the agent with low-level event streaming, returning detailed events as they occur.\n *\n * This method provides fine-grained control over streaming, emitting events for every\n * operation during execution. This is useful when you need to:\n * - Stream individual LLM tokens as they're generated\n * - Monitor detailed execution flow with timing information\n * - Handle specific event types (model start/end, tool calls, etc.)\n * - Debug or trace agent behavior at a granular level\n *\n * For simpler state-based streaming, use `stream` instead.\n *\n * @param state - The initial state for the agent execution. Can be:\n * - An object containing `messages` array and any middleware-specific state properties\n * - A Command object for more advanced control flow\n *\n * @param config - Optional runtime configuration including:\n * @param config.context - The context for the agent execution.\n * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc.\n * @param config.store - The store for the agent execution for persisting state, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Memory storage}.\n * @param config.signal - An optional {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} for the agent execution.\n * @param config.recursionLimit - The recursion limit for the agent execution.\n * @param config.streamMode - The streaming mode for the agent execution, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/streaming#supported-stream-modes | Supported stream modes}.\n *\n * @param streamOptions - Additional streaming options (passed to LangGraph's streamEvents).\n *\n * @returns An IterableReadableStream of detailed events including:\n * - `on_chat_model_start`: When the LLM begins processing\n * - `on_chat_model_stream`: Streaming tokens from the LLM\n * - `on_chat_model_end`: When the LLM completes\n * - `on_tool_start`: When a tool execution begins\n * - `on_tool_end`: When a tool execution completes\n * - `on_chain_start`: When middleware chains begin\n * - `on_chain_end`: When middleware chains complete\n * - And other LangGraph v2 stream events\n *\n * @example\n * ```typescript\n * const agent = new ReactAgent({\n * llm: myModel,\n * tools: [calculator, webSearch]\n * });\n *\n * const stream = await agent.streamEvents({\n * messages: [{ role: \"human\", content: \"What's 2+2 and the weather in NYC?\" }]\n * }, {\n * version: \"v2\"\n * });\n *\n * for await (const event of stream) {\n * if (event.event === \"on_chat_model_stream\") {\n * process.stdout.write(event.data.chunk.content); // Stream tokens\n * }\n * }\n * ```\n */\n async streamEvents(\n state: InvokeStateParameter<TMiddleware>,\n config?: StreamConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n > & { version?: \"v1\" | \"v2\" },\n streamOptions?: any\n ): Promise<IterableReadableStream<any>> {\n const initializedState = await this.#initializeMiddlewareStates(state);\n await this.#populatePrivateState(config);\n return this.#graph.streamEvents(\n initializedState,\n {\n ...(config as any),\n version: config?.version ?? \"v2\",\n },\n streamOptions\n ) as IterableReadableStream<any>;\n }\n\n /**\n * Visualize the graph as a PNG image.\n * @param params - Parameters for the drawMermaidPng method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns PNG image as a buffer\n */\n async drawMermaidPng(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }) {\n const representation = await this.#graph.getGraphAsync();\n const image = await representation.drawMermaidPng(params);\n const arrayBuffer = await image.arrayBuffer();\n const buffer = new Uint8Array(arrayBuffer);\n return buffer;\n }\n\n /**\n * Draw the graph as a Mermaid string.\n * @param params - Parameters for the drawMermaid method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns Mermaid string\n */\n async drawMermaid(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }) {\n const representation = await this.#graph.getGraphAsync();\n return representation.drawMermaid(params);\n }\n\n /**\n * The following are internal methods to enable support for LangGraph Platform.\n * They are not part of the createAgent public API.\n *\n * Note: we intentionally return as `never` to avoid type errors due to type inference.\n */\n\n /**\n * @internal\n */\n getGraphAsync(config?: RunnableConfig) {\n return this.#graph.getGraphAsync(config) as never;\n }\n /**\n * @internal\n */\n getState(config: RunnableConfig, options?: GetStateOptions) {\n return this.#graph.getState(config, options) as never;\n }\n /**\n * @internal\n */\n getStateHistory(config: RunnableConfig, options?: CheckpointListOptions) {\n return this.#graph.getStateHistory(config, options) as never;\n }\n /**\n * @internal\n */\n getSubgraphs(namespace?: string, recurse?: boolean) {\n return this.#graph.getSubgraphs(namespace, recurse) as never;\n }\n /**\n * @internal\n */\n getSubgraphAsync(namespace?: string, recurse?: boolean) {\n return this.#graph.getSubgraphsAsync(namespace, recurse) as never;\n }\n}\n"],"mappings":";;;;;;;;;;;AA4FA,IAAa,aAAb,MAY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D,SAAO,KAAKrB,OAAO,SAAS,QAAQ,QAAQ;CAC7C;;;;CAID,gBAAgBoB,QAAwBE,SAAiC;AACvE,SAAO,KAAKtB,OAAO,gBAAgB,QAAQ,QAAQ;CACpD;;;;CAID,aAAauB,WAAoBC,SAAmB;AAClD,SAAO,KAAKxB,OAAO,aAAa,WAAW,QAAQ;CACpD;;;;CAID,iBAAiBuB,WAAoBC,SAAmB;AACtD,SAAO,KAAKxB,OAAO,kBAAkB,WAAW,QAAQ;CACzD;AACF"}
|
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
|
|
2
|
-
const __langchain_langgraph = require_rolldown_runtime.__toESM(require("@langchain/langgraph"));
|
|
3
|
-
|
|
4
|
-
//#region src/agents/middlewareAgent/annotation.ts
|
|
5
|
-
function createAgentAnnotationConditional(hasStructuredResponse = true, middlewareList = []) {
|
|
6
|
-
const baseAnnotation = {
|
|
7
|
-
messages: (0, __langchain_langgraph.Annotation)({
|
|
8
|
-
reducer: __langchain_langgraph.messagesStateReducer,
|
|
9
|
-
default: () => []
|
|
10
|
-
}),
|
|
11
|
-
jumpTo: (0, __langchain_langgraph.Annotation)({
|
|
12
|
-
reducer: (_x, y) => y,
|
|
13
|
-
default: () => void 0
|
|
14
|
-
})
|
|
15
|
-
};
|
|
16
|
-
for (const middleware of middlewareList) if (middleware.stateSchema) {
|
|
17
|
-
let parsedDefaults = {};
|
|
18
|
-
try {
|
|
19
|
-
parsedDefaults = middleware.stateSchema.parse({});
|
|
20
|
-
} catch {}
|
|
21
|
-
const { shape } = middleware.stateSchema;
|
|
22
|
-
for (const [key] of Object.entries(shape)) {
|
|
23
|
-
/**
|
|
24
|
-
* Skip private state properties
|
|
25
|
-
*/
|
|
26
|
-
if (key.startsWith("_")) continue;
|
|
27
|
-
if (!(key in baseAnnotation)) {
|
|
28
|
-
const defaultValue = parsedDefaults[key] ?? void 0;
|
|
29
|
-
baseAnnotation[key] = (0, __langchain_langgraph.Annotation)({
|
|
30
|
-
reducer: (x, y) => y ?? x,
|
|
31
|
-
default: () => defaultValue
|
|
32
|
-
});
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
if (!hasStructuredResponse) return __langchain_langgraph.Annotation.Root(baseAnnotation);
|
|
37
|
-
return __langchain_langgraph.Annotation.Root({
|
|
38
|
-
...baseAnnotation,
|
|
39
|
-
structuredResponse: (0, __langchain_langgraph.Annotation)()
|
|
40
|
-
});
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
//#endregion
|
|
44
|
-
exports.createAgentAnnotationConditional = createAgentAnnotationConditional;
|
|
45
|
-
//# sourceMappingURL=annotation.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"annotation.cjs","names":["middlewareList: TMiddleware","baseAnnotation: Record<string, any>","messagesStateReducer","_x: any","y: any","parsedDefaults: Record<string, any>","x: any","Annotation"],"sources":["../../../src/agents/middlewareAgent/annotation.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { BaseMessage } from \"@langchain/core/messages\";\nimport {\n Annotation,\n Messages,\n AnnotationRoot,\n messagesStateReducer,\n type BinaryOperatorAggregate,\n type LastValue,\n} from \"@langchain/langgraph\";\nimport type { ResponseFormatUndefined } from \"../annotation.js\";\nimport type { AgentMiddleware, InferMiddlewareStates } from \"./types.js\";\n\n// Create annotation conditionally - for ResponseFormatUndefined, don't include structuredResponse\n// Helper type for the merged annotation\ntype MergedAnnotationSpec<\n T extends Record<string, any> | ResponseFormatUndefined,\n TMiddleware extends readonly AgentMiddleware<any, any, any>[]\n> = {\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n jumpTo: LastValue<\"model_request\" | \"tools\" | undefined>;\n} & (T extends ResponseFormatUndefined\n ? {}\n : { structuredResponse: LastValue<T> }) &\n InferMiddlewareStates<TMiddleware>;\n\nexport function createAgentAnnotationConditional<\n T extends Record<string, any> | ResponseFormatUndefined,\n TMiddleware extends readonly AgentMiddleware<any, any, any>[] = []\n>(\n hasStructuredResponse = true,\n middlewareList: TMiddleware = [] as unknown as TMiddleware\n): AnnotationRoot<MergedAnnotationSpec<T, TMiddleware>> {\n const baseAnnotation: Record<string, any> = {\n messages: Annotation<BaseMessage[], Messages>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n jumpTo: Annotation<\"model_request\" | \"tools\" | undefined>({\n /**\n * Since `jumpTo` acts as a control command, we only want\n * to apply it if explicitly set.\n */\n reducer: (_x: any, y: any) => y,\n default: () => undefined,\n }),\n };\n\n // Add middleware state properties to the annotation\n for (const middleware of middlewareList) {\n if (middleware.stateSchema) {\n // Parse empty object to get default values\n let parsedDefaults: Record<string, any> = {};\n try {\n parsedDefaults = middleware.stateSchema.parse({});\n } catch {\n // If parsing fails, we'll use undefined as defaults\n }\n\n const { shape } = middleware.stateSchema;\n for (const [key] of Object.entries(shape)) {\n /**\n * Skip private state properties\n */\n if (key.startsWith(\"_\")) {\n continue;\n }\n\n if (!(key in baseAnnotation)) {\n const defaultValue = parsedDefaults[key] ?? undefined;\n baseAnnotation[key] = Annotation({\n reducer: (x: any, y: any) => y ?? x,\n default: () => defaultValue,\n });\n }\n }\n }\n }\n\n if (!hasStructuredResponse) {\n return Annotation.Root(baseAnnotation) as AnnotationRoot<\n MergedAnnotationSpec<T, TMiddleware>\n >;\n }\n\n return Annotation.Root({\n ...baseAnnotation,\n structuredResponse:\n Annotation<T extends ResponseFormatUndefined ? never : T>(),\n }) as unknown as AnnotationRoot<MergedAnnotationSpec<T, TMiddleware>>;\n}\n"],"mappings":";;;;AA0BA,SAAgB,iCAId,wBAAwB,MACxBA,iBAA8B,CAAE,GACsB;CACtD,MAAMC,iBAAsC;EAC1C,gDAA8C;GAC5C,SAASC;GACT,SAAS,MAAM,CAAE;EAClB,EAAC;EACF,8CAA0D;GAKxD,SAAS,CAACC,IAASC,MAAW;GAC9B,SAAS,MAAM;EAChB,EAAC;CACH;AAGD,MAAK,MAAM,cAAc,eACvB,KAAI,WAAW,aAAa;EAE1B,IAAIC,iBAAsC,CAAE;AAC5C,MAAI;GACF,iBAAiB,WAAW,YAAY,MAAM,CAAE,EAAC;EAClD,QAAO,CAEP;EAED,MAAM,EAAE,OAAO,GAAG,WAAW;AAC7B,OAAK,MAAM,CAAC,IAAI,IAAI,OAAO,QAAQ,MAAM,EAAE;;;;AAIzC,OAAI,IAAI,WAAW,IAAI,CACrB;AAGF,OAAI,EAAE,OAAO,iBAAiB;IAC5B,MAAM,eAAe,eAAe,QAAQ;IAC5C,eAAe,6CAAkB;KAC/B,SAAS,CAACC,GAAQF,MAAW,KAAK;KAClC,SAAS,MAAM;IAChB,EAAC;GACH;EACF;CACF;AAGH,KAAI,CAAC,sBACH,QAAOG,iCAAW,KAAK,eAAe;AAKxC,QAAOA,iCAAW,KAAK;EACrB,GAAG;EACH,2DAC6D;CAC9D,EAAC;AACH"}
|
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import { Annotation, messagesStateReducer } from "@langchain/langgraph";
|
|
2
|
-
|
|
3
|
-
//#region src/agents/middlewareAgent/annotation.ts
|
|
4
|
-
function createAgentAnnotationConditional(hasStructuredResponse = true, middlewareList = []) {
|
|
5
|
-
const baseAnnotation = {
|
|
6
|
-
messages: Annotation({
|
|
7
|
-
reducer: messagesStateReducer,
|
|
8
|
-
default: () => []
|
|
9
|
-
}),
|
|
10
|
-
jumpTo: Annotation({
|
|
11
|
-
reducer: (_x, y) => y,
|
|
12
|
-
default: () => void 0
|
|
13
|
-
})
|
|
14
|
-
};
|
|
15
|
-
for (const middleware of middlewareList) if (middleware.stateSchema) {
|
|
16
|
-
let parsedDefaults = {};
|
|
17
|
-
try {
|
|
18
|
-
parsedDefaults = middleware.stateSchema.parse({});
|
|
19
|
-
} catch {}
|
|
20
|
-
const { shape } = middleware.stateSchema;
|
|
21
|
-
for (const [key] of Object.entries(shape)) {
|
|
22
|
-
/**
|
|
23
|
-
* Skip private state properties
|
|
24
|
-
*/
|
|
25
|
-
if (key.startsWith("_")) continue;
|
|
26
|
-
if (!(key in baseAnnotation)) {
|
|
27
|
-
const defaultValue = parsedDefaults[key] ?? void 0;
|
|
28
|
-
baseAnnotation[key] = Annotation({
|
|
29
|
-
reducer: (x, y) => y ?? x,
|
|
30
|
-
default: () => defaultValue
|
|
31
|
-
});
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
if (!hasStructuredResponse) return Annotation.Root(baseAnnotation);
|
|
36
|
-
return Annotation.Root({
|
|
37
|
-
...baseAnnotation,
|
|
38
|
-
structuredResponse: Annotation()
|
|
39
|
-
});
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
//#endregion
|
|
43
|
-
export { createAgentAnnotationConditional };
|
|
44
|
-
//# sourceMappingURL=annotation.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"annotation.js","names":["middlewareList: TMiddleware","baseAnnotation: Record<string, any>","_x: any","y: any","parsedDefaults: Record<string, any>","x: any"],"sources":["../../../src/agents/middlewareAgent/annotation.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { BaseMessage } from \"@langchain/core/messages\";\nimport {\n Annotation,\n Messages,\n AnnotationRoot,\n messagesStateReducer,\n type BinaryOperatorAggregate,\n type LastValue,\n} from \"@langchain/langgraph\";\nimport type { ResponseFormatUndefined } from \"../annotation.js\";\nimport type { AgentMiddleware, InferMiddlewareStates } from \"./types.js\";\n\n// Create annotation conditionally - for ResponseFormatUndefined, don't include structuredResponse\n// Helper type for the merged annotation\ntype MergedAnnotationSpec<\n T extends Record<string, any> | ResponseFormatUndefined,\n TMiddleware extends readonly AgentMiddleware<any, any, any>[]\n> = {\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n jumpTo: LastValue<\"model_request\" | \"tools\" | undefined>;\n} & (T extends ResponseFormatUndefined\n ? {}\n : { structuredResponse: LastValue<T> }) &\n InferMiddlewareStates<TMiddleware>;\n\nexport function createAgentAnnotationConditional<\n T extends Record<string, any> | ResponseFormatUndefined,\n TMiddleware extends readonly AgentMiddleware<any, any, any>[] = []\n>(\n hasStructuredResponse = true,\n middlewareList: TMiddleware = [] as unknown as TMiddleware\n): AnnotationRoot<MergedAnnotationSpec<T, TMiddleware>> {\n const baseAnnotation: Record<string, any> = {\n messages: Annotation<BaseMessage[], Messages>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n jumpTo: Annotation<\"model_request\" | \"tools\" | undefined>({\n /**\n * Since `jumpTo` acts as a control command, we only want\n * to apply it if explicitly set.\n */\n reducer: (_x: any, y: any) => y,\n default: () => undefined,\n }),\n };\n\n // Add middleware state properties to the annotation\n for (const middleware of middlewareList) {\n if (middleware.stateSchema) {\n // Parse empty object to get default values\n let parsedDefaults: Record<string, any> = {};\n try {\n parsedDefaults = middleware.stateSchema.parse({});\n } catch {\n // If parsing fails, we'll use undefined as defaults\n }\n\n const { shape } = middleware.stateSchema;\n for (const [key] of Object.entries(shape)) {\n /**\n * Skip private state properties\n */\n if (key.startsWith(\"_\")) {\n continue;\n }\n\n if (!(key in baseAnnotation)) {\n const defaultValue = parsedDefaults[key] ?? undefined;\n baseAnnotation[key] = Annotation({\n reducer: (x: any, y: any) => y ?? x,\n default: () => defaultValue,\n });\n }\n }\n }\n }\n\n if (!hasStructuredResponse) {\n return Annotation.Root(baseAnnotation) as AnnotationRoot<\n MergedAnnotationSpec<T, TMiddleware>\n >;\n }\n\n return Annotation.Root({\n ...baseAnnotation,\n structuredResponse:\n Annotation<T extends ResponseFormatUndefined ? never : T>(),\n }) as unknown as AnnotationRoot<MergedAnnotationSpec<T, TMiddleware>>;\n}\n"],"mappings":";;;AA0BA,SAAgB,iCAId,wBAAwB,MACxBA,iBAA8B,CAAE,GACsB;CACtD,MAAMC,iBAAsC;EAC1C,UAAU,WAAoC;GAC5C,SAAS;GACT,SAAS,MAAM,CAAE;EAClB,EAAC;EACF,QAAQ,WAAkD;GAKxD,SAAS,CAACC,IAASC,MAAW;GAC9B,SAAS,MAAM;EAChB,EAAC;CACH;AAGD,MAAK,MAAM,cAAc,eACvB,KAAI,WAAW,aAAa;EAE1B,IAAIC,iBAAsC,CAAE;AAC5C,MAAI;GACF,iBAAiB,WAAW,YAAY,MAAM,CAAE,EAAC;EAClD,QAAO,CAEP;EAED,MAAM,EAAE,OAAO,GAAG,WAAW;AAC7B,OAAK,MAAM,CAAC,IAAI,IAAI,OAAO,QAAQ,MAAM,EAAE;;;;AAIzC,OAAI,IAAI,WAAW,IAAI,CACrB;AAGF,OAAI,EAAE,OAAO,iBAAiB;IAC5B,MAAM,eAAe,eAAe,QAAQ;IAC5C,eAAe,OAAO,WAAW;KAC/B,SAAS,CAACC,GAAQF,MAAW,KAAK;KAClC,SAAS,MAAM;IAChB,EAAC;GACH;EACF;CACF;AAGH,KAAI,CAAC,sBACH,QAAO,WAAW,KAAK,eAAe;AAKxC,QAAO,WAAW,KAAK;EACrB,GAAG;EACH,oBACE,YAA2D;CAC9D,EAAC;AACH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"constants.d.cts","names":["JUMP_TO_TARGETS"],"sources":["../../../src/agents/middlewareAgent/constants.d.ts"],"sourcesContent":["export declare const JUMP_TO_TARGETS: readonly [\"model\", \"tools\", \"end\"];\n"],"mappings":";cAAqBA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"constants.d.ts","names":["JUMP_TO_TARGETS"],"sources":["../../../src/agents/middlewareAgent/constants.d.ts"],"sourcesContent":["export declare const JUMP_TO_TARGETS: readonly [\"model\", \"tools\", \"end\"];\n"],"mappings":";cAAqBA"}
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
const require_ReactAgent = require('./ReactAgent.cjs');
|
|
2
|
-
const require_middleware = require('./middleware.cjs');
|
|
3
|
-
|
|
4
|
-
//#region src/agents/middlewareAgent/index.ts
|
|
5
|
-
function createAgent(params) {
|
|
6
|
-
return new require_ReactAgent.ReactAgent(params);
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
//#endregion
|
|
10
|
-
exports.createAgent = createAgent;
|
|
11
|
-
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["params: CreateAgentParams<StructuredResponseFormat, ContextSchema, any>","ReactAgent"],"sources":["../../../src/agents/middlewareAgent/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodType,\n} from \"@langchain/core/utils/types\";\n\nimport type {\n AnyAnnotationRoot,\n ResponseFormatUndefined,\n} from \"../annotation.js\";\nimport type { CreateAgentParams, AgentMiddleware } from \"./types.js\";\nimport type { ExtractZodArrayTypes } from \"../types.js\";\nimport type {\n ToolStrategy,\n TypedToolStrategy,\n ProviderStrategy,\n ResponseFormat,\n JsonSchemaFormat,\n} from \"../responses.js\";\nimport { ReactAgent } from \"./ReactAgent.js\";\n\n/**\n * Creates a production-ready ReAct (Reasoning + Acting) agent that combines language models with tools\n * and middleware to create systems that can reason about tasks, decide which tools to use, and iteratively\n * work towards solutions.\n *\n * The agent follows the ReAct pattern, interleaving reasoning steps with tool calls to iteratively\n * work towards solutions. It can handle multiple tool calls in sequence or parallel, maintain state\n * across interactions, and provide auditable decision processes.\n *\n * ## Core Components\n *\n * ### Model\n * The reasoning engine can be specified as:\n * - **String identifier**: `\"openai:gpt-4o\"` for simple setup\n * - **Model instance**: Configured model object for full control\n * - **Dynamic function**: Select models at runtime based on state\n *\n * ### Tools\n * Tools give agents the ability to take actions:\n * - Pass an array of tools created with the `tool` function\n * - Or provide a configured `ToolNode` for custom error handling\n *\n * ### Prompt\n * Shape how your agent approaches tasks:\n * - String for simple instructions\n * - SystemMessage for structured prompts\n * - Function for dynamic prompts based on state\n *\n * ### Middleware\n * Middleware allows you to extend the agent's behavior:\n * - Add pre/post-model processing for context injection or validation\n * - Add dynamic control flows, e.g. terminate invocation or retries\n * - Add human-in-the-loop capabilities\n * - Add tool calls to the agent\n * - Add tool results to the agent\n *\n * ## Advanced Features\n *\n * - **Structured Output**: Use `responseFormat` with a Zod schema to get typed responses\n * - **Memory**: Extend the state schema to remember information across interactions\n * - **Streaming**: Get real-time updates as the agent processes\n *\n * @param options - Configuration options for the agent\n * @param options.llm - The language model as an instance of a chat model\n * @param options.model - The language model as a string identifier, see more in {@link https://docs.langchain.com/oss/javascript/langchain/models#basic-usage | Models}.\n * @param options.tools - Array of tools or configured ToolNode\n * @param options.prompt - System instructions (string, SystemMessage, or function)\n * @param options.responseFormat - Zod schema for structured output\n * @param options.stateSchema - Custom state schema for memory\n * @param options.middleware - Array of middleware for extending agent behavior, see more in {@link https://docs.langchain.com/oss/javascript/langchain/middleware | Middleware}.\n *\n * @returns A ReactAgent instance with `invoke` and `stream` methods\n *\n * @example Basic agent with tools\n * ```ts\n * import { createAgent, tool } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const search = tool(\n * ({ query }) => `Results for: ${query}`,\n * {\n * name: \"search\",\n * description: \"Search for information\",\n * schema: z.object({\n * query: z.string().describe(\"The search query\"),\n * })\n * }\n * );\n *\n * const agent = createAgent({\n * llm: \"openai:gpt-4o\",\n * tools: [search],\n * });\n *\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Search for ReAct agents\" }],\n * });\n * ```\n *\n * @example Structured output\n * ```ts\n * import { createAgent } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const ContactInfo = z.object({\n * name: z.string(),\n * email: z.string(),\n * phone: z.string(),\n * });\n *\n * const agent = createAgent({\n * llm: \"openai:gpt-4o\",\n * tools: [],\n * responseFormat: ContactInfo,\n * });\n *\n * const result = await agent.invoke({\n * messages: [{\n * role: \"user\",\n * content: \"Extract: John Doe, john@example.com, (555) 123-4567\"\n * }],\n * });\n *\n * console.log(result.structuredResponse);\n * // { name: 'John Doe', email: 'john@example.com', phone: '(555) 123-4567' }\n * ```\n *\n * @example Streaming responses\n * ```ts\n * const stream = await agent.stream(\n * { messages: [{ role: \"user\", content: \"What's the weather?\" }] },\n * { streamMode: \"values\" }\n * );\n *\n * for await (const chunk of stream) {\n * // ...\n * }\n * ```\n */\n// Overload 1: With responseFormat as single InteropZodType\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<T, ContextSchema, InteropZodType<T>> & {\n responseFormat: InteropZodType<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, ContextSchema, TMiddleware>;\n\n// Overload 2: With responseFormat as array of InteropZodTypes (infers union type)\nexport function createAgent<\n T extends readonly InteropZodType<any>[],\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<\n ExtractZodArrayTypes<T> extends Record<string, any>\n ? ExtractZodArrayTypes<T>\n : Record<string, any>,\n ContextSchema,\n T\n > & {\n responseFormat: T;\n middleware?: TMiddleware;\n }\n): ReactAgent<\n ExtractZodArrayTypes<T> extends Record<string, any>\n ? ExtractZodArrayTypes<T>\n : Record<string, any>,\n ContextSchema,\n TMiddleware\n>;\n\n// Overload 3: With responseFormat as JsonSchemaFormat (JSON schema object)\nexport function createAgent<\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n ContextSchema,\n JsonSchemaFormat\n > & {\n responseFormat: JsonSchemaFormat;\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, ContextSchema, TMiddleware>;\n\n// Overload 4: With responseFormat as array of JsonSchemaFormat (JSON schema objects)\nexport function createAgent<\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n ContextSchema,\n JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat[];\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, ContextSchema, TMiddleware>;\n\n// Overload 4.5: With responseFormat as union of JsonSchemaFormat | JsonSchemaFormat[]\nexport function createAgent<\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n ContextSchema,\n JsonSchemaFormat | JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat | JsonSchemaFormat[];\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, ContextSchema, TMiddleware>;\n\n// Overload 5: With responseFormat as TypedToolStrategy (for union types from toolStrategy)\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<T, ContextSchema, TypedToolStrategy<T>> & {\n responseFormat: TypedToolStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, ContextSchema, TMiddleware>;\n\n// Overload 6: With responseFormat as single ToolStrategy instance\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<T, ContextSchema, ToolStrategy<T>> & {\n responseFormat: ToolStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, ContextSchema, TMiddleware>;\n\n// Overload 7: With responseFormat as ProviderStrategy\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<T, ContextSchema, ProviderStrategy<T>> & {\n responseFormat: ProviderStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, ContextSchema, TMiddleware>;\n\n// Overload 8: Without responseFormat property at all - with proper middleware state typing\nexport function createAgent<\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: Omit<\n CreateAgentParams<ResponseFormatUndefined, ContextSchema, never>,\n \"responseFormat\"\n > & { middleware?: TMiddleware }\n): ReactAgent<ResponseFormatUndefined, ContextSchema, TMiddleware>;\n\n// Overload 9: With responseFormat explicitly undefined\nexport function createAgent<\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: Omit<\n CreateAgentParams<ResponseFormatUndefined, ContextSchema, never>,\n \"responseFormat\"\n > & {\n responseFormat?: undefined;\n middleware?: TMiddleware;\n }\n): ReactAgent<ResponseFormatUndefined, ContextSchema, TMiddleware>;\n\n// Overload 10: For other ResponseFormat values (failsafe)\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any> = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<\n StructuredResponseFormat,\n ContextSchema,\n ResponseFormat\n > & {\n responseFormat: ResponseFormat;\n middleware?: TMiddleware;\n }\n): ReactAgent<StructuredResponseFormat, ContextSchema, TMiddleware>;\n\n// Implementation\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any>,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject,\n TMiddleware extends readonly AgentMiddleware<any, any, any>[] = []\n>(\n params: CreateAgentParams<StructuredResponseFormat, ContextSchema, any>\n): ReactAgent<StructuredResponseFormat, ContextSchema, TMiddleware> {\n return new ReactAgent(params);\n}\n\nexport { createMiddleware } from \"./middleware.js\";\n"],"mappings":";;;;AA6WA,SAAgB,YAKdA,QACkE;AAClE,QAAO,IAAIC,8BAAW;AACvB"}
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { ReactAgent } from "./ReactAgent.js";
|
|
2
|
-
import { createMiddleware } from "./middleware.js";
|
|
3
|
-
|
|
4
|
-
//#region src/agents/middlewareAgent/index.ts
|
|
5
|
-
function createAgent(params) {
|
|
6
|
-
return new ReactAgent(params);
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
//#endregion
|
|
10
|
-
export { createAgent };
|
|
11
|
-
//# sourceMappingURL=index.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["params: CreateAgentParams<StructuredResponseFormat, ContextSchema, any>"],"sources":["../../../src/agents/middlewareAgent/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodType,\n} from \"@langchain/core/utils/types\";\n\nimport type {\n AnyAnnotationRoot,\n ResponseFormatUndefined,\n} from \"../annotation.js\";\nimport type { CreateAgentParams, AgentMiddleware } from \"./types.js\";\nimport type { ExtractZodArrayTypes } from \"../types.js\";\nimport type {\n ToolStrategy,\n TypedToolStrategy,\n ProviderStrategy,\n ResponseFormat,\n JsonSchemaFormat,\n} from \"../responses.js\";\nimport { ReactAgent } from \"./ReactAgent.js\";\n\n/**\n * Creates a production-ready ReAct (Reasoning + Acting) agent that combines language models with tools\n * and middleware to create systems that can reason about tasks, decide which tools to use, and iteratively\n * work towards solutions.\n *\n * The agent follows the ReAct pattern, interleaving reasoning steps with tool calls to iteratively\n * work towards solutions. It can handle multiple tool calls in sequence or parallel, maintain state\n * across interactions, and provide auditable decision processes.\n *\n * ## Core Components\n *\n * ### Model\n * The reasoning engine can be specified as:\n * - **String identifier**: `\"openai:gpt-4o\"` for simple setup\n * - **Model instance**: Configured model object for full control\n * - **Dynamic function**: Select models at runtime based on state\n *\n * ### Tools\n * Tools give agents the ability to take actions:\n * - Pass an array of tools created with the `tool` function\n * - Or provide a configured `ToolNode` for custom error handling\n *\n * ### Prompt\n * Shape how your agent approaches tasks:\n * - String for simple instructions\n * - SystemMessage for structured prompts\n * - Function for dynamic prompts based on state\n *\n * ### Middleware\n * Middleware allows you to extend the agent's behavior:\n * - Add pre/post-model processing for context injection or validation\n * - Add dynamic control flows, e.g. terminate invocation or retries\n * - Add human-in-the-loop capabilities\n * - Add tool calls to the agent\n * - Add tool results to the agent\n *\n * ## Advanced Features\n *\n * - **Structured Output**: Use `responseFormat` with a Zod schema to get typed responses\n * - **Memory**: Extend the state schema to remember information across interactions\n * - **Streaming**: Get real-time updates as the agent processes\n *\n * @param options - Configuration options for the agent\n * @param options.llm - The language model as an instance of a chat model\n * @param options.model - The language model as a string identifier, see more in {@link https://docs.langchain.com/oss/javascript/langchain/models#basic-usage | Models}.\n * @param options.tools - Array of tools or configured ToolNode\n * @param options.prompt - System instructions (string, SystemMessage, or function)\n * @param options.responseFormat - Zod schema for structured output\n * @param options.stateSchema - Custom state schema for memory\n * @param options.middleware - Array of middleware for extending agent behavior, see more in {@link https://docs.langchain.com/oss/javascript/langchain/middleware | Middleware}.\n *\n * @returns A ReactAgent instance with `invoke` and `stream` methods\n *\n * @example Basic agent with tools\n * ```ts\n * import { createAgent, tool } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const search = tool(\n * ({ query }) => `Results for: ${query}`,\n * {\n * name: \"search\",\n * description: \"Search for information\",\n * schema: z.object({\n * query: z.string().describe(\"The search query\"),\n * })\n * }\n * );\n *\n * const agent = createAgent({\n * llm: \"openai:gpt-4o\",\n * tools: [search],\n * });\n *\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Search for ReAct agents\" }],\n * });\n * ```\n *\n * @example Structured output\n * ```ts\n * import { createAgent } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const ContactInfo = z.object({\n * name: z.string(),\n * email: z.string(),\n * phone: z.string(),\n * });\n *\n * const agent = createAgent({\n * llm: \"openai:gpt-4o\",\n * tools: [],\n * responseFormat: ContactInfo,\n * });\n *\n * const result = await agent.invoke({\n * messages: [{\n * role: \"user\",\n * content: \"Extract: John Doe, john@example.com, (555) 123-4567\"\n * }],\n * });\n *\n * console.log(result.structuredResponse);\n * // { name: 'John Doe', email: 'john@example.com', phone: '(555) 123-4567' }\n * ```\n *\n * @example Streaming responses\n * ```ts\n * const stream = await agent.stream(\n * { messages: [{ role: \"user\", content: \"What's the weather?\" }] },\n * { streamMode: \"values\" }\n * );\n *\n * for await (const chunk of stream) {\n * // ...\n * }\n * ```\n */\n// Overload 1: With responseFormat as single InteropZodType\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<T, ContextSchema, InteropZodType<T>> & {\n responseFormat: InteropZodType<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, ContextSchema, TMiddleware>;\n\n// Overload 2: With responseFormat as array of InteropZodTypes (infers union type)\nexport function createAgent<\n T extends readonly InteropZodType<any>[],\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<\n ExtractZodArrayTypes<T> extends Record<string, any>\n ? ExtractZodArrayTypes<T>\n : Record<string, any>,\n ContextSchema,\n T\n > & {\n responseFormat: T;\n middleware?: TMiddleware;\n }\n): ReactAgent<\n ExtractZodArrayTypes<T> extends Record<string, any>\n ? ExtractZodArrayTypes<T>\n : Record<string, any>,\n ContextSchema,\n TMiddleware\n>;\n\n// Overload 3: With responseFormat as JsonSchemaFormat (JSON schema object)\nexport function createAgent<\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n ContextSchema,\n JsonSchemaFormat\n > & {\n responseFormat: JsonSchemaFormat;\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, ContextSchema, TMiddleware>;\n\n// Overload 4: With responseFormat as array of JsonSchemaFormat (JSON schema objects)\nexport function createAgent<\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n ContextSchema,\n JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat[];\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, ContextSchema, TMiddleware>;\n\n// Overload 4.5: With responseFormat as union of JsonSchemaFormat | JsonSchemaFormat[]\nexport function createAgent<\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n ContextSchema,\n JsonSchemaFormat | JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat | JsonSchemaFormat[];\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, ContextSchema, TMiddleware>;\n\n// Overload 5: With responseFormat as TypedToolStrategy (for union types from toolStrategy)\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<T, ContextSchema, TypedToolStrategy<T>> & {\n responseFormat: TypedToolStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, ContextSchema, TMiddleware>;\n\n// Overload 6: With responseFormat as single ToolStrategy instance\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<T, ContextSchema, ToolStrategy<T>> & {\n responseFormat: ToolStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, ContextSchema, TMiddleware>;\n\n// Overload 7: With responseFormat as ProviderStrategy\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<T, ContextSchema, ProviderStrategy<T>> & {\n responseFormat: ProviderStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, ContextSchema, TMiddleware>;\n\n// Overload 8: Without responseFormat property at all - with proper middleware state typing\nexport function createAgent<\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: Omit<\n CreateAgentParams<ResponseFormatUndefined, ContextSchema, never>,\n \"responseFormat\"\n > & { middleware?: TMiddleware }\n): ReactAgent<ResponseFormatUndefined, ContextSchema, TMiddleware>;\n\n// Overload 9: With responseFormat explicitly undefined\nexport function createAgent<\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: Omit<\n CreateAgentParams<ResponseFormatUndefined, ContextSchema, never>,\n \"responseFormat\"\n > & {\n responseFormat?: undefined;\n middleware?: TMiddleware;\n }\n): ReactAgent<ResponseFormatUndefined, ContextSchema, TMiddleware>;\n\n// Overload 10: For other ResponseFormat values (failsafe)\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any> = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware<\n any,\n any,\n any\n >[] = readonly AgentMiddleware<any, any, any>[]\n>(\n params: CreateAgentParams<\n StructuredResponseFormat,\n ContextSchema,\n ResponseFormat\n > & {\n responseFormat: ResponseFormat;\n middleware?: TMiddleware;\n }\n): ReactAgent<StructuredResponseFormat, ContextSchema, TMiddleware>;\n\n// Implementation\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any>,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject,\n TMiddleware extends readonly AgentMiddleware<any, any, any>[] = []\n>(\n params: CreateAgentParams<StructuredResponseFormat, ContextSchema, any>\n): ReactAgent<StructuredResponseFormat, ContextSchema, TMiddleware> {\n return new ReactAgent(params);\n}\n\nexport { createMiddleware } from \"./middleware.js\";\n"],"mappings":";;;;AA6WA,SAAgB,YAKdA,QACkE;AAClE,QAAO,IAAI,WAAW;AACvB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"callLimit.cjs","names":["z","exceededHint: string[]","middlewareOptions?: ModelCallLimitMiddlewareConfig","createMiddleware","AIMessage"],"sources":["../../../../src/agents/middlewareAgent/middleware/callLimit.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { AIMessage } from \"@langchain/core/messages\";\nimport { InferInteropZodInput } from \"@langchain/core/utils/types\";\n\nimport { createMiddleware } from \"../middleware.js\";\n\nconst DEFAULT_EXIT_BEHAVIOR = \"end\";\n\nconst contextSchema = z.object({\n /**\n * The maximum number of model calls allowed per thread.\n */\n threadLimit: z.number().optional(),\n /**\n * The maximum number of model calls allowed per run.\n */\n runLimit: z.number().optional(),\n /**\n * The behavior to take when the limit is exceeded.\n * - \"throw\" will throw an error and stop the agent.\n * - \"end\" will end the agent.\n * @default \"end\"\n */\n exitBehavior: z.enum([\"throw\", \"end\"]).optional(),\n});\nexport type ModelCallLimitMiddlewareConfig = Partial<\n InferInteropZodInput<typeof contextSchema>\n>;\n\n/**\n * Error thrown when the model call limit is exceeded.\n *\n * @param threadLimit - The maximum number of model calls allowed per thread.\n * @param runLimit - The maximum number of model calls allowed per run.\n * @param threadCount - The number of model calls made at the thread level.\n * @param runCount - The number of model calls made at the run level.\n */\nclass ModelCallLimitMiddlewareError extends Error {\n constructor({\n threadLimit,\n runLimit,\n threadCount,\n runCount,\n }: {\n threadLimit?: number;\n runLimit?: number;\n threadCount?: number;\n runCount?: number;\n }) {\n const exceededHint: string[] = [];\n if (typeof threadLimit === \"number\" && typeof threadCount === \"number\") {\n exceededHint.push(\n `thread level call limit reached with ${threadCount} model calls`\n );\n }\n if (typeof runLimit === \"number\" && typeof runCount === \"number\") {\n exceededHint.push(\n `run level call limit reached with ${runCount} model calls`\n );\n }\n super(\n `Model call limits exceeded${\n exceededHint.length > 0 ? `: ${exceededHint.join(\", \")}` : \"\"\n }`\n );\n this.name = \"ModelCallLimitMiddlewareError\";\n }\n}\n\n/**\n * Creates a middleware to limit the number of model calls at both thread and run levels.\n *\n * This middleware helps prevent excessive model API calls by enforcing limits on how many\n * times the model can be invoked. It supports two types of limits:\n *\n * - **Thread-level limit**: Restricts the total number of model calls across an entire conversation thread\n * - **Run-level limit**: Restricts the number of model calls within a single agent run/invocation\n *\n * ## How It Works\n *\n * The middleware intercepts model requests before they are sent and checks the current call counts\n * against the configured limits. If either limit is exceeded, it throws a `ModelCallLimitMiddlewareError`\n * to stop execution and prevent further API calls.\n *\n * ## Use Cases\n *\n * - **Cost Control**: Prevent runaway costs from excessive model calls in production\n * - **Testing**: Ensure agents don't make too many calls during development/testing\n * - **Safety**: Limit potential infinite loops or recursive agent behaviors\n * - **Rate Limiting**: Enforce organizational policies on model usage per conversation\n *\n * @param middlewareOptions - Configuration options for the call limits\n * @param middlewareOptions.threadLimit - Maximum number of model calls allowed per thread (optional)\n * @param middlewareOptions.runLimit - Maximum number of model calls allowed per run (optional)\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @throws {ModelCallLimitMiddlewareError} When either the thread or run limit is exceeded\n *\n * @example\n * ```typescript\n * import { createAgent, modelCallLimitMiddleware } from \"langchain\";\n *\n * // Limit to 10 calls per thread and 3 calls per run\n * const agent = createAgent({\n * model: \"openai:gpt-4o-mini\",\n * tools: [myTool],\n * middleware: [\n * modelCallLimitMiddleware({\n * threadLimit: 10,\n * runLimit: 3\n * })\n * ]\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Limits can also be configured at runtime via context\n * const result = await agent.invoke(\n * { messages: [\"Hello\"] },\n * {\n * configurable: {\n * threadLimit: 5 // Override the default limit for this run\n * }\n * }\n * );\n * ```\n */\nexport function modelCallLimitMiddleware(\n middlewareOptions?: ModelCallLimitMiddlewareConfig\n) {\n return createMiddleware({\n name: \"ModelCallLimitMiddleware\",\n contextSchema,\n beforeModelJumpTo: [\"end\"],\n beforeModel: (state, runtime) => {\n const exitBehavior =\n runtime.context.exitBehavior ??\n middlewareOptions?.exitBehavior ??\n DEFAULT_EXIT_BEHAVIOR;\n const threadLimit =\n runtime.context.threadLimit ?? middlewareOptions?.threadLimit;\n const runLimit = runtime.context.runLimit ?? middlewareOptions?.runLimit;\n\n if (\n typeof threadLimit === \"number\" &&\n threadLimit <= runtime.threadLevelCallCount\n ) {\n const error = new ModelCallLimitMiddlewareError({\n threadLimit,\n threadCount: runtime.threadLevelCallCount,\n });\n if (exitBehavior === \"end\") {\n return {\n jumpTo: \"end\",\n messages: [new AIMessage(error.message)],\n };\n }\n\n throw error;\n }\n if (\n typeof runLimit === \"number\" &&\n runLimit <= runtime.runModelCallCount\n ) {\n const error = new ModelCallLimitMiddlewareError({\n runLimit,\n runCount: runtime.runModelCallCount,\n });\n if (exitBehavior === \"end\") {\n return {\n jumpTo: \"end\",\n messages: [new AIMessage(error.message)],\n };\n }\n\n throw error;\n }\n\n return state;\n },\n });\n}\n"],"mappings":";;;;;;AAMA,MAAM,wBAAwB;AAE9B,MAAM,gBAAgBA,SAAE,OAAO;CAI7B,aAAaA,SAAE,QAAQ,CAAC,UAAU;CAIlC,UAAUA,SAAE,QAAQ,CAAC,UAAU;CAO/B,cAAcA,SAAE,KAAK,CAAC,SAAS,KAAM,EAAC,CAAC,UAAU;AAClD,EAAC;;;;;;;;;AAaF,IAAM,gCAAN,cAA4C,MAAM;CAChD,YAAY,EACV,aACA,UACA,aACA,UAMD,EAAE;EACD,MAAMC,eAAyB,CAAE;AACjC,MAAI,OAAO,gBAAgB,YAAY,OAAO,gBAAgB,UAC5D,aAAa,KACX,CAAC,qCAAqC,EAAE,YAAY,YAAY,CAAC,CAClE;AAEH,MAAI,OAAO,aAAa,YAAY,OAAO,aAAa,UACtD,aAAa,KACX,CAAC,kCAAkC,EAAE,SAAS,YAAY,CAAC,CAC5D;EAEH,MACE,CAAC,0BAA0B,EACzB,aAAa,SAAS,IAAI,CAAC,EAAE,EAAE,aAAa,KAAK,KAAK,EAAE,GAAG,IAC3D,CACH;EACD,KAAK,OAAO;CACb;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DD,SAAgB,yBACdC,mBACA;AACA,QAAOC,oCAAiB;EACtB,MAAM;EACN;EACA,mBAAmB,CAAC,KAAM;EAC1B,aAAa,CAAC,OAAO,YAAY;GAC/B,MAAM,eACJ,QAAQ,QAAQ,gBAChB,mBAAmB,gBACnB;GACF,MAAM,cACJ,QAAQ,QAAQ,eAAe,mBAAmB;GACpD,MAAM,WAAW,QAAQ,QAAQ,YAAY,mBAAmB;AAEhE,OACE,OAAO,gBAAgB,YACvB,eAAe,QAAQ,sBACvB;IACA,MAAM,QAAQ,IAAI,8BAA8B;KAC9C;KACA,aAAa,QAAQ;IACtB;AACD,QAAI,iBAAiB,MACnB,QAAO;KACL,QAAQ;KACR,UAAU,CAAC,IAAIC,oCAAU,MAAM,QAAS;IACzC;AAGH,UAAM;GACP;AACD,OACE,OAAO,aAAa,YACpB,YAAY,QAAQ,mBACpB;IACA,MAAM,QAAQ,IAAI,8BAA8B;KAC9C;KACA,UAAU,QAAQ;IACnB;AACD,QAAI,iBAAiB,MACnB,QAAO;KACL,QAAQ;KACR,UAAU,CAAC,IAAIA,oCAAU,MAAM,QAAS;IACzC;AAGH,UAAM;GACP;AAED,UAAO;EACR;CACF,EAAC;AACH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"callLimit.d.cts","names":["z","InferInteropZodInput","contextSchema","ZodNumber","ZodOptional","ZodEnum","ZodTypeAny","ZodObject","ModelCallLimitMiddlewareConfig","Partial","modelCallLimitMiddleware","__index_js4","AgentMiddleware"],"sources":["../../../../src/agents/middlewareAgent/middleware/callLimit.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { InferInteropZodInput } from \"@langchain/core/utils/types\";\ndeclare const contextSchema: z.ZodObject<{\n /**\n * The maximum number of model calls allowed per thread.\n */\n threadLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * The maximum number of model calls allowed per run.\n */\n runLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * The behavior to take when the limit is exceeded.\n * - \"throw\" will throw an error and stop the agent.\n * - \"end\" will end the agent.\n * @default \"end\"\n */\n exitBehavior: z.ZodOptional<z.ZodEnum<[\"throw\", \"end\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"end\" | \"throw\" | undefined;\n}, {\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"end\" | \"throw\" | undefined;\n}>;\nexport type ModelCallLimitMiddlewareConfig = Partial<InferInteropZodInput<typeof contextSchema>>;\n/**\n * Creates a middleware to limit the number of model calls at both thread and run levels.\n *\n * This middleware helps prevent excessive model API calls by enforcing limits on how many\n * times the model can be invoked. It supports two types of limits:\n *\n * - **Thread-level limit**: Restricts the total number of model calls across an entire conversation thread\n * - **Run-level limit**: Restricts the number of model calls within a single agent run/invocation\n *\n * ## How It Works\n *\n * The middleware intercepts model requests before they are sent and checks the current call counts\n * against the configured limits. If either limit is exceeded, it throws a `ModelCallLimitMiddlewareError`\n * to stop execution and prevent further API calls.\n *\n * ## Use Cases\n *\n * - **Cost Control**: Prevent runaway costs from excessive model calls in production\n * - **Testing**: Ensure agents don't make too many calls during development/testing\n * - **Safety**: Limit potential infinite loops or recursive agent behaviors\n * - **Rate Limiting**: Enforce organizational policies on model usage per conversation\n *\n * @param middlewareOptions - Configuration options for the call limits\n * @param middlewareOptions.threadLimit - Maximum number of model calls allowed per thread (optional)\n * @param middlewareOptions.runLimit - Maximum number of model calls allowed per run (optional)\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @throws {ModelCallLimitMiddlewareError} When either the thread or run limit is exceeded\n *\n * @example\n * ```typescript\n * import { createAgent, modelCallLimitMiddleware } from \"langchain\";\n *\n * // Limit to 10 calls per thread and 3 calls per run\n * const agent = createAgent({\n * model: \"openai:gpt-4o-mini\",\n * tools: [myTool],\n * middleware: [\n * modelCallLimitMiddleware({\n * threadLimit: 10,\n * runLimit: 3\n * })\n * ]\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Limits can also be configured at runtime via context\n * const result = await agent.invoke(\n * { messages: [\"Hello\"] },\n * {\n * configurable: {\n * threadLimit: 5 // Override the default limit for this run\n * }\n * }\n * );\n * ```\n */\nexport declare function modelCallLimitMiddleware(middlewareOptions?: ModelCallLimitMiddlewareConfig): import(\"./index.js\").AgentMiddleware<undefined, z.ZodObject<{\n /**\n * The maximum number of model calls allowed per thread.\n */\n threadLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * The maximum number of model calls allowed per run.\n */\n runLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * The behavior to take when the limit is exceeded.\n * - \"throw\" will throw an error and stop the agent.\n * - \"end\" will end the agent.\n * @default \"end\"\n */\n exitBehavior: z.ZodOptional<z.ZodEnum<[\"throw\", \"end\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"end\" | \"throw\" | undefined;\n}, {\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"end\" | \"throw\" | undefined;\n}>, any>;\nexport {};\n"],"mappings":";;;;;cAEcE,eAAeF,CAAAA,CAAEO;;;AADoC;EAyBjE,WAAA,EApBeP,CAAAA,CAAEI,WAoBjB,CApB6BJ,CAAAA,CAAEG,SAoB/B,CAAA;EAAA;;;EAhBqC,QAAvBC,EAAFJ,CAAAA,CAAEI,WAAAA,CAAYJ,CAAAA,CAAEG,SAAdC,CAAAA;EAAW;;;;AARa;AAyBxC;EAA0C,YAAA,EAVxBJ,CAAAA,CAAEI,WAUsB,CAVVJ,CAAAA,CAAEK,OAUQ,CAAA,CAAA,OAAA,EAAA,KAAA,CAAA,CAAA,CAAA;CAAA,EAAA,OAAuCH,EATrEF,CAAAA,CAAEM,UASmEJ,EAAAA;EAAa,WAAzCD,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAoB,QAA5BQ,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAO,YAAA,CAAA,EAAA,KAAA,GAAA,OAAA,GAAA,SAAA;AA6DpD,CAAA,EAAA;EAAgD,WAAA,CAAA,EAAA,MAAA,GAAA,SAAA;EAAA,QAAqBD,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAA8B,YAIlEL,CAAAA,EAAAA,KAAAA,GAAAA,OAAAA,GAAAA,SAAAA;CAAS,CAAA;AAIdH,KArEhBQ,8BAAAA,GAAiCC,OAqEfN,CArEuBF,oBAqEvBE,CAAAA,OArEmDD,aAqEnDC,CAAAA,CAAAA;;;;;;;AAR4G;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAlHO,wBAAAA,qBAA6CF,iCAA4F,2BAAXR,CAAAA,CAAEO;;;;eAIvIP,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEG;;;;YAInBH,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEG;;;;;;;gBAOZH,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEK;YACtBL,CAAAA,CAAEM"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"callLimit.d.ts","names":["z","InferInteropZodInput","contextSchema","ZodNumber","ZodOptional","ZodEnum","ZodTypeAny","ZodObject","ModelCallLimitMiddlewareConfig","Partial","modelCallLimitMiddleware","__index_js5","AgentMiddleware"],"sources":["../../../../src/agents/middlewareAgent/middleware/callLimit.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { InferInteropZodInput } from \"@langchain/core/utils/types\";\ndeclare const contextSchema: z.ZodObject<{\n /**\n * The maximum number of model calls allowed per thread.\n */\n threadLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * The maximum number of model calls allowed per run.\n */\n runLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * The behavior to take when the limit is exceeded.\n * - \"throw\" will throw an error and stop the agent.\n * - \"end\" will end the agent.\n * @default \"end\"\n */\n exitBehavior: z.ZodOptional<z.ZodEnum<[\"throw\", \"end\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"end\" | \"throw\" | undefined;\n}, {\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"end\" | \"throw\" | undefined;\n}>;\nexport type ModelCallLimitMiddlewareConfig = Partial<InferInteropZodInput<typeof contextSchema>>;\n/**\n * Creates a middleware to limit the number of model calls at both thread and run levels.\n *\n * This middleware helps prevent excessive model API calls by enforcing limits on how many\n * times the model can be invoked. It supports two types of limits:\n *\n * - **Thread-level limit**: Restricts the total number of model calls across an entire conversation thread\n * - **Run-level limit**: Restricts the number of model calls within a single agent run/invocation\n *\n * ## How It Works\n *\n * The middleware intercepts model requests before they are sent and checks the current call counts\n * against the configured limits. If either limit is exceeded, it throws a `ModelCallLimitMiddlewareError`\n * to stop execution and prevent further API calls.\n *\n * ## Use Cases\n *\n * - **Cost Control**: Prevent runaway costs from excessive model calls in production\n * - **Testing**: Ensure agents don't make too many calls during development/testing\n * - **Safety**: Limit potential infinite loops or recursive agent behaviors\n * - **Rate Limiting**: Enforce organizational policies on model usage per conversation\n *\n * @param middlewareOptions - Configuration options for the call limits\n * @param middlewareOptions.threadLimit - Maximum number of model calls allowed per thread (optional)\n * @param middlewareOptions.runLimit - Maximum number of model calls allowed per run (optional)\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @throws {ModelCallLimitMiddlewareError} When either the thread or run limit is exceeded\n *\n * @example\n * ```typescript\n * import { createAgent, modelCallLimitMiddleware } from \"langchain\";\n *\n * // Limit to 10 calls per thread and 3 calls per run\n * const agent = createAgent({\n * model: \"openai:gpt-4o-mini\",\n * tools: [myTool],\n * middleware: [\n * modelCallLimitMiddleware({\n * threadLimit: 10,\n * runLimit: 3\n * })\n * ]\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Limits can also be configured at runtime via context\n * const result = await agent.invoke(\n * { messages: [\"Hello\"] },\n * {\n * configurable: {\n * threadLimit: 5 // Override the default limit for this run\n * }\n * }\n * );\n * ```\n */\nexport declare function modelCallLimitMiddleware(middlewareOptions?: ModelCallLimitMiddlewareConfig): import(\"./index.js\").AgentMiddleware<undefined, z.ZodObject<{\n /**\n * The maximum number of model calls allowed per thread.\n */\n threadLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * The maximum number of model calls allowed per run.\n */\n runLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * The behavior to take when the limit is exceeded.\n * - \"throw\" will throw an error and stop the agent.\n * - \"end\" will end the agent.\n * @default \"end\"\n */\n exitBehavior: z.ZodOptional<z.ZodEnum<[\"throw\", \"end\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"end\" | \"throw\" | undefined;\n}, {\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"end\" | \"throw\" | undefined;\n}>, any>;\nexport {};\n"],"mappings":";;;;;cAEcE,eAAeF,CAAAA,CAAEO;;;AADoC;EAyBjE,WAAA,EApBeP,CAAAA,CAAEI,WAoBjB,CApB6BJ,CAAAA,CAAEG,SAoB/B,CAAA;EAAA;;;EAhBqC,QAAvBC,EAAFJ,CAAAA,CAAEI,WAAAA,CAAYJ,CAAAA,CAAEG,SAAdC,CAAAA;EAAW;;;;AARa;AAyBxC;EAA0C,YAAA,EAVxBJ,CAAAA,CAAEI,WAUsB,CAVVJ,CAAAA,CAAEK,OAUQ,CAAA,CAAA,OAAA,EAAA,KAAA,CAAA,CAAA,CAAA;CAAA,EAAA,OAAuCH,EATrEF,CAAAA,CAAEM,UASmEJ,EAAAA;EAAa,WAAzCD,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAoB,QAA5BQ,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAO,YAAA,CAAA,EAAA,KAAA,GAAA,OAAA,GAAA,SAAA;AA6DpD,CAAA,EAAA;EAAgD,WAAA,CAAA,EAAA,MAAA,GAAA,SAAA;EAAA,QAAqBD,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAA8B,YAIlEL,CAAAA,EAAAA,KAAAA,GAAAA,OAAAA,GAAAA,SAAAA;CAAS,CAAA;AAIdH,KArEhBQ,8BAAAA,GAAiCC,OAqEfN,CArEuBF,oBAqEvBE,CAAAA,OArEmDD,aAqEnDC,CAAAA,CAAAA;;;;;;;AAR4G;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAlHO,wBAAAA,qBAA6CF,iCAA4F,2BAAXR,CAAAA,CAAEO;;;;eAIvIP,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEG;;;;YAInBH,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEG;;;;;;;gBAOZH,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEK;YACtBL,CAAAA,CAAEM"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"callLimit.js","names":["exceededHint: string[]","middlewareOptions?: ModelCallLimitMiddlewareConfig"],"sources":["../../../../src/agents/middlewareAgent/middleware/callLimit.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { AIMessage } from \"@langchain/core/messages\";\nimport { InferInteropZodInput } from \"@langchain/core/utils/types\";\n\nimport { createMiddleware } from \"../middleware.js\";\n\nconst DEFAULT_EXIT_BEHAVIOR = \"end\";\n\nconst contextSchema = z.object({\n /**\n * The maximum number of model calls allowed per thread.\n */\n threadLimit: z.number().optional(),\n /**\n * The maximum number of model calls allowed per run.\n */\n runLimit: z.number().optional(),\n /**\n * The behavior to take when the limit is exceeded.\n * - \"throw\" will throw an error and stop the agent.\n * - \"end\" will end the agent.\n * @default \"end\"\n */\n exitBehavior: z.enum([\"throw\", \"end\"]).optional(),\n});\nexport type ModelCallLimitMiddlewareConfig = Partial<\n InferInteropZodInput<typeof contextSchema>\n>;\n\n/**\n * Error thrown when the model call limit is exceeded.\n *\n * @param threadLimit - The maximum number of model calls allowed per thread.\n * @param runLimit - The maximum number of model calls allowed per run.\n * @param threadCount - The number of model calls made at the thread level.\n * @param runCount - The number of model calls made at the run level.\n */\nclass ModelCallLimitMiddlewareError extends Error {\n constructor({\n threadLimit,\n runLimit,\n threadCount,\n runCount,\n }: {\n threadLimit?: number;\n runLimit?: number;\n threadCount?: number;\n runCount?: number;\n }) {\n const exceededHint: string[] = [];\n if (typeof threadLimit === \"number\" && typeof threadCount === \"number\") {\n exceededHint.push(\n `thread level call limit reached with ${threadCount} model calls`\n );\n }\n if (typeof runLimit === \"number\" && typeof runCount === \"number\") {\n exceededHint.push(\n `run level call limit reached with ${runCount} model calls`\n );\n }\n super(\n `Model call limits exceeded${\n exceededHint.length > 0 ? `: ${exceededHint.join(\", \")}` : \"\"\n }`\n );\n this.name = \"ModelCallLimitMiddlewareError\";\n }\n}\n\n/**\n * Creates a middleware to limit the number of model calls at both thread and run levels.\n *\n * This middleware helps prevent excessive model API calls by enforcing limits on how many\n * times the model can be invoked. It supports two types of limits:\n *\n * - **Thread-level limit**: Restricts the total number of model calls across an entire conversation thread\n * - **Run-level limit**: Restricts the number of model calls within a single agent run/invocation\n *\n * ## How It Works\n *\n * The middleware intercepts model requests before they are sent and checks the current call counts\n * against the configured limits. If either limit is exceeded, it throws a `ModelCallLimitMiddlewareError`\n * to stop execution and prevent further API calls.\n *\n * ## Use Cases\n *\n * - **Cost Control**: Prevent runaway costs from excessive model calls in production\n * - **Testing**: Ensure agents don't make too many calls during development/testing\n * - **Safety**: Limit potential infinite loops or recursive agent behaviors\n * - **Rate Limiting**: Enforce organizational policies on model usage per conversation\n *\n * @param middlewareOptions - Configuration options for the call limits\n * @param middlewareOptions.threadLimit - Maximum number of model calls allowed per thread (optional)\n * @param middlewareOptions.runLimit - Maximum number of model calls allowed per run (optional)\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @throws {ModelCallLimitMiddlewareError} When either the thread or run limit is exceeded\n *\n * @example\n * ```typescript\n * import { createAgent, modelCallLimitMiddleware } from \"langchain\";\n *\n * // Limit to 10 calls per thread and 3 calls per run\n * const agent = createAgent({\n * model: \"openai:gpt-4o-mini\",\n * tools: [myTool],\n * middleware: [\n * modelCallLimitMiddleware({\n * threadLimit: 10,\n * runLimit: 3\n * })\n * ]\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Limits can also be configured at runtime via context\n * const result = await agent.invoke(\n * { messages: [\"Hello\"] },\n * {\n * configurable: {\n * threadLimit: 5 // Override the default limit for this run\n * }\n * }\n * );\n * ```\n */\nexport function modelCallLimitMiddleware(\n middlewareOptions?: ModelCallLimitMiddlewareConfig\n) {\n return createMiddleware({\n name: \"ModelCallLimitMiddleware\",\n contextSchema,\n beforeModelJumpTo: [\"end\"],\n beforeModel: (state, runtime) => {\n const exitBehavior =\n runtime.context.exitBehavior ??\n middlewareOptions?.exitBehavior ??\n DEFAULT_EXIT_BEHAVIOR;\n const threadLimit =\n runtime.context.threadLimit ?? middlewareOptions?.threadLimit;\n const runLimit = runtime.context.runLimit ?? middlewareOptions?.runLimit;\n\n if (\n typeof threadLimit === \"number\" &&\n threadLimit <= runtime.threadLevelCallCount\n ) {\n const error = new ModelCallLimitMiddlewareError({\n threadLimit,\n threadCount: runtime.threadLevelCallCount,\n });\n if (exitBehavior === \"end\") {\n return {\n jumpTo: \"end\",\n messages: [new AIMessage(error.message)],\n };\n }\n\n throw error;\n }\n if (\n typeof runLimit === \"number\" &&\n runLimit <= runtime.runModelCallCount\n ) {\n const error = new ModelCallLimitMiddlewareError({\n runLimit,\n runCount: runtime.runModelCallCount,\n });\n if (exitBehavior === \"end\") {\n return {\n jumpTo: \"end\",\n messages: [new AIMessage(error.message)],\n };\n }\n\n throw error;\n }\n\n return state;\n },\n });\n}\n"],"mappings":";;;;;AAMA,MAAM,wBAAwB;AAE9B,MAAM,g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AQ,mBACpB;IACA,MAAM,QAAQ,IAAI,8BAA8B;KAC9C;KACA,UAAU,QAAQ;IACnB;AACD,QAAI,iBAAiB,MACnB,QAAO;KACL,QAAQ;KACR,UAAU,CAAC,IAAI,UAAU,MAAM,QAAS;IACzC;AAGH,UAAM;GACP;AAED,UAAO;EACR;CACF,EAAC;AACH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"contextEditing.cjs","names":["config: ClearToolUsesEditConfig","params: {\n tokens: number;\n messages: BaseMessage[];\n countTokens: TokenCounter;\n }","candidates: Array<{ idx: number; msg: ToolMessage }>","ToolMessage","#findAIMessageForToolCall","#buildClearedToolInputMessage","previousMessages: BaseMessage[]","toolCallId: string","AIMessage","message: AIMessage","config: ContextEditingMiddlewareConfig","createMiddleware","request: ModelRequest","SystemMessage","countTokens: TokenCounter","countTokensApproximately","messages: BaseMessage[]"],"sources":["../../../../src/agents/middlewareAgent/middleware/contextEditing.ts"],"sourcesContent":["/**\n * Context editing middleware.\n *\n * This middleware mirrors Anthropic's context editing capabilities by clearing\n * older tool results once the conversation grows beyond a configurable token\n * threshold. The implementation is intentionally model-agnostic so it can be used\n * with any LangChain chat model.\n */\n\nimport type { BaseMessage } from \"@langchain/core/messages\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport {\n AIMessage,\n ToolMessage,\n SystemMessage,\n} from \"@langchain/core/messages\";\n\nimport { countTokensApproximately } from \"./utils.js\";\nimport { createMiddleware } from \"../middleware.js\";\nimport type { ModelRequest } from \"../types.js\";\n\nconst DEFAULT_TOOL_PLACEHOLDER = \"[cleared]\";\n\n/**\n * Function type for counting tokens in a sequence of messages.\n */\nexport type TokenCounter = (\n messages: BaseMessage[]\n) => number | Promise<number>;\n\n/**\n * Protocol describing a context editing strategy.\n *\n * Implement this interface to create custom strategies for managing\n * conversation context size. The `apply` method should modify the\n * messages array in-place and return the updated token count.\n *\n * @example\n * ```ts\n * import { SystemMessage } from \"langchain\";\n *\n * class RemoveOldSystemMessages implements ContextEdit {\n * async apply({ tokens, messages, countTokens }) {\n * // Remove old system messages if over limit\n * if (tokens > 50000) {\n * messages = messages.filter(SystemMessage.isInstance);\n * return await countTokens(messages);\n * }\n * return tokens;\n * }\n * }\n * ```\n */\nexport interface ContextEdit {\n /**\n * Apply an edit to the message list, returning the new token count.\n *\n * This method should:\n * 1. Check if editing is needed based on `tokens` parameter\n * 2. Modify the `messages` array in-place (if needed)\n * 3. Return the new token count after modifications\n *\n * @param params - Parameters for the editing operation\n * @returns The updated token count after applying edits\n */\n apply(params: {\n /**\n * Current token count of all messages\n */\n tokens: number;\n /**\n * Array of messages to potentially edit (modify in-place)\n */\n messages: BaseMessage[];\n /**\n * Function to count tokens in a message array\n */\n countTokens: TokenCounter;\n }): number | Promise<number>;\n}\n\n/**\n * Configuration for clearing tool outputs when token limits are exceeded.\n */\nexport interface ClearToolUsesEditConfig {\n /**\n * Token count that triggers the edit.\n * @default 100000\n */\n triggerTokens?: number;\n\n /**\n * Minimum number of tokens to reclaim when the edit runs.\n * @default 0\n */\n clearAtLeast?: number;\n\n /**\n * Number of most recent tool results that must be preserved.\n * @default 3\n */\n keep?: number;\n\n /**\n * Whether to clear the originating tool call parameters on the AI message.\n * @default false\n */\n clearToolInputs?: boolean;\n\n /**\n * List of tool names to exclude from clearing.\n * @default []\n */\n excludeTools?: string[];\n\n /**\n * Placeholder text inserted for cleared tool outputs.\n * @default \"[cleared]\"\n */\n placeholder?: string;\n}\n\n/**\n * Strategy for clearing tool outputs when token limits are exceeded.\n *\n * This strategy mirrors Anthropic's `clear_tool_uses_20250919` behavior by\n * replacing older tool results with a placeholder text when the conversation\n * grows too large. It preserves the most recent tool results and can exclude\n * specific tools from being cleared.\n *\n * @example\n * ```ts\n * import { ClearToolUsesEdit } from \"langchain\";\n *\n * const edit = new ClearToolUsesEdit({\n * triggerTokens: 100000, // Start clearing at 100K tokens\n * clearAtLeast: 0, // Clear as much as needed\n * keep: 3, // Always keep 3 most recent results\n * excludeTools: [\"important\"], // Never clear \"important\" tool\n * clearToolInputs: false, // Keep tool call arguments\n * placeholder: \"[cleared]\", // Replacement text\n * });\n * ```\n */\nexport class ClearToolUsesEdit implements ContextEdit {\n triggerTokens: number;\n clearAtLeast: number;\n keep: number;\n clearToolInputs: boolean;\n excludeTools: Set<string>;\n placeholder: string;\n\n constructor(config: ClearToolUsesEditConfig = {}) {\n this.triggerTokens = config.triggerTokens ?? 100000;\n this.clearAtLeast = config.clearAtLeast ?? 0;\n this.keep = config.keep ?? 3;\n this.clearToolInputs = config.clearToolInputs ?? false;\n this.excludeTools = new Set(config.excludeTools ?? []);\n this.placeholder = config.placeholder ?? DEFAULT_TOOL_PLACEHOLDER;\n }\n\n async apply(params: {\n tokens: number;\n messages: BaseMessage[];\n countTokens: TokenCounter;\n }): Promise<number> {\n const { tokens, messages, countTokens } = params;\n\n if (tokens <= this.triggerTokens) {\n return tokens;\n }\n\n /**\n * Find all tool message candidates with their actual indices in the messages array\n */\n const candidates: Array<{ idx: number; msg: ToolMessage }> = [];\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n if (ToolMessage.isInstance(msg)) {\n candidates.push({ idx: i, msg });\n }\n }\n\n /**\n * Keep the most recent tool messages\n */\n const candidatesToClear =\n this.keep >= candidates.length\n ? []\n : this.keep > 0\n ? candidates.slice(0, -this.keep)\n : candidates;\n\n let clearedTokens = 0;\n for (const { idx, msg: toolMessage } of candidatesToClear) {\n /**\n * Stop if we've cleared enough tokens\n */\n if (this.clearAtLeast > 0 && clearedTokens >= this.clearAtLeast) {\n break;\n }\n\n /**\n * Skip if already cleared\n */\n const contextEditing = toolMessage.response_metadata?.context_editing as\n | { cleared?: boolean }\n | undefined;\n if (contextEditing?.cleared) {\n continue;\n }\n\n /**\n * Find the corresponding AI message\n */\n const aiMessage = this.#findAIMessageForToolCall(\n messages.slice(0, idx),\n toolMessage.tool_call_id\n );\n\n if (!aiMessage) {\n continue;\n }\n\n /**\n * Find the corresponding tool call\n */\n const toolCall = aiMessage.tool_calls?.find(\n (call) => call.id === toolMessage.tool_call_id\n );\n\n if (!toolCall) {\n continue;\n }\n\n /**\n * Skip if tool is excluded\n */\n const toolName = toolMessage.name || toolCall.name;\n if (this.excludeTools.has(toolName)) {\n continue;\n }\n\n /**\n * Clear the tool message\n */\n messages[idx] = new ToolMessage({\n tool_call_id: toolMessage.tool_call_id,\n content: this.placeholder,\n name: toolMessage.name,\n artifact: undefined,\n response_metadata: {\n ...toolMessage.response_metadata,\n context_editing: {\n cleared: true,\n strategy: \"clear_tool_uses\",\n },\n },\n });\n\n /**\n * Optionally clear the tool inputs\n */\n if (this.clearToolInputs) {\n const aiMsgIdx = messages.indexOf(aiMessage);\n if (aiMsgIdx >= 0) {\n messages[aiMsgIdx] = this.#buildClearedToolInputMessage(\n aiMessage,\n toolMessage.tool_call_id\n );\n }\n }\n\n /**\n * Recalculate tokens\n */\n const newTokenCount = await countTokens(messages);\n clearedTokens = Math.max(0, tokens - newTokenCount);\n }\n\n return tokens - clearedTokens;\n }\n\n #findAIMessageForToolCall(\n previousMessages: BaseMessage[],\n toolCallId: string\n ): AIMessage | null {\n // Search backwards through previous messages\n for (let i = previousMessages.length - 1; i >= 0; i--) {\n const msg = previousMessages[i];\n if (AIMessage.isInstance(msg)) {\n const hasToolCall = msg.tool_calls?.some(\n (call) => call.id === toolCallId\n );\n if (hasToolCall) {\n return msg;\n }\n }\n }\n return null;\n }\n\n #buildClearedToolInputMessage(\n message: AIMessage,\n toolCallId: string\n ): AIMessage {\n const updatedToolCalls = message.tool_calls?.map((toolCall) => {\n if (toolCall.id === toolCallId) {\n return { ...toolCall, args: {} };\n }\n return toolCall;\n });\n\n const metadata = { ...message.response_metadata };\n const contextEntry = {\n ...(metadata.context_editing as Record<string, unknown>),\n };\n\n const clearedIds = new Set<string>(\n contextEntry.cleared_tool_inputs as string[] | undefined\n );\n clearedIds.add(toolCallId);\n contextEntry.cleared_tool_inputs = Array.from(clearedIds).sort();\n metadata.context_editing = contextEntry;\n\n return new AIMessage({\n content: message.content,\n tool_calls: updatedToolCalls,\n response_metadata: metadata,\n id: message.id,\n name: message.name,\n additional_kwargs: message.additional_kwargs,\n });\n }\n}\n\n/**\n * Configuration for the Context Editing Middleware.\n */\nexport interface ContextEditingMiddlewareConfig {\n /**\n * Sequence of edit strategies to apply. Defaults to a single\n * ClearToolUsesEdit mirroring Anthropic defaults.\n */\n edits?: ContextEdit[];\n\n /**\n * Whether to use approximate token counting (faster, less accurate)\n * or exact counting implemented by the chat model (potentially slower, more accurate).\n * Currently only OpenAI models support exact counting.\n * @default \"approx\"\n */\n tokenCountMethod?: \"approx\" | \"model\";\n}\n\n/**\n * Middleware that automatically prunes tool results to manage context size.\n *\n * This middleware applies a sequence of edits when the total input token count\n * exceeds configured thresholds. By default, it uses the `ClearToolUsesEdit` strategy\n * which mirrors Anthropic's `clear_tool_uses_20250919` behaviour by clearing older\n * tool results once the conversation exceeds 100,000 tokens.\n *\n * ## Basic Usage\n *\n * Use the middleware with default settings to automatically manage context:\n *\n * @example Basic usage with defaults\n * ```ts\n * import { contextEditingMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * tools: [searchTool, calculatorTool],\n * middleware: [\n * contextEditingMiddleware(),\n * ],\n * });\n * ```\n *\n * The default configuration:\n * - Triggers when context exceeds **100,000 tokens**\n * - Keeps the **3 most recent** tool results\n * - Uses **approximate token counting** (fast)\n * - Does not clear tool call arguments\n *\n * ## Custom Configuration\n *\n * Customize the clearing behavior with `ClearToolUsesEdit`:\n *\n * @example Custom ClearToolUsesEdit configuration\n * ```ts\n * import { contextEditingMiddleware, ClearToolUsesEdit } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * tools: [searchTool, calculatorTool],\n * middleware: [\n * contextEditingMiddleware({\n * edits: [\n * new ClearToolUsesEdit({\n * triggerTokens: 50000, // Clear when exceeding 50K tokens\n * clearAtLeast: 1000, // Reclaim at least 1K tokens\n * keep: 5, // Keep 5 most recent tool results\n * excludeTools: [\"search\"], // Never clear search results\n * clearToolInputs: true, // Also clear tool call arguments\n * }),\n * ],\n * tokenCountMethod: \"approx\", // Use approximate counting (or \"model\")\n * }),\n * ],\n * });\n * ```\n *\n * ## Custom Editing Strategies\n *\n * Implement your own context editing strategy by creating a class that\n * implements the `ContextEdit` interface:\n *\n * @example Custom editing strategy\n * ```ts\n * import { contextEditingMiddleware, type ContextEdit, type TokenCounter } from \"langchain\";\n * import type { BaseMessage } from \"@langchain/core/messages\";\n *\n * class CustomEdit implements ContextEdit {\n * async apply(params: {\n * tokens: number;\n * messages: BaseMessage[];\n * countTokens: TokenCounter;\n * }): Promise<number> {\n * // Implement your custom editing logic here\n * // and apply it to the messages array, then\n * // return the new token count after edits\n * return countTokens(messages);\n * }\n * }\n * ```\n *\n * @param config - Configuration options for the middleware\n * @returns A middleware instance that can be used with `createAgent`\n */\nexport function contextEditingMiddleware(\n config: ContextEditingMiddlewareConfig = {}\n) {\n const edits = config.edits ?? [new ClearToolUsesEdit()];\n const tokenCountMethod = config.tokenCountMethod ?? \"approx\";\n\n return createMiddleware({\n name: \"ContextEditingMiddleware\",\n modifyModelRequest: async (request: ModelRequest) => {\n if (!request.messages || request.messages.length === 0) {\n return request;\n }\n\n /**\n * Use model's token counting method\n */\n const systemMsg = request.systemPrompt\n ? [new SystemMessage(request.systemPrompt)]\n : [];\n\n const countTokens: TokenCounter =\n tokenCountMethod === \"approx\"\n ? countTokensApproximately\n : async (messages: BaseMessage[]): Promise<number> => {\n const allMessages = [...systemMsg, ...messages];\n\n /**\n * Check if model has getNumTokensFromMessages method\n * currently only OpenAI models have this method\n */\n if (\"getNumTokensFromMessages\" in request.model) {\n return (\n request.model as LanguageModelLike & {\n getNumTokensFromMessages: (\n messages: BaseMessage[]\n ) => Promise<{\n totalCount: number;\n countPerMessage: number[];\n }>;\n }\n )\n .getNumTokensFromMessages(allMessages)\n .then(({ totalCount }) => totalCount);\n }\n\n throw new Error(\n `Model \"${request.model.getName()}\" does not support token counting`\n );\n };\n\n let tokens = await countTokens(request.messages);\n\n /**\n * Apply each edit in sequence\n */\n for (const edit of edits) {\n tokens = await edit.apply({\n tokens,\n messages: request.messages,\n countTokens,\n });\n }\n\n return request;\n },\n });\n}\n"],"mappings":";;;;;;AAqBA,MAAM,2BAA2B;;;;;;;;;;;;;;;;;;;;;;;AA2HjC,IAAa,oBAAb,MAAsD;CACpD;CACA;CACA;CACA;CACA;CACA;CAEA,YAAYA,SAAkC,CAAE,GAAE;EAChD,KAAK,gBAAgB,OAAO,iBAAiB;EAC7C,KAAK,eAAe,OAAO,gBAAgB;EAC3C,KAAK,OAAO,OAAO,QAAQ;EAC3B,KAAK,kBAAkB,OAAO,mBAAmB;EACjD,KAAK,eAAe,IAAI,IAAI,OAAO,gBAAgB,CAAE;EACrD,KAAK,cAAc,OAAO,eAAe;CAC1C;CAED,MAAM,MAAMC,QAIQ;EAClB,MAAM,EAAE,QAAQ,UAAU,aAAa,GAAG;AAE1C,MAAI,UAAU,KAAK,cACjB,QAAO;;;;EAMT,MAAMC,aAAuD,CAAE;AAC/D,OAAK,IAAI,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;GACxC,MAAM,MAAM,SAAS;AACrB,OAAIC,sCAAY,WAAW,IAAI,EAC7B,WAAW,KAAK;IAAE,KAAK;IAAG;GAAK,EAAC;EAEnC;;;;EAKD,MAAM,oBACJ,KAAK,QAAQ,WAAW,SACpB,CAAE,IACF,KAAK,OAAO,IACZ,WAAW,MAAM,GAAG,CAAC,KAAK,KAAK,GAC/B;EAEN,IAAI,gBAAgB;AACpB,OAAK,MAAM,EAAE,KAAK,KAAK,aAAa,IAAI,mBAAmB;;;;AAIzD,OAAI,KAAK,eAAe,KAAK,iBAAiB,KAAK,aACjD;;;;GAMF,MAAM,iBAAiB,YAAY,mBAAmB;AAGtD,OAAI,gBAAgB,QAClB;;;;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 @@
|
|
|
1
|
-
{"version":3,"file":"contextEditing.d.cts","names":["BaseMessage","TokenCounter","Promise","ContextEdit","ClearToolUsesEditConfig","ClearToolUsesEdit","Set","ContextEditingMiddlewareConfig","contextEditingMiddleware","__index_js2","AgentMiddleware"],"sources":["../../../../src/agents/middlewareAgent/middleware/contextEditing.d.ts"],"sourcesContent":["/**\n * Context editing middleware.\n *\n * This middleware mirrors Anthropic's context editing capabilities by clearing\n * older tool results once the conversation grows beyond a configurable token\n * threshold. The implementation is intentionally model-agnostic so it can be used\n * with any LangChain chat model.\n */\nimport type { BaseMessage } from \"@langchain/core/messages\";\n/**\n * Function type for counting tokens in a sequence of messages.\n */\nexport type TokenCounter = (messages: BaseMessage[]) => number | Promise<number>;\n/**\n * Protocol describing a context editing strategy.\n *\n * Implement this interface to create custom strategies for managing\n * conversation context size. The `apply` method should modify the\n * messages array in-place and return the updated token count.\n *\n * @example\n * ```ts\n * import { SystemMessage } from \"langchain\";\n *\n * class RemoveOldSystemMessages implements ContextEdit {\n * async apply({ tokens, messages, countTokens }) {\n * // Remove old system messages if over limit\n * if (tokens > 50000) {\n * messages = messages.filter(SystemMessage.isInstance);\n * return await countTokens(messages);\n * }\n * return tokens;\n * }\n * }\n * ```\n */\nexport interface ContextEdit {\n /**\n * Apply an edit to the message list, returning the new token count.\n *\n * This method should:\n * 1. Check if editing is needed based on `tokens` parameter\n * 2. Modify the `messages` array in-place (if needed)\n * 3. Return the new token count after modifications\n *\n * @param params - Parameters for the editing operation\n * @returns The updated token count after applying edits\n */\n apply(params: {\n /**\n * Current token count of all messages\n */\n tokens: number;\n /**\n * Array of messages to potentially edit (modify in-place)\n */\n messages: BaseMessage[];\n /**\n * Function to count tokens in a message array\n */\n countTokens: TokenCounter;\n }): number | Promise<number>;\n}\n/**\n * Configuration for clearing tool outputs when token limits are exceeded.\n */\nexport interface ClearToolUsesEditConfig {\n /**\n * Token count that triggers the edit.\n * @default 100000\n */\n triggerTokens?: number;\n /**\n * Minimum number of tokens to reclaim when the edit runs.\n * @default 0\n */\n clearAtLeast?: number;\n /**\n * Number of most recent tool results that must be preserved.\n * @default 3\n */\n keep?: number;\n /**\n * Whether to clear the originating tool call parameters on the AI message.\n * @default false\n */\n clearToolInputs?: boolean;\n /**\n * List of tool names to exclude from clearing.\n * @default []\n */\n excludeTools?: string[];\n /**\n * Placeholder text inserted for cleared tool outputs.\n * @default \"[cleared]\"\n */\n placeholder?: string;\n}\n/**\n * Strategy for clearing tool outputs when token limits are exceeded.\n *\n * This strategy mirrors Anthropic's `clear_tool_uses_20250919` behavior by\n * replacing older tool results with a placeholder text when the conversation\n * grows too large. It preserves the most recent tool results and can exclude\n * specific tools from being cleared.\n *\n * @example\n * ```ts\n * import { ClearToolUsesEdit } from \"langchain\";\n *\n * const edit = new ClearToolUsesEdit({\n * triggerTokens: 100000, // Start clearing at 100K tokens\n * clearAtLeast: 0, // Clear as much as needed\n * keep: 3, // Always keep 3 most recent results\n * excludeTools: [\"important\"], // Never clear \"important\" tool\n * clearToolInputs: false, // Keep tool call arguments\n * placeholder: \"[cleared]\", // Replacement text\n * });\n * ```\n */\nexport declare class ClearToolUsesEdit implements ContextEdit {\n #private;\n triggerTokens: number;\n clearAtLeast: number;\n keep: number;\n clearToolInputs: boolean;\n excludeTools: Set<string>;\n placeholder: string;\n constructor(config?: ClearToolUsesEditConfig);\n apply(params: {\n tokens: number;\n messages: BaseMessage[];\n countTokens: TokenCounter;\n }): Promise<number>;\n}\n/**\n * Configuration for the Context Editing Middleware.\n */\nexport interface ContextEditingMiddlewareConfig {\n /**\n * Sequence of edit strategies to apply. Defaults to a single\n * ClearToolUsesEdit mirroring Anthropic defaults.\n */\n edits?: ContextEdit[];\n /**\n * Whether to use approximate token counting (faster, less accurate)\n * or exact counting implemented by the chat model (potentially slower, more accurate).\n * Currently only OpenAI models support exact counting.\n * @default \"approx\"\n */\n tokenCountMethod?: \"approx\" | \"model\";\n}\n/**\n * Middleware that automatically prunes tool results to manage context size.\n *\n * This middleware applies a sequence of edits when the total input token count\n * exceeds configured thresholds. By default, it uses the `ClearToolUsesEdit` strategy\n * which mirrors Anthropic's `clear_tool_uses_20250919` behaviour by clearing older\n * tool results once the conversation exceeds 100,000 tokens.\n *\n * ## Basic Usage\n *\n * Use the middleware with default settings to automatically manage context:\n *\n * @example Basic usage with defaults\n * ```ts\n * import { contextEditingMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * tools: [searchTool, calculatorTool],\n * middleware: [\n * contextEditingMiddleware(),\n * ],\n * });\n * ```\n *\n * The default configuration:\n * - Triggers when context exceeds **100,000 tokens**\n * - Keeps the **3 most recent** tool results\n * - Uses **approximate token counting** (fast)\n * - Does not clear tool call arguments\n *\n * ## Custom Configuration\n *\n * Customize the clearing behavior with `ClearToolUsesEdit`:\n *\n * @example Custom ClearToolUsesEdit configuration\n * ```ts\n * import { contextEditingMiddleware, ClearToolUsesEdit } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * tools: [searchTool, calculatorTool],\n * middleware: [\n * contextEditingMiddleware({\n * edits: [\n * new ClearToolUsesEdit({\n * triggerTokens: 50000, // Clear when exceeding 50K tokens\n * clearAtLeast: 1000, // Reclaim at least 1K tokens\n * keep: 5, // Keep 5 most recent tool results\n * excludeTools: [\"search\"], // Never clear search results\n * clearToolInputs: true, // Also clear tool call arguments\n * }),\n * ],\n * tokenCountMethod: \"approx\", // Use approximate counting (or \"model\")\n * }),\n * ],\n * });\n * ```\n *\n * ## Custom Editing Strategies\n *\n * Implement your own context editing strategy by creating a class that\n * implements the `ContextEdit` interface:\n *\n * @example Custom editing strategy\n * ```ts\n * import { contextEditingMiddleware, type ContextEdit, type TokenCounter } from \"langchain\";\n * import type { BaseMessage } from \"@langchain/core/messages\";\n *\n * class CustomEdit implements ContextEdit {\n * async apply(params: {\n * tokens: number;\n * messages: BaseMessage[];\n * countTokens: TokenCounter;\n * }): Promise<number> {\n * // Implement your custom editing logic here\n * // and apply it to the messages array, then\n * // return the new token count after edits\n * return countTokens(messages);\n * }\n * }\n * ```\n *\n * @param config - Configuration options for the middleware\n * @returns A middleware instance that can be used with `createAgent`\n */\nexport declare function contextEditingMiddleware(config?: ContextEditingMiddlewareConfig): import(\"./index.js\").AgentMiddleware<undefined, undefined, any>;\n"],"mappings":";;;;;AAoCA;;;AAwBqBC,KAhDTA,YAAAA,GAgDSA,CAAAA,QAAAA,EAhDiBD,WAgDjBC,EAAAA,EAAAA,GAAAA,MAAAA,GAhD4CC,OAgD5CD,CAAAA,MAAAA,CAAAA;;AACG;AAKxB;AAsDA;;;;;;;;AAA6D;AAkB7D;AAqGA;;;;AAA+H;;;;;;UA3M9GE,WAAAA;;;;;;;;;;;;;;;;;;;;cAoBCH;;;;iBAIGC;eACJC;;;;;UAKAE,uBAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAsDIC,iBAAAA,YAA6BF;;;;;;gBAMhCG;;uBAEOF;;;cAGPJ;iBACGC;MACbC;;;;;UAKSK,8BAAAA;;;;;UAKLJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgGYK,wBAAAA,UAAkCD,iCAA8B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"contextEditing.d.ts","names":["BaseMessage","TokenCounter","Promise","ContextEdit","ClearToolUsesEditConfig","ClearToolUsesEdit","Set","ContextEditingMiddlewareConfig","contextEditingMiddleware","__index_js3","AgentMiddleware"],"sources":["../../../../src/agents/middlewareAgent/middleware/contextEditing.d.ts"],"sourcesContent":["/**\n * Context editing middleware.\n *\n * This middleware mirrors Anthropic's context editing capabilities by clearing\n * older tool results once the conversation grows beyond a configurable token\n * threshold. The implementation is intentionally model-agnostic so it can be used\n * with any LangChain chat model.\n */\nimport type { BaseMessage } from \"@langchain/core/messages\";\n/**\n * Function type for counting tokens in a sequence of messages.\n */\nexport type TokenCounter = (messages: BaseMessage[]) => number | Promise<number>;\n/**\n * Protocol describing a context editing strategy.\n *\n * Implement this interface to create custom strategies for managing\n * conversation context size. The `apply` method should modify the\n * messages array in-place and return the updated token count.\n *\n * @example\n * ```ts\n * import { SystemMessage } from \"langchain\";\n *\n * class RemoveOldSystemMessages implements ContextEdit {\n * async apply({ tokens, messages, countTokens }) {\n * // Remove old system messages if over limit\n * if (tokens > 50000) {\n * messages = messages.filter(SystemMessage.isInstance);\n * return await countTokens(messages);\n * }\n * return tokens;\n * }\n * }\n * ```\n */\nexport interface ContextEdit {\n /**\n * Apply an edit to the message list, returning the new token count.\n *\n * This method should:\n * 1. Check if editing is needed based on `tokens` parameter\n * 2. Modify the `messages` array in-place (if needed)\n * 3. Return the new token count after modifications\n *\n * @param params - Parameters for the editing operation\n * @returns The updated token count after applying edits\n */\n apply(params: {\n /**\n * Current token count of all messages\n */\n tokens: number;\n /**\n * Array of messages to potentially edit (modify in-place)\n */\n messages: BaseMessage[];\n /**\n * Function to count tokens in a message array\n */\n countTokens: TokenCounter;\n }): number | Promise<number>;\n}\n/**\n * Configuration for clearing tool outputs when token limits are exceeded.\n */\nexport interface ClearToolUsesEditConfig {\n /**\n * Token count that triggers the edit.\n * @default 100000\n */\n triggerTokens?: number;\n /**\n * Minimum number of tokens to reclaim when the edit runs.\n * @default 0\n */\n clearAtLeast?: number;\n /**\n * Number of most recent tool results that must be preserved.\n * @default 3\n */\n keep?: number;\n /**\n * Whether to clear the originating tool call parameters on the AI message.\n * @default false\n */\n clearToolInputs?: boolean;\n /**\n * List of tool names to exclude from clearing.\n * @default []\n */\n excludeTools?: string[];\n /**\n * Placeholder text inserted for cleared tool outputs.\n * @default \"[cleared]\"\n */\n placeholder?: string;\n}\n/**\n * Strategy for clearing tool outputs when token limits are exceeded.\n *\n * This strategy mirrors Anthropic's `clear_tool_uses_20250919` behavior by\n * replacing older tool results with a placeholder text when the conversation\n * grows too large. It preserves the most recent tool results and can exclude\n * specific tools from being cleared.\n *\n * @example\n * ```ts\n * import { ClearToolUsesEdit } from \"langchain\";\n *\n * const edit = new ClearToolUsesEdit({\n * triggerTokens: 100000, // Start clearing at 100K tokens\n * clearAtLeast: 0, // Clear as much as needed\n * keep: 3, // Always keep 3 most recent results\n * excludeTools: [\"important\"], // Never clear \"important\" tool\n * clearToolInputs: false, // Keep tool call arguments\n * placeholder: \"[cleared]\", // Replacement text\n * });\n * ```\n */\nexport declare class ClearToolUsesEdit implements ContextEdit {\n #private;\n triggerTokens: number;\n clearAtLeast: number;\n keep: number;\n clearToolInputs: boolean;\n excludeTools: Set<string>;\n placeholder: string;\n constructor(config?: ClearToolUsesEditConfig);\n apply(params: {\n tokens: number;\n messages: BaseMessage[];\n countTokens: TokenCounter;\n }): Promise<number>;\n}\n/**\n * Configuration for the Context Editing Middleware.\n */\nexport interface ContextEditingMiddlewareConfig {\n /**\n * Sequence of edit strategies to apply. Defaults to a single\n * ClearToolUsesEdit mirroring Anthropic defaults.\n */\n edits?: ContextEdit[];\n /**\n * Whether to use approximate token counting (faster, less accurate)\n * or exact counting implemented by the chat model (potentially slower, more accurate).\n * Currently only OpenAI models support exact counting.\n * @default \"approx\"\n */\n tokenCountMethod?: \"approx\" | \"model\";\n}\n/**\n * Middleware that automatically prunes tool results to manage context size.\n *\n * This middleware applies a sequence of edits when the total input token count\n * exceeds configured thresholds. By default, it uses the `ClearToolUsesEdit` strategy\n * which mirrors Anthropic's `clear_tool_uses_20250919` behaviour by clearing older\n * tool results once the conversation exceeds 100,000 tokens.\n *\n * ## Basic Usage\n *\n * Use the middleware with default settings to automatically manage context:\n *\n * @example Basic usage with defaults\n * ```ts\n * import { contextEditingMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * tools: [searchTool, calculatorTool],\n * middleware: [\n * contextEditingMiddleware(),\n * ],\n * });\n * ```\n *\n * The default configuration:\n * - Triggers when context exceeds **100,000 tokens**\n * - Keeps the **3 most recent** tool results\n * - Uses **approximate token counting** (fast)\n * - Does not clear tool call arguments\n *\n * ## Custom Configuration\n *\n * Customize the clearing behavior with `ClearToolUsesEdit`:\n *\n * @example Custom ClearToolUsesEdit configuration\n * ```ts\n * import { contextEditingMiddleware, ClearToolUsesEdit } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * tools: [searchTool, calculatorTool],\n * middleware: [\n * contextEditingMiddleware({\n * edits: [\n * new ClearToolUsesEdit({\n * triggerTokens: 50000, // Clear when exceeding 50K tokens\n * clearAtLeast: 1000, // Reclaim at least 1K tokens\n * keep: 5, // Keep 5 most recent tool results\n * excludeTools: [\"search\"], // Never clear search results\n * clearToolInputs: true, // Also clear tool call arguments\n * }),\n * ],\n * tokenCountMethod: \"approx\", // Use approximate counting (or \"model\")\n * }),\n * ],\n * });\n * ```\n *\n * ## Custom Editing Strategies\n *\n * Implement your own context editing strategy by creating a class that\n * implements the `ContextEdit` interface:\n *\n * @example Custom editing strategy\n * ```ts\n * import { contextEditingMiddleware, type ContextEdit, type TokenCounter } from \"langchain\";\n * import type { BaseMessage } from \"@langchain/core/messages\";\n *\n * class CustomEdit implements ContextEdit {\n * async apply(params: {\n * tokens: number;\n * messages: BaseMessage[];\n * countTokens: TokenCounter;\n * }): Promise<number> {\n * // Implement your custom editing logic here\n * // and apply it to the messages array, then\n * // return the new token count after edits\n * return countTokens(messages);\n * }\n * }\n * ```\n *\n * @param config - Configuration options for the middleware\n * @returns A middleware instance that can be used with `createAgent`\n */\nexport declare function contextEditingMiddleware(config?: ContextEditingMiddlewareConfig): import(\"./index.js\").AgentMiddleware<undefined, undefined, any>;\n"],"mappings":";;;;;AAoCA;;;AAwBqBC,KAhDTA,YAAAA,GAgDSA,CAAAA,QAAAA,EAhDiBD,WAgDjBC,EAAAA,EAAAA,GAAAA,MAAAA,GAhD4CC,OAgD5CD,CAAAA,MAAAA,CAAAA;;AACG;AAKxB;AAsDA;;;;;;;;AAA6D;AAkB7D;AAqGA;;;;AAA+H;;;;;;UA3M9GE,WAAAA;;;;;;;;;;;;;;;;;;;;cAoBCH;;;;iBAIGC;eACJC;;;;;UAKAE,uBAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAsDIC,iBAAAA,YAA6BF;;;;;;gBAMhCG;;uBAEOF;;;cAGPJ;iBACGC;MACbC;;;;;UAKSK,8BAAAA;;;;;UAKLJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgGYK,wBAAAA,UAAkCD,iCAA8B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"contextEditing.js","names":["config: ClearToolUsesEditConfig","params: {\n tokens: number;\n messages: BaseMessage[];\n countTokens: TokenCounter;\n }","candidates: Array<{ idx: number; msg: ToolMessage }>","#findAIMessageForToolCall","#buildClearedToolInputMessage","previousMessages: BaseMessage[]","toolCallId: string","message: AIMessage","config: ContextEditingMiddlewareConfig","request: ModelRequest","countTokens: TokenCounter","messages: BaseMessage[]"],"sources":["../../../../src/agents/middlewareAgent/middleware/contextEditing.ts"],"sourcesContent":["/**\n * Context editing middleware.\n *\n * This middleware mirrors Anthropic's context editing capabilities by clearing\n * older tool results once the conversation grows beyond a configurable token\n * threshold. The implementation is intentionally model-agnostic so it can be used\n * with any LangChain chat model.\n */\n\nimport type { BaseMessage } from \"@langchain/core/messages\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport {\n AIMessage,\n ToolMessage,\n SystemMessage,\n} from \"@langchain/core/messages\";\n\nimport { countTokensApproximately } from \"./utils.js\";\nimport { createMiddleware } from \"../middleware.js\";\nimport type { ModelRequest } from \"../types.js\";\n\nconst DEFAULT_TOOL_PLACEHOLDER = \"[cleared]\";\n\n/**\n * Function type for counting tokens in a sequence of messages.\n */\nexport type TokenCounter = (\n messages: BaseMessage[]\n) => number | Promise<number>;\n\n/**\n * Protocol describing a context editing strategy.\n *\n * Implement this interface to create custom strategies for managing\n * conversation context size. The `apply` method should modify the\n * messages array in-place and return the updated token count.\n *\n * @example\n * ```ts\n * import { SystemMessage } from \"langchain\";\n *\n * class RemoveOldSystemMessages implements ContextEdit {\n * async apply({ tokens, messages, countTokens }) {\n * // Remove old system messages if over limit\n * if (tokens > 50000) {\n * messages = messages.filter(SystemMessage.isInstance);\n * return await countTokens(messages);\n * }\n * return tokens;\n * }\n * }\n * ```\n */\nexport interface ContextEdit {\n /**\n * Apply an edit to the message list, returning the new token count.\n *\n * This method should:\n * 1. Check if editing is needed based on `tokens` parameter\n * 2. Modify the `messages` array in-place (if needed)\n * 3. Return the new token count after modifications\n *\n * @param params - Parameters for the editing operation\n * @returns The updated token count after applying edits\n */\n apply(params: {\n /**\n * Current token count of all messages\n */\n tokens: number;\n /**\n * Array of messages to potentially edit (modify in-place)\n */\n messages: BaseMessage[];\n /**\n * Function to count tokens in a message array\n */\n countTokens: TokenCounter;\n }): number | Promise<number>;\n}\n\n/**\n * Configuration for clearing tool outputs when token limits are exceeded.\n */\nexport interface ClearToolUsesEditConfig {\n /**\n * Token count that triggers the edit.\n * @default 100000\n */\n triggerTokens?: number;\n\n /**\n * Minimum number of tokens to reclaim when the edit runs.\n * @default 0\n */\n clearAtLeast?: number;\n\n /**\n * Number of most recent tool results that must be preserved.\n * @default 3\n */\n keep?: number;\n\n /**\n * Whether to clear the originating tool call parameters on the AI message.\n * @default false\n */\n clearToolInputs?: boolean;\n\n /**\n * List of tool names to exclude from clearing.\n * @default []\n */\n excludeTools?: string[];\n\n /**\n * Placeholder text inserted for cleared tool outputs.\n * @default \"[cleared]\"\n */\n placeholder?: string;\n}\n\n/**\n * Strategy for clearing tool outputs when token limits are exceeded.\n *\n * This strategy mirrors Anthropic's `clear_tool_uses_20250919` behavior by\n * replacing older tool results with a placeholder text when the conversation\n * grows too large. It preserves the most recent tool results and can exclude\n * specific tools from being cleared.\n *\n * @example\n * ```ts\n * import { ClearToolUsesEdit } from \"langchain\";\n *\n * const edit = new ClearToolUsesEdit({\n * triggerTokens: 100000, // Start clearing at 100K tokens\n * clearAtLeast: 0, // Clear as much as needed\n * keep: 3, // Always keep 3 most recent results\n * excludeTools: [\"important\"], // Never clear \"important\" tool\n * clearToolInputs: false, // Keep tool call arguments\n * placeholder: \"[cleared]\", // Replacement text\n * });\n * ```\n */\nexport class ClearToolUsesEdit implements ContextEdit {\n triggerTokens: number;\n clearAtLeast: number;\n keep: number;\n clearToolInputs: boolean;\n excludeTools: Set<string>;\n placeholder: string;\n\n constructor(config: ClearToolUsesEditConfig = {}) {\n this.triggerTokens = config.triggerTokens ?? 100000;\n this.clearAtLeast = config.clearAtLeast ?? 0;\n this.keep = config.keep ?? 3;\n this.clearToolInputs = config.clearToolInputs ?? false;\n this.excludeTools = new Set(config.excludeTools ?? []);\n this.placeholder = config.placeholder ?? DEFAULT_TOOL_PLACEHOLDER;\n }\n\n async apply(params: {\n tokens: number;\n messages: BaseMessage[];\n countTokens: TokenCounter;\n }): Promise<number> {\n const { tokens, messages, countTokens } = params;\n\n if (tokens <= this.triggerTokens) {\n return tokens;\n }\n\n /**\n * Find all tool message candidates with their actual indices in the messages array\n */\n const candidates: Array<{ idx: number; msg: ToolMessage }> = [];\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n if (ToolMessage.isInstance(msg)) {\n candidates.push({ idx: i, msg });\n }\n }\n\n /**\n * Keep the most recent tool messages\n */\n const candidatesToClear =\n this.keep >= candidates.length\n ? []\n : this.keep > 0\n ? candidates.slice(0, -this.keep)\n : candidates;\n\n let clearedTokens = 0;\n for (const { idx, msg: toolMessage } of candidatesToClear) {\n /**\n * Stop if we've cleared enough tokens\n */\n if (this.clearAtLeast > 0 && clearedTokens >= this.clearAtLeast) {\n break;\n }\n\n /**\n * Skip if already cleared\n */\n const contextEditing = toolMessage.response_metadata?.context_editing as\n | { cleared?: boolean }\n | undefined;\n if (contextEditing?.cleared) {\n continue;\n }\n\n /**\n * Find the corresponding AI message\n */\n const aiMessage = this.#findAIMessageForToolCall(\n messages.slice(0, idx),\n toolMessage.tool_call_id\n );\n\n if (!aiMessage) {\n continue;\n }\n\n /**\n * Find the corresponding tool call\n */\n const toolCall = aiMessage.tool_calls?.find(\n (call) => call.id === toolMessage.tool_call_id\n );\n\n if (!toolCall) {\n continue;\n }\n\n /**\n * Skip if tool is excluded\n */\n const toolName = toolMessage.name || toolCall.name;\n if (this.excludeTools.has(toolName)) {\n continue;\n }\n\n /**\n * Clear the tool message\n */\n messages[idx] = new ToolMessage({\n tool_call_id: toolMessage.tool_call_id,\n content: this.placeholder,\n name: toolMessage.name,\n artifact: undefined,\n response_metadata: {\n ...toolMessage.response_metadata,\n context_editing: {\n cleared: true,\n strategy: \"clear_tool_uses\",\n },\n },\n });\n\n /**\n * Optionally clear the tool inputs\n */\n if (this.clearToolInputs) {\n const aiMsgIdx = messages.indexOf(aiMessage);\n if (aiMsgIdx >= 0) {\n messages[aiMsgIdx] = this.#buildClearedToolInputMessage(\n aiMessage,\n toolMessage.tool_call_id\n );\n }\n }\n\n /**\n * Recalculate tokens\n */\n const newTokenCount = await countTokens(messages);\n clearedTokens = Math.max(0, tokens - newTokenCount);\n }\n\n return tokens - clearedTokens;\n }\n\n #findAIMessageForToolCall(\n previousMessages: BaseMessage[],\n toolCallId: string\n ): AIMessage | null {\n // Search backwards through previous messages\n for (let i = previousMessages.length - 1; i >= 0; i--) {\n const msg = previousMessages[i];\n if (AIMessage.isInstance(msg)) {\n const hasToolCall = msg.tool_calls?.some(\n (call) => call.id === toolCallId\n );\n if (hasToolCall) {\n return msg;\n }\n }\n }\n return null;\n }\n\n #buildClearedToolInputMessage(\n message: AIMessage,\n toolCallId: string\n ): AIMessage {\n const updatedToolCalls = message.tool_calls?.map((toolCall) => {\n if (toolCall.id === toolCallId) {\n return { ...toolCall, args: {} };\n }\n return toolCall;\n });\n\n const metadata = { ...message.response_metadata };\n const contextEntry = {\n ...(metadata.context_editing as Record<string, unknown>),\n };\n\n const clearedIds = new Set<string>(\n contextEntry.cleared_tool_inputs as string[] | undefined\n );\n clearedIds.add(toolCallId);\n contextEntry.cleared_tool_inputs = Array.from(clearedIds).sort();\n metadata.context_editing = contextEntry;\n\n return new AIMessage({\n content: message.content,\n tool_calls: updatedToolCalls,\n response_metadata: metadata,\n id: message.id,\n name: message.name,\n additional_kwargs: message.additional_kwargs,\n });\n }\n}\n\n/**\n * Configuration for the Context Editing Middleware.\n */\nexport interface ContextEditingMiddlewareConfig {\n /**\n * Sequence of edit strategies to apply. Defaults to a single\n * ClearToolUsesEdit mirroring Anthropic defaults.\n */\n edits?: ContextEdit[];\n\n /**\n * Whether to use approximate token counting (faster, less accurate)\n * or exact counting implemented by the chat model (potentially slower, more accurate).\n * Currently only OpenAI models support exact counting.\n * @default \"approx\"\n */\n tokenCountMethod?: \"approx\" | \"model\";\n}\n\n/**\n * Middleware that automatically prunes tool results to manage context size.\n *\n * This middleware applies a sequence of edits when the total input token count\n * exceeds configured thresholds. By default, it uses the `ClearToolUsesEdit` strategy\n * which mirrors Anthropic's `clear_tool_uses_20250919` behaviour by clearing older\n * tool results once the conversation exceeds 100,000 tokens.\n *\n * ## Basic Usage\n *\n * Use the middleware with default settings to automatically manage context:\n *\n * @example Basic usage with defaults\n * ```ts\n * import { contextEditingMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * tools: [searchTool, calculatorTool],\n * middleware: [\n * contextEditingMiddleware(),\n * ],\n * });\n * ```\n *\n * The default configuration:\n * - Triggers when context exceeds **100,000 tokens**\n * - Keeps the **3 most recent** tool results\n * - Uses **approximate token counting** (fast)\n * - Does not clear tool call arguments\n *\n * ## Custom Configuration\n *\n * Customize the clearing behavior with `ClearToolUsesEdit`:\n *\n * @example Custom ClearToolUsesEdit configuration\n * ```ts\n * import { contextEditingMiddleware, ClearToolUsesEdit } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * tools: [searchTool, calculatorTool],\n * middleware: [\n * contextEditingMiddleware({\n * edits: [\n * new ClearToolUsesEdit({\n * triggerTokens: 50000, // Clear when exceeding 50K tokens\n * clearAtLeast: 1000, // Reclaim at least 1K tokens\n * keep: 5, // Keep 5 most recent tool results\n * excludeTools: [\"search\"], // Never clear search results\n * clearToolInputs: true, // Also clear tool call arguments\n * }),\n * ],\n * tokenCountMethod: \"approx\", // Use approximate counting (or \"model\")\n * }),\n * ],\n * });\n * ```\n *\n * ## Custom Editing Strategies\n *\n * Implement your own context editing strategy by creating a class that\n * implements the `ContextEdit` interface:\n *\n * @example Custom editing strategy\n * ```ts\n * import { contextEditingMiddleware, type ContextEdit, type TokenCounter } from \"langchain\";\n * import type { BaseMessage } from \"@langchain/core/messages\";\n *\n * class CustomEdit implements ContextEdit {\n * async apply(params: {\n * tokens: number;\n * messages: BaseMessage[];\n * countTokens: TokenCounter;\n * }): Promise<number> {\n * // Implement your custom editing logic here\n * // and apply it to the messages array, then\n * // return the new token count after edits\n * return countTokens(messages);\n * }\n * }\n * ```\n *\n * @param config - Configuration options for the middleware\n * @returns A middleware instance that can be used with `createAgent`\n */\nexport function contextEditingMiddleware(\n config: ContextEditingMiddlewareConfig = {}\n) {\n const edits = config.edits ?? [new ClearToolUsesEdit()];\n const tokenCountMethod = config.tokenCountMethod ?? \"approx\";\n\n return createMiddleware({\n name: \"ContextEditingMiddleware\",\n modifyModelRequest: async (request: ModelRequest) => {\n if (!request.messages || request.messages.length === 0) {\n return request;\n }\n\n /**\n * Use model's token counting method\n */\n const systemMsg = request.systemPrompt\n ? [new SystemMessage(request.systemPrompt)]\n : [];\n\n const countTokens: TokenCounter =\n tokenCountMethod === \"approx\"\n ? countTokensApproximately\n : async (messages: BaseMessage[]): Promise<number> => {\n const allMessages = [...systemMsg, ...messages];\n\n /**\n * Check if model has getNumTokensFromMessages method\n * currently only OpenAI models have this method\n */\n if (\"getNumTokensFromMessages\" in request.model) {\n return (\n request.model as LanguageModelLike & {\n getNumTokensFromMessages: (\n messages: BaseMessage[]\n ) => Promise<{\n totalCount: number;\n countPerMessage: number[];\n }>;\n }\n )\n .getNumTokensFromMessages(allMessages)\n .then(({ totalCount }) => totalCount);\n }\n\n throw new Error(\n `Model \"${request.model.getName()}\" does not support token counting`\n );\n };\n\n let tokens = await countTokens(request.messages);\n\n /**\n * Apply each edit in sequence\n */\n for (const edit of edits) {\n tokens = await edit.apply({\n tokens,\n messages: request.messages,\n countTokens,\n });\n }\n\n return request;\n },\n });\n}\n"],"mappings":";;;;;AAqBA,MAAM,2BAA2B;;;;;;;;;;;;;;;;;;;;;;;AA2HjC,IAAa,oBAAb,MAAsD;CACpD;CACA;CACA;CACA;CACA;CACA;CAEA,YAAYA,SAAkC,CAAE,GAAE;EAChD,KAAK,gBAAgB,OAAO,iBAAiB;EAC7C,KAAK,eAAe,OAAO,gBAAgB;EAC3C,KAAK,OAAO,OAAO,QAAQ;EAC3B,KAAK,kBAAkB,OAAO,mBAAmB;EACjD,KAAK,eAAe,IAAI,IAAI,OAAO,gBAAgB,CAAE;EACrD,KAAK,cAAc,OAAO,eAAe;CAC1C;CAED,MAAM,MAAMC,QAIQ;EAClB,MAAM,EAAE,QAAQ,UAAU,aAAa,GAAG;AAE1C,MAAI,UAAU,KAAK,cACjB,QAAO;;;;EAMT,MAAMC,aAAuD,CAAE;AAC/D,OAAK,IAAI,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;GACxC,MAAM,MAAM,SAAS;AACrB,OAAI,YAAY,WAAW,IAAI,EAC7B,WAAW,KAAK;IAAE,KAAK;IAAG;GAAK,EAAC;EAEnC;;;;EAKD,MAAM,oBACJ,KAAK,QAAQ,WAAW,SAC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MACR,CAAC,OAAO,EAAE,QAAQ,MAAM,SAAS,CAAC,iCAAiC,CAAC;GAEvE;GAEP,IAAI,SAAS,MAAM,YAAY,QAAQ,SAAS;;;;AAKhD,QAAK,MAAM,QAAQ,OACjB,SAAS,MAAM,KAAK,MAAM;IACxB;IACA,UAAU,QAAQ;IAClB;GACD,EAAC;AAGJ,UAAO;EACR;CACF,EAAC;AACH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"dynamicSystemPrompt.cjs","names":["fn: DynamicSystemPromptMiddlewareConfig<TContextSchema>","createMiddleware"],"sources":["../../../../src/agents/middlewareAgent/middleware/dynamicSystemPrompt.ts"],"sourcesContent":["import { createMiddleware } from \"../middleware.js\";\nimport type { Runtime, AgentBuiltInState } from \"../types.js\";\n\nexport type DynamicSystemPromptMiddlewareConfig<TContextSchema> = (\n state: AgentBuiltInState,\n runtime: Runtime<TContextSchema>\n) => string | Promise<string>;\n\n/**\n * Dynamic System Prompt Middleware\n *\n * Allows setting the system prompt dynamically right before each model invocation.\n * Useful when the prompt depends on the current agent state or per-invocation context.\n *\n * @typeParam TContextSchema - The shape of the runtime context available at invocation time.\n * If your agent defines a `contextSchema`, pass the inferred type here to get full type-safety\n * for `runtime.context`.\n *\n * @param fn - Function that receives the current agent `state` and `runtime`, and\n * returns the system prompt for the next model call as a string.\n *\n * @returns A middleware instance that sets `systemPrompt` for the next model call.\n *\n * @example Basic usage with typed context\n * ```ts\n * import { z } from \"zod\";\n * import { dynamicSystemPrompt } from \"langchain\";\n * import { createAgent, SystemMessage } from \"langchain\";\n *\n * const contextSchema = z.object({ region: z.string().optional() });\n *\n * const middleware = dynamicSystemPrompt<z.infer<typeof contextSchema>>(\n * (_state, runtime) => `You are a helpful assistant. Region: ${runtime.context.region ?? \"n/a\"}`\n * );\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * contextSchema,\n * middleware: [middleware],\n * });\n *\n * await agent.invoke({ messages }, { context: { region: \"EU\" } });\n * ```\n *\n * @public\n */\nexport function dynamicSystemPromptMiddleware<TContextSchema = unknown>(\n fn: DynamicSystemPromptMiddlewareConfig<TContextSchema>\n) {\n return createMiddleware({\n name: \"DynamicSystemPromptMiddleware\",\n modifyModelRequest: async (options, state, runtime) => {\n const systemPrompt = await fn(\n state as AgentBuiltInState,\n runtime as Runtime<TContextSchema>\n );\n\n if (typeof systemPrompt !== \"string\") {\n throw new Error(\n \"dynamicSystemPromptMiddleware function must return a string\"\n );\n }\n\n return { ...options, systemPrompt };\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,SAAgB,8BACdA,IACA;AACA,QAAOC,oCAAiB;EACtB,MAAM;EACN,oBAAoB,OAAO,SAAS,OAAO,YAAY;GACrD,MAAM,eAAe,MAAM,GACzB,OACA,QACD;AAED,OAAI,OAAO,iBAAiB,SAC1B,OAAM,IAAI,MACR;AAIJ,UAAO;IAAE,GAAG;IAAS;GAAc;EACpC;CACF,EAAC;AACH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"dynamicSystemPrompt.d.cts","names":["Runtime","AgentBuiltInState","DynamicSystemPromptMiddlewareConfig","TContextSchema","Promise","dynamicSystemPromptMiddleware","__index_js0","AgentMiddleware"],"sources":["../../../../src/agents/middlewareAgent/middleware/dynamicSystemPrompt.d.ts"],"sourcesContent":["import type { Runtime, AgentBuiltInState } from \"../types.js\";\nexport type DynamicSystemPromptMiddlewareConfig<TContextSchema> = (state: AgentBuiltInState, runtime: Runtime<TContextSchema>) => string | Promise<string>;\n/**\n * Dynamic System Prompt Middleware\n *\n * Allows setting the system prompt dynamically right before each model invocation.\n * Useful when the prompt depends on the current agent state or per-invocation context.\n *\n * @typeParam TContextSchema - The shape of the runtime context available at invocation time.\n * If your agent defines a `contextSchema`, pass the inferred type here to get full type-safety\n * for `runtime.context`.\n *\n * @param fn - Function that receives the current agent `state` and `runtime`, and\n * returns the system prompt for the next model call as a string.\n *\n * @returns A middleware instance that sets `systemPrompt` for the next model call.\n *\n * @example Basic usage with typed context\n * ```ts\n * import { z } from \"zod\";\n * import { dynamicSystemPrompt } from \"langchain\";\n * import { createAgent, SystemMessage } from \"langchain\";\n *\n * const contextSchema = z.object({ region: z.string().optional() });\n *\n * const middleware = dynamicSystemPrompt<z.infer<typeof contextSchema>>(\n * (_state, runtime) => `You are a helpful assistant. Region: ${runtime.context.region ?? \"n/a\"}`\n * );\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * contextSchema,\n * middleware: [middleware],\n * });\n *\n * await agent.invoke({ messages }, { context: { region: \"EU\" } });\n * ```\n *\n * @public\n */\nexport declare function dynamicSystemPromptMiddleware<TContextSchema = unknown>(fn: DynamicSystemPromptMiddlewareConfig<TContextSchema>): import(\"./index.js\").AgentMiddleware<undefined, undefined, any>;\n"],"mappings":";;;KACYE,8DAA8DD,4BAA4BD,QAAQG,6BAA6BC;;AAA3I;;;;;;AAAkJ;AAuClJ;;;;;AAA8K;;;;;;;;;;;;;;;;;;;;;;;;;iBAAtJC,4DAA4DH,oCAAoCC,kBAAD"}
|