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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.cts","names":["InteropZodObject","InteropZodType","LangGraphRunnableConfig","START","StateGraph","LanguageModelLike","BaseChatModel","SystemMessage","BaseMessageLike","BaseMessage","All","BaseCheckpointSaver","BaseStore","DynamicTool","StructuredToolInterface","Runnable","RunnableLike","RunnableToolLike","ToolNode","PreHookAnnotation","AnyAnnotationRoot","ToAnnotationRoot","ResponseFormat","ToolStrategy","TypedToolStrategy","ProviderStrategy","ResponseFormatUndefined","JsonSchemaFormat","META_EXTRAS_DESCRIPTION_PREFIX","N","ExecutedToolCall","Record","LLMCall","ExtractZodType","T","U","ExtractZodArrayTypes","Rest","A","InferResponseFormatType","ReducedZodChannel","TReducerSchema","ServerTool","ClientTool","Prompt","StateSchema","ContextSchema","Promise","AgentState","AnnotationRoot","AgentRuntime","ContextType","AbortSignal","CreateAgentParams","StructuredResponseType","DynamicLLMFunction","ResponseFormatType","ConfigurableModelInterface","InternalAgentState","WithStateGraphNodes","Graph","SD","S","K","I","O","C"],"sources":["../../src/agents/types.d.ts"],"sourcesContent":["import type { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport type { LangGraphRunnableConfig, START, StateGraph } from \"@langchain/langgraph\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport type { SystemMessage, BaseMessageLike, BaseMessage } from \"@langchain/core/messages\";\nimport type { All, BaseCheckpointSaver, BaseStore } from \"@langchain/langgraph-checkpoint\";\nimport type { DynamicTool, StructuredToolInterface } from \"@langchain/core/tools\";\nimport type { Runnable, RunnableLike, RunnableToolLike } from \"@langchain/core/runnables\";\nimport type { ToolNode } from \"./nodes/ToolNode.js\";\nimport type { PreHookAnnotation, AnyAnnotationRoot, ToAnnotationRoot } from \"./annotation.js\";\nimport type { ResponseFormat, ToolStrategy, TypedToolStrategy, ProviderStrategy, ResponseFormatUndefined, JsonSchemaFormat } from \"./responses.js\";\nexport declare const META_EXTRAS_DESCRIPTION_PREFIX = \"lg:\";\nexport type N = typeof START | \"agent\" | \"tools\";\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ExecutedToolCall {\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, unknown>;\n /**\n * The ID of the tool call.\n */\n tool_id: string;\n /**\n * The result of the tool call (if available).\n */\n result?: unknown;\n}\n/**\n * Information about an LLM invocation.\n */\nexport interface LLMCall {\n /**\n * The messages that were sent to the LLM.\n */\n messages: BaseMessage[];\n /**\n * The response from the LLM.\n */\n response?: BaseMessage;\n}\n/**\n * Type helper to extract the inferred type from a single Zod schema or array of schemas\n */\nexport type ExtractZodType<T> = T extends InteropZodType<infer U> ? U : T extends readonly InteropZodType<any>[] ? ExtractZodArrayTypes<T> : never;\n/**\n * Type helper to extract union type from an array of Zod schemas\n */\nexport type ExtractZodArrayTypes<T extends readonly InteropZodType<any>[]> = T extends readonly [InteropZodType<infer A>, ...infer Rest] ? Rest extends readonly InteropZodType<any>[] ? A | ExtractZodArrayTypes<Rest> : A : never;\n/**\n * Type helper to extract the structured response type from responseFormat\n */\nexport type InferResponseFormatType<T> = T extends InteropZodType<infer U> ? U extends Record<string, any> ? U : Record<string, any> : T extends readonly InteropZodType<any>[] ? ExtractZodArrayTypes<T> : T extends ToolStrategy[] ? Record<string, any> // ToolStrategy arrays will be handled at runtime\n : T extends ResponseFormat ? Record<string, any> // Single ResponseFormat will be handled at runtime\n : Record<string, any>;\n/** @internal */\nexport type ReducedZodChannel<T extends InteropZodType, TReducerSchema extends InteropZodType> = T & {\n lg_reducer_schema: TReducerSchema;\n};\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool = StructuredToolInterface | DynamicTool | RunnableToolLike;\nexport type Prompt<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = SystemMessage | string | ((state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], config: LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>) => BaseMessageLike[] | Promise<BaseMessageLike[]>) | Runnable;\nexport type AgentState<AnnotationRoot extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = ToAnnotationRoot<AnnotationRoot>[\"State\"] & PreHookAnnotation[\"State\"];\nexport interface AgentRuntime<ContextType = Record<string, unknown>> {\n /**\n * The context of the agent.\n */\n context?: ContextType;\n /**\n * The store passed to the agent.\n */\n store?: BaseStore;\n /**\n * The writer of the agent to write to the output stream.\n */\n writer?: (chunk: unknown) => void;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n}\nexport type CreateAgentParams<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nStructuredResponseType extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ResponseFormatType = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined> = {\n /** The chat model that can utilize OpenAI-style tool calling. */\n llm?: LanguageModelLike | DynamicLLMFunction<StateSchema, ContextSchema>;\n /**\n * Initializes a ChatModel based on the provided model name and provider.\n * It supports various model providers and allows for runtime configuration of model parameters.\n *\n * @uses {@link initChatModel}\n * @example\n * ```ts\n * const agent = createAgent({\n * model: \"anthropic:claude-3-7-sonnet-latest\",\n * // ...\n * });\n * ```\n */\n model?: string;\n /** A list of tools or a ToolNode. */\n tools: ToolNode | (ServerTool | ClientTool)[];\n /**\n * An optional prompt for the LLM. This takes full graph state BEFORE the LLM is called and prepares the input to LLM.\n *\n * Can take a few different forms:\n *\n * - str: This is converted to a SystemMessage and added to the beginning of the list of messages in state[\"messages\"].\n * - SystemMessage: this is added to the beginning of the list of messages in state[\"messages\"].\n * - Function: This function should take in full graph state and the output is then passed to the language model.\n * - Runnable: This runnable should take in full graph state and the output is then passed to the language model.\n *\n * Note:\n * Prior to `v0.2.46`, the prompt was set using `stateModifier` / `messagesModifier` parameters.\n * This is now deprecated and will be removed in a future release.\n *\n * Cannot be used together with `prepareCall`.\n */\n prompt?: Prompt<StateSchema, ContextSchema>;\n /**\n * Additional state schema for the agent. It allows to define additional state keys that will be\n * persisted between agent invocations.\n *\n * @example\n * ```ts\n * // State schema defines data that persists across agent invocations\n * const stateSchema = z.object({\n * userPreferences: z.object({\n * theme: z.enum([\"light\", \"dark\"]),\n * language: z.string(),\n * }),\n * taskHistory: z.array(z.string()),\n * currentWorkflow: z.string().optional(),\n * });\n *\n * // Context schema defines runtime parameters passed per invocation\n * const contextSchema = z.object({ ... });\n *\n * const agent = createAgent({\n * llm: model,\n * tools: [updatePreferences, addTask],\n * stateSchema, // Persisted: preferences, e.g. task history, workflow state\n * contextSchema, // Per-invocation: user ID, session, API keys, etc.\n * prompt: (state, config) => {\n * // ...\n * },\n * });\n *\n * // First invocation - state starts empty, context provided\n * await agent.invoke({\n * messages: [new HumanMessage(\"Set my theme to dark\")],\n * }, {\n * context: { userId: \"user123\", sessionId: \"sess456\", apiKeys: {...} }\n * });\n *\n * // Second invocation - state persists, new context\n * await agent.invoke({\n * messages: [new HumanMessage(\"Add a task to review code\")],\n * }, {\n * context: { userId: \"user123\", sessionId: \"sess789\", apiKeys: {...} }\n * });\n * // State now contains: userPreferences.theme=\"dark\", taskHistory=[\"review code\"]\n * ```\n */\n stateSchema?: StateSchema;\n /**\n * An optional schema for the context. It allows to pass in a typed context object into the agent\n * invocation and allows to access it in hooks such as `prompt`, `preModelHook`, `postModelHook`, etc.\n * As opposed to the agent state, defined in `stateSchema`, the context is not persisted between\n * agent invocations.\n *\n * @example\n * ```ts\n * const agent = createAgent({\n * llm: model,\n * tools: [getWeather],\n * contextSchema: z.object({\n * capital: z.string(),\n * }),\n * prompt: (state, config) => {\n * return [\n * new SystemMessage(`You are a helpful assistant. The capital of France is ${config.context.capital}.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new SystemMessage(\"You are a helpful assistant.\"),\n * new HumanMessage(\"What is the capital of France?\"),\n * ],\n * }, {\n * context: {\n * capital: \"Paris\",\n * },\n * });\n * ```\n */\n contextSchema?: ContextSchema;\n /** An optional checkpoint saver to persist the agent's state. */\n checkpointSaver?: BaseCheckpointSaver | boolean;\n /** An optional checkpoint saver to persist the agent's state. Alias of \"checkpointSaver\". */\n checkpointer?: BaseCheckpointSaver | boolean;\n /** An optional list of node names to interrupt before running. */\n interruptBefore?: N[] | All;\n /** An optional list of node names to interrupt after running. */\n interruptAfter?: N[] | All;\n store?: BaseStore;\n /**\n * An optional schema for the final agent output.\n *\n * If provided, output will be formatted to match the given schema and returned in the 'structuredResponse' state key.\n * If not provided, `structuredResponse` will not be present in the output state.\n *\n * Can be passed in as:\n * - Zod schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: z.object({\n * capital: z.string(),\n * }),\n * // ...\n * });\n * ```\n * - JSON schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: {\n * type: \"json_schema\",\n * schema: {\n * type: \"object\",\n * properties: {\n * capital: { type: \"string\" },\n * },\n * required: [\"capital\"],\n * },\n * },\n * // ...\n * });\n * ```\n * - Create React Agent ResponseFormat\n * ```ts\n * import { providerStrategy, toolStrategy } from \"langchain\";\n * const agent = createAgent({\n * responseFormat: providerStrategy(\n * z.object({\n * capital: z.string(),\n * })\n * ),\n * // or\n * responseFormat: [\n * toolStrategy({ ... }),\n * toolStrategy({ ... }),\n * ]\n * // ...\n * });\n * ```\n *\n * **Note**: The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.\n * This is not the only strategy to get structured responses, see more options in [this guide](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output/).\n */\n responseFormat?: ResponseFormatType;\n /**\n * An optional name for the agent.\n */\n name?: string;\n /**\n * An optional description for the agent.\n * This can be used to describe the agent to the underlying supervisor LLM.\n */\n description?: string;\n /**\n * Use to specify how to expose the agent name to the underlying supervisor LLM.\n * - `undefined`: Relies on the LLM provider {@link AIMessage#name}. Currently, only OpenAI supports this.\n * - `\"inline\"`: Add the agent name directly into the content field of the {@link AIMessage} using XML-style tags.\n * Example: `\"How can I help you\"` -> `\"<name>agent_name</name><content>How can I help you?</content>\"`\n */\n includeAgentName?: \"inline\" | undefined;\n /**\n * An optional node to add before the `agent` node (i.e., the node that calls the LLM).\n * Useful for managing long message histories (e.g., message trimming, summarization, etc.).\n */\n preModelHook?: RunnableLike<ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], ToAnnotationRoot<StateSchema>[\"Update\"] & PreHookAnnotation[\"Update\"], LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>>;\n /**\n * An optional node to add after the `agent` node (i.e., the node that calls the LLM).\n * Useful for implementing human-in-the-loop, guardrails, validation, or other post-processing.\n */\n postModelHook?: RunnableLike<ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], ToAnnotationRoot<StateSchema>[\"Update\"] & PreHookAnnotation[\"Update\"], LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>>;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n /**\n * Determines the version of the graph to create.\n *\n * Can be one of\n * - `\"v1\"`: The tool node processes a single message. All tool calls in the message are\n * executed in parallel within the tool node.\n * - `\"v2\"`: The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n *\n * @default `\"v2\"`\n */\n version?: \"v1\" | \"v2\";\n};\nexport interface ConfigurableModelInterface {\n _queuedMethodOperations: Record<string, unknown>;\n _model: () => Promise<BaseChatModel>;\n}\nexport type InternalAgentState<StructuredResponseType extends Record<string, unknown> | undefined = Record<string, unknown>> = {\n messages: BaseMessage[];\n} & (StructuredResponseType extends ResponseFormatUndefined ? Record<string, never> : {\n structuredResponse: StructuredResponseType;\n});\nexport type WithStateGraphNodes<K extends string, Graph> = Graph extends StateGraph<infer SD, infer S, infer U, infer N, infer I, infer O, infer C> ? StateGraph<SD, S, U, N | K, I, O, C> : never;\n/**\n * @deprecated likely to be removed in the next version of the agent\n */\ntype DynamicLLMFunction<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = (state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], runtime: AgentRuntime<ToAnnotationRoot<ContextSchema>[\"State\"]>) => Promise<LanguageModelLike> | LanguageModelLike;\nexport {};\n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AAA,MAAAA;EAAmB;EAEf,KAAKD,EAvGjBQ,QAuGiBR,GAAAA,CAvGLgC,UAuGKhC,GAvGQiC,UAuGRjC,CAAAA,EAAAA;EAAG;;;;;;;;;;;;;;;;EAmFkB,MAAyBS,CAAAA,EAzK7DyB,MAyK6DzB,CAzKtD0B,WAyKsD1B,EAzKzC2B,aAyKyC3B,CAAAA;EAAiB;;;;;;;;AAInE;AAuB2K;;;;;;;;;;;;;;;;;AAIoL;;;;;;;;;;;;;;;;;;;gBA1JrW0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAkCEC;;oBAEEnC;;iBAEHA;;oBAEGkB,MAAMnB;;mBAEPmB,MAAMnB;UACfE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mBAsDS4C;;;;;;;;;;;;;;;;;;;;;iBAqBFxC,aAAaK,iBAAiBwB,wBAAwB1B,4BAA4BE,iBAAiBwB,yBAAyB1B,6BAA6BjB,wBAAwBmB,iBAAiByB;;;;;kBAKjM9B,aAAaK,iBAAiBwB,wBAAwB1B,4BAA4BE,iBAAiBwB,yBAAyB1B,6BAA6BjB,wBAAwBmB,iBAAiByB;;;;WAIzMM;;;;;;;;;;;;;;;;;KA2BRG,uCAAuCnC,oBAAoBpB,mBAAmBoB,yCAAyCA,oBAAoBpB,mBAAmBoB,6BAA6BC,iBAAiBwB,wBAAwB1B,qCAAqC+B,aAAa7B,iBAAiByB,6BAA6BC,QAAQ1C,qBAAqBA"}
|
|
1
|
+
{"version":3,"file":"types.d.cts","names":["InteropZodObject","InteropZodType","LangGraphRunnableConfig","START","StateGraph","LanguageModelLike","SystemMessage","BaseMessageLike","BaseMessage","All","BaseCheckpointSaver","BaseStore","DynamicTool","StructuredToolInterface","Runnable","RunnableLike","RunnableToolLike","ToolNode","PreHookAnnotation","AnyAnnotationRoot","ToAnnotationRoot","ResponseFormatUndefined","ResponseFormat","ToolStrategy","TypedToolStrategy","ProviderStrategy","JsonSchemaFormat","META_EXTRAS_DESCRIPTION_PREFIX","N","ExecutedToolCall","Record","LLMCall","ExtractZodType","T","U","ExtractZodArrayTypes","Rest","A","InferResponseFormatType","ReducedZodChannel","TReducerSchema","ServerTool","ClientTool","Prompt","StateSchema","ContextSchema","Promise","AgentState","AnnotationRoot","AgentRuntime","ContextType","AbortSignal","CreateAgentParams","StructuredResponseType","DynamicLLMFunction","ResponseFormatType","InternalAgentState","WithStateGraphNodes","Graph","SD","S","K","I","O","C"],"sources":["../../src/agents/types.d.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport type { LangGraphRunnableConfig, START, StateGraph } from \"@langchain/langgraph\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { SystemMessage, BaseMessageLike, BaseMessage } from \"@langchain/core/messages\";\nimport type { All, BaseCheckpointSaver, BaseStore } from \"@langchain/langgraph-checkpoint\";\nimport type { DynamicTool, StructuredToolInterface } from \"@langchain/core/tools\";\nimport type { Runnable, RunnableLike, RunnableToolLike } from \"@langchain/core/runnables\";\nimport type { ToolNode } from \"./nodes/ToolNode.js\";\nimport type { PreHookAnnotation, AnyAnnotationRoot, ToAnnotationRoot, ResponseFormatUndefined } from \"./annotation.js\";\nimport type { ResponseFormat, ToolStrategy, TypedToolStrategy, ProviderStrategy, JsonSchemaFormat } from \"./responses.js\";\nexport declare const META_EXTRAS_DESCRIPTION_PREFIX = \"lg:\";\nexport type N = typeof START | \"agent\" | \"tools\";\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ExecutedToolCall {\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, unknown>;\n /**\n * The ID of the tool call.\n */\n tool_id: string;\n /**\n * The result of the tool call (if available).\n */\n result?: unknown;\n}\n/**\n * Information about an LLM invocation.\n */\nexport interface LLMCall {\n /**\n * The messages that were sent to the LLM.\n */\n messages: BaseMessage[];\n /**\n * The response from the LLM.\n */\n response?: BaseMessage;\n}\n/**\n * Type helper to extract the inferred type from a single Zod schema or array of schemas\n */\nexport type ExtractZodType<T> = T extends InteropZodType<infer U> ? U : T extends readonly InteropZodType<any>[] ? ExtractZodArrayTypes<T> : never;\n/**\n * Type helper to extract union type from an array of Zod schemas\n */\nexport type ExtractZodArrayTypes<T extends readonly InteropZodType<any>[]> = T extends readonly [InteropZodType<infer A>, ...infer Rest] ? Rest extends readonly InteropZodType<any>[] ? A | ExtractZodArrayTypes<Rest> : A : never;\n/**\n * Type helper to extract the structured response type from responseFormat\n */\nexport type InferResponseFormatType<T> = T extends InteropZodType<infer U> ? U extends Record<string, any> ? U : Record<string, any> : T extends readonly InteropZodType<any>[] ? ExtractZodArrayTypes<T> : T extends ToolStrategy[] ? Record<string, any> // ToolStrategy arrays will be handled at runtime\n : T extends ResponseFormat ? Record<string, any> // Single ResponseFormat will be handled at runtime\n : Record<string, any>;\n/** @internal */\nexport type ReducedZodChannel<T extends InteropZodType, TReducerSchema extends InteropZodType> = T & {\n lg_reducer_schema: TReducerSchema;\n};\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool = StructuredToolInterface | DynamicTool | RunnableToolLike;\nexport type Prompt<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = SystemMessage | string | ((state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], config: LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>) => BaseMessageLike[] | Promise<BaseMessageLike[]>) | Runnable;\nexport type AgentState<AnnotationRoot extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = ToAnnotationRoot<AnnotationRoot>[\"State\"] & PreHookAnnotation[\"State\"];\nexport interface AgentRuntime<ContextType = Record<string, unknown>> {\n /**\n * The context of the agent.\n */\n context?: ContextType;\n /**\n * The store passed to the agent.\n */\n store?: BaseStore;\n /**\n * The writer of the agent to write to the output stream.\n */\n writer?: (chunk: unknown) => void;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n}\nexport type CreateAgentParams<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, StructuredResponseType extends Record<string, unknown> = Record<string, unknown>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ResponseFormatType = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined> = {\n /** The chat model that can utilize OpenAI-style tool calling. */\n llm?: LanguageModelLike | DynamicLLMFunction<StateSchema, ContextSchema>;\n /**\n * Initializes a ChatModel based on the provided model name and provider.\n * It supports various model providers and allows for runtime configuration of model parameters.\n *\n * @uses {@link initChatModel}\n * @example\n * ```ts\n * const agent = createAgent({\n * model: \"anthropic:claude-3-7-sonnet-latest\",\n * // ...\n * });\n * ```\n */\n model?: string;\n /** A list of tools or a ToolNode. */\n tools: ToolNode | (ServerTool | ClientTool)[];\n /**\n * An optional prompt for the LLM. This takes full graph state BEFORE the LLM is called and prepares the input to LLM.\n *\n * Can take a few different forms:\n *\n * - str: This is converted to a SystemMessage and added to the beginning of the list of messages in state[\"messages\"].\n * - SystemMessage: this is added to the beginning of the list of messages in state[\"messages\"].\n * - Function: This function should take in full graph state and the output is then passed to the language model.\n * - Runnable: This runnable should take in full graph state and the output is then passed to the language model.\n *\n * Note:\n * Prior to `v0.2.46`, the prompt was set using `stateModifier` / `messagesModifier` parameters.\n * This is now deprecated and will be removed in a future release.\n *\n * Cannot be used together with `prepareCall`.\n */\n prompt?: Prompt<StateSchema, ContextSchema>;\n /**\n * Additional state schema for the agent. It allows to define additional state keys that will be\n * persisted between agent invocations.\n *\n * @example\n * ```ts\n * // State schema defines data that persists across agent invocations\n * const stateSchema = z.object({\n * userPreferences: z.object({\n * theme: z.enum([\"light\", \"dark\"]),\n * language: z.string(),\n * }),\n * taskHistory: z.array(z.string()),\n * currentWorkflow: z.string().optional(),\n * });\n *\n * // Context schema defines runtime parameters passed per invocation\n * const contextSchema = z.object({ ... });\n *\n * const agent = createAgent({\n * llm: model,\n * tools: [updatePreferences, addTask],\n * stateSchema, // Persisted: preferences, e.g. task history, workflow state\n * contextSchema, // Per-invocation: user ID, session, API keys, etc.\n * prompt: (state, config) => {\n * // ...\n * },\n * });\n *\n * // First invocation - state starts empty, context provided\n * await agent.invoke({\n * messages: [new HumanMessage(\"Set my theme to dark\")],\n * }, {\n * context: { userId: \"user123\", sessionId: \"sess456\", apiKeys: {...} }\n * });\n *\n * // Second invocation - state persists, new context\n * await agent.invoke({\n * messages: [new HumanMessage(\"Add a task to review code\")],\n * }, {\n * context: { userId: \"user123\", sessionId: \"sess789\", apiKeys: {...} }\n * });\n * // State now contains: userPreferences.theme=\"dark\", taskHistory=[\"review code\"]\n * ```\n */\n stateSchema?: StateSchema;\n /**\n * An optional schema for the context. It allows to pass in a typed context object into the agent\n * invocation and allows to access it in hooks such as `prompt`, `preModelHook`, `postModelHook`, etc.\n * As opposed to the agent state, defined in `stateSchema`, the context is not persisted between\n * agent invocations.\n *\n * @example\n * ```ts\n * const agent = createAgent({\n * llm: model,\n * tools: [getWeather],\n * contextSchema: z.object({\n * capital: z.string(),\n * }),\n * prompt: (state, config) => {\n * return [\n * new SystemMessage(`You are a helpful assistant. The capital of France is ${config.context.capital}.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new SystemMessage(\"You are a helpful assistant.\"),\n * new HumanMessage(\"What is the capital of France?\"),\n * ],\n * }, {\n * context: {\n * capital: \"Paris\",\n * },\n * });\n * ```\n */\n contextSchema?: ContextSchema;\n /** An optional checkpoint saver to persist the agent's state. */\n checkpointSaver?: BaseCheckpointSaver | boolean;\n /** An optional checkpoint saver to persist the agent's state. Alias of \"checkpointSaver\". */\n checkpointer?: BaseCheckpointSaver | boolean;\n /** An optional list of node names to interrupt before running. */\n interruptBefore?: N[] | All;\n /** An optional list of node names to interrupt after running. */\n interruptAfter?: N[] | All;\n store?: BaseStore;\n /**\n * An optional schema for the final agent output.\n *\n * If provided, output will be formatted to match the given schema and returned in the 'structuredResponse' state key.\n * If not provided, `structuredResponse` will not be present in the output state.\n *\n * Can be passed in as:\n * - Zod schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: z.object({\n * capital: z.string(),\n * }),\n * // ...\n * });\n * ```\n * - JSON schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: {\n * type: \"json_schema\",\n * schema: {\n * type: \"object\",\n * properties: {\n * capital: { type: \"string\" },\n * },\n * required: [\"capital\"],\n * },\n * },\n * // ...\n * });\n * ```\n * - Create React Agent ResponseFormat\n * ```ts\n * import { providerStrategy, toolStrategy } from \"langchain\";\n * const agent = createAgent({\n * responseFormat: providerStrategy(\n * z.object({\n * capital: z.string(),\n * })\n * ),\n * // or\n * responseFormat: [\n * toolStrategy({ ... }),\n * toolStrategy({ ... }),\n * ]\n * // ...\n * });\n * ```\n *\n * **Note**: The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.\n * This is not the only strategy to get structured responses, see more options in [this guide](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output/).\n */\n responseFormat?: ResponseFormatType;\n /**\n * An optional name for the agent.\n */\n name?: string;\n /**\n * An optional description for the agent.\n * This can be used to describe the agent to the underlying supervisor LLM.\n */\n description?: string;\n /**\n * Use to specify how to expose the agent name to the underlying supervisor LLM.\n * - `undefined`: Relies on the LLM provider {@link AIMessage#name}. Currently, only OpenAI supports this.\n * - `\"inline\"`: Add the agent name directly into the content field of the {@link AIMessage} using XML-style tags.\n * Example: `\"How can I help you\"` -> `\"<name>agent_name</name><content>How can I help you?</content>\"`\n */\n includeAgentName?: \"inline\" | undefined;\n /**\n * An optional node to add before the `agent` node (i.e., the node that calls the LLM).\n * Useful for managing long message histories (e.g., message trimming, summarization, etc.).\n */\n preModelHook?: RunnableLike<ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], ToAnnotationRoot<StateSchema>[\"Update\"] & PreHookAnnotation[\"Update\"], LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>>;\n /**\n * An optional node to add after the `agent` node (i.e., the node that calls the LLM).\n * Useful for implementing human-in-the-loop, guardrails, validation, or other post-processing.\n */\n postModelHook?: RunnableLike<ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], ToAnnotationRoot<StateSchema>[\"Update\"] & PreHookAnnotation[\"Update\"], LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>>;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n /**\n * Determines the version of the graph to create.\n *\n * Can be one of\n * - `\"v1\"`: The tool node processes a single message. All tool calls in the message are\n * executed in parallel within the tool node.\n * - `\"v2\"`: The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n *\n * @default `\"v2\"`\n */\n version?: \"v1\" | \"v2\";\n};\nexport type InternalAgentState<StructuredResponseType extends Record<string, unknown> | undefined = Record<string, unknown>> = {\n messages: BaseMessage[];\n} & (StructuredResponseType extends ResponseFormatUndefined ? Record<string, never> : {\n structuredResponse: StructuredResponseType;\n});\nexport type WithStateGraphNodes<K extends string, Graph> = Graph extends StateGraph<infer SD, infer S, infer U, infer N, infer I, infer O, infer C> ? StateGraph<SD, S, U, N | K, I, O, C> : never;\n/**\n * @deprecated likely to be removed in the next version of the agent\n */\ntype DynamicLLMFunction<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = (state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], runtime: AgentRuntime<ToAnnotationRoot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WAFmcnB,EAEtboB,aAFsbpB,CAAAA;EAAgB;;;;;;;;;;;;;EAmHne,KAEXf,CAAAA,EAAAA,MAAAA;EAAmB;EAEH,KAEhBkB,EAvGXX,QAuGWW,GAAAA,CAvGCa,UAuGDb,GAvGcc,UAuGdd,CAAAA,EAAAA;EAAC;;;;;;;;;;;;;;;;EAmFsC,MAA5BR,CAAAA,EAzKpBuB,MAyKoBvB,CAzKbwB,WAyKaxB,EAzKAyB,aAyKAzB,CAAAA;EAAgB;;;;;;;;;AAIzB;AAmB2K;;;;;;;;;;;;;;;;;AAIoL;;;;;;;;;;;;;;;;;;gBAtJrWwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAkCEC;;oBAEEnC;;iBAEHA;;oBAEGkB,MAAMnB;;mBAEPmB,MAAMnB;UACfE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mBAsDS4C;;;;;;;;;;;;;;;;;;;;;iBAqBFxC,aAAaK,iBAAiBwB,wBAAwB1B,4BAA4BE,iBAAiBwB,yBAAyB1B,6BAA6BhB,wBAAwBkB,iBAAiByB;;;;;kBAKjM9B,aAAaK,iBAAiBwB,wBAAwB1B,4BAA4BE,iBAAiBwB,yBAAyB1B,6BAA6BhB,wBAAwBkB,iBAAiByB;;;;WAIzMM;;;;;;;;;;;;;;;;;KAuBRG,uCAAuCnC,oBAAoBnB,mBAAmBmB,yCAAyCA,oBAAoBnB,mBAAmBmB,6BAA6BC,iBAAiBwB,wBAAwB1B,qCAAqC+B,aAAa7B,iBAAiByB,6BAA6BC,QAAQzC,qBAAqBA"}
|
package/dist/agents/types.d.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { AnyAnnotationRoot, PreHookAnnotation, ResponseFormatUndefined, ToAnnotationRoot } from "./annotation.js";
|
|
2
|
+
import { JsonSchemaFormat, ProviderStrategy, ResponseFormat, ToolStrategy, TypedToolStrategy } from "./responses.js";
|
|
3
3
|
import { ToolNode } from "./nodes/ToolNode.js";
|
|
4
4
|
import { BaseMessage, BaseMessageLike, SystemMessage } from "@langchain/core/messages";
|
|
5
|
-
import { BaseChatModel } from "@langchain/core/language_models/chat_models";
|
|
6
5
|
import { Runnable, RunnableLike, RunnableToolLike } from "@langchain/core/runnables";
|
|
7
6
|
import { DynamicTool, StructuredToolInterface } from "@langchain/core/tools";
|
|
8
7
|
import { LangGraphRunnableConfig, START, StateGraph } from "@langchain/langgraph";
|
|
@@ -46,9 +45,7 @@ interface AgentRuntime<ContextType = Record<string, unknown>> {
|
|
|
46
45
|
*/
|
|
47
46
|
signal?: AbortSignal;
|
|
48
47
|
}
|
|
49
|
-
type CreateAgentParams<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,
|
|
50
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
51
|
-
StructuredResponseType extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ResponseFormatType = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined> = {
|
|
48
|
+
type CreateAgentParams<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, StructuredResponseType extends Record<string, unknown> = Record<string, unknown>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ResponseFormatType = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined> = {
|
|
52
49
|
/** The chat model that can utilize OpenAI-style tool calling. */
|
|
53
50
|
llm?: LanguageModelLike | DynamicLLMFunction<StateSchema, ContextSchema>;
|
|
54
51
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","names":["InteropZodObject","InteropZodType","LangGraphRunnableConfig","START","StateGraph","LanguageModelLike","BaseChatModel","SystemMessage","BaseMessageLike","BaseMessage","All","BaseCheckpointSaver","BaseStore","DynamicTool","StructuredToolInterface","Runnable","RunnableLike","RunnableToolLike","ToolNode","PreHookAnnotation","AnyAnnotationRoot","ToAnnotationRoot","ResponseFormat","ToolStrategy","TypedToolStrategy","ProviderStrategy","ResponseFormatUndefined","JsonSchemaFormat","META_EXTRAS_DESCRIPTION_PREFIX","N","ExecutedToolCall","Record","LLMCall","ExtractZodType","T","U","ExtractZodArrayTypes","Rest","A","InferResponseFormatType","ReducedZodChannel","TReducerSchema","ServerTool","ClientTool","Prompt","StateSchema","ContextSchema","Promise","AgentState","AnnotationRoot","AgentRuntime","ContextType","AbortSignal","CreateAgentParams","StructuredResponseType","DynamicLLMFunction","ResponseFormatType","ConfigurableModelInterface","InternalAgentState","WithStateGraphNodes","Graph","SD","S","K","I","O","C"],"sources":["../../src/agents/types.d.ts"],"sourcesContent":["import type { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport type { LangGraphRunnableConfig, START, StateGraph } from \"@langchain/langgraph\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport type { SystemMessage, BaseMessageLike, BaseMessage } from \"@langchain/core/messages\";\nimport type { All, BaseCheckpointSaver, BaseStore } from \"@langchain/langgraph-checkpoint\";\nimport type { DynamicTool, StructuredToolInterface } from \"@langchain/core/tools\";\nimport type { Runnable, RunnableLike, RunnableToolLike } from \"@langchain/core/runnables\";\nimport type { ToolNode } from \"./nodes/ToolNode.js\";\nimport type { PreHookAnnotation, AnyAnnotationRoot, ToAnnotationRoot } from \"./annotation.js\";\nimport type { ResponseFormat, ToolStrategy, TypedToolStrategy, ProviderStrategy, ResponseFormatUndefined, JsonSchemaFormat } from \"./responses.js\";\nexport declare const META_EXTRAS_DESCRIPTION_PREFIX = \"lg:\";\nexport type N = typeof START | \"agent\" | \"tools\";\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ExecutedToolCall {\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, unknown>;\n /**\n * The ID of the tool call.\n */\n tool_id: string;\n /**\n * The result of the tool call (if available).\n */\n result?: unknown;\n}\n/**\n * Information about an LLM invocation.\n */\nexport interface LLMCall {\n /**\n * The messages that were sent to the LLM.\n */\n messages: BaseMessage[];\n /**\n * The response from the LLM.\n */\n response?: BaseMessage;\n}\n/**\n * Type helper to extract the inferred type from a single Zod schema or array of schemas\n */\nexport type ExtractZodType<T> = T extends InteropZodType<infer U> ? U : T extends readonly InteropZodType<any>[] ? ExtractZodArrayTypes<T> : never;\n/**\n * Type helper to extract union type from an array of Zod schemas\n */\nexport type ExtractZodArrayTypes<T extends readonly InteropZodType<any>[]> = T extends readonly [InteropZodType<infer A>, ...infer Rest] ? Rest extends readonly InteropZodType<any>[] ? A | ExtractZodArrayTypes<Rest> : A : never;\n/**\n * Type helper to extract the structured response type from responseFormat\n */\nexport type InferResponseFormatType<T> = T extends InteropZodType<infer U> ? U extends Record<string, any> ? U : Record<string, any> : T extends readonly InteropZodType<any>[] ? ExtractZodArrayTypes<T> : T extends ToolStrategy[] ? Record<string, any> // ToolStrategy arrays will be handled at runtime\n : T extends ResponseFormat ? Record<string, any> // Single ResponseFormat will be handled at runtime\n : Record<string, any>;\n/** @internal */\nexport type ReducedZodChannel<T extends InteropZodType, TReducerSchema extends InteropZodType> = T & {\n lg_reducer_schema: TReducerSchema;\n};\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool = StructuredToolInterface | DynamicTool | RunnableToolLike;\nexport type Prompt<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = SystemMessage | string | ((state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], config: LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>) => BaseMessageLike[] | Promise<BaseMessageLike[]>) | Runnable;\nexport type AgentState<AnnotationRoot extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = ToAnnotationRoot<AnnotationRoot>[\"State\"] & PreHookAnnotation[\"State\"];\nexport interface AgentRuntime<ContextType = Record<string, unknown>> {\n /**\n * The context of the agent.\n */\n context?: ContextType;\n /**\n * The store passed to the agent.\n */\n store?: BaseStore;\n /**\n * The writer of the agent to write to the output stream.\n */\n writer?: (chunk: unknown) => void;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n}\nexport type CreateAgentParams<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nStructuredResponseType extends Record<string, any> = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ResponseFormatType = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined> = {\n /** The chat model that can utilize OpenAI-style tool calling. */\n llm?: LanguageModelLike | DynamicLLMFunction<StateSchema, ContextSchema>;\n /**\n * Initializes a ChatModel based on the provided model name and provider.\n * It supports various model providers and allows for runtime configuration of model parameters.\n *\n * @uses {@link initChatModel}\n * @example\n * ```ts\n * const agent = createAgent({\n * model: \"anthropic:claude-3-7-sonnet-latest\",\n * // ...\n * });\n * ```\n */\n model?: string;\n /** A list of tools or a ToolNode. */\n tools: ToolNode | (ServerTool | ClientTool)[];\n /**\n * An optional prompt for the LLM. This takes full graph state BEFORE the LLM is called and prepares the input to LLM.\n *\n * Can take a few different forms:\n *\n * - str: This is converted to a SystemMessage and added to the beginning of the list of messages in state[\"messages\"].\n * - SystemMessage: this is added to the beginning of the list of messages in state[\"messages\"].\n * - Function: This function should take in full graph state and the output is then passed to the language model.\n * - Runnable: This runnable should take in full graph state and the output is then passed to the language model.\n *\n * Note:\n * Prior to `v0.2.46`, the prompt was set using `stateModifier` / `messagesModifier` parameters.\n * This is now deprecated and will be removed in a future release.\n *\n * Cannot be used together with `prepareCall`.\n */\n prompt?: Prompt<StateSchema, ContextSchema>;\n /**\n * Additional state schema for the agent. It allows to define additional state keys that will be\n * persisted between agent invocations.\n *\n * @example\n * ```ts\n * // State schema defines data that persists across agent invocations\n * const stateSchema = z.object({\n * userPreferences: z.object({\n * theme: z.enum([\"light\", \"dark\"]),\n * language: z.string(),\n * }),\n * taskHistory: z.array(z.string()),\n * currentWorkflow: z.string().optional(),\n * });\n *\n * // Context schema defines runtime parameters passed per invocation\n * const contextSchema = z.object({ ... });\n *\n * const agent = createAgent({\n * llm: model,\n * tools: [updatePreferences, addTask],\n * stateSchema, // Persisted: preferences, e.g. task history, workflow state\n * contextSchema, // Per-invocation: user ID, session, API keys, etc.\n * prompt: (state, config) => {\n * // ...\n * },\n * });\n *\n * // First invocation - state starts empty, context provided\n * await agent.invoke({\n * messages: [new HumanMessage(\"Set my theme to dark\")],\n * }, {\n * context: { userId: \"user123\", sessionId: \"sess456\", apiKeys: {...} }\n * });\n *\n * // Second invocation - state persists, new context\n * await agent.invoke({\n * messages: [new HumanMessage(\"Add a task to review code\")],\n * }, {\n * context: { userId: \"user123\", sessionId: \"sess789\", apiKeys: {...} }\n * });\n * // State now contains: userPreferences.theme=\"dark\", taskHistory=[\"review code\"]\n * ```\n */\n stateSchema?: StateSchema;\n /**\n * An optional schema for the context. It allows to pass in a typed context object into the agent\n * invocation and allows to access it in hooks such as `prompt`, `preModelHook`, `postModelHook`, etc.\n * As opposed to the agent state, defined in `stateSchema`, the context is not persisted between\n * agent invocations.\n *\n * @example\n * ```ts\n * const agent = createAgent({\n * llm: model,\n * tools: [getWeather],\n * contextSchema: z.object({\n * capital: z.string(),\n * }),\n * prompt: (state, config) => {\n * return [\n * new SystemMessage(`You are a helpful assistant. The capital of France is ${config.context.capital}.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new SystemMessage(\"You are a helpful assistant.\"),\n * new HumanMessage(\"What is the capital of France?\"),\n * ],\n * }, {\n * context: {\n * capital: \"Paris\",\n * },\n * });\n * ```\n */\n contextSchema?: ContextSchema;\n /** An optional checkpoint saver to persist the agent's state. */\n checkpointSaver?: BaseCheckpointSaver | boolean;\n /** An optional checkpoint saver to persist the agent's state. Alias of \"checkpointSaver\". */\n checkpointer?: BaseCheckpointSaver | boolean;\n /** An optional list of node names to interrupt before running. */\n interruptBefore?: N[] | All;\n /** An optional list of node names to interrupt after running. */\n interruptAfter?: N[] | All;\n store?: BaseStore;\n /**\n * An optional schema for the final agent output.\n *\n * If provided, output will be formatted to match the given schema and returned in the 'structuredResponse' state key.\n * If not provided, `structuredResponse` will not be present in the output state.\n *\n * Can be passed in as:\n * - Zod schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: z.object({\n * capital: z.string(),\n * }),\n * // ...\n * });\n * ```\n * - JSON schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: {\n * type: \"json_schema\",\n * schema: {\n * type: \"object\",\n * properties: {\n * capital: { type: \"string\" },\n * },\n * required: [\"capital\"],\n * },\n * },\n * // ...\n * });\n * ```\n * - Create React Agent ResponseFormat\n * ```ts\n * import { providerStrategy, toolStrategy } from \"langchain\";\n * const agent = createAgent({\n * responseFormat: providerStrategy(\n * z.object({\n * capital: z.string(),\n * })\n * ),\n * // or\n * responseFormat: [\n * toolStrategy({ ... }),\n * toolStrategy({ ... }),\n * ]\n * // ...\n * });\n * ```\n *\n * **Note**: The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.\n * This is not the only strategy to get structured responses, see more options in [this guide](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output/).\n */\n responseFormat?: ResponseFormatType;\n /**\n * An optional name for the agent.\n */\n name?: string;\n /**\n * An optional description for the agent.\n * This can be used to describe the agent to the underlying supervisor LLM.\n */\n description?: string;\n /**\n * Use to specify how to expose the agent name to the underlying supervisor LLM.\n * - `undefined`: Relies on the LLM provider {@link AIMessage#name}. Currently, only OpenAI supports this.\n * - `\"inline\"`: Add the agent name directly into the content field of the {@link AIMessage} using XML-style tags.\n * Example: `\"How can I help you\"` -> `\"<name>agent_name</name><content>How can I help you?</content>\"`\n */\n includeAgentName?: \"inline\" | undefined;\n /**\n * An optional node to add before the `agent` node (i.e., the node that calls the LLM).\n * Useful for managing long message histories (e.g., message trimming, summarization, etc.).\n */\n preModelHook?: RunnableLike<ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], ToAnnotationRoot<StateSchema>[\"Update\"] & PreHookAnnotation[\"Update\"], LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>>;\n /**\n * An optional node to add after the `agent` node (i.e., the node that calls the LLM).\n * Useful for implementing human-in-the-loop, guardrails, validation, or other post-processing.\n */\n postModelHook?: RunnableLike<ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], ToAnnotationRoot<StateSchema>[\"Update\"] & PreHookAnnotation[\"Update\"], LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>>;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n /**\n * Determines the version of the graph to create.\n *\n * Can be one of\n * - `\"v1\"`: The tool node processes a single message. All tool calls in the message are\n * executed in parallel within the tool node.\n * - `\"v2\"`: The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n *\n * @default `\"v2\"`\n */\n version?: \"v1\" | \"v2\";\n};\nexport interface ConfigurableModelInterface {\n _queuedMethodOperations: Record<string, unknown>;\n _model: () => Promise<BaseChatModel>;\n}\nexport type InternalAgentState<StructuredResponseType extends Record<string, unknown> | undefined = Record<string, unknown>> = {\n messages: BaseMessage[];\n} & (StructuredResponseType extends ResponseFormatUndefined ? Record<string, never> : {\n structuredResponse: StructuredResponseType;\n});\nexport type WithStateGraphNodes<K extends string, Graph> = Graph extends StateGraph<infer SD, infer S, infer U, infer N, infer I, infer O, infer C> ? StateGraph<SD, S, U, N | K, I, O, C> : never;\n/**\n * @deprecated likely to be removed in the next version of the agent\n */\ntype DynamicLLMFunction<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = (state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], runtime: AgentRuntime<ToAnnotationRoot<ContextSchema>[\"State\"]>) => Promise<LanguageModelLike> | LanguageModelLike;\nexport {};\n"],"mappings":";;;;;;;;;;;;;KAYY6B,CAAAA,UAAW1B;AAAvB;AA0CA;;;;AAaka;AACla;AAAsB,KAdViC,oBAcU,CAAA,UAAA,SAd8BnC,cAc9B,CAAA,GAAA,CAAA,EAAA,CAAA,GAduDiC,CAcvD,SAAA,SAAA,CAd2EjC,cAc3E,CAAA,KAAA,EAAA,CAAA,EAAA,GAAA,KAAA,KAAA,CAAA,GAdqHoC,IAcrH,SAAA,SAd2IpC,cAc3I,CAAA,GAAA,CAAA,EAAA,GAdmKqC,CAcnK,GAduKF,oBAcvK,CAd4LC,IAc5L,CAAA,GAdoMC,CAcpM,GAAA,KAAA;;;;;AAKRa,KARFT,UAAAA,GAAaX,MAQXoB,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA;AAIFvC,KAXA+B,UAAAA,GAAa7B,uBAWbF,GAXuCC,WAWvCD,GAXqDK,gBAWrDL;AAQCwC,KAlBDR,MAkBCQ,CAAAA,oBAlB0BhC,iBAkB1BgC,GAlB8CpD,gBAkB9CoD,GAlBiEhC,iBAkBjEgC,EAAAA,sBAlB0GhC,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wB1B,4BAA4BE,iBAAiBwB,yBAAyB1B,6BAA6BjB,wBAAwBmB,iBAAiByB;;;;WAIzMM;;;;;;;;;;;;;;;;;KA2BRG,uCAAuCnC,oBAAoBpB,mBAAmBoB,yCAAyCA,oBAAoBpB,mBAAmBoB,6BAA6BC,iBAAiBwB,wBAAwB1B,qCAAqC+B,aAAa7B,iBAAiByB,6BAA6BC,QAAQ1C,qBAAqBA"}
|
|
1
|
+
{"version":3,"file":"types.d.ts","names":["InteropZodObject","InteropZodType","LangGraphRunnableConfig","START","StateGraph","LanguageModelLike","SystemMessage","BaseMessageLike","BaseMessage","All","BaseCheckpointSaver","BaseStore","DynamicTool","StructuredToolInterface","Runnable","RunnableLike","RunnableToolLike","ToolNode","PreHookAnnotation","AnyAnnotationRoot","ToAnnotationRoot","ResponseFormatUndefined","ResponseFormat","ToolStrategy","TypedToolStrategy","ProviderStrategy","JsonSchemaFormat","META_EXTRAS_DESCRIPTION_PREFIX","N","ExecutedToolCall","Record","LLMCall","ExtractZodType","T","U","ExtractZodArrayTypes","Rest","A","InferResponseFormatType","ReducedZodChannel","TReducerSchema","ServerTool","ClientTool","Prompt","StateSchema","ContextSchema","Promise","AgentState","AnnotationRoot","AgentRuntime","ContextType","AbortSignal","CreateAgentParams","StructuredResponseType","DynamicLLMFunction","ResponseFormatType","InternalAgentState","WithStateGraphNodes","Graph","SD","S","K","I","O","C"],"sources":["../../src/agents/types.d.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport type { LangGraphRunnableConfig, START, StateGraph } from \"@langchain/langgraph\";\nimport type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport type { SystemMessage, BaseMessageLike, BaseMessage } from \"@langchain/core/messages\";\nimport type { All, BaseCheckpointSaver, BaseStore } from \"@langchain/langgraph-checkpoint\";\nimport type { DynamicTool, StructuredToolInterface } from \"@langchain/core/tools\";\nimport type { Runnable, RunnableLike, RunnableToolLike } from \"@langchain/core/runnables\";\nimport type { ToolNode } from \"./nodes/ToolNode.js\";\nimport type { PreHookAnnotation, AnyAnnotationRoot, ToAnnotationRoot, ResponseFormatUndefined } from \"./annotation.js\";\nimport type { ResponseFormat, ToolStrategy, TypedToolStrategy, ProviderStrategy, JsonSchemaFormat } from \"./responses.js\";\nexport declare const META_EXTRAS_DESCRIPTION_PREFIX = \"lg:\";\nexport type N = typeof START | \"agent\" | \"tools\";\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ExecutedToolCall {\n /**\n * The name of the tool that was called.\n */\n name: string;\n /**\n * The arguments that were passed to the tool.\n */\n args: Record<string, unknown>;\n /**\n * The ID of the tool call.\n */\n tool_id: string;\n /**\n * The result of the tool call (if available).\n */\n result?: unknown;\n}\n/**\n * Information about an LLM invocation.\n */\nexport interface LLMCall {\n /**\n * The messages that were sent to the LLM.\n */\n messages: BaseMessage[];\n /**\n * The response from the LLM.\n */\n response?: BaseMessage;\n}\n/**\n * Type helper to extract the inferred type from a single Zod schema or array of schemas\n */\nexport type ExtractZodType<T> = T extends InteropZodType<infer U> ? U : T extends readonly InteropZodType<any>[] ? ExtractZodArrayTypes<T> : never;\n/**\n * Type helper to extract union type from an array of Zod schemas\n */\nexport type ExtractZodArrayTypes<T extends readonly InteropZodType<any>[]> = T extends readonly [InteropZodType<infer A>, ...infer Rest] ? Rest extends readonly InteropZodType<any>[] ? A | ExtractZodArrayTypes<Rest> : A : never;\n/**\n * Type helper to extract the structured response type from responseFormat\n */\nexport type InferResponseFormatType<T> = T extends InteropZodType<infer U> ? U extends Record<string, any> ? U : Record<string, any> : T extends readonly InteropZodType<any>[] ? ExtractZodArrayTypes<T> : T extends ToolStrategy[] ? Record<string, any> // ToolStrategy arrays will be handled at runtime\n : T extends ResponseFormat ? Record<string, any> // Single ResponseFormat will be handled at runtime\n : Record<string, any>;\n/** @internal */\nexport type ReducedZodChannel<T extends InteropZodType, TReducerSchema extends InteropZodType> = T & {\n lg_reducer_schema: TReducerSchema;\n};\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool = StructuredToolInterface | DynamicTool | RunnableToolLike;\nexport type Prompt<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = SystemMessage | string | ((state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], config: LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>) => BaseMessageLike[] | Promise<BaseMessageLike[]>) | Runnable;\nexport type AgentState<AnnotationRoot extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = ToAnnotationRoot<AnnotationRoot>[\"State\"] & PreHookAnnotation[\"State\"];\nexport interface AgentRuntime<ContextType = Record<string, unknown>> {\n /**\n * The context of the agent.\n */\n context?: ContextType;\n /**\n * The store passed to the agent.\n */\n store?: BaseStore;\n /**\n * The writer of the agent to write to the output stream.\n */\n writer?: (chunk: unknown) => void;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n}\nexport type CreateAgentParams<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, StructuredResponseType extends Record<string, unknown> = Record<string, unknown>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ResponseFormatType = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined> = {\n /** The chat model that can utilize OpenAI-style tool calling. */\n llm?: LanguageModelLike | DynamicLLMFunction<StateSchema, ContextSchema>;\n /**\n * Initializes a ChatModel based on the provided model name and provider.\n * It supports various model providers and allows for runtime configuration of model parameters.\n *\n * @uses {@link initChatModel}\n * @example\n * ```ts\n * const agent = createAgent({\n * model: \"anthropic:claude-3-7-sonnet-latest\",\n * // ...\n * });\n * ```\n */\n model?: string;\n /** A list of tools or a ToolNode. */\n tools: ToolNode | (ServerTool | ClientTool)[];\n /**\n * An optional prompt for the LLM. This takes full graph state BEFORE the LLM is called and prepares the input to LLM.\n *\n * Can take a few different forms:\n *\n * - str: This is converted to a SystemMessage and added to the beginning of the list of messages in state[\"messages\"].\n * - SystemMessage: this is added to the beginning of the list of messages in state[\"messages\"].\n * - Function: This function should take in full graph state and the output is then passed to the language model.\n * - Runnable: This runnable should take in full graph state and the output is then passed to the language model.\n *\n * Note:\n * Prior to `v0.2.46`, the prompt was set using `stateModifier` / `messagesModifier` parameters.\n * This is now deprecated and will be removed in a future release.\n *\n * Cannot be used together with `prepareCall`.\n */\n prompt?: Prompt<StateSchema, ContextSchema>;\n /**\n * Additional state schema for the agent. It allows to define additional state keys that will be\n * persisted between agent invocations.\n *\n * @example\n * ```ts\n * // State schema defines data that persists across agent invocations\n * const stateSchema = z.object({\n * userPreferences: z.object({\n * theme: z.enum([\"light\", \"dark\"]),\n * language: z.string(),\n * }),\n * taskHistory: z.array(z.string()),\n * currentWorkflow: z.string().optional(),\n * });\n *\n * // Context schema defines runtime parameters passed per invocation\n * const contextSchema = z.object({ ... });\n *\n * const agent = createAgent({\n * llm: model,\n * tools: [updatePreferences, addTask],\n * stateSchema, // Persisted: preferences, e.g. task history, workflow state\n * contextSchema, // Per-invocation: user ID, session, API keys, etc.\n * prompt: (state, config) => {\n * // ...\n * },\n * });\n *\n * // First invocation - state starts empty, context provided\n * await agent.invoke({\n * messages: [new HumanMessage(\"Set my theme to dark\")],\n * }, {\n * context: { userId: \"user123\", sessionId: \"sess456\", apiKeys: {...} }\n * });\n *\n * // Second invocation - state persists, new context\n * await agent.invoke({\n * messages: [new HumanMessage(\"Add a task to review code\")],\n * }, {\n * context: { userId: \"user123\", sessionId: \"sess789\", apiKeys: {...} }\n * });\n * // State now contains: userPreferences.theme=\"dark\", taskHistory=[\"review code\"]\n * ```\n */\n stateSchema?: StateSchema;\n /**\n * An optional schema for the context. It allows to pass in a typed context object into the agent\n * invocation and allows to access it in hooks such as `prompt`, `preModelHook`, `postModelHook`, etc.\n * As opposed to the agent state, defined in `stateSchema`, the context is not persisted between\n * agent invocations.\n *\n * @example\n * ```ts\n * const agent = createAgent({\n * llm: model,\n * tools: [getWeather],\n * contextSchema: z.object({\n * capital: z.string(),\n * }),\n * prompt: (state, config) => {\n * return [\n * new SystemMessage(`You are a helpful assistant. The capital of France is ${config.context.capital}.`),\n * ];\n * },\n * });\n *\n * const result = await agent.invoke({\n * messages: [\n * new SystemMessage(\"You are a helpful assistant.\"),\n * new HumanMessage(\"What is the capital of France?\"),\n * ],\n * }, {\n * context: {\n * capital: \"Paris\",\n * },\n * });\n * ```\n */\n contextSchema?: ContextSchema;\n /** An optional checkpoint saver to persist the agent's state. */\n checkpointSaver?: BaseCheckpointSaver | boolean;\n /** An optional checkpoint saver to persist the agent's state. Alias of \"checkpointSaver\". */\n checkpointer?: BaseCheckpointSaver | boolean;\n /** An optional list of node names to interrupt before running. */\n interruptBefore?: N[] | All;\n /** An optional list of node names to interrupt after running. */\n interruptAfter?: N[] | All;\n store?: BaseStore;\n /**\n * An optional schema for the final agent output.\n *\n * If provided, output will be formatted to match the given schema and returned in the 'structuredResponse' state key.\n * If not provided, `structuredResponse` will not be present in the output state.\n *\n * Can be passed in as:\n * - Zod schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: z.object({\n * capital: z.string(),\n * }),\n * // ...\n * });\n * ```\n * - JSON schema\n * ```ts\n * const agent = createAgent({\n * responseFormat: {\n * type: \"json_schema\",\n * schema: {\n * type: \"object\",\n * properties: {\n * capital: { type: \"string\" },\n * },\n * required: [\"capital\"],\n * },\n * },\n * // ...\n * });\n * ```\n * - Create React Agent ResponseFormat\n * ```ts\n * import { providerStrategy, toolStrategy } from \"langchain\";\n * const agent = createAgent({\n * responseFormat: providerStrategy(\n * z.object({\n * capital: z.string(),\n * })\n * ),\n * // or\n * responseFormat: [\n * toolStrategy({ ... }),\n * toolStrategy({ ... }),\n * ]\n * // ...\n * });\n * ```\n *\n * **Note**: The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.\n * This is not the only strategy to get structured responses, see more options in [this guide](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output/).\n */\n responseFormat?: ResponseFormatType;\n /**\n * An optional name for the agent.\n */\n name?: string;\n /**\n * An optional description for the agent.\n * This can be used to describe the agent to the underlying supervisor LLM.\n */\n description?: string;\n /**\n * Use to specify how to expose the agent name to the underlying supervisor LLM.\n * - `undefined`: Relies on the LLM provider {@link AIMessage#name}. Currently, only OpenAI supports this.\n * - `\"inline\"`: Add the agent name directly into the content field of the {@link AIMessage} using XML-style tags.\n * Example: `\"How can I help you\"` -> `\"<name>agent_name</name><content>How can I help you?</content>\"`\n */\n includeAgentName?: \"inline\" | undefined;\n /**\n * An optional node to add before the `agent` node (i.e., the node that calls the LLM).\n * Useful for managing long message histories (e.g., message trimming, summarization, etc.).\n */\n preModelHook?: RunnableLike<ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], ToAnnotationRoot<StateSchema>[\"Update\"] & PreHookAnnotation[\"Update\"], LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>>;\n /**\n * An optional node to add after the `agent` node (i.e., the node that calls the LLM).\n * Useful for implementing human-in-the-loop, guardrails, validation, or other post-processing.\n */\n postModelHook?: RunnableLike<ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], ToAnnotationRoot<StateSchema>[\"Update\"] & PreHookAnnotation[\"Update\"], LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>>;\n /**\n * An optional abort signal that indicates that the overall operation should be aborted.\n */\n signal?: AbortSignal;\n /**\n * Determines the version of the graph to create.\n *\n * Can be one of\n * - `\"v1\"`: The tool node processes a single message. All tool calls in the message are\n * executed in parallel within the tool node.\n * - `\"v2\"`: The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n *\n * @default `\"v2\"`\n */\n version?: \"v1\" | \"v2\";\n};\nexport type InternalAgentState<StructuredResponseType extends Record<string, unknown> | undefined = Record<string, unknown>> = {\n messages: BaseMessage[];\n} & (StructuredResponseType extends ResponseFormatUndefined ? Record<string, never> : {\n structuredResponse: StructuredResponseType;\n});\nexport type WithStateGraphNodes<K extends string, Graph> = Graph extends StateGraph<infer SD, infer S, infer U, infer N, infer I, infer O, infer C> ? StateGraph<SD, S, U, N | K, I, O, C> : never;\n/**\n * @deprecated likely to be removed in the next version of the agent\n */\ntype DynamicLLMFunction<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = (state: ToAnnotationRoot<StateSchema>[\"State\"] & PreHookAnnotation[\"State\"], runtime: AgentRuntime<ToAnnotationRoot<ContextSchema>[\"State\"]>) => Promise<LanguageModelLike> | LanguageModelLike;\nexport {};\n"],"mappings":";;;;;;;;;;;;AAYY4B,KAAAA,CAAAA,GAAC,OAAUzB,KAAK,GAAA,OAAA,GAAA,OAAA;AA0C5B;;;;AAaka;AACla;;AAA8CgB,KAdlCgB,oBAckChB,CAAAA,UAAAA,SAdMlB,cAcNkB,CAAAA,GAAAA,CAAAA,EAAAA,CAAAA,GAd+Bc,CAc/Bd,SAAAA,SAAAA,CAdmDlB,cAcnDkB,CAAAA,KAAAA,EAAAA,CAAAA,EAAAA,GAAAA,KAAAA,KAAAA,CAAAA,GAd6FiB,IAc7FjB,SAAAA,SAdmHlB,cAcnHkB,CAAAA,GAAAA,CAAAA,EAAAA,GAd2IkB,CAc3IlB,GAd+IgB,oBAc/IhB,CAdoKiB,IAcpKjB,CAAAA,GAd4KkB,CAc5KlB,GAAAA,KAAAA;;;;;AASlCR,KAZA8B,UAAAA,GAAaX,MAYbnB,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA;AAQCwC,KAnBDT,UAAAA,GAAa7B,uBAm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,6BAA6BhB,wBAAwBkB,iBAAiByB;;;;;kBAKjM9B,aAAaK,iBAAiBwB,wBAAwB1B,4BAA4BE,iBAAiBwB,yBAAyB1B,6BAA6BhB,wBAAwBkB,iBAAiByB;;;;WAIzMM;;;;;;;;;;;;;;;;;KAuBRG,uCAAuCnC,oBAAoBnB,mBAAmBmB,yCAAyCA,oBAAoBnB,mBAAmBmB,6BAA6BC,iBAAiBwB,wBAAwB1B,qCAAqC+B,aAAa7B,iBAAiByB,6BAA6BC,QAAQzC,qBAAqBA"}
|
package/dist/agents/utils.cjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
2
|
const require_errors = require('./errors.cjs');
|
|
3
3
|
const require_constants = require('./constants.cjs');
|
|
4
|
+
const require_model = require('./model.cjs');
|
|
4
5
|
const __langchain_core_messages = require_rolldown_runtime.__toESM(require("@langchain/core/messages"));
|
|
5
6
|
const __langchain_core_runnables = require_rolldown_runtime.__toESM(require("@langchain/core/runnables"));
|
|
6
7
|
|
|
@@ -22,11 +23,11 @@ const CONTENT_PATTERN = /<content>(.*?)<\/content>/s;
|
|
|
22
23
|
* @internal
|
|
23
24
|
*/
|
|
24
25
|
function _addInlineAgentName(message) {
|
|
25
|
-
|
|
26
|
-
if (!
|
|
26
|
+
if (!__langchain_core_messages.AIMessage.isInstance(message) || __langchain_core_messages.AIMessageChunk.isInstance(message)) return message;
|
|
27
|
+
if (!message.name) return message;
|
|
27
28
|
const { name } = message;
|
|
28
29
|
if (typeof message.content === "string") return new __langchain_core_messages.AIMessage({
|
|
29
|
-
...
|
|
30
|
+
...message.lc_kwargs,
|
|
30
31
|
content: `<name>${name}</name><content>${message.content}</content>`,
|
|
31
32
|
name: void 0
|
|
32
33
|
});
|
|
@@ -69,7 +70,7 @@ function _addInlineAgentName(message) {
|
|
|
69
70
|
* @internal
|
|
70
71
|
*/
|
|
71
72
|
function _removeInlineAgentName(message) {
|
|
72
|
-
if (!
|
|
73
|
+
if (!__langchain_core_messages.AIMessage.isInstance(message) || !message.content) return message;
|
|
73
74
|
let updatedContent = [];
|
|
74
75
|
let updatedName;
|
|
75
76
|
if (Array.isArray(message.content)) updatedContent = message.content.filter((block) => {
|
|
@@ -113,14 +114,8 @@ function _removeInlineAgentName(message) {
|
|
|
113
114
|
function isClientTool(tool) {
|
|
114
115
|
return __langchain_core_runnables.Runnable.isRunnable(tool);
|
|
115
116
|
}
|
|
116
|
-
function isBaseChatModel(model) {
|
|
117
|
-
return "invoke" in model && typeof model.invoke === "function" && "_modelType" in model;
|
|
118
|
-
}
|
|
119
|
-
function isConfigurableModel(model) {
|
|
120
|
-
return typeof model === "object" && model != null && "_queuedMethodOperations" in model && "_model" in model && typeof model._model === "function";
|
|
121
|
-
}
|
|
122
117
|
function _isChatModelWithBindTools(llm) {
|
|
123
|
-
if (!isBaseChatModel(llm)) return false;
|
|
118
|
+
if (!require_model.isBaseChatModel(llm)) return false;
|
|
124
119
|
return "bindTools" in llm && typeof llm.bindTools === "function";
|
|
125
120
|
}
|
|
126
121
|
function getPromptRunnable(prompt) {
|
|
@@ -131,7 +126,7 @@ function getPromptRunnable(prompt) {
|
|
|
131
126
|
promptRunnable = __langchain_core_runnables.RunnableLambda.from((state) => {
|
|
132
127
|
return [systemMessage, ...state.messages ?? []];
|
|
133
128
|
}).withConfig({ runName: require_constants.PROMPT_RUNNABLE_NAME });
|
|
134
|
-
} else if (
|
|
129
|
+
} else if (__langchain_core_messages.SystemMessage.isInstance(prompt)) promptRunnable = __langchain_core_runnables.RunnableLambda.from((state) => [prompt, ...state.messages]).withConfig({ runName: require_constants.PROMPT_RUNNABLE_NAME });
|
|
135
130
|
else if (typeof prompt === "function") promptRunnable = __langchain_core_runnables.RunnableLambda.from(prompt).withConfig({ runName: require_constants.PROMPT_RUNNABLE_NAME });
|
|
136
131
|
else if (__langchain_core_runnables.Runnable.isRunnable(prompt)) promptRunnable = prompt;
|
|
137
132
|
else throw new Error(`Got unexpected type for 'prompt': ${typeof prompt}`);
|
|
@@ -165,12 +160,12 @@ const _simpleBindTools = (llm, toolClasses, options = {}) => {
|
|
|
165
160
|
async function bindTools(llm, toolClasses, options = {}) {
|
|
166
161
|
const model = _simpleBindTools(llm, toolClasses, options);
|
|
167
162
|
if (model) return model;
|
|
168
|
-
if (isConfigurableModel(llm)) {
|
|
163
|
+
if (require_model.isConfigurableModel(llm)) {
|
|
169
164
|
const model$1 = _simpleBindTools(await llm._model(), toolClasses, options);
|
|
170
165
|
if (model$1) return model$1;
|
|
171
166
|
}
|
|
172
167
|
if (__langchain_core_runnables.RunnableSequence.isRunnableSequence(llm)) {
|
|
173
|
-
const modelStep = llm.steps.findIndex((step) => __langchain_core_runnables.RunnableBinding.isRunnableBinding(step) || isBaseChatModel(step) || isConfigurableModel(step));
|
|
168
|
+
const modelStep = llm.steps.findIndex((step) => __langchain_core_runnables.RunnableBinding.isRunnableBinding(step) || require_model.isBaseChatModel(step) || require_model.isConfigurableModel(step));
|
|
174
169
|
if (modelStep >= 0) {
|
|
175
170
|
const model$1 = _simpleBindTools(llm.steps[modelStep], toolClasses, options);
|
|
176
171
|
if (model$1) {
|
|
@@ -201,7 +196,7 @@ function validateLLMHasNoBoundTools(llm) {
|
|
|
201
196
|
/**
|
|
202
197
|
* If model is configurable, get the underlying model
|
|
203
198
|
*/
|
|
204
|
-
if (isConfigurableModel(model))
|
|
199
|
+
if (require_model.isConfigurableModel(model))
|
|
205
200
|
/**
|
|
206
201
|
* Can't validate async model retrieval in constructor
|
|
207
202
|
*/
|
|
@@ -227,19 +222,7 @@ function validateLLMHasNoBoundTools(llm) {
|
|
|
227
222
|
*/
|
|
228
223
|
function hasToolCalls(messages) {
|
|
229
224
|
const lastMessage = messages.at(-1);
|
|
230
|
-
return Boolean(
|
|
231
|
-
}
|
|
232
|
-
const CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = ["ChatOpenAI", "FakeToolCallingModel"];
|
|
233
|
-
/**
|
|
234
|
-
* Identifies the models that support JSON schema output
|
|
235
|
-
* @param model - The model to check
|
|
236
|
-
* @returns True if the model supports JSON schema output, false otherwise
|
|
237
|
-
*/
|
|
238
|
-
function hasSupportForJsonSchemaOutput(model) {
|
|
239
|
-
if (!isBaseChatModel(model)) return false;
|
|
240
|
-
const chatModelClass = model.getName();
|
|
241
|
-
if (CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.includes(chatModelClass) && (chatModelClass === "ChatOpenAI" && "model" in model && typeof model.model === "string" && model.model.startsWith("gpt-4") || chatModelClass === "FakeToolCallingModel" && "structuredResponse" in model)) return true;
|
|
242
|
-
return false;
|
|
225
|
+
return Boolean(__langchain_core_messages.AIMessage.isInstance(lastMessage) && lastMessage.tool_calls && lastMessage.tool_calls.length > 0);
|
|
243
226
|
}
|
|
244
227
|
|
|
245
228
|
//#endregion
|
|
@@ -247,7 +230,6 @@ exports._addInlineAgentName = _addInlineAgentName;
|
|
|
247
230
|
exports._removeInlineAgentName = _removeInlineAgentName;
|
|
248
231
|
exports.bindTools = bindTools;
|
|
249
232
|
exports.getPromptRunnable = getPromptRunnable;
|
|
250
|
-
exports.hasSupportForJsonSchemaOutput = hasSupportForJsonSchemaOutput;
|
|
251
233
|
exports.hasToolCalls = hasToolCalls;
|
|
252
234
|
exports.isClientTool = isClientTool;
|
|
253
235
|
exports.validateLLMHasNoBoundTools = validateLLMHasNoBoundTools;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","names":["message: T","AIMessage","updatedContent: MessageContent","updatedName: string | undefined","tool: ClientTool | ServerTool","Runnable","model: LanguageModelLike","model: unknown","llm: LanguageModelLike","prompt?: Prompt","promptRunnable: Runnable","RunnableLambda","state: typeof MessagesAnnotation.State","PROMPT_RUNNABLE_NAME","SystemMessage","toolClasses: (ClientTool | ServerTool)[]","options: Partial<BaseChatModelCallOptions>","RunnableBinding","model","RunnableSequence","nextSteps: unknown[]","step: RunnableLike","MultipleToolsBoundError","messages: BaseMessage[]"],"sources":["../../src/agents/utils.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport {\n AIMessage,\n BaseMessage,\n BaseMessageLike,\n MessageContent,\n SystemMessage,\n AIMessageChunk,\n isAIMessage,\n isAIMessageChunk,\n isBaseMessage,\n isBaseMessageChunk,\n} from \"@langchain/core/messages\";\nimport { MessagesAnnotation } from \"@langchain/langgraph\";\nimport {\n BaseChatModel,\n type BindToolsInput,\n type BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n LanguageModelLike,\n BaseLanguageModelInput,\n} from \"@langchain/core/language_models/base\";\nimport {\n Runnable,\n RunnableLike,\n RunnableConfig,\n RunnableLambda,\n RunnableSequence,\n RunnableBinding,\n} from \"@langchain/core/runnables\";\n\nimport { MultipleToolsBoundError } from \"./errors.js\";\nimport { PROMPT_RUNNABLE_NAME } from \"./constants.js\";\nimport {\n ServerTool,\n ClientTool,\n ConfigurableModelInterface,\n Prompt,\n} from \"./types.js\";\n\nconst NAME_PATTERN = /<name>(.*?)<\\/name>/s;\nconst CONTENT_PATTERN = /<content>(.*?)<\\/content>/s;\n\nexport type AgentNameMode = \"inline\";\n\n/**\n * Attach formatted agent names to the messages passed to and from a language model.\n *\n * This is useful for making a message history with multiple agents more coherent.\n *\n * NOTE: agent name is consumed from the message.name field.\n * If you're using an agent built with createAgent, name is automatically set.\n * If you're building a custom agent, make sure to set the name on the AI message returned by the LLM.\n *\n * @param message - Message to add agent name formatting to\n * @returns Message with agent name formatting\n *\n * @internal\n */\nexport function _addInlineAgentName<T extends BaseMessageLike>(\n message: T\n): T | AIMessage {\n const isAI =\n isBaseMessage(message) &&\n (isAIMessage(message) ||\n (isBaseMessageChunk(message) && isAIMessageChunk(message)));\n\n if (!isAI || !message.name) {\n return message;\n }\n\n const { name } = message;\n\n if (typeof message.content === \"string\") {\n return new AIMessage({\n ...(Object.keys(message.lc_kwargs ?? {}).length > 0\n ? message.lc_kwargs\n : message),\n content: `<name>${name}</name><content>${message.content}</content>`,\n name: undefined,\n });\n }\n\n const updatedContent = [];\n let textBlockCount = 0;\n\n for (const contentBlock of message.content) {\n if (typeof contentBlock === \"string\") {\n textBlockCount += 1;\n updatedContent.push(\n `<name>${name}</name><content>${contentBlock}</content>`\n );\n } else if (\n typeof contentBlock === \"object\" &&\n \"type\" in contentBlock &&\n contentBlock.type === \"text\"\n ) {\n textBlockCount += 1;\n updatedContent.push({\n ...contentBlock,\n text: `<name>${name}</name><content>${contentBlock.text}</content>`,\n });\n } else {\n updatedContent.push(contentBlock);\n }\n }\n\n if (!textBlockCount) {\n updatedContent.unshift({\n type: \"text\",\n text: `<name>${name}</name><content></content>`,\n });\n }\n return new AIMessage({\n ...message.lc_kwargs,\n content: updatedContent as MessageContent,\n name: undefined,\n });\n}\n\n/**\n * Remove explicit name and content XML tags from the AI message content.\n *\n * Examples:\n *\n * @example\n * ```typescript\n * removeInlineAgentName(new AIMessage({ content: \"<name>assistant</name><content>Hello</content>\", name: \"assistant\" }))\n * // AIMessage with content: \"Hello\"\n *\n * removeInlineAgentName(new AIMessage({ content: [{type: \"text\", text: \"<name>assistant</name><content>Hello</content>\"}], name: \"assistant\" }))\n * // AIMessage with content: [{type: \"text\", text: \"Hello\"}]\n * ```\n *\n * @internal\n */\nexport function _removeInlineAgentName<T extends BaseMessage>(message: T): T {\n if (!isAIMessage(message) || !message.content) {\n return message;\n }\n\n let updatedContent: MessageContent = [];\n let updatedName: string | undefined;\n\n if (Array.isArray(message.content)) {\n updatedContent = message.content\n .filter((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n // don't include empty content blocks that were added because there was no text block to modify\n if (nameMatch && (!contentMatch || contentMatch[1] === \"\")) {\n // capture name from text block\n // eslint-disable-next-line prefer-destructuring\n updatedName = nameMatch[1];\n return false;\n }\n return true;\n }\n return true;\n })\n .map((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return block;\n }\n\n // capture name from text block\n // eslint-disable-next-line prefer-destructuring\n updatedName = nameMatch[1];\n\n return {\n ...block,\n text: contentMatch[1],\n };\n }\n return block;\n });\n } else {\n const content = message.content as string;\n const nameMatch = content.match(NAME_PATTERN);\n const contentMatch = content.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return message;\n }\n\n // eslint-disable-next-line prefer-destructuring\n updatedName = nameMatch[1];\n // eslint-disable-next-line prefer-destructuring\n updatedContent = contentMatch[1];\n }\n\n return new AIMessage({\n ...(Object.keys(message.lc_kwargs ?? {}).length > 0\n ? message.lc_kwargs\n : message),\n content: updatedContent,\n name: updatedName,\n }) as T;\n}\n\nexport function isClientTool(\n tool: ClientTool | ServerTool\n): tool is ClientTool {\n return Runnable.isRunnable(tool);\n}\n\nexport function isBaseChatModel(\n model: LanguageModelLike\n): model is BaseChatModel {\n return (\n \"invoke\" in model &&\n typeof model.invoke === \"function\" &&\n \"_modelType\" in model\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function isConfigurableModel(\n model: unknown\n): model is ConfigurableModelInterface {\n return (\n typeof model === \"object\" &&\n model != null &&\n \"_queuedMethodOperations\" in model &&\n \"_model\" in model &&\n typeof model._model === \"function\"\n );\n}\n\nfunction _isChatModelWithBindTools(\n llm: LanguageModelLike\n): llm is BaseChatModel & Required<Pick<BaseChatModel, \"bindTools\">> {\n if (!isBaseChatModel(llm)) return false;\n return \"bindTools\" in llm && typeof llm.bindTools === \"function\";\n}\n\nexport function getPromptRunnable(prompt?: Prompt): Runnable {\n let promptRunnable: Runnable;\n\n if (prompt == null) {\n promptRunnable = RunnableLambda.from(\n (state: typeof MessagesAnnotation.State) => state.messages\n ).withConfig({ runName: PROMPT_RUNNABLE_NAME });\n } else if (typeof prompt === \"string\") {\n const systemMessage = new SystemMessage(prompt);\n promptRunnable = RunnableLambda.from(\n (state: typeof MessagesAnnotation.State) => {\n return [systemMessage, ...(state.messages ?? [])];\n }\n ).withConfig({ runName: PROMPT_RUNNABLE_NAME });\n } else if (isBaseMessage(prompt) && prompt._getType() === \"system\") {\n promptRunnable = RunnableLambda.from(\n (state: typeof MessagesAnnotation.State) => [prompt, ...state.messages]\n ).withConfig({ runName: PROMPT_RUNNABLE_NAME });\n } else if (typeof prompt === \"function\") {\n promptRunnable = RunnableLambda.from(prompt).withConfig({\n runName: PROMPT_RUNNABLE_NAME,\n });\n } else if (Runnable.isRunnable(prompt)) {\n promptRunnable = prompt;\n } else {\n throw new Error(`Got unexpected type for 'prompt': ${typeof prompt}`);\n }\n\n return promptRunnable;\n}\n\nexport async function shouldBindTools(\n llm: LanguageModelLike,\n tools: (ClientTool | ServerTool)[]\n): Promise<boolean> {\n // If model is a RunnableSequence, find a RunnableBinding or BaseChatModel in its steps\n let model = llm;\n if (RunnableSequence.isRunnableSequence(model)) {\n model =\n model.steps.find(\n (step) =>\n RunnableBinding.isRunnableBinding(step) ||\n isBaseChatModel(step) ||\n isConfigurableModel(step)\n ) || model;\n }\n\n if (isConfigurableModel(model)) {\n model = await model._model();\n }\n\n // If not a RunnableBinding, we should bind tools\n if (!RunnableBinding.isRunnableBinding(model)) {\n return true;\n }\n\n let boundTools = (() => {\n // check if model.kwargs contain the tools key\n if (\n model.kwargs != null &&\n typeof model.kwargs === \"object\" &&\n \"tools\" in model.kwargs &&\n Array.isArray(model.kwargs.tools)\n ) {\n return (model.kwargs.tools ?? null) as BindToolsInput[] | null;\n }\n\n // Some models can bind the tools via `withConfig()` instead of `bind()`\n if (\n model.config != null &&\n typeof model.config === \"object\" &&\n \"tools\" in model.config &&\n Array.isArray(model.config.tools)\n ) {\n return (model.config.tools ?? null) as BindToolsInput[] | null;\n }\n\n return null;\n })();\n\n // google-style\n if (\n boundTools != null &&\n boundTools.length === 1 &&\n \"functionDeclarations\" in boundTools[0]\n ) {\n boundTools = boundTools[0].functionDeclarations;\n }\n\n // If no tools in kwargs, we should bind tools\n if (boundTools == null) return true;\n\n // Check if tools count matches\n if (tools.length !== boundTools.length) {\n throw new Error(\n \"Number of tools in the model.bindTools() and tools passed to createAgent must match\"\n );\n }\n\n const toolNames = new Set<string>(\n tools.flatMap((tool) => (isClientTool(tool) ? tool.name : []))\n );\n\n const boundToolNames = new Set<string>();\n\n for (const boundTool of boundTools) {\n let boundToolName: string | undefined;\n\n // OpenAI-style tool\n if (\"type\" in boundTool && boundTool.type === \"function\") {\n boundToolName = boundTool.function.name;\n }\n // Anthropic or Google-style tool\n else if (\"name\" in boundTool) {\n boundToolName = boundTool.name;\n }\n // Bedrock-style tool\n else if (\"toolSpec\" in boundTool && \"name\" in boundTool.toolSpec) {\n boundToolName = boundTool.toolSpec.name;\n }\n // unknown tool type so we'll ignore it\n else {\n continue;\n }\n\n if (boundToolName) {\n boundToolNames.add(boundToolName);\n }\n }\n\n const missingTools = [...toolNames].filter((x) => !boundToolNames.has(x));\n if (missingTools.length > 0) {\n throw new Error(\n `Missing tools '${missingTools}' in the model.bindTools().` +\n `Tools in the model.bindTools() must match the tools passed to createAgent.`\n );\n }\n\n return false;\n}\n\nconst _simpleBindTools = (\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n) => {\n if (_isChatModelWithBindTools(llm)) {\n return llm.bindTools(toolClasses, options);\n }\n\n if (\n RunnableBinding.isRunnableBinding(llm) &&\n _isChatModelWithBindTools(llm.bound)\n ) {\n const newBound = llm.bound.bindTools(toolClasses, options);\n\n if (RunnableBinding.isRunnableBinding(newBound)) {\n return new RunnableBinding({\n bound: newBound.bound,\n config: { ...llm.config, ...newBound.config },\n kwargs: { ...llm.kwargs, ...newBound.kwargs },\n configFactories: newBound.configFactories ?? llm.configFactories,\n });\n }\n\n return new RunnableBinding({\n bound: newBound,\n config: llm.config,\n kwargs: llm.kwargs,\n configFactories: llm.configFactories,\n });\n }\n\n return null;\n};\n\nexport async function bindTools(\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n): Promise<\n | RunnableSequence<any, any>\n | RunnableBinding<any, any, RunnableConfig<Record<string, any>>>\n | Runnable<BaseLanguageModelInput, AIMessageChunk, BaseChatModelCallOptions>\n> {\n const model = _simpleBindTools(llm, toolClasses, options);\n if (model) return model;\n\n if (isConfigurableModel(llm)) {\n const model = _simpleBindTools(await llm._model(), toolClasses, options);\n if (model) return model;\n }\n\n if (RunnableSequence.isRunnableSequence(llm)) {\n const modelStep = llm.steps.findIndex(\n (step) =>\n RunnableBinding.isRunnableBinding(step) ||\n isBaseChatModel(step) ||\n isConfigurableModel(step)\n );\n\n if (modelStep >= 0) {\n const model = _simpleBindTools(\n llm.steps[modelStep],\n toolClasses,\n options\n );\n if (model) {\n const nextSteps: unknown[] = llm.steps.slice();\n nextSteps.splice(modelStep, 1, model);\n\n return RunnableSequence.from(\n nextSteps as [RunnableLike, ...RunnableLike[], RunnableLike]\n );\n }\n }\n }\n\n throw new Error(`llm ${llm} must define bindTools method.`);\n}\n\n/**\n * Check if the LLM already has bound tools and throw if it does.\n *\n * @param llm - The LLM to check.\n * @returns void\n */\nexport function validateLLMHasNoBoundTools(llm: LanguageModelLike): void {\n /**\n * If llm is a function, we can't validate until runtime, so skip\n */\n if (typeof llm === \"function\") {\n return;\n }\n\n let model = llm;\n\n /**\n * If model is a RunnableSequence, find a RunnableBinding in its steps\n */\n if (RunnableSequence.isRunnableSequence(model)) {\n model =\n model.steps.find((step: RunnableLike) =>\n RunnableBinding.isRunnableBinding(step)\n ) || model;\n }\n\n /**\n * If model is configurable, get the underlying model\n */\n if (isConfigurableModel(model)) {\n /**\n * Can't validate async model retrieval in constructor\n */\n return;\n }\n\n /**\n * Check if model is a RunnableBinding with bound tools\n */\n if (RunnableBinding.isRunnableBinding(model)) {\n const hasToolsInKwargs =\n model.kwargs != null &&\n typeof model.kwargs === \"object\" &&\n \"tools\" in model.kwargs &&\n Array.isArray(model.kwargs.tools) &&\n model.kwargs.tools.length > 0;\n\n const hasToolsInConfig =\n model.config != null &&\n typeof model.config === \"object\" &&\n \"tools\" in model.config &&\n Array.isArray(model.config.tools) &&\n model.config.tools.length > 0;\n\n if (hasToolsInKwargs || hasToolsInConfig) {\n throw new MultipleToolsBoundError();\n }\n }\n\n /**\n * Also check if model has tools property directly (e.g., FakeToolCallingModel)\n */\n if (\n \"tools\" in model &&\n model.tools !== undefined &&\n Array.isArray(model.tools) &&\n model.tools.length > 0\n ) {\n throw new MultipleToolsBoundError();\n }\n}\n\n/**\n * Check if the last message in the messages array has tool calls.\n *\n * @param messages - The messages to check.\n * @returns True if the last message has tool calls, false otherwise.\n */\nexport function hasToolCalls(messages: BaseMessage[]): boolean {\n const lastMessage = messages.at(-1);\n return Boolean(\n lastMessage instanceof AIMessage &&\n lastMessage.tool_calls &&\n lastMessage.tool_calls.length > 0\n );\n}\n\n/**\n * Check if the model name supports structured output\n * @param modelName - The name of the model\n * @returns True if the model supports structured output, false otherwise\n */\nexport function hasSupportForStructuredOutput(modelName?: string): boolean {\n return (\n modelName?.startsWith(\"gpt-4\") || modelName?.startsWith(\"gpt-5\") || false\n );\n}\n\nconst CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = [\n \"ChatOpenAI\",\n \"FakeToolCallingModel\",\n];\n\n/**\n * Identifies the models that support JSON schema output\n * @param model - The model to check\n * @returns True if the model supports JSON schema output, false otherwise\n */\nexport function hasSupportForJsonSchemaOutput(\n model: LanguageModelLike\n): boolean {\n if (!isBaseChatModel(model)) {\n return false;\n }\n\n const chatModelClass = model.getName();\n if (\n CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.includes(chatModelClass) &&\n ((chatModelClass === \"ChatOpenAI\" &&\n /**\n * OpenAI models\n */\n \"model\" in model &&\n typeof model.model === \"string\" &&\n model.model.startsWith(\"gpt-4\")) ||\n /**\n * for testing purposes only\n */\n (chatModelClass === \"FakeToolCallingModel\" &&\n \"structuredResponse\" in model))\n ) {\n return true;\n }\n\n return false;\n}\n"],"mappings":";;;;;;;AAyCA,MAAM,eAAe;AACrB,MAAM,kBAAkB;;;;;;;;;;;;;;;AAkBxB,SAAgB,oBACdA,SACe;CACf,MAAM,oDACU,QAAQ,gDACT,QAAQ,sDACC,QAAQ,oDAAqB,QAAQ;AAE7D,KAAI,CAAC,QAAQ,CAAC,QAAQ,KACpB,QAAO;CAGT,MAAM,EAAE,MAAM,GAAG;AAEjB,KAAI,OAAO,QAAQ,YAAY,SAC7B,QAAO,IAAIC,oCAAU;EACnB,GAAI,OAAO,KAAK,QAAQ,aAAa,CAAE,EAAC,CAAC,SAAS,IAC9C,QAAQ,YACR;EACJ,SAAS,CAAC,MAAM,EAAE,KAAK,gBAAgB,EAAE,QAAQ,QAAQ,UAAU,CAAC;EACpE,MAAM;CACP;CAGH,MAAM,iBAAiB,CAAE;CACzB,IAAI,iBAAiB;AAErB,MAAK,MAAM,gBAAgB,QAAQ,QACjC,KAAI,OAAO,iBAAiB,UAAU;EACpC,kBAAkB;EAClB,eAAe,KACb,CAAC,MAAM,EAAE,KAAK,gBAAgB,EAAE,aAAa,UAAU,CAAC,CACzD;CACF,WACC,OAAO,iBAAiB,YACxB,UAAU,gBACV,aAAa,SAAS,QACtB;EACA,kBAAkB;EAClB,eAAe,KAAK;GAClB,GAAG;GACH,MAAM,CAAC,MAAM,EAAE,KAAK,gBAAgB,EAAE,aAAa,KAAK,UAAU,CAAC;EACpE,EAAC;CACH,OACC,eAAe,KAAK,aAAa;AAIrC,KAAI,CAAC,gBACH,eAAe,QAAQ;EACrB,MAAM;EACN,MAAM,CAAC,MAAM,EAAE,KAAK,0BAA0B,CAAC;CAChD,EAAC;AAEJ,QAAO,IAAIA,oCAAU;EACnB,GAAG,QAAQ;EACX,SAAS;EACT,MAAM;C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mB,MAAM,EAC5C,QACE,MAAM,MAAM,KAAK,CAACE,SAChBJ,2CAAgB,kBAAkB,KAAK,CACxC,IAAI;;;;AAMT,KAAI,oBAAoB,MAAM;;;;AAI5B;;;;AAMF,KAAIA,2CAAgB,kBAAkB,MAAM,EAAE;EAC5C,MAAM,mBACJ,MAAM,UAAU,QAChB,OAAO,MAAM,WAAW,YACxB,WAAW,MAAM,UACjB,MAAM,QAAQ,MAAM,OAAO,MAAM,IACjC,MAAM,OAAO,MAAM,SAAS;EAE9B,MAAM,mBACJ,MAAM,UAAU,QAChB,OAAO,MAAM,WAAW,YACxB,WAAW,MAAM,UACjB,MAAM,QAAQ,MAAM,OAAO,MAAM,IACjC,MAAM,OAAO,MAAM,SAAS;AAE9B,MAAI,oBAAoB,iBACtB,OAAM,IAAIK;CAEb;;;;AAKD,KACE,WAAW,SACX,MAAM,UAAU,UAChB,MAAM,QAAQ,MAAM,MAAM,IAC1B,MAAM,MAAM,SAAS,EAErB,OAAM,IAAIA;AAEb;;;;;;;AAQD,SAAgB,aAAaC,UAAkC;CAC7D,MAAM,cAAc,SAAS,GAAG,GAAG;AACnC,QAAO,QACL,uBAAuBtB,uCACrB,YAAY,cACZ,YAAY,WAAW,SAAS,EACnC;AACF;AAaD,MAAM,8CAA8C,CAClD,cACA,sBACD;;;;;;AAOD,SAAgB,8BACdK,OACS;AACT,KAAI,CAAC,gBAAgB,MAAM,CACzB,QAAO;CAGT,MAAM,iBAAiB,MAAM,SAAS;AACtC,KACE,4CAA4C,SAAS,eAAe,KAClE,mBAAmB,gBAInB,WAAW,SACX,OAAO,MAAM,UAAU,YACvB,MAAM,MAAM,WAAW,QAAQ,IAI9B,mBAAmB,0BAClB,wBAAwB,OAE5B,QAAO;AAGT,QAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"utils.cjs","names":["message: T","AIMessage","AIMessageChunk","updatedContent: MessageContent","updatedName: string | undefined","tool: ClientTool | ServerTool","Runnable","llm: LanguageModelLike","isBaseChatModel","prompt?: Prompt","promptRunnable: Runnable","RunnableLambda","state: typeof MessagesAnnotation.State","PROMPT_RUNNABLE_NAME","SystemMessage","toolClasses: (ClientTool | ServerTool)[]","options: Partial<BaseChatModelCallOptions>","RunnableBinding","isConfigurableModel","model","RunnableSequence","nextSteps: unknown[]","step: RunnableLike","MultipleToolsBoundError","messages: BaseMessage[]"],"sources":["../../src/agents/utils.ts"],"sourcesContent":["import {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageLike,\n SystemMessage,\n MessageContent,\n} from \"@langchain/core/messages\";\nimport { MessagesAnnotation } from \"@langchain/langgraph\";\nimport {\n BaseChatModel,\n type BindToolsInput,\n type BaseChatModelCallOptions,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n LanguageModelLike,\n BaseLanguageModelInput,\n} from \"@langchain/core/language_models/base\";\nimport {\n Runnable,\n RunnableLike,\n RunnableConfig,\n RunnableLambda,\n RunnableSequence,\n RunnableBinding,\n} from \"@langchain/core/runnables\";\n\nimport { MultipleToolsBoundError } from \"./errors.js\";\nimport { PROMPT_RUNNABLE_NAME } from \"./constants.js\";\nimport { ServerTool, ClientTool, Prompt } from \"./types.js\";\nimport { isBaseChatModel, isConfigurableModel } from \"./model.js\";\n\nconst NAME_PATTERN = /<name>(.*?)<\\/name>/s;\nconst CONTENT_PATTERN = /<content>(.*?)<\\/content>/s;\n\nexport type AgentNameMode = \"inline\";\n\n/**\n * Attach formatted agent names to the messages passed to and from a language model.\n *\n * This is useful for making a message history with multiple agents more coherent.\n *\n * NOTE: agent name is consumed from the message.name field.\n * If you're using an agent built with createAgent, name is automatically set.\n * If you're building a custom agent, make sure to set the name on the AI message returned by the LLM.\n *\n * @param message - Message to add agent name formatting to\n * @returns Message with agent name formatting\n *\n * @internal\n */\nexport function _addInlineAgentName<T extends BaseMessageLike>(\n message: T\n): T | AIMessage {\n if (!AIMessage.isInstance(message) || AIMessageChunk.isInstance(message)) {\n return message;\n }\n\n if (!message.name) {\n return message;\n }\n\n const { name } = message;\n\n if (typeof message.content === \"string\") {\n return new AIMessage({\n ...message.lc_kwargs,\n content: `<name>${name}</name><content>${message.content}</content>`,\n name: undefined,\n });\n }\n\n const updatedContent = [];\n let textBlockCount = 0;\n\n for (const contentBlock of message.content) {\n if (typeof contentBlock === \"string\") {\n textBlockCount += 1;\n updatedContent.push(\n `<name>${name}</name><content>${contentBlock}</content>`\n );\n } else if (\n typeof contentBlock === \"object\" &&\n \"type\" in contentBlock &&\n contentBlock.type === \"text\"\n ) {\n textBlockCount += 1;\n updatedContent.push({\n ...contentBlock,\n text: `<name>${name}</name><content>${contentBlock.text}</content>`,\n });\n } else {\n updatedContent.push(contentBlock);\n }\n }\n\n if (!textBlockCount) {\n updatedContent.unshift({\n type: \"text\",\n text: `<name>${name}</name><content></content>`,\n });\n }\n return new AIMessage({\n ...message.lc_kwargs,\n content: updatedContent as MessageContent,\n name: undefined,\n });\n}\n\n/**\n * Remove explicit name and content XML tags from the AI message content.\n *\n * Examples:\n *\n * @example\n * ```typescript\n * removeInlineAgentName(new AIMessage({ content: \"<name>assistant</name><content>Hello</content>\", name: \"assistant\" }))\n * // AIMessage with content: \"Hello\"\n *\n * removeInlineAgentName(new AIMessage({ content: [{type: \"text\", text: \"<name>assistant</name><content>Hello</content>\"}], name: \"assistant\" }))\n * // AIMessage with content: [{type: \"text\", text: \"Hello\"}]\n * ```\n *\n * @internal\n */\nexport function _removeInlineAgentName<T extends BaseMessage>(message: T): T {\n if (!AIMessage.isInstance(message) || !message.content) {\n return message;\n }\n\n let updatedContent: MessageContent = [];\n let updatedName: string | undefined;\n\n if (Array.isArray(message.content)) {\n updatedContent = message.content\n .filter((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n // don't include empty content blocks that were added because there was no text block to modify\n if (nameMatch && (!contentMatch || contentMatch[1] === \"\")) {\n // capture name from text block\n updatedName = nameMatch[1];\n return false;\n }\n return true;\n }\n return true;\n })\n .map((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n const nameMatch = block.text.match(NAME_PATTERN);\n const contentMatch = block.text.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return block;\n }\n\n // capture name from text block\n updatedName = nameMatch[1];\n\n return {\n ...block,\n text: contentMatch[1],\n };\n }\n return block;\n });\n } else {\n const content = message.content as string;\n const nameMatch = content.match(NAME_PATTERN);\n const contentMatch = content.match(CONTENT_PATTERN);\n\n if (!nameMatch || !contentMatch) {\n return message;\n }\n\n updatedName = nameMatch[1];\n updatedContent = contentMatch[1];\n }\n\n return new AIMessage({\n ...(Object.keys(message.lc_kwargs ?? {}).length > 0\n ? message.lc_kwargs\n : message),\n content: updatedContent,\n name: updatedName,\n }) as T;\n}\n\nexport function isClientTool(\n tool: ClientTool | ServerTool\n): tool is ClientTool {\n return Runnable.isRunnable(tool);\n}\n\nfunction _isChatModelWithBindTools(\n llm: LanguageModelLike\n): llm is BaseChatModel & Required<Pick<BaseChatModel, \"bindTools\">> {\n if (!isBaseChatModel(llm)) return false;\n return \"bindTools\" in llm && typeof llm.bindTools === \"function\";\n}\n\nexport function getPromptRunnable(prompt?: Prompt): Runnable {\n let promptRunnable: Runnable;\n\n if (prompt == null) {\n promptRunnable = RunnableLambda.from(\n (state: typeof MessagesAnnotation.State) => state.messages\n ).withConfig({ runName: PROMPT_RUNNABLE_NAME });\n } else if (typeof prompt === \"string\") {\n const systemMessage = new SystemMessage(prompt);\n promptRunnable = RunnableLambda.from(\n (state: typeof MessagesAnnotation.State) => {\n return [systemMessage, ...(state.messages ?? [])];\n }\n ).withConfig({ runName: PROMPT_RUNNABLE_NAME });\n } else if (SystemMessage.isInstance(prompt)) {\n promptRunnable = RunnableLambda.from(\n (state: typeof MessagesAnnotation.State) => [prompt, ...state.messages]\n ).withConfig({ runName: PROMPT_RUNNABLE_NAME });\n } else if (typeof prompt === \"function\") {\n promptRunnable = RunnableLambda.from(prompt).withConfig({\n runName: PROMPT_RUNNABLE_NAME,\n });\n } else if (Runnable.isRunnable(prompt)) {\n promptRunnable = prompt;\n } else {\n throw new Error(`Got unexpected type for 'prompt': ${typeof prompt}`);\n }\n\n return promptRunnable;\n}\n\nexport async function shouldBindTools(\n llm: LanguageModelLike,\n tools: (ClientTool | ServerTool)[]\n): Promise<boolean> {\n // If model is a RunnableSequence, find a RunnableBinding or BaseChatModel in its steps\n let model = llm;\n if (RunnableSequence.isRunnableSequence(model)) {\n model =\n model.steps.find(\n (step) =>\n RunnableBinding.isRunnableBinding(step) ||\n isBaseChatModel(step) ||\n isConfigurableModel(step)\n ) || model;\n }\n\n if (isConfigurableModel(model)) {\n model = await model._model();\n }\n\n // If not a RunnableBinding, we should bind tools\n if (!RunnableBinding.isRunnableBinding(model)) {\n return true;\n }\n\n let boundTools = (() => {\n // check if model.kwargs contain the tools key\n if (\n model.kwargs != null &&\n typeof model.kwargs === \"object\" &&\n \"tools\" in model.kwargs &&\n Array.isArray(model.kwargs.tools)\n ) {\n return (model.kwargs.tools ?? null) as BindToolsInput[] | null;\n }\n\n // Some models can bind the tools via `withConfig()` instead of `bind()`\n if (\n model.config != null &&\n typeof model.config === \"object\" &&\n \"tools\" in model.config &&\n Array.isArray(model.config.tools)\n ) {\n return (model.config.tools ?? null) as BindToolsInput[] | null;\n }\n\n return null;\n })();\n\n // google-style\n if (\n boundTools != null &&\n boundTools.length === 1 &&\n \"functionDeclarations\" in boundTools[0]\n ) {\n boundTools = boundTools[0].functionDeclarations;\n }\n\n // If no tools in kwargs, we should bind tools\n if (boundTools == null) return true;\n\n // Check if tools count matches\n if (tools.length !== boundTools.length) {\n throw new Error(\n \"Number of tools in the model.bindTools() and tools passed to createAgent must match\"\n );\n }\n\n const toolNames = new Set<string>(\n tools.flatMap((tool) => (isClientTool(tool) ? tool.name : []))\n );\n\n const boundToolNames = new Set<string>();\n\n for (const boundTool of boundTools) {\n let boundToolName: string | undefined;\n\n // OpenAI-style tool\n if (\"type\" in boundTool && boundTool.type === \"function\") {\n boundToolName = boundTool.function.name;\n }\n // Anthropic or Google-style tool\n else if (\"name\" in boundTool) {\n boundToolName = boundTool.name;\n }\n // Bedrock-style tool\n else if (\"toolSpec\" in boundTool && \"name\" in boundTool.toolSpec) {\n boundToolName = boundTool.toolSpec.name;\n }\n // unknown tool type so we'll ignore it\n else {\n continue;\n }\n\n if (boundToolName) {\n boundToolNames.add(boundToolName);\n }\n }\n\n const missingTools = [...toolNames].filter((x) => !boundToolNames.has(x));\n if (missingTools.length > 0) {\n throw new Error(\n `Missing tools '${missingTools}' in the model.bindTools().` +\n `Tools in the model.bindTools() must match the tools passed to createAgent.`\n );\n }\n\n return false;\n}\n\nconst _simpleBindTools = (\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n) => {\n if (_isChatModelWithBindTools(llm)) {\n return llm.bindTools(toolClasses, options);\n }\n\n if (\n RunnableBinding.isRunnableBinding(llm) &&\n _isChatModelWithBindTools(llm.bound)\n ) {\n const newBound = llm.bound.bindTools(toolClasses, options);\n\n if (RunnableBinding.isRunnableBinding(newBound)) {\n return new RunnableBinding({\n bound: newBound.bound,\n config: { ...llm.config, ...newBound.config },\n kwargs: { ...llm.kwargs, ...newBound.kwargs },\n configFactories: newBound.configFactories ?? llm.configFactories,\n });\n }\n\n return new RunnableBinding({\n bound: newBound,\n config: llm.config,\n kwargs: llm.kwargs,\n configFactories: llm.configFactories,\n });\n }\n\n return null;\n};\n\nexport async function bindTools(\n llm: LanguageModelLike,\n toolClasses: (ClientTool | ServerTool)[],\n options: Partial<BaseChatModelCallOptions> = {}\n): Promise<\n | RunnableSequence<unknown, unknown>\n | RunnableBinding<unknown, unknown, RunnableConfig<Record<string, unknown>>>\n | Runnable<BaseLanguageModelInput, AIMessageChunk, BaseChatModelCallOptions>\n> {\n const model = _simpleBindTools(llm, toolClasses, options);\n if (model) return model;\n\n if (isConfigurableModel(llm)) {\n const model = _simpleBindTools(await llm._model(), toolClasses, options);\n if (model) return model;\n }\n\n if (RunnableSequence.isRunnableSequence(llm)) {\n const modelStep = llm.steps.findIndex(\n (step) =>\n RunnableBinding.isRunnableBinding(step) ||\n isBaseChatModel(step) ||\n isConfigurableModel(step)\n );\n\n if (modelStep >= 0) {\n const model = _simpleBindTools(\n llm.steps[modelStep],\n toolClasses,\n options\n );\n if (model) {\n const nextSteps: unknown[] = llm.steps.slice();\n nextSteps.splice(modelStep, 1, model);\n\n return RunnableSequence.from(\n nextSteps as [RunnableLike, ...RunnableLike[], RunnableLike]\n );\n }\n }\n }\n\n throw new Error(`llm ${llm} must define bindTools method.`);\n}\n\n/**\n * Check if the LLM already has bound tools and throw if it does.\n *\n * @param llm - The LLM to check.\n * @returns void\n */\nexport function validateLLMHasNoBoundTools(llm: LanguageModelLike): void {\n /**\n * If llm is a function, we can't validate until runtime, so skip\n */\n if (typeof llm === \"function\") {\n return;\n }\n\n let model = llm;\n\n /**\n * If model is a RunnableSequence, find a RunnableBinding in its steps\n */\n if (RunnableSequence.isRunnableSequence(model)) {\n model =\n model.steps.find((step: RunnableLike) =>\n RunnableBinding.isRunnableBinding(step)\n ) || model;\n }\n\n /**\n * If model is configurable, get the underlying model\n */\n if (isConfigurableModel(model)) {\n /**\n * Can't validate async model retrieval in constructor\n */\n return;\n }\n\n /**\n * Check if model is a RunnableBinding with bound tools\n */\n if (RunnableBinding.isRunnableBinding(model)) {\n const hasToolsInKwargs =\n model.kwargs != null &&\n typeof model.kwargs === \"object\" &&\n \"tools\" in model.kwargs &&\n Array.isArray(model.kwargs.tools) &&\n model.kwargs.tools.length > 0;\n\n const hasToolsInConfig =\n model.config != null &&\n typeof model.config === \"object\" &&\n \"tools\" in model.config &&\n Array.isArray(model.config.tools) &&\n model.config.tools.length > 0;\n\n if (hasToolsInKwargs || hasToolsInConfig) {\n throw new MultipleToolsBoundError();\n }\n }\n\n /**\n * Also check if model has tools property directly (e.g., FakeToolCallingModel)\n */\n if (\n \"tools\" in model &&\n model.tools !== undefined &&\n Array.isArray(model.tools) &&\n model.tools.length > 0\n ) {\n throw new MultipleToolsBoundError();\n }\n}\n\n/**\n * Check if the last message in the messages array has tool calls.\n *\n * @param messages - The messages to check.\n * @returns True if the last message has tool calls, false otherwise.\n */\nexport function hasToolCalls(messages: BaseMessage[]): boolean {\n const lastMessage = messages.at(-1);\n return Boolean(\n AIMessage.isInstance(lastMessage) &&\n lastMessage.tool_calls &&\n lastMessage.tool_calls.length > 0\n );\n}\n"],"mappings":";;;;;;;;AAgCA,MAAM,eAAe;AACrB,MAAM,kBAAkB;;;;;;;;;;;;;;;AAkBxB,SAAgB,oBACdA,SACe;AACf,KAAI,CAACC,oCAAU,WAAW,QAAQ,IAAIC,yCAAe,WAAW,QAAQ,CACtE,QAAO;AAGT,KAAI,CAAC,QAAQ,KACX,QAAO;CAGT,MAAM,EAAE,MAAM,GAAG;AAEjB,KAAI,OAAO,QAAQ,YAAY,SAC7B,QAAO,IAAID,oCAAU;EACnB,GAAG,QAAQ;EACX,SAAS,CAAC,MAAM,EAAE,KAAK,gBAAgB,EAAE,QAAQ,QAAQ,UAAU,CAAC;EACpE,MAAM;CACP;CAGH,MAAM,iBAAiB,CAAE;CACzB,IAAI,iBAAiB;AAErB,MAAK,MAAM,gBAAgB,QAAQ,QACjC,KAAI,OAAO,iBAAiB,UAAU;EACpC,kBAAkB;EAClB,eAAe,KACb,CAAC,MAAM,EAAE,KAAK,gBAAgB,EAAE,aAAa,UAAU,CAAC,CACzD;CACF,WACC,OAAO,iBAAiB,YACxB,UAAU,gBACV,aAAa,SAAS,QACtB;EACA,kBAAkB;EAClB,eAAe,KAAK;GAClB,GAAG;GACH,MAAM,CAAC,MAAM,EAAE,KAAK,gBAAgB,EAAE,aAAa,KAAK,UAAU,CAAC;EACpE,EAAC;CACH,OACC,eAAe,KAAK,aAAa;AAIrC,KAAI,CAAC,gBACH,eAAe,QAAQ;EACrB,MAAM;EACN,MAAM,CAAC,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AAI;;;;AAMT,KAAIC,kCAAoB,MAAM;;;;AAI5B;;;;AAMF,KAAID,2CAAgB,kBAAkB,MAAM,EAAE;EAC5C,MAAM,mBACJ,MAAM,UAAU,QAChB,OAAO,MAAM,WAAW,YACxB,WAAW,MAAM,UACjB,MAAM,QAAQ,MAAM,OAAO,MAAM,IACjC,MAAM,OAAO,MAAM,SAAS;EAE9B,MAAM,mBACJ,MAAM,UAAU,QAChB,OAAO,MAAM,WAAW,YACxB,WAAW,MAAM,UACjB,MAAM,QAAQ,MAAM,OAAO,MAAM,IACjC,MAAM,OAAO,MAAM,SAAS;AAE9B,MAAI,oBAAoB,iBACtB,OAAM,IAAIM;CAEb;;;;AAKD,KACE,WAAW,SACX,MAAM,UAAU,UAChB,MAAM,QAAQ,MAAM,MAAM,IAC1B,MAAM,MAAM,SAAS,EAErB,OAAM,IAAIA;AAEb;;;;;;;AAQD,SAAgB,aAAaC,UAAkC;CAC7D,MAAM,cAAc,SAAS,GAAG,GAAG;AACnC,QAAO,QACLvB,oCAAU,WAAW,YAAY,IAC/B,YAAY,cACZ,YAAY,WAAW,SAAS,EACnC;AACF"}
|
package/dist/agents/utils.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { MultipleToolsBoundError } from "./errors.js";
|
|
2
2
|
import { PROMPT_RUNNABLE_NAME } from "./constants.js";
|
|
3
|
-
import {
|
|
3
|
+
import { isBaseChatModel, isConfigurableModel } from "./model.js";
|
|
4
|
+
import { AIMessage, AIMessageChunk, SystemMessage } from "@langchain/core/messages";
|
|
4
5
|
import { Runnable, RunnableBinding, RunnableLambda, RunnableSequence } from "@langchain/core/runnables";
|
|
5
6
|
|
|
6
7
|
//#region src/agents/utils.ts
|
|
@@ -21,11 +22,11 @@ const CONTENT_PATTERN = /<content>(.*?)<\/content>/s;
|
|
|
21
22
|
* @internal
|
|
22
23
|
*/
|
|
23
24
|
function _addInlineAgentName(message) {
|
|
24
|
-
|
|
25
|
-
if (!
|
|
25
|
+
if (!AIMessage.isInstance(message) || AIMessageChunk.isInstance(message)) return message;
|
|
26
|
+
if (!message.name) return message;
|
|
26
27
|
const { name } = message;
|
|
27
28
|
if (typeof message.content === "string") return new AIMessage({
|
|
28
|
-
...
|
|
29
|
+
...message.lc_kwargs,
|
|
29
30
|
content: `<name>${name}</name><content>${message.content}</content>`,
|
|
30
31
|
name: void 0
|
|
31
32
|
});
|
|
@@ -68,7 +69,7 @@ function _addInlineAgentName(message) {
|
|
|
68
69
|
* @internal
|
|
69
70
|
*/
|
|
70
71
|
function _removeInlineAgentName(message) {
|
|
71
|
-
if (!
|
|
72
|
+
if (!AIMessage.isInstance(message) || !message.content) return message;
|
|
72
73
|
let updatedContent = [];
|
|
73
74
|
let updatedName;
|
|
74
75
|
if (Array.isArray(message.content)) updatedContent = message.content.filter((block) => {
|
|
@@ -112,12 +113,6 @@ function _removeInlineAgentName(message) {
|
|
|
112
113
|
function isClientTool(tool) {
|
|
113
114
|
return Runnable.isRunnable(tool);
|
|
114
115
|
}
|
|
115
|
-
function isBaseChatModel(model) {
|
|
116
|
-
return "invoke" in model && typeof model.invoke === "function" && "_modelType" in model;
|
|
117
|
-
}
|
|
118
|
-
function isConfigurableModel(model) {
|
|
119
|
-
return typeof model === "object" && model != null && "_queuedMethodOperations" in model && "_model" in model && typeof model._model === "function";
|
|
120
|
-
}
|
|
121
116
|
function _isChatModelWithBindTools(llm) {
|
|
122
117
|
if (!isBaseChatModel(llm)) return false;
|
|
123
118
|
return "bindTools" in llm && typeof llm.bindTools === "function";
|
|
@@ -130,7 +125,7 @@ function getPromptRunnable(prompt) {
|
|
|
130
125
|
promptRunnable = RunnableLambda.from((state) => {
|
|
131
126
|
return [systemMessage, ...state.messages ?? []];
|
|
132
127
|
}).withConfig({ runName: PROMPT_RUNNABLE_NAME });
|
|
133
|
-
} else if (
|
|
128
|
+
} else if (SystemMessage.isInstance(prompt)) promptRunnable = RunnableLambda.from((state) => [prompt, ...state.messages]).withConfig({ runName: PROMPT_RUNNABLE_NAME });
|
|
134
129
|
else if (typeof prompt === "function") promptRunnable = RunnableLambda.from(prompt).withConfig({ runName: PROMPT_RUNNABLE_NAME });
|
|
135
130
|
else if (Runnable.isRunnable(prompt)) promptRunnable = prompt;
|
|
136
131
|
else throw new Error(`Got unexpected type for 'prompt': ${typeof prompt}`);
|
|
@@ -226,21 +221,9 @@ function validateLLMHasNoBoundTools(llm) {
|
|
|
226
221
|
*/
|
|
227
222
|
function hasToolCalls(messages) {
|
|
228
223
|
const lastMessage = messages.at(-1);
|
|
229
|
-
return Boolean(lastMessage
|
|
230
|
-
}
|
|
231
|
-
const CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = ["ChatOpenAI", "FakeToolCallingModel"];
|
|
232
|
-
/**
|
|
233
|
-
* Identifies the models that support JSON schema output
|
|
234
|
-
* @param model - The model to check
|
|
235
|
-
* @returns True if the model supports JSON schema output, false otherwise
|
|
236
|
-
*/
|
|
237
|
-
function hasSupportForJsonSchemaOutput(model) {
|
|
238
|
-
if (!isBaseChatModel(model)) return false;
|
|
239
|
-
const chatModelClass = model.getName();
|
|
240
|
-
if (CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.includes(chatModelClass) && (chatModelClass === "ChatOpenAI" && "model" in model && typeof model.model === "string" && model.model.startsWith("gpt-4") || chatModelClass === "FakeToolCallingModel" && "structuredResponse" in model)) return true;
|
|
241
|
-
return false;
|
|
224
|
+
return Boolean(AIMessage.isInstance(lastMessage) && lastMessage.tool_calls && lastMessage.tool_calls.length > 0);
|
|
242
225
|
}
|
|
243
226
|
|
|
244
227
|
//#endregion
|
|
245
|
-
export { _addInlineAgentName, _removeInlineAgentName, bindTools, getPromptRunnable,
|
|
228
|
+
export { _addInlineAgentName, _removeInlineAgentName, bindTools, getPromptRunnable, hasToolCalls, isClientTool, validateLLMHasNoBoundTools };
|
|
246
229
|
//# sourceMappingURL=utils.js.map
|