langchain 1.0.0-alpha.5 → 1.0.0-alpha.7
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/dist/agents/ReactAgent.cjs +5 -5
- package/dist/agents/ReactAgent.cjs.map +1 -1
- package/dist/agents/ReactAgent.d.cts +2 -5
- package/dist/agents/ReactAgent.d.cts.map +1 -1
- package/dist/agents/ReactAgent.d.ts +2 -5
- package/dist/agents/ReactAgent.d.ts.map +1 -1
- package/dist/agents/ReactAgent.js +6 -6
- package/dist/agents/ReactAgent.js.map +1 -1
- package/dist/agents/annotation.cjs.map +1 -1
- package/dist/agents/annotation.d.cts +13 -8
- package/dist/agents/annotation.d.cts.map +1 -1
- package/dist/agents/annotation.d.ts +13 -8
- package/dist/agents/annotation.d.ts.map +1 -1
- package/dist/agents/annotation.js.map +1 -1
- package/dist/agents/createAgent.cjs.map +1 -1
- package/dist/agents/createAgent.js.map +1 -1
- package/dist/agents/index.cjs +2 -2
- package/dist/agents/index.cjs.map +1 -1
- package/dist/agents/index.d.cts +50 -50
- package/dist/agents/index.d.cts.map +1 -1
- package/dist/agents/index.d.ts +50 -50
- package/dist/agents/index.d.ts.map +1 -1
- package/dist/agents/index.js +2 -2
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/interrupt.d.cts +14 -1
- package/dist/agents/interrupt.d.cts.map +1 -1
- package/dist/agents/interrupt.d.ts +14 -1
- package/dist/agents/interrupt.d.ts.map +1 -1
- package/dist/agents/middlewareAgent/ReactAgent.cjs +273 -66
- package/dist/agents/middlewareAgent/ReactAgent.cjs.map +1 -1
- package/dist/agents/middlewareAgent/ReactAgent.d.cts +102 -16
- package/dist/agents/middlewareAgent/ReactAgent.d.cts.map +1 -1
- package/dist/agents/middlewareAgent/ReactAgent.d.ts +102 -16
- package/dist/agents/middlewareAgent/ReactAgent.d.ts.map +1 -1
- package/dist/agents/middlewareAgent/ReactAgent.js +275 -68
- package/dist/agents/middlewareAgent/ReactAgent.js.map +1 -1
- package/dist/agents/middlewareAgent/annotation.cjs +12 -6
- package/dist/agents/middlewareAgent/annotation.cjs.map +1 -1
- package/dist/agents/middlewareAgent/annotation.js +12 -6
- package/dist/agents/middlewareAgent/annotation.js.map +1 -1
- package/dist/agents/middlewareAgent/constants.d.cts +5 -0
- package/dist/agents/middlewareAgent/constants.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/constants.d.ts +5 -0
- package/dist/agents/middlewareAgent/constants.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/index.cjs.map +1 -1
- package/dist/agents/middlewareAgent/index.js.map +1 -1
- package/dist/agents/middlewareAgent/middleware/bigTool.cjs +162 -0
- package/dist/agents/middlewareAgent/middleware/bigTool.cjs.map +1 -0
- package/dist/agents/middlewareAgent/middleware/bigTool.d.cts +113 -0
- package/dist/agents/middlewareAgent/middleware/bigTool.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/middleware/bigTool.d.ts +113 -0
- package/dist/agents/middlewareAgent/middleware/bigTool.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/middleware/bigTool.js +161 -0
- package/dist/agents/middlewareAgent/middleware/bigTool.js.map +1 -0
- package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.cjs +58 -0
- package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.cjs.map +1 -0
- package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.d.cts +46 -0
- package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.d.ts +46 -0
- package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.js +58 -0
- package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.js.map +1 -0
- package/dist/agents/middlewareAgent/middleware/hitl.cjs +311 -0
- package/dist/agents/middlewareAgent/middleware/hitl.cjs.map +1 -0
- package/dist/agents/middlewareAgent/middleware/hitl.d.cts +419 -0
- package/dist/agents/middlewareAgent/middleware/hitl.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/middleware/hitl.d.ts +419 -0
- package/dist/agents/middlewareAgent/middleware/hitl.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/middleware/hitl.js +310 -0
- package/dist/agents/middlewareAgent/middleware/hitl.js.map +1 -0
- package/dist/agents/middlewareAgent/middleware/index.cjs +32 -0
- package/dist/agents/middlewareAgent/middleware/index.cjs.map +1 -0
- package/dist/agents/middlewareAgent/middleware/index.d.cts +6 -0
- package/dist/agents/middlewareAgent/middleware/index.d.ts +6 -0
- package/dist/agents/middlewareAgent/middleware/index.js +21 -0
- package/dist/agents/middlewareAgent/middleware/index.js.map +1 -0
- package/dist/agents/middlewareAgent/{middlewares → middleware}/promptCaching.cjs +72 -27
- package/dist/agents/middlewareAgent/middleware/promptCaching.cjs.map +1 -0
- package/dist/agents/middlewareAgent/{middlewares → middleware}/promptCaching.d.cts +60 -15
- package/dist/agents/middlewareAgent/middleware/promptCaching.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/{middlewares → middleware}/promptCaching.d.ts +60 -15
- package/dist/agents/middlewareAgent/middleware/promptCaching.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/{middlewares → middleware}/promptCaching.js +71 -26
- package/dist/agents/middlewareAgent/middleware/promptCaching.js.map +1 -0
- package/dist/agents/middlewareAgent/{middlewares → middleware}/summarization.cjs +35 -23
- package/dist/agents/middlewareAgent/middleware/summarization.cjs.map +1 -0
- package/dist/agents/middlewareAgent/{middlewares → middleware}/summarization.d.cts +7 -5
- package/dist/agents/middlewareAgent/middleware/summarization.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/{middlewares → middleware}/summarization.d.ts +7 -5
- package/dist/agents/middlewareAgent/middleware/summarization.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/{middlewares → middleware}/summarization.js +29 -17
- package/dist/agents/middlewareAgent/middleware/summarization.js.map +1 -0
- package/dist/agents/middlewareAgent/middleware.cjs +8 -5
- package/dist/agents/middlewareAgent/middleware.cjs.map +1 -1
- package/dist/agents/middlewareAgent/middleware.d.cts +67 -7
- package/dist/agents/middlewareAgent/middleware.d.cts.map +1 -1
- package/dist/agents/middlewareAgent/middleware.d.ts +67 -7
- package/dist/agents/middlewareAgent/middleware.d.ts.map +1 -1
- package/dist/agents/middlewareAgent/middleware.js +8 -5
- package/dist/agents/middlewareAgent/middleware.js.map +1 -1
- package/dist/agents/middlewareAgent/nodes/AfterModalNode.cjs +2 -2
- package/dist/agents/middlewareAgent/nodes/AfterModalNode.cjs.map +1 -1
- package/dist/agents/middlewareAgent/nodes/AfterModalNode.js +2 -2
- package/dist/agents/middlewareAgent/nodes/AfterModalNode.js.map +1 -1
- package/dist/agents/middlewareAgent/nodes/AgentNode.cjs +125 -83
- package/dist/agents/middlewareAgent/nodes/AgentNode.cjs.map +1 -1
- package/dist/agents/middlewareAgent/nodes/AgentNode.js +128 -86
- package/dist/agents/middlewareAgent/nodes/AgentNode.js.map +1 -1
- package/dist/agents/middlewareAgent/nodes/BeforeModalNode.cjs +2 -2
- package/dist/agents/middlewareAgent/nodes/BeforeModalNode.cjs.map +1 -1
- package/dist/agents/middlewareAgent/nodes/BeforeModalNode.js +2 -2
- package/dist/agents/middlewareAgent/nodes/BeforeModalNode.js.map +1 -1
- package/dist/agents/middlewareAgent/nodes/middleware.cjs +42 -17
- package/dist/agents/middlewareAgent/nodes/middleware.cjs.map +1 -1
- package/dist/agents/middlewareAgent/nodes/middleware.js +42 -18
- package/dist/agents/middlewareAgent/nodes/middleware.js.map +1 -1
- package/dist/agents/middlewareAgent/nodes/utils.cjs +30 -16
- package/dist/agents/middlewareAgent/nodes/utils.cjs.map +1 -1
- package/dist/agents/middlewareAgent/nodes/utils.js +28 -14
- package/dist/agents/middlewareAgent/nodes/utils.js.map +1 -1
- package/dist/agents/middlewareAgent/types.d.cts +162 -88
- package/dist/agents/middlewareAgent/types.d.cts.map +1 -1
- package/dist/agents/middlewareAgent/types.d.ts +162 -88
- package/dist/agents/middlewareAgent/types.d.ts.map +1 -1
- package/dist/agents/model.cjs +13 -0
- package/dist/agents/model.cjs.map +1 -0
- package/dist/agents/model.js +11 -0
- package/dist/agents/model.js.map +1 -0
- package/dist/agents/nodes/AgentNode.cjs +60 -32
- package/dist/agents/nodes/AgentNode.cjs.map +1 -1
- package/dist/agents/nodes/AgentNode.js +61 -33
- package/dist/agents/nodes/AgentNode.js.map +1 -1
- package/dist/agents/nodes/ToolNode.cjs +4 -4
- package/dist/agents/nodes/ToolNode.cjs.map +1 -1
- package/dist/agents/nodes/ToolNode.d.cts +2 -3
- package/dist/agents/nodes/ToolNode.d.cts.map +1 -1
- package/dist/agents/nodes/ToolNode.d.ts +1 -2
- package/dist/agents/nodes/ToolNode.d.ts.map +1 -1
- package/dist/agents/nodes/ToolNode.js +5 -5
- package/dist/agents/nodes/ToolNode.js.map +1 -1
- package/dist/agents/responses.cjs +53 -11
- package/dist/agents/responses.cjs.map +1 -1
- package/dist/agents/responses.d.cts +12 -20
- package/dist/agents/responses.d.cts.map +1 -1
- package/dist/agents/responses.d.ts +12 -20
- package/dist/agents/responses.d.ts.map +1 -1
- package/dist/agents/responses.js +53 -12
- package/dist/agents/responses.js.map +1 -1
- package/dist/agents/types.d.cts +3 -6
- package/dist/agents/types.d.cts.map +1 -1
- package/dist/agents/types.d.ts +3 -6
- package/dist/agents/types.d.ts.map +1 -1
- package/dist/agents/utils.cjs +11 -29
- package/dist/agents/utils.cjs.map +1 -1
- package/dist/agents/utils.js +9 -26
- package/dist/agents/utils.js.map +1 -1
- package/dist/agents/withAgentName.cjs.map +1 -1
- package/dist/agents/withAgentName.js.map +1 -1
- package/dist/chains/api/prompts.cjs.map +1 -1
- package/dist/chains/api/prompts.js.map +1 -1
- package/dist/chains/constitutional_ai/constitutional_chain.cjs.map +1 -1
- package/dist/chains/constitutional_ai/constitutional_chain.js.map +1 -1
- package/dist/chains/index.cjs +0 -3
- package/dist/chains/index.cjs.map +1 -1
- package/dist/chains/index.d.cts +1 -2
- package/dist/chains/index.d.ts +1 -2
- package/dist/chains/index.js +1 -3
- package/dist/chains/index.js.map +1 -1
- package/dist/chains/openai_functions/extraction.cjs.map +1 -1
- package/dist/chains/openai_functions/extraction.d.cts +1 -3
- package/dist/chains/openai_functions/extraction.d.cts.map +1 -1
- package/dist/chains/openai_functions/extraction.d.ts +1 -3
- package/dist/chains/openai_functions/extraction.d.ts.map +1 -1
- package/dist/chains/openai_functions/extraction.js.map +1 -1
- package/dist/chains/openai_functions/index.cjs +0 -5
- package/dist/chains/openai_functions/index.cjs.map +1 -1
- package/dist/chains/openai_functions/index.d.cts +1 -2
- package/dist/chains/openai_functions/index.d.ts +1 -2
- package/dist/chains/openai_functions/index.js +1 -4
- package/dist/chains/openai_functions/index.js.map +1 -1
- package/dist/chains/openai_functions/openapi.cjs +4 -4
- package/dist/chains/openai_functions/openapi.cjs.map +1 -1
- package/dist/chains/openai_functions/openapi.d.cts +1 -1
- package/dist/chains/openai_functions/openapi.js +4 -4
- package/dist/chains/openai_functions/openapi.js.map +1 -1
- package/dist/chains/openai_functions/tagging.cjs.map +1 -1
- package/dist/chains/openai_functions/tagging.d.cts +1 -3
- package/dist/chains/openai_functions/tagging.d.cts.map +1 -1
- package/dist/chains/openai_functions/tagging.d.ts +1 -3
- package/dist/chains/openai_functions/tagging.d.ts.map +1 -1
- package/dist/chains/openai_functions/tagging.js.map +1 -1
- package/dist/chains/query_constructor/index.cjs +4 -4
- package/dist/chains/query_constructor/index.cjs.map +1 -1
- package/dist/chains/query_constructor/index.d.cts +4 -2
- package/dist/chains/query_constructor/index.d.cts.map +1 -1
- package/dist/chains/query_constructor/index.d.ts +4 -2
- package/dist/chains/query_constructor/index.d.ts.map +1 -1
- package/dist/chains/query_constructor/index.js +1 -1
- package/dist/chains/query_constructor/index.js.map +1 -1
- package/dist/chains/question_answering/load.d.ts +2 -2
- package/dist/chains/question_answering/load.d.ts.map +1 -1
- package/dist/chains/question_answering/map_reduce_prompts.cjs.map +1 -1
- package/dist/chains/question_answering/map_reduce_prompts.js.map +1 -1
- package/dist/chains/question_answering/refine_prompts.cjs.map +1 -1
- package/dist/chains/question_answering/refine_prompts.js.map +1 -1
- package/dist/chains/question_answering/stuff_prompts.cjs.map +1 -1
- package/dist/chains/question_answering/stuff_prompts.js.map +1 -1
- package/dist/chains/router/multi_prompt.cjs +4 -4
- package/dist/chains/router/multi_prompt.cjs.map +1 -1
- package/dist/chains/router/multi_prompt.js +1 -1
- package/dist/chains/router/multi_prompt.js.map +1 -1
- package/dist/chains/router/multi_retrieval_qa.cjs +4 -4
- package/dist/chains/router/multi_retrieval_qa.cjs.map +1 -1
- package/dist/chains/router/multi_retrieval_qa.js +1 -1
- package/dist/chains/router/multi_retrieval_qa.js.map +1 -1
- package/dist/chains/sql_db/sql_db_prompt.cjs.map +1 -1
- package/dist/chains/sql_db/sql_db_prompt.d.cts.map +1 -1
- package/dist/chains/sql_db/sql_db_prompt.d.ts.map +1 -1
- package/dist/chains/sql_db/sql_db_prompt.js.map +1 -1
- package/dist/chains/summarization/stuff_prompts.cjs.map +1 -1
- package/dist/chains/summarization/stuff_prompts.js.map +1 -1
- package/dist/chat_models/universal.cjs +8 -5
- package/dist/chat_models/universal.cjs.map +1 -1
- package/dist/chat_models/universal.d.cts +2 -2
- package/dist/chat_models/universal.d.cts.map +1 -1
- package/dist/chat_models/universal.d.ts +2 -2
- package/dist/chat_models/universal.d.ts.map +1 -1
- package/dist/chat_models/universal.js +8 -5
- package/dist/chat_models/universal.js.map +1 -1
- package/dist/document_loaders/fs/directory.cjs.map +1 -1
- package/dist/document_loaders/fs/directory.d.cts +0 -1
- package/dist/document_loaders/fs/directory.d.cts.map +1 -1
- package/dist/document_loaders/fs/directory.d.ts +0 -1
- package/dist/document_loaders/fs/directory.d.ts.map +1 -1
- package/dist/document_loaders/fs/directory.js.map +1 -1
- package/dist/document_loaders/fs/json.cjs +7 -1
- package/dist/document_loaders/fs/json.cjs.map +1 -1
- package/dist/document_loaders/fs/json.js +7 -1
- package/dist/document_loaders/fs/json.js.map +1 -1
- package/dist/embeddings/cache_backed.cjs +1 -1
- package/dist/embeddings/cache_backed.cjs.map +1 -1
- package/dist/embeddings/cache_backed.d.cts +1 -1
- package/dist/embeddings/cache_backed.d.ts +2 -2
- package/dist/embeddings/cache_backed.js +2 -2
- package/dist/embeddings/cache_backed.js.map +1 -1
- package/dist/evaluation/agents/trajectory.d.cts.map +1 -1
- package/dist/evaluation/comparison/pairwise.d.cts.map +1 -1
- package/dist/evaluation/criteria/criteria.d.cts.map +1 -1
- package/dist/evaluation/embedding_distance/base.cjs +2 -4
- package/dist/evaluation/embedding_distance/base.cjs.map +1 -1
- package/dist/evaluation/embedding_distance/base.js +2 -3
- package/dist/evaluation/embedding_distance/base.js.map +1 -1
- package/dist/evaluation/loader.cjs +7 -12
- package/dist/evaluation/loader.cjs.map +1 -1
- package/dist/evaluation/loader.d.cts +8 -2
- package/dist/evaluation/loader.d.cts.map +1 -1
- package/dist/evaluation/loader.d.ts +8 -2
- package/dist/evaluation/loader.d.ts.map +1 -1
- package/dist/evaluation/loader.js +7 -12
- package/dist/evaluation/loader.js.map +1 -1
- package/dist/hub/base.cjs.map +1 -1
- package/dist/hub/base.js.map +1 -1
- package/dist/index.cjs +38 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +11 -4
- package/dist/index.d.ts +11 -4
- package/dist/index.js +18 -4
- package/dist/index.js.map +1 -1
- package/dist/langchain-core/dist/load/serializable.d.cts.map +1 -1
- package/dist/langchain-core/dist/messages/base.d.cts +24 -33
- package/dist/langchain-core/dist/messages/base.d.cts.map +1 -1
- package/dist/langchain-core/dist/messages/content/index.d.cts +21 -2
- package/dist/langchain-core/dist/messages/content/index.d.cts.map +1 -1
- package/dist/langchain-core/dist/messages/content/tools.d.cts +67 -6
- package/dist/langchain-core/dist/messages/content/tools.d.cts.map +1 -1
- package/dist/langchain-core/dist/messages/message.d.cts +598 -0
- package/dist/langchain-core/dist/messages/message.d.cts.map +1 -0
- package/dist/langchain-core/dist/messages/metadata.d.cts +97 -0
- package/dist/langchain-core/dist/messages/metadata.d.cts.map +1 -0
- package/dist/langchain-core/dist/messages/utils.d.cts +75 -0
- package/dist/langchain-core/dist/messages/utils.d.cts.map +1 -0
- package/dist/langchain-core/dist/prompt_values.d.cts.map +1 -1
- package/dist/langchain-core/dist/utils/types/index.d.cts.map +1 -1
- package/dist/libs/langchain-core/dist/load/serializable.d.ts.map +1 -1
- package/dist/libs/langchain-core/dist/messages/base.d.ts +24 -33
- package/dist/libs/langchain-core/dist/messages/base.d.ts.map +1 -1
- package/dist/libs/langchain-core/dist/messages/content/index.d.ts +21 -2
- package/dist/libs/langchain-core/dist/messages/content/index.d.ts.map +1 -1
- package/dist/libs/langchain-core/dist/messages/content/tools.d.ts +67 -6
- package/dist/libs/langchain-core/dist/messages/content/tools.d.ts.map +1 -1
- package/dist/libs/langchain-core/dist/messages/message.d.ts +598 -0
- package/dist/libs/langchain-core/dist/messages/message.d.ts.map +1 -0
- package/dist/libs/langchain-core/dist/messages/metadata.d.ts +97 -0
- package/dist/libs/langchain-core/dist/messages/metadata.d.ts.map +1 -0
- package/dist/libs/langchain-core/dist/messages/utils.d.ts +75 -0
- package/dist/libs/langchain-core/dist/messages/utils.d.ts.map +1 -0
- package/dist/libs/langchain-core/dist/prompt_values.d.ts.map +1 -1
- package/dist/libs/langchain-core/dist/utils/types/index.d.ts +2 -0
- package/dist/libs/langchain-core/dist/utils/types/index.d.ts.map +1 -1
- package/dist/libs/langchain-core/dist/utils/types/zod.d.ts +1 -0
- package/dist/load/import_map.cjs +3 -14
- package/dist/load/import_map.cjs.map +1 -1
- package/dist/load/import_map.js +3 -14
- package/dist/load/import_map.js.map +1 -1
- package/dist/memory/prompt.cjs.map +1 -1
- package/dist/memory/prompt.d.cts.map +1 -1
- package/dist/memory/prompt.d.ts.map +1 -1
- package/dist/memory/prompt.js.map +1 -1
- package/dist/output_parsers/combining.cjs +1 -1
- package/dist/output_parsers/combining.cjs.map +1 -1
- package/dist/output_parsers/combining.js +1 -1
- package/dist/output_parsers/combining.js.map +1 -1
- package/dist/output_parsers/expression_type_handlers/array_literal_expression_handler.cjs.map +1 -1
- package/dist/output_parsers/expression_type_handlers/array_literal_expression_handler.js.map +1 -1
- package/dist/output_parsers/expression_type_handlers/base.cjs +1 -1
- package/dist/output_parsers/expression_type_handlers/base.cjs.map +1 -1
- package/dist/output_parsers/expression_type_handlers/base.js +1 -1
- package/dist/output_parsers/expression_type_handlers/base.js.map +1 -1
- package/dist/output_parsers/regex.cjs.map +1 -1
- package/dist/output_parsers/regex.js.map +1 -1
- package/dist/output_parsers/structured.cjs +4 -4
- package/dist/output_parsers/structured.cjs.map +1 -1
- package/dist/output_parsers/structured.d.cts +1 -1
- package/dist/output_parsers/structured.d.cts.map +1 -1
- package/dist/output_parsers/structured.d.ts +1 -1
- package/dist/output_parsers/structured.d.ts.map +1 -1
- package/dist/output_parsers/structured.js +2 -2
- package/dist/output_parsers/structured.js.map +1 -1
- package/dist/retrievers/ensemble.cjs.map +1 -1
- package/dist/retrievers/ensemble.js.map +1 -1
- package/dist/storage/file_system.cjs +1 -1
- package/dist/storage/file_system.cjs.map +1 -1
- package/dist/storage/file_system.js +1 -1
- package/dist/storage/file_system.js.map +1 -1
- package/dist/tools/fs.cjs +5 -5
- package/dist/tools/fs.cjs.map +1 -1
- package/dist/tools/fs.d.cts +1 -1
- package/dist/tools/fs.d.cts.map +1 -1
- package/dist/tools/fs.d.ts +1 -1
- package/dist/tools/fs.d.ts.map +1 -1
- package/dist/tools/fs.js +1 -1
- package/dist/tools/fs.js.map +1 -1
- package/dist/tools/retriever.cjs +2 -2
- package/dist/tools/retriever.cjs.map +1 -1
- package/dist/tools/retriever.d.cts +1 -1
- package/dist/tools/retriever.d.cts.map +1 -1
- package/dist/tools/retriever.d.ts +1 -1
- package/dist/tools/retriever.d.ts.map +1 -1
- package/dist/tools/retriever.js +1 -1
- package/dist/tools/retriever.js.map +1 -1
- package/dist/tools/sql.cjs +1 -2
- package/dist/tools/sql.cjs.map +1 -1
- package/dist/tools/sql.d.cts +1 -1
- package/dist/tools/sql.d.cts.map +1 -1
- package/dist/tools/sql.d.ts +1 -1
- package/dist/tools/sql.d.ts.map +1 -1
- package/dist/tools/sql.js +1 -2
- package/dist/tools/sql.js.map +1 -1
- package/dist/types/expression-parser.d.cts +2 -0
- package/dist/types/expression-parser.d.cts.map +1 -1
- package/dist/types/expression-parser.d.ts +2 -0
- package/dist/types/expression-parser.d.ts.map +1 -1
- package/dist/util/hub.cjs +1 -1
- package/dist/util/hub.js +1 -1
- package/dist/util/openapi.cjs +1 -1
- package/dist/util/openapi.cjs.map +1 -1
- package/dist/util/openapi.js +1 -1
- package/dist/util/openapi.js.map +1 -1
- package/package.json +15 -21
- package/dist/agents/middlewareAgent/middlewares/hitl.cjs +0 -235
- package/dist/agents/middlewareAgent/middlewares/hitl.cjs.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/hitl.d.cts +0 -199
- package/dist/agents/middlewareAgent/middlewares/hitl.d.cts.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/hitl.d.ts +0 -199
- package/dist/agents/middlewareAgent/middlewares/hitl.d.ts.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/hitl.js +0 -234
- package/dist/agents/middlewareAgent/middlewares/hitl.js.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/index.cjs +0 -8
- package/dist/agents/middlewareAgent/middlewares/index.d.cts +0 -4
- package/dist/agents/middlewareAgent/middlewares/index.d.ts +0 -4
- package/dist/agents/middlewareAgent/middlewares/index.js +0 -5
- package/dist/agents/middlewareAgent/middlewares/promptCaching.cjs.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/promptCaching.d.cts.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/promptCaching.d.ts.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/promptCaching.js.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/summarization.cjs.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/summarization.d.cts.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/summarization.d.ts.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/summarization.js.map +0 -1
- package/dist/chains/openai_functions/structured_output.cjs +0 -107
- package/dist/chains/openai_functions/structured_output.cjs.map +0 -1
- package/dist/chains/openai_functions/structured_output.d.cts +0 -38
- package/dist/chains/openai_functions/structured_output.d.cts.map +0 -1
- package/dist/chains/openai_functions/structured_output.d.ts +0 -38
- package/dist/chains/openai_functions/structured_output.d.ts.map +0 -1
- package/dist/chains/openai_functions/structured_output.js +0 -105
- package/dist/chains/openai_functions/structured_output.js.map +0 -1
- package/dist/chains/openai_moderation.cjs +0 -107
- package/dist/chains/openai_moderation.cjs.map +0 -1
- package/dist/chains/openai_moderation.d.cts +0 -74
- package/dist/chains/openai_moderation.d.cts.map +0 -1
- package/dist/chains/openai_moderation.d.ts +0 -74
- package/dist/chains/openai_moderation.d.ts.map +0 -1
- package/dist/chains/openai_moderation.js +0 -106
- package/dist/chains/openai_moderation.js.map +0 -1
|
@@ -1,33 +1,59 @@
|
|
|
1
1
|
import { initChatModel } from "../../../chat_models/universal.js";
|
|
2
2
|
import { MultipleStructuredOutputsError } from "../../errors.js";
|
|
3
|
-
import { bindTools, getPromptRunnable,
|
|
3
|
+
import { bindTools, getPromptRunnable, hasToolCalls, validateLLMHasNoBoundTools } from "../../utils.js";
|
|
4
4
|
import { RunnableCallable } from "../../RunnableCallable.js";
|
|
5
5
|
import { mergeAbortSignals } from "../../nodes/utils.js";
|
|
6
6
|
import { withAgentName } from "../../withAgentName.js";
|
|
7
|
-
import { ProviderStrategy, ToolStrategy, transformResponseFormat } from "../../responses.js";
|
|
8
|
-
import { parseToolCalls
|
|
9
|
-
import { AIMessage,
|
|
7
|
+
import { ProviderStrategy, ToolStrategy, hasSupportForJsonSchemaOutput, transformResponseFormat } from "../../responses.js";
|
|
8
|
+
import { parseToolCalls } from "./utils.js";
|
|
9
|
+
import { AIMessage, ToolMessage } from "@langchain/core/messages";
|
|
10
10
|
import { Command } from "@langchain/langgraph";
|
|
11
|
-
import { getSchemaDescription } from "@langchain/core/utils/types";
|
|
12
|
-
import { z } from "zod";
|
|
11
|
+
import { getSchemaDescription, interopParse } from "@langchain/core/utils/types";
|
|
12
|
+
import { z } from "zod/v3";
|
|
13
13
|
|
|
14
14
|
//#region src/agents/middlewareAgent/nodes/AgentNode.ts
|
|
15
15
|
var AgentNode = class extends RunnableCallable {
|
|
16
16
|
#options;
|
|
17
|
-
#structuredToolInfo = {};
|
|
18
17
|
constructor(options) {
|
|
19
18
|
super({
|
|
20
19
|
name: options.name ?? "model",
|
|
21
20
|
func: (input, config) => this.#run(input, config)
|
|
22
21
|
});
|
|
23
22
|
this.#options = options;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Returns response format primtivies based on given model and response format provided by the user.
|
|
26
|
+
*
|
|
27
|
+
* If the the user selects a tool output:
|
|
28
|
+
* - return a record of tools to extract structured output from the model's response
|
|
29
|
+
*
|
|
30
|
+
* if the the user selects a native schema output or if the model supports JSON schema output:
|
|
31
|
+
* - return a provider strategy to extract structured output from the model's response
|
|
32
|
+
*
|
|
33
|
+
* @param model - The model to get the response format for.
|
|
34
|
+
* @returns The response format.
|
|
35
|
+
*/
|
|
36
|
+
#getResponseFormat(model) {
|
|
37
|
+
if (!this.#options.responseFormat) return void 0;
|
|
38
|
+
const strategies = transformResponseFormat(this.#options.responseFormat, void 0, model);
|
|
39
|
+
/**
|
|
40
|
+
* we either define a list of provider strategies or a list of tool strategies
|
|
41
|
+
*/
|
|
42
|
+
const isProviderStrategy = strategies.every((format) => format instanceof ProviderStrategy);
|
|
24
43
|
/**
|
|
25
44
|
* Populate a list of structured tool info.
|
|
26
45
|
*/
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
46
|
+
if (!isProviderStrategy) return {
|
|
47
|
+
type: "tool",
|
|
48
|
+
tools: strategies.filter((format) => format instanceof ToolStrategy).reduce((acc, format) => {
|
|
49
|
+
acc[format.name] = format;
|
|
50
|
+
return acc;
|
|
51
|
+
}, {})
|
|
52
|
+
};
|
|
53
|
+
return {
|
|
54
|
+
type: "native",
|
|
55
|
+
strategy: strategies[0]
|
|
56
|
+
};
|
|
31
57
|
}
|
|
32
58
|
async #run(state, config) {
|
|
33
59
|
/**
|
|
@@ -35,7 +61,7 @@ var AgentNode = class extends RunnableCallable {
|
|
|
35
61
|
* If so, we should generate structured response (if needed) and stop
|
|
36
62
|
*/
|
|
37
63
|
const lastMessage = state.messages.at(-1);
|
|
38
|
-
if (lastMessage &&
|
|
64
|
+
if (lastMessage && ToolMessage.isInstance(lastMessage) && lastMessage.name && this.#options.shouldReturnDirect.has(lastMessage.name))
|
|
39
65
|
/**
|
|
40
66
|
* return directly without invoking the model again
|
|
41
67
|
*/
|
|
@@ -54,9 +80,9 @@ var AgentNode = class extends RunnableCallable {
|
|
|
54
80
|
if (response instanceof Command) return response;
|
|
55
81
|
response.name = this.name;
|
|
56
82
|
response.lc_kwargs.name = this.name;
|
|
57
|
-
if (this.#areMoreStepsNeeded(state, response)) return { messages: [new AIMessage(
|
|
83
|
+
if (this.#areMoreStepsNeeded(state, response)) return { messages: [new AIMessage({
|
|
84
|
+
content: "Sorry, need more steps to process this request.",
|
|
58
85
|
name: this.name,
|
|
59
|
-
lc_kwargs: { name: this.name },
|
|
60
86
|
id: response.id
|
|
61
87
|
})] };
|
|
62
88
|
return { messages: [response] };
|
|
@@ -67,23 +93,15 @@ var AgentNode = class extends RunnableCallable {
|
|
|
67
93
|
* @param config - The config of the agent.
|
|
68
94
|
* @returns The model.
|
|
69
95
|
*/
|
|
70
|
-
#deriveModel(
|
|
71
|
-
if (this.#options.model)
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
}
|
|
75
|
-
const model = this.#options.llm;
|
|
76
|
-
/**
|
|
77
|
-
* If the model is a function, call it to get the model.
|
|
78
|
-
*/
|
|
79
|
-
if (typeof model === "function") return model(state, config);
|
|
80
|
-
if (model) return model;
|
|
81
|
-
throw new Error("No model option was provided, either via `model` or via `llm` option.");
|
|
96
|
+
#deriveModel() {
|
|
97
|
+
if (typeof this.#options.model === "string") return initChatModel(this.#options.model);
|
|
98
|
+
if (this.#options.model) return this.#options.model;
|
|
99
|
+
throw new Error("No model option was provided, either via `model` option.");
|
|
82
100
|
}
|
|
83
101
|
async #invokeModel(state, config, options = {}) {
|
|
84
|
-
const model = await this.#deriveModel(
|
|
102
|
+
const model = await this.#deriveModel();
|
|
85
103
|
/**
|
|
86
|
-
* Execute
|
|
104
|
+
* Execute modifyModelRequest hooks from beforeModelNodes
|
|
87
105
|
*/
|
|
88
106
|
const preparedOptions = await this.#executePrepareModelRequestHooks(model, state, config);
|
|
89
107
|
/**
|
|
@@ -95,19 +113,16 @@ var AgentNode = class extends RunnableCallable {
|
|
|
95
113
|
* Check if the LLM already has bound tools and throw if it does.
|
|
96
114
|
*/
|
|
97
115
|
validateLLMHasNoBoundTools(finalModel);
|
|
98
|
-
const
|
|
116
|
+
const structuredResponseFormat = this.#getResponseFormat(finalModel);
|
|
117
|
+
const modelWithTools = await this.#bindTools(finalModel, preparedOptions, structuredResponseFormat);
|
|
99
118
|
let modelInput = this.#getModelInputState(state);
|
|
119
|
+
/**
|
|
120
|
+
* Use messages from preparedOptions if provided
|
|
121
|
+
*/
|
|
100
122
|
if (preparedOptions?.messages) modelInput = {
|
|
101
123
|
...modelInput,
|
|
102
124
|
messages: preparedOptions.messages
|
|
103
125
|
};
|
|
104
|
-
if (preparedOptions?.systemMessage) {
|
|
105
|
-
const systemMsg = new SystemMessage(preparedOptions.systemMessage);
|
|
106
|
-
modelInput = {
|
|
107
|
-
...modelInput,
|
|
108
|
-
messages: [systemMsg, ...modelInput.messages]
|
|
109
|
-
};
|
|
110
|
-
}
|
|
111
126
|
const signal = mergeAbortSignals(this.#options.signal, config.signal);
|
|
112
127
|
const invokeConfig = {
|
|
113
128
|
...config,
|
|
@@ -118,15 +133,16 @@ var AgentNode = class extends RunnableCallable {
|
|
|
118
133
|
* if the user requests a native schema output, try to parse the response
|
|
119
134
|
* and return the structured response if it is valid
|
|
120
135
|
*/
|
|
121
|
-
if (
|
|
122
|
-
const structuredResponse =
|
|
136
|
+
if (structuredResponseFormat?.type === "native") {
|
|
137
|
+
const structuredResponse = structuredResponseFormat.strategy.parse(response);
|
|
123
138
|
if (structuredResponse) return {
|
|
124
139
|
structuredResponse,
|
|
125
140
|
messages: [response]
|
|
126
141
|
};
|
|
142
|
+
return response;
|
|
127
143
|
}
|
|
128
|
-
if (!response.tool_calls) return response;
|
|
129
|
-
const toolCalls = response.tool_calls.filter((call) => call.name in
|
|
144
|
+
if (!structuredResponseFormat || !response.tool_calls) return response;
|
|
145
|
+
const toolCalls = response.tool_calls.filter((call) => call.name in structuredResponseFormat.tools);
|
|
130
146
|
/**
|
|
131
147
|
* if there were not structured tool calls, we can return the response
|
|
132
148
|
*/
|
|
@@ -135,10 +151,10 @@ var AgentNode = class extends RunnableCallable {
|
|
|
135
151
|
* if there were multiple structured tool calls, we should throw an error as this
|
|
136
152
|
* scenario is not defined/supported.
|
|
137
153
|
*/
|
|
138
|
-
if (toolCalls.length > 1) return this.#handleMultipleStructuredOutputs(response, toolCalls);
|
|
139
|
-
const toolStrategy =
|
|
154
|
+
if (toolCalls.length > 1) return this.#handleMultipleStructuredOutputs(response, toolCalls, structuredResponseFormat);
|
|
155
|
+
const toolStrategy = structuredResponseFormat.tools[toolCalls[0].name];
|
|
140
156
|
const toolMessageContent = toolStrategy?.options?.toolMessageContent;
|
|
141
|
-
return this.#handleSingleStructuredOutput(response, toolCalls[0], toolMessageContent ?? options.lastMessage);
|
|
157
|
+
return this.#handleSingleStructuredOutput(response, toolCalls[0], structuredResponseFormat, toolMessageContent ?? options.lastMessage);
|
|
142
158
|
}
|
|
143
159
|
/**
|
|
144
160
|
* If the model returns multiple structured outputs, we need to handle it.
|
|
@@ -146,21 +162,17 @@ var AgentNode = class extends RunnableCallable {
|
|
|
146
162
|
* @param toolCalls - The tool calls that were made
|
|
147
163
|
* @returns The response from the model
|
|
148
164
|
*/
|
|
149
|
-
#handleMultipleStructuredOutputs(response, toolCalls) {
|
|
150
|
-
/**
|
|
151
|
-
* the following should never happen, let's throw an error if it does
|
|
152
|
-
*/
|
|
153
|
-
if (this.#options.responseFormat instanceof ProviderStrategy) throw new Error("Multiple structured outputs should not apply to native structured output responses");
|
|
165
|
+
#handleMultipleStructuredOutputs(response, toolCalls, responseFormat) {
|
|
154
166
|
const multipleStructuredOutputsError = new MultipleStructuredOutputsError(toolCalls.map((call) => call.name));
|
|
155
|
-
return this.#handleToolStrategyError(multipleStructuredOutputsError, response, toolCalls[0]);
|
|
167
|
+
return this.#handleToolStrategyError(multipleStructuredOutputsError, response, toolCalls[0], responseFormat);
|
|
156
168
|
}
|
|
157
169
|
/**
|
|
158
170
|
* If the model returns a single structured output, we need to handle it.
|
|
159
171
|
* @param toolCall - The tool call that was made
|
|
160
172
|
* @returns The structured response and a message to the LLM if needed
|
|
161
173
|
*/
|
|
162
|
-
#handleSingleStructuredOutput(response, toolCall, lastMessage) {
|
|
163
|
-
const tool =
|
|
174
|
+
#handleSingleStructuredOutput(response, toolCall, responseFormat, lastMessage) {
|
|
175
|
+
const tool = responseFormat.tools[toolCall.name];
|
|
164
176
|
try {
|
|
165
177
|
const structuredResponse = tool.parse(toolCall.args);
|
|
166
178
|
return {
|
|
@@ -168,10 +180,10 @@ var AgentNode = class extends RunnableCallable {
|
|
|
168
180
|
messages: [response, new AIMessage(lastMessage ?? `Returning structured response: ${JSON.stringify(structuredResponse)}`)]
|
|
169
181
|
};
|
|
170
182
|
} catch (error) {
|
|
171
|
-
return this.#handleToolStrategyError(error, response, toolCall);
|
|
183
|
+
return this.#handleToolStrategyError(error, response, toolCall, responseFormat);
|
|
172
184
|
}
|
|
173
185
|
}
|
|
174
|
-
async #handleToolStrategyError(error, response, toolCall) {
|
|
186
|
+
async #handleToolStrategyError(error, response, toolCall, responseFormat) {
|
|
175
187
|
/**
|
|
176
188
|
* Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.
|
|
177
189
|
* There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user
|
|
@@ -179,7 +191,7 @@ var AgentNode = class extends RunnableCallable {
|
|
|
179
191
|
* schema objects, these will be transformed into multiple `ToolStrategy` entries but all
|
|
180
192
|
* with the same `handleError` option.
|
|
181
193
|
*/
|
|
182
|
-
const errorHandler = Object.values(
|
|
194
|
+
const errorHandler = Object.values(responseFormat.tools).at(0)?.options?.handleError;
|
|
183
195
|
const toolCallId = toolCall.id;
|
|
184
196
|
if (!toolCallId) throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");
|
|
185
197
|
/**
|
|
@@ -222,7 +234,7 @@ var AgentNode = class extends RunnableCallable {
|
|
|
222
234
|
throw error;
|
|
223
235
|
}
|
|
224
236
|
#areMoreStepsNeeded(state, response) {
|
|
225
|
-
const allToolsReturnDirect = response
|
|
237
|
+
const allToolsReturnDirect = AIMessage.isInstance(response) && response.tool_calls?.every((call) => this.#options.shouldReturnDirect.has(call.name));
|
|
226
238
|
const remainingSteps = "remainingSteps" in state ? state.remainingSteps : void 0;
|
|
227
239
|
return Boolean(remainingSteps && (remainingSteps < 1 && allToolsReturnDirect || remainingSteps < 2 && hasToolCalls(state.messages)));
|
|
228
240
|
}
|
|
@@ -238,34 +250,63 @@ var AgentNode = class extends RunnableCallable {
|
|
|
238
250
|
};
|
|
239
251
|
}
|
|
240
252
|
async #executePrepareModelRequestHooks(model, state, config) {
|
|
241
|
-
if (!this.#options.
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
253
|
+
if (!this.#options.modifyModelRequestHookMiddleware || this.#options.modifyModelRequestHookMiddleware.length === 0) return void 0;
|
|
254
|
+
/**
|
|
255
|
+
* Get the prompt for system message
|
|
256
|
+
*/
|
|
257
|
+
const systemPrompt = this.#options.systemPrompt;
|
|
258
|
+
/**
|
|
259
|
+
* Prepare the initial call options
|
|
260
|
+
*/
|
|
245
261
|
let currentOptions = {
|
|
246
262
|
model,
|
|
247
|
-
|
|
263
|
+
systemPrompt,
|
|
248
264
|
messages: state.messages,
|
|
249
|
-
tools:
|
|
265
|
+
tools: this.#options.toolClasses.map((tool) => tool.name)
|
|
250
266
|
};
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
267
|
+
/**
|
|
268
|
+
* Execute modifyModelRequest hooks from all middleware
|
|
269
|
+
*/
|
|
270
|
+
const middlewareList = this.#options.modifyModelRequestHookMiddleware;
|
|
271
|
+
for (const [middleware, getMiddlewareState] of middlewareList) {
|
|
272
|
+
/**
|
|
273
|
+
* Merge context with default context of middleware
|
|
274
|
+
*/
|
|
275
|
+
const context = middleware.contextSchema ? interopParse(middleware.contextSchema, config?.context || {}) : config?.context;
|
|
276
|
+
/**
|
|
277
|
+
* Create runtime
|
|
278
|
+
*/
|
|
257
279
|
const runtime = {
|
|
258
280
|
toolCalls: parseToolCalls(state.messages),
|
|
259
|
-
|
|
260
|
-
context
|
|
281
|
+
tools: this.#options.toolClasses,
|
|
282
|
+
context,
|
|
283
|
+
writer: config.writer,
|
|
284
|
+
interrupt: config.interrupt,
|
|
285
|
+
signal: config.signal,
|
|
286
|
+
terminate: (result$1) => ({
|
|
287
|
+
type: "terminate",
|
|
288
|
+
result: result$1
|
|
289
|
+
})
|
|
261
290
|
};
|
|
262
|
-
const result = await middleware.
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
291
|
+
const result = await middleware.modifyModelRequest(
|
|
292
|
+
currentOptions,
|
|
293
|
+
{
|
|
294
|
+
messages: state.messages,
|
|
295
|
+
...getMiddlewareState()
|
|
296
|
+
},
|
|
297
|
+
/**
|
|
298
|
+
* ensure runtime is frozen to prevent modifications
|
|
299
|
+
*/
|
|
300
|
+
Object.freeze({
|
|
301
|
+
...runtime,
|
|
302
|
+
context
|
|
303
|
+
})
|
|
304
|
+
);
|
|
305
|
+
/**
|
|
306
|
+
* raise meaningful error if unknown tools were selected
|
|
307
|
+
*/
|
|
308
|
+
const unknownTools = result?.tools?.filter((tool) => !this.#options.toolClasses.some((t) => t.name === tool)) ?? [];
|
|
309
|
+
if (unknownTools.length > 0) throw new Error(`Unknown tools selected in middleware "${middleware.name}": ${unknownTools.join(", ")}, available tools: ${this.#options.toolClasses.map((t) => t.name).join(", ")}!`);
|
|
269
310
|
if (result) currentOptions = {
|
|
270
311
|
...currentOptions,
|
|
271
312
|
...result
|
|
@@ -273,10 +314,11 @@ var AgentNode = class extends RunnableCallable {
|
|
|
273
314
|
}
|
|
274
315
|
return currentOptions;
|
|
275
316
|
}
|
|
276
|
-
async #bindTools(model, preparedOptions) {
|
|
277
|
-
const options = {
|
|
278
|
-
const structuredTools = Object.values(
|
|
279
|
-
const
|
|
317
|
+
async #bindTools(model, preparedOptions, structuredResponseFormat) {
|
|
318
|
+
const options = {};
|
|
319
|
+
const structuredTools = Object.values(structuredResponseFormat && "tools" in structuredResponseFormat ? structuredResponseFormat.tools : {});
|
|
320
|
+
const preparedTools = preparedOptions?.tools ?? [];
|
|
321
|
+
const allTools = [...preparedTools.length > 0 ? this.#options.toolClasses.filter((tool) => typeof tool.name === "string" && preparedTools.includes(tool.name)) : this.#options.toolClasses, ...structuredTools.map((toolStrategy) => toolStrategy.tool)];
|
|
280
322
|
/**
|
|
281
323
|
* If there are structured tools, we need to set the tool choice to "any"
|
|
282
324
|
* so that the model can choose to use a structured tool or not.
|
|
@@ -285,15 +327,15 @@ var AgentNode = class extends RunnableCallable {
|
|
|
285
327
|
/**
|
|
286
328
|
* check if the user requests a native schema output
|
|
287
329
|
*/
|
|
288
|
-
if (
|
|
330
|
+
if (structuredResponseFormat?.type === "native") {
|
|
289
331
|
/**
|
|
290
332
|
* if the model does not support JSON schema output, throw an error
|
|
291
333
|
*/
|
|
292
334
|
if (!hasSupportForJsonSchemaOutput(model)) throw new Error("Model does not support native structured output responses. Please use a model that supports native structured output responses or use a tool output.");
|
|
293
335
|
const jsonSchemaParams = {
|
|
294
|
-
name:
|
|
295
|
-
description: getSchemaDescription(
|
|
296
|
-
schema:
|
|
336
|
+
name: structuredResponseFormat.strategy.schema?.name ?? "extract",
|
|
337
|
+
description: getSchemaDescription(structuredResponseFormat.strategy.schema),
|
|
338
|
+
schema: structuredResponseFormat.strategy.schema,
|
|
297
339
|
strict: true
|
|
298
340
|
};
|
|
299
341
|
Object.assign(options, {
|
|
@@ -303,7 +345,7 @@ var AgentNode = class extends RunnableCallable {
|
|
|
303
345
|
},
|
|
304
346
|
ls_structured_output_format: {
|
|
305
347
|
kwargs: { method: "json_schema" },
|
|
306
|
-
schema:
|
|
348
|
+
schema: structuredResponseFormat.strategy.schema
|
|
307
349
|
},
|
|
308
350
|
strict: true
|
|
309
351
|
});
|
|
@@ -318,7 +360,7 @@ var AgentNode = class extends RunnableCallable {
|
|
|
318
360
|
/**
|
|
319
361
|
* Create a model runnable with the prompt and agent name
|
|
320
362
|
*/
|
|
321
|
-
const modelRunnable = getPromptRunnable(this.#options.
|
|
363
|
+
const modelRunnable = getPromptRunnable(preparedOptions?.systemPrompt ?? this.#options.systemPrompt).pipe(this.#options.includeAgentName === "inline" ? withAgentName(modelWithTools, this.#options.includeAgentName) : modelWithTools);
|
|
322
364
|
return modelRunnable;
|
|
323
365
|
}
|
|
324
366
|
static get nodeOptions() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AgentNode.js","names":["options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>","#run","#options","#structuredToolInfo","state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]","config: RunnableConfig","#invokeModel","#areMoreStepsNeeded","options: {\n lastMessage?: string;\n }","#deriveModel","#executePrepareModelRequestHooks","#bindTools","#getModelInputState","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","response: AIMessage","toolCalls: ToolCall[]","#handleToolStrategyError","toolCall: ToolCall","lastMessage?: string","error: ToolStrategyError","response: BaseMessage","model: LanguageModelLike","config: LangGraphRunnableConfig","systemMessage: BaseMessage | undefined","currentOptions: ModelRequest","runtime: Runtime<any>","preparedOptions?: ModelRequest","options: Partial<BaseChatModelCallOptions & AnthropicModelSettings>"],"sources":["../../../../src/agents/middlewareAgent/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport {\n BaseMessage,\n AIMessage,\n ToolMessage,\n SystemMessage,\n isBaseMessage,\n isToolMessage,\n} from \"@langchain/core/messages\";\nimport { z } from \"zod\";\nimport { Command, type LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n} from \"@langchain/core/utils/types\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\n\nimport { initChatModel } from \"../../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError } from \"../../errors.js\";\nimport { RunnableCallable } from \"../../RunnableCallable.js\";\nimport { PreHookAnnotation, AnyAnnotationRoot } from \"../../annotation.js\";\nimport {\n bindTools,\n getPromptRunnable,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n hasSupportForJsonSchemaOutput,\n} from \"../../utils.js\";\nimport { mergeAbortSignals } from \"../../nodes/utils.js\";\nimport {\n ModelRequest,\n CreateAgentParams,\n InternalAgentState,\n AnthropicModelSettings,\n Runtime,\n AgentMiddleware,\n} from \"../types.js\";\nimport type { ClientTool, ServerTool } from \"../../types.js\";\nimport { withAgentName } from \"../../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n} from \"../../responses.js\";\nimport { parseToolCalls, parseToolResults } from \"./utils.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\nexport interface AgentNodeOptions<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends Pick<\n CreateAgentParams<StructuredResponseFormat, ContextSchema>,\n | \"llm\"\n | \"model\"\n | \"prompt\"\n | \"includeAgentName\"\n | \"name\"\n | \"responseFormat\"\n | \"middlewares\"\n > {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n prepareModelRequestHookMiddlewares?: [\n AgentMiddleware<any, any, any>,\n () => any\n ][];\n}\n\nexport class AgentNode<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n { messages: BaseMessage[] } | { structuredResponse: StructuredResponseFormat }\n> {\n #options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>;\n\n #structuredToolInfo: Record<string, ToolStrategy> = {};\n\n constructor(\n options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) =>\n this.#run(input, config as RunnableConfig) as any,\n });\n\n this.#options = options;\n\n /**\n * Populate a list of structured tool info.\n */\n this.#structuredToolInfo = (\n transformResponseFormat(this.#options.responseFormat).filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce((acc, format) => {\n acc[format.name] = format;\n return acc;\n }, {} as Record<string, ToolStrategy>);\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages.at(-1);\n if (\n lastMessage &&\n isToolMessage(lastMessage) &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n /**\n * return directly without invoking the model again\n */\n return { messages: [] };\n }\n\n const response = await this.#invokeModel(state, config);\n\n /**\n * if we were able to generate a structured response, return it\n */\n if (\"structuredResponse\" in response) {\n return {\n messages: [...state.messages, ...(response.messages || [])],\n structuredResponse: response.structuredResponse,\n };\n }\n\n /**\n * if we need to direct the agent to the model, return the update\n */\n if (response instanceof Command) {\n return response;\n }\n\n response.name = this.name;\n response.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, response)) {\n return {\n messages: [\n new AIMessage(\"Sorry, need more steps to process this request.\", {\n name: this.name,\n lc_kwargs: { name: this.name },\n id: response.id,\n }),\n ],\n };\n }\n\n return { messages: [response] };\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n if (this.#options.model) {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n throw new Error(\"`model` option must be a string.\");\n }\n\n const model = this.#options.llm;\n\n /**\n * If the model is a function, call it to get the model.\n */\n if (typeof model === \"function\") {\n return model(state, config);\n }\n\n if (model) {\n return model;\n }\n\n throw new Error(\n \"No model option was provided, either via `model` or via `llm` option.\"\n );\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> {\n const model = await this.#deriveModel(state, config);\n\n /**\n * Execute prepareModelRequest hooks from beforeModelNodes\n */\n const preparedOptions = await this.#executePrepareModelRequestHooks(\n model,\n state,\n config\n );\n\n /**\n * If user provides a model in the preparedOptions, use it,\n * otherwise use the model from the options\n */\n const finalModel = preparedOptions?.model ?? model;\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(finalModel);\n\n const modelWithTools = await this.#bindTools(finalModel, preparedOptions);\n let modelInput = this.#getModelInputState(state);\n\n // Use messages from preparedOptions if provided\n if (preparedOptions?.messages) {\n modelInput = { ...modelInput, messages: preparedOptions.messages };\n }\n\n // Add system message if provided\n if (preparedOptions?.systemMessage) {\n // Prepend a system message if needed\n const systemMsg = new SystemMessage(preparedOptions.systemMessage);\n modelInput = {\n ...modelInput,\n messages: [systemMsg, ...modelInput.messages],\n };\n }\n\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const invokeConfig = {\n ...config,\n signal,\n };\n\n const response = (await modelWithTools.invoke(\n modelInput,\n invokeConfig\n )) as AIMessage;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n const structuredResponse = this.#options.responseFormat.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n }\n\n if (!response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in this.#structuredToolInfo\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(response, toolCalls);\n }\n\n const toolStrategy = this.#structuredToolInfo[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n toolMessageContent ?? options.lastMessage\n );\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[]\n ): Promise<Command> {\n /**\n * the following should never happen, let's throw an error if it does\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n throw new Error(\n \"Multiple structured outputs should not apply to native structured output responses\"\n );\n }\n\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0]\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = this.#structuredToolInfo[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(this.#structuredToolInfo).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided `true` as the `errorHandler` option, return a new AIMessage\n * with the error message and retry the tool call.\n */\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * throw otherwise, e.g. if `errorHandler` is not defined or set to `false`\n */\n throw error;\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n response instanceof AIMessage &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages)))\n );\n }\n\n #getModelInputState(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]\n ): Omit<InternalAgentState<StructuredResponseFormat>, \"llmInputMessages\"> {\n const { messages, llmInputMessages, ...rest } = state;\n if (llmInputMessages && llmInputMessages.length > 0) {\n return { messages: llmInputMessages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n return { messages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n\n async #executePrepareModelRequestHooks(\n model: LanguageModelLike,\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: LangGraphRunnableConfig\n ): Promise<ModelRequest | undefined> {\n if (\n !this.#options.prepareModelRequestHookMiddlewares ||\n this.#options.prepareModelRequestHookMiddlewares.length === 0\n ) {\n return undefined;\n }\n\n // Get the prompt for system message\n let systemMessage: BaseMessage | undefined;\n if (typeof this.#options.prompt === \"string\") {\n systemMessage = new SystemMessage(this.#options.prompt);\n } else if (isBaseMessage(this.#options.prompt)) {\n systemMessage = this.#options.prompt;\n }\n\n // Prepare the initial call options\n let currentOptions: ModelRequest = {\n model,\n systemMessage,\n messages: state.messages,\n tools: [],\n };\n\n // Execute prepareModelRequest hooks from all middlewares\n const middlewares = this.#options.prepareModelRequestHookMiddlewares;\n for (const [middleware, getMiddlewareState] of middlewares) {\n // Merge context with default context of middleware\n const context = {\n ...(middleware.contextSchema?.parse({}) || {}),\n ...(config?.context || {}),\n };\n\n // Create runtime\n const runtime: Runtime<any> = {\n toolCalls: parseToolCalls(state.messages),\n toolResults: parseToolResults(state.messages),\n context,\n };\n\n const result = await middleware.prepareModelRequest!(\n currentOptions,\n {\n messages: state.messages,\n ...getMiddlewareState(),\n },\n {\n ...runtime,\n context,\n }\n );\n\n if (result) {\n currentOptions = { ...currentOptions, ...result };\n }\n }\n\n return currentOptions;\n }\n\n async #bindTools(\n model: LanguageModelLike,\n preparedOptions?: ModelRequest\n ): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions & AnthropicModelSettings> =\n {\n ...preparedOptions?.modelSettings,\n };\n const structuredTools = Object.values(this.#structuredToolInfo);\n\n // Use tools from preparedOptions if provided, otherwise use default tools\n const allTools = this.#options.toolClasses.concat(\n ...structuredTools.map((toolStrategy) => toolStrategy.tool),\n ...(preparedOptions?.tools || [])\n );\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice =\n preparedOptions?.toolChoice ||\n (structuredTools.length > 0 ? \"any\" : undefined);\n\n /**\n * check if the user requests a native schema output\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n /**\n * if the model does not support JSON schema output, throw an error\n */\n if (!hasSupportForJsonSchemaOutput(model)) {\n throw new Error(\n \"Model does not support native structured output responses. Please use a model that supports native structured output responses or use a tool output.\"\n );\n }\n\n const jsonSchemaParams = {\n name: this.#options.responseFormat.schema?.name ?? \"extract\",\n description: getSchemaDescription(this.#options.responseFormat.schema),\n schema: this.#options.responseFormat.schema,\n strict: true,\n };\n\n Object.assign(options, {\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: this.#options.responseFormat.schema,\n },\n strict: true,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n */\n const modelRunnable = getPromptRunnable(this.#options.prompt).pipe(\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools\n );\n\n return modelRunnable;\n }\n\n static get nodeOptions() {\n return {\n input: z.object({\n messages: z.array(z.custom<BaseMessage>()),\n }),\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAkFA,IAAa,YAAb,cAMU,iBAGR;CACA;CAEA,sBAAoD,CAAE;CAEtD,YACEA,SACA;EACA,MAAM;GACJ,MAAM,QAAQ,QAAQ;GACtB,MAAM,CAAC,OAAO,WACZ,KAAKC,KAAK,OAAO,OAAyB;EAC7C,EAAC;EAEF,KAAKC,WAAW;;;;EAKhB,KAAKC,sBACH,wBAAwB,KAAKD,SAAS,eAAe,CAAC,OACpD,CAAC,WAAW,kB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":"AgentNode.js","names":["options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>","#run","#options","model: string | LanguageModelLike","state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]","config: RunnableConfig","#invokeModel","#areMoreStepsNeeded","options: {\n lastMessage?: string;\n }","#deriveModel","#executePrepareModelRequestHooks","#getResponseFormat","#bindTools","#getModelInputState","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","response: AIMessage","toolCalls: ToolCall[]","responseFormat: ToolResponseFormat","#handleToolStrategyError","toolCall: ToolCall","lastMessage?: string","error: ToolStrategyError","response: BaseMessage","model: LanguageModelLike","config: LangGraphRunnableConfig","currentOptions: ModelRequest","runtime: Runtime<unknown, unknown>","result","preparedOptions: ModelRequest | undefined","structuredResponseFormat: ResponseFormat | undefined","options: Partial<BaseChatModelCallOptions>"],"sources":["../../../../src/agents/middlewareAgent/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport { BaseMessage, AIMessage, ToolMessage } from \"@langchain/core/messages\";\nimport { z } from \"zod/v3\";\nimport { Command, type LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n interopParse,\n} from \"@langchain/core/utils/types\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\n\nimport { initChatModel } from \"../../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError } from \"../../errors.js\";\nimport { RunnableCallable } from \"../../RunnableCallable.js\";\nimport { PreHookAnnotation, AnyAnnotationRoot } from \"../../annotation.js\";\nimport {\n bindTools,\n getPromptRunnable,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n} from \"../../utils.js\";\nimport { mergeAbortSignals } from \"../../nodes/utils.js\";\nimport {\n ModelRequest,\n CreateAgentParams,\n InternalAgentState,\n Runtime,\n AgentMiddleware,\n} from \"../types.js\";\nimport type { ClientTool, ServerTool } from \"../../types.js\";\nimport { withAgentName } from \"../../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n hasSupportForJsonSchemaOutput,\n} from \"../../responses.js\";\nimport { parseToolCalls } from \"./utils.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\nexport interface AgentNodeOptions<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends Pick<\n CreateAgentParams<StructuredResponseFormat, ContextSchema>,\n | \"model\"\n | \"systemPrompt\"\n | \"includeAgentName\"\n | \"name\"\n | \"responseFormat\"\n | \"middleware\"\n > {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n modifyModelRequestHookMiddleware?: [\n AgentMiddleware<any, any, any>,\n () => any\n ][];\n}\n\ninterface NativeResponseFormat {\n type: \"native\";\n strategy: ProviderStrategy;\n}\n\ninterface ToolResponseFormat {\n type: \"tool\";\n tools: Record<string, ToolStrategy>;\n}\n\ntype ResponseFormat = NativeResponseFormat | ToolResponseFormat;\n\nexport class AgentNode<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n { messages: BaseMessage[] } | { structuredResponse: StructuredResponseFormat }\n> {\n #options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>;\n\n constructor(\n options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) =>\n this.#run(input, config as RunnableConfig) as any,\n });\n\n this.#options = options;\n }\n\n /**\n * Returns response format primtivies based on given model and response format provided by the user.\n *\n * If the the user selects a tool output:\n * - return a record of tools to extract structured output from the model's response\n *\n * if the the user selects a native schema output or if the model supports JSON schema output:\n * - return a provider strategy to extract structured output from the model's response\n *\n * @param model - The model to get the response format for.\n * @returns The response format.\n */\n #getResponseFormat(\n model: string | LanguageModelLike\n ): ResponseFormat | undefined {\n if (!this.#options.responseFormat) {\n return undefined;\n }\n\n const strategies = transformResponseFormat(\n this.#options.responseFormat,\n undefined,\n model\n );\n\n /**\n * we either define a list of provider strategies or a list of tool strategies\n */\n const isProviderStrategy = strategies.every(\n (format) => format instanceof ProviderStrategy\n );\n\n /**\n * Populate a list of structured tool info.\n */\n if (!isProviderStrategy) {\n return {\n type: \"tool\",\n tools: (\n strategies.filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce((acc, format) => {\n acc[format.name] = format;\n return acc;\n }, {} as Record<string, ToolStrategy>),\n };\n }\n\n return {\n type: \"native\",\n /**\n * there can only be one provider strategy\n */\n strategy: strategies[0] as ProviderStrategy,\n };\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages.at(-1);\n if (\n lastMessage &&\n ToolMessage.isInstance(lastMessage) &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n /**\n * return directly without invoking the model again\n */\n return { messages: [] };\n }\n\n const response = await this.#invokeModel(state, config);\n\n /**\n * if we were able to generate a structured response, return it\n */\n if (\"structuredResponse\" in response) {\n return {\n messages: [...state.messages, ...(response.messages || [])],\n structuredResponse: response.structuredResponse,\n };\n }\n\n /**\n * if we need to direct the agent to the model, return the update\n */\n if (response instanceof Command) {\n return response;\n }\n\n response.name = this.name;\n response.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, response)) {\n return {\n messages: [\n new AIMessage({\n content: \"Sorry, need more steps to process this request.\",\n name: this.name,\n id: response.id,\n }),\n ],\n };\n }\n\n return { messages: [response] };\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel() {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n if (this.#options.model) {\n return this.#options.model;\n }\n\n throw new Error(\"No model option was provided, either via `model` option.\");\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> {\n const model = await this.#deriveModel();\n\n /**\n * Execute modifyModelRequest hooks from beforeModelNodes\n */\n const preparedOptions = await this.#executePrepareModelRequestHooks(\n model,\n state,\n config\n );\n\n /**\n * If user provides a model in the preparedOptions, use it,\n * otherwise use the model from the options\n */\n const finalModel = preparedOptions?.model ?? model;\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(finalModel);\n\n const structuredResponseFormat = this.#getResponseFormat(finalModel);\n const modelWithTools = await this.#bindTools(\n finalModel,\n preparedOptions,\n structuredResponseFormat\n );\n let modelInput = this.#getModelInputState(state);\n\n /**\n * Use messages from preparedOptions if provided\n */\n if (preparedOptions?.messages) {\n modelInput = { ...modelInput, messages: preparedOptions.messages };\n }\n\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const invokeConfig = { ...config, signal };\n const response = (await modelWithTools.invoke(\n modelInput,\n invokeConfig\n )) as AIMessage;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (structuredResponseFormat?.type === \"native\") {\n const structuredResponse =\n structuredResponseFormat.strategy.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n\n return response;\n }\n\n if (!structuredResponseFormat || !response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in structuredResponseFormat.tools\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(\n response,\n toolCalls,\n structuredResponseFormat\n );\n }\n\n const toolStrategy = structuredResponseFormat.tools[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n structuredResponseFormat,\n toolMessageContent ?? options.lastMessage\n );\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[],\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0],\n responseFormat\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = responseFormat.tools[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall,\n responseFormat\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(responseFormat.tools).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided `true` as the `errorHandler` option, return a new AIMessage\n * with the error message and retry the tool call.\n */\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * throw otherwise, e.g. if `errorHandler` is not defined or set to `false`\n */\n throw error;\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n AIMessage.isInstance(response) &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages)))\n );\n }\n\n #getModelInputState(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]\n ): Omit<InternalAgentState<StructuredResponseFormat>, \"llmInputMessages\"> {\n const { messages, llmInputMessages, ...rest } = state;\n if (llmInputMessages && llmInputMessages.length > 0) {\n return { messages: llmInputMessages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n return { messages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n\n async #executePrepareModelRequestHooks(\n model: LanguageModelLike,\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: LangGraphRunnableConfig\n ): Promise<ModelRequest | undefined> {\n if (\n !this.#options.modifyModelRequestHookMiddleware ||\n this.#options.modifyModelRequestHookMiddleware.length === 0\n ) {\n return undefined;\n }\n\n /**\n * Get the prompt for system message\n */\n const systemPrompt = this.#options.systemPrompt;\n\n /**\n * Prepare the initial call options\n */\n let currentOptions: ModelRequest = {\n model,\n systemPrompt,\n messages: state.messages,\n tools: this.#options.toolClasses.map((tool) => tool.name as string),\n };\n\n /**\n * Execute modifyModelRequest hooks from all middleware\n */\n const middlewareList = this.#options.modifyModelRequestHookMiddleware;\n for (const [middleware, getMiddlewareState] of middlewareList) {\n /**\n * Merge context with default context of middleware\n */\n const context = middleware.contextSchema\n ? interopParse(middleware.contextSchema, config?.context || {})\n : config?.context;\n\n /**\n * Create runtime\n */\n const runtime: Runtime<unknown, unknown> = {\n toolCalls: parseToolCalls(state.messages),\n tools: this.#options.toolClasses,\n context,\n writer: config.writer,\n interrupt: config.interrupt,\n signal: config.signal,\n terminate: (result) => ({ type: \"terminate\", result }),\n };\n\n const result = await middleware.modifyModelRequest!(\n currentOptions,\n {\n messages: state.messages,\n ...getMiddlewareState(),\n },\n /**\n * ensure runtime is frozen to prevent modifications\n */\n Object.freeze({\n ...runtime,\n context,\n })\n );\n\n /**\n * raise meaningful error if unknown tools were selected\n */\n const unknownTools =\n result?.tools?.filter(\n (tool) => !this.#options.toolClasses.some((t) => t.name === tool)\n ) ?? [];\n if (unknownTools.length > 0) {\n throw new Error(\n `Unknown tools selected in middleware \"${\n middleware.name\n }\": ${unknownTools.join(\n \", \"\n )}, available tools: ${this.#options.toolClasses\n .map((t) => t.name)\n .join(\", \")}!`\n );\n }\n\n if (result) {\n currentOptions = { ...currentOptions, ...result };\n }\n }\n\n return currentOptions;\n }\n\n async #bindTools(\n model: LanguageModelLike,\n preparedOptions: ModelRequest | undefined,\n structuredResponseFormat: ResponseFormat | undefined\n ): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions> = {};\n const structuredTools = Object.values(\n structuredResponseFormat && \"tools\" in structuredResponseFormat\n ? structuredResponseFormat.tools\n : {}\n );\n\n // Use tools from preparedOptions if provided, otherwise use default tools\n const preparedTools = preparedOptions?.tools ?? [];\n const allTools = [\n ...(preparedTools.length > 0\n ? this.#options.toolClasses.filter(\n (tool) =>\n typeof tool.name === \"string\" && preparedTools.includes(tool.name)\n )\n : this.#options.toolClasses),\n ...structuredTools.map((toolStrategy) => toolStrategy.tool),\n ];\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice =\n preparedOptions?.toolChoice ||\n (structuredTools.length > 0 ? \"any\" : undefined);\n\n /**\n * check if the user requests a native schema output\n */\n if (structuredResponseFormat?.type === \"native\") {\n /**\n * if the model does not support JSON schema output, throw an error\n */\n if (!hasSupportForJsonSchemaOutput(model)) {\n throw new Error(\n \"Model does not support native structured output responses. Please use a model that supports native structured output responses or use a tool output.\"\n );\n }\n\n const jsonSchemaParams = {\n name: structuredResponseFormat.strategy.schema?.name ?? \"extract\",\n description: getSchemaDescription(\n structuredResponseFormat.strategy.schema\n ),\n schema: structuredResponseFormat.strategy.schema,\n strict: true,\n };\n\n Object.assign(options, {\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: structuredResponseFormat.strategy.schema,\n },\n strict: true,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n */\n const modelRunnable = getPromptRunnable(\n preparedOptions?.systemPrompt ?? this.#options.systemPrompt\n ).pipe(\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools\n );\n\n return modelRunnable;\n }\n\n static get nodeOptions(): {\n input: z.ZodObject<{ messages: z.ZodArray<z.ZodType<BaseMessage>> }>;\n } {\n return {\n input: z.object({\n messages: z.array(z.custom<BaseMessage>()),\n }),\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAuFA,IAAa,YAAb,cAMU,iBAGR;CACA;CAEA,YACEA,SACA;EACA,MAAM;GACJ,MAAM,QAAQ,QAAQ;GACtB,MAAM,CAAC,OAAO,WACZ,KAAKC,KAAK,OAAO,OAAyB;EAC7C,EAAC;EAEF,KAAKC,WAAW;CACjB;;;;;;;;;;;;;CAcD,mBACEC,OAC4B;AAC5B,MAAI,CAAC,KAAKD,SAAS,eACjB,QAAO;EAGT,MAAM,aAAa,wBACjB,KAAKA,SAAS,gBACd,QACA,MACD;;;;EAKD,MAAM,qBAAqB,WAAW,MACpC,CAAC,WAAW,kBAAkB,iBAC/B;;;;AAKD,M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AO,UAAU;GACtD,GAAG;GACH,aAAa;EACd,EAAC;;;;EAKF,MAAM,gBAAgB,kBACpB,iBAAiB,gBAAgB,KAAKA,SAAS,aAChD,CAAC,KACA,KAAKA,SAAS,qBAAqB,WAC/B,cAAc,gBAAgB,KAAKA,SAAS,iBAAiB,GAC7D,eACL;AAED,SAAO;CACR;CAED,WAAW,cAET;AACA,SAAO,EACL,OAAO,EAAE,OAAO,EACd,UAAU,EAAE,MAAM,EAAE,QAAqB,CAAC,CAC3C,EAAC,CACH;CACF;AACF"}
|
|
@@ -17,8 +17,8 @@ var BeforeModelNode = class extends require_middleware.MiddlewareNode {
|
|
|
17
17
|
});
|
|
18
18
|
this.middleware = middleware;
|
|
19
19
|
}
|
|
20
|
-
runHook(state, runtime
|
|
21
|
-
return this.middleware.beforeModel(state, runtime
|
|
20
|
+
runHook(state, runtime) {
|
|
21
|
+
return this.middleware.beforeModel(state, runtime);
|
|
22
22
|
}
|
|
23
23
|
};
|
|
24
24
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BeforeModalNode.cjs","names":["MiddlewareNode","middleware: AgentMiddleware<any, any, any>","state: TStateSchema","config?: RunnableConfig<TContextSchema>","runtime: Runtime<
|
|
1
|
+
{"version":3,"file":"BeforeModalNode.cjs","names":["MiddlewareNode","middleware: AgentMiddleware<any, any, any>","state: TStateSchema","config?: RunnableConfig<TContextSchema>","runtime: Runtime<TStateSchema, TContextSchema>"],"sources":["../../../../src/agents/middlewareAgent/nodes/BeforeModalNode.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { RunnableConfig } from \"@langchain/core/runnables\";\nimport { MiddlewareNode } from \"./middleware.js\";\nimport type {\n AgentBuiltInState,\n AgentMiddleware,\n MiddlewareResult,\n Runtime,\n} from \"../types.js\";\n\n/**\n * Node for executing a single middleware's beforeModel hook.\n */\nexport class BeforeModelNode<\n TStateSchema extends Record<string, any> = Record<string, any>,\n TContextSchema extends Record<string, any> = Record<string, any>\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"beforeModalNodes\"];\n\n constructor(public middleware: AgentMiddleware<any, any, any>) {\n super({\n name: `BeforeModelNode_${middleware.name}`,\n func: async (\n state: TStateSchema,\n config?: RunnableConfig<TContextSchema>\n ) => this.invokeMiddleware(state, config),\n });\n }\n\n runHook(state: TStateSchema, runtime: Runtime<TStateSchema, TContextSchema>) {\n return this.middleware.beforeModel!(\n state as Record<string, any> & AgentBuiltInState,\n runtime as Runtime<TStateSchema, unknown>\n ) as Promise<MiddlewareResult<TStateSchema>>;\n }\n}\n"],"mappings":";;;;;;AAaA,IAAa,kBAAb,cAGUA,kCAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;CAAmB;CAE1D,YAAmBC,YAA4C;EAC7D,MAAM;GACJ,MAAM,CAAC,gBAAgB,EAAE,WAAW,MAAM;GAC1C,MAAM,OACJC,OACAC,WACG,KAAK,iBAAiB,OAAO,OAAO;EAC1C,EAAC;EAPe;CAQlB;CAED,QAAQD,OAAqBE,SAAgD;AAC3E,SAAO,KAAK,WAAW,YACrB,OACA,QACD;CACF;AACF"}
|
|
@@ -17,8 +17,8 @@ var BeforeModelNode = class extends MiddlewareNode {
|
|
|
17
17
|
});
|
|
18
18
|
this.middleware = middleware;
|
|
19
19
|
}
|
|
20
|
-
runHook(state, runtime
|
|
21
|
-
return this.middleware.beforeModel(state, runtime
|
|
20
|
+
runHook(state, runtime) {
|
|
21
|
+
return this.middleware.beforeModel(state, runtime);
|
|
22
22
|
}
|
|
23
23
|
};
|
|
24
24
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BeforeModalNode.js","names":["middleware: AgentMiddleware<any, any, any>","state: TStateSchema","config?: RunnableConfig<TContextSchema>","runtime: Runtime<
|
|
1
|
+
{"version":3,"file":"BeforeModalNode.js","names":["middleware: AgentMiddleware<any, any, any>","state: TStateSchema","config?: RunnableConfig<TContextSchema>","runtime: Runtime<TStateSchema, TContextSchema>"],"sources":["../../../../src/agents/middlewareAgent/nodes/BeforeModalNode.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { RunnableConfig } from \"@langchain/core/runnables\";\nimport { MiddlewareNode } from \"./middleware.js\";\nimport type {\n AgentBuiltInState,\n AgentMiddleware,\n MiddlewareResult,\n Runtime,\n} from \"../types.js\";\n\n/**\n * Node for executing a single middleware's beforeModel hook.\n */\nexport class BeforeModelNode<\n TStateSchema extends Record<string, any> = Record<string, any>,\n TContextSchema extends Record<string, any> = Record<string, any>\n> extends MiddlewareNode<TStateSchema, TContextSchema> {\n lc_namespace = [\"langchain\", \"agents\", \"beforeModalNodes\"];\n\n constructor(public middleware: AgentMiddleware<any, any, any>) {\n super({\n name: `BeforeModelNode_${middleware.name}`,\n func: async (\n state: TStateSchema,\n config?: RunnableConfig<TContextSchema>\n ) => this.invokeMiddleware(state, config),\n });\n }\n\n runHook(state: TStateSchema, runtime: Runtime<TStateSchema, TContextSchema>) {\n return this.middleware.beforeModel!(\n state as Record<string, any> & AgentBuiltInState,\n runtime as Runtime<TStateSchema, unknown>\n ) as Promise<MiddlewareResult<TStateSchema>>;\n }\n}\n"],"mappings":";;;;;;AAaA,IAAa,kBAAb,cAGU,eAA6C;CACrD,eAAe;EAAC;EAAa;EAAU;CAAmB;CAE1D,YAAmBA,YAA4C;EAC7D,MAAM;GACJ,MAAM,CAAC,gBAAgB,EAAE,WAAW,MAAM;GAC1C,MAAM,OACJC,OACAC,WACG,KAAK,iBAAiB,OAAO,OAAO;EAC1C,EAAC;EAPe;CAQlB;CAED,QAAQD,OAAqBE,SAAgD;AAC3E,SAAO,KAAK,WAAW,YACrB,OACA,QACD;CACF;AACF"}
|