langchain 1.0.0-alpha.4 → 1.0.0-alpha.6
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 +1 -3
- package/dist/agents/ReactAgent.d.cts.map +1 -1
- package/dist/agents/ReactAgent.d.ts +1 -3
- 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/RunnableCallable.cjs +5 -0
- package/dist/agents/RunnableCallable.cjs.map +1 -1
- package/dist/agents/RunnableCallable.d.cts +2 -0
- package/dist/agents/RunnableCallable.d.cts.map +1 -1
- package/dist/agents/RunnableCallable.d.ts +2 -0
- package/dist/agents/RunnableCallable.d.ts.map +1 -1
- package/dist/agents/RunnableCallable.js +5 -0
- package/dist/agents/RunnableCallable.js.map +1 -1
- package/dist/agents/annotation.cjs.map +1 -1
- package/dist/agents/annotation.d.cts +5 -7
- package/dist/agents/annotation.d.cts.map +1 -1
- package/dist/agents/annotation.d.ts +4 -6
- package/dist/agents/annotation.d.ts.map +1 -1
- package/dist/agents/annotation.js.map +1 -1
- package/dist/agents/createAgent.cjs +10 -0
- package/dist/agents/createAgent.cjs.map +1 -0
- package/dist/agents/createAgent.js +10 -0
- package/dist/agents/createAgent.js.map +1 -0
- package/dist/agents/index.cjs +23 -4
- package/dist/agents/index.cjs.map +1 -1
- package/dist/agents/index.d.cts +84 -21
- package/dist/agents/index.d.cts.map +1 -1
- package/dist/agents/index.d.ts +84 -21
- package/dist/agents/index.d.ts.map +1 -1
- package/dist/agents/index.js +23 -4
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/middlewareAgent/ReactAgent.cjs +255 -0
- package/dist/agents/middlewareAgent/ReactAgent.cjs.map +1 -0
- package/dist/agents/middlewareAgent/ReactAgent.d.cts +67 -0
- package/dist/agents/middlewareAgent/ReactAgent.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/ReactAgent.d.ts +67 -0
- package/dist/agents/middlewareAgent/ReactAgent.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/ReactAgent.js +254 -0
- package/dist/agents/middlewareAgent/ReactAgent.js.map +1 -0
- package/dist/agents/middlewareAgent/annotation.cjs +39 -0
- package/dist/agents/middlewareAgent/annotation.cjs.map +1 -0
- package/dist/agents/middlewareAgent/annotation.js +38 -0
- package/dist/agents/middlewareAgent/annotation.js.map +1 -0
- package/dist/agents/middlewareAgent/index.cjs +11 -0
- package/dist/agents/middlewareAgent/index.cjs.map +1 -0
- package/dist/agents/middlewareAgent/index.js +11 -0
- package/dist/agents/middlewareAgent/index.js.map +1 -0
- package/dist/agents/middlewareAgent/middleware/hitl.cjs +235 -0
- package/dist/agents/middlewareAgent/middleware/hitl.cjs.map +1 -0
- package/dist/agents/middlewareAgent/middleware/hitl.d.cts +199 -0
- package/dist/agents/middlewareAgent/middleware/hitl.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/middleware/hitl.d.ts +199 -0
- package/dist/agents/middlewareAgent/middleware/hitl.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/middleware/hitl.js +234 -0
- package/dist/agents/middlewareAgent/middleware/hitl.js.map +1 -0
- package/dist/agents/middlewareAgent/middleware/index.cjs +26 -0
- package/dist/agents/middlewareAgent/middleware/index.cjs.map +1 -0
- package/dist/agents/middlewareAgent/middleware/index.d.cts +4 -0
- package/dist/agents/middlewareAgent/middleware/index.d.ts +4 -0
- package/dist/agents/middlewareAgent/middleware/index.js +17 -0
- package/dist/agents/middlewareAgent/middleware/index.js.map +1 -0
- package/dist/agents/middlewareAgent/middleware/promptCaching.cjs +182 -0
- package/dist/agents/middlewareAgent/middleware/promptCaching.cjs.map +1 -0
- package/dist/agents/middlewareAgent/middleware/promptCaching.d.cts +152 -0
- package/dist/agents/middlewareAgent/middleware/promptCaching.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/middleware/promptCaching.d.ts +152 -0
- package/dist/agents/middlewareAgent/middleware/promptCaching.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/middleware/promptCaching.js +181 -0
- package/dist/agents/middlewareAgent/middleware/promptCaching.js.map +1 -0
- package/dist/agents/middlewareAgent/middleware/summarization.cjs +262 -0
- package/dist/agents/middlewareAgent/middleware/summarization.cjs.map +1 -0
- package/dist/agents/middlewareAgent/middleware/summarization.d.cts +89 -0
- package/dist/agents/middlewareAgent/middleware/summarization.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/middleware/summarization.d.ts +89 -0
- package/dist/agents/middlewareAgent/middleware/summarization.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/middleware/summarization.js +260 -0
- package/dist/agents/middlewareAgent/middleware/summarization.js.map +1 -0
- package/dist/agents/middlewareAgent/middleware.cjs +47 -0
- package/dist/agents/middlewareAgent/middleware.cjs.map +1 -0
- package/dist/agents/middlewareAgent/middleware.d.cts +46 -0
- package/dist/agents/middlewareAgent/middleware.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/middleware.d.ts +46 -0
- package/dist/agents/middlewareAgent/middleware.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/middleware.js +46 -0
- package/dist/agents/middlewareAgent/middleware.js.map +1 -0
- package/dist/agents/middlewareAgent/nodes/AfterModalNode.cjs +29 -0
- package/dist/agents/middlewareAgent/nodes/AfterModalNode.cjs.map +1 -0
- package/dist/agents/middlewareAgent/nodes/AfterModalNode.js +29 -0
- package/dist/agents/middlewareAgent/nodes/AfterModalNode.js.map +1 -0
- package/dist/agents/middlewareAgent/nodes/AgentNode.cjs +325 -0
- package/dist/agents/middlewareAgent/nodes/AgentNode.cjs.map +1 -0
- package/dist/agents/middlewareAgent/nodes/AgentNode.js +324 -0
- package/dist/agents/middlewareAgent/nodes/AgentNode.js.map +1 -0
- package/dist/agents/middlewareAgent/nodes/BeforeModalNode.cjs +27 -0
- package/dist/agents/middlewareAgent/nodes/BeforeModalNode.cjs.map +1 -0
- package/dist/agents/middlewareAgent/nodes/BeforeModalNode.js +27 -0
- package/dist/agents/middlewareAgent/nodes/BeforeModalNode.js.map +1 -0
- package/dist/agents/middlewareAgent/nodes/middleware.cjs +73 -0
- package/dist/agents/middlewareAgent/nodes/middleware.cjs.map +1 -0
- package/dist/agents/middlewareAgent/nodes/middleware.js +73 -0
- package/dist/agents/middlewareAgent/nodes/middleware.js.map +1 -0
- package/dist/agents/middlewareAgent/nodes/utils.cjs +74 -0
- package/dist/agents/middlewareAgent/nodes/utils.cjs.map +1 -0
- package/dist/agents/middlewareAgent/nodes/utils.js +70 -0
- package/dist/agents/middlewareAgent/nodes/utils.js.map +1 -0
- package/dist/agents/middlewareAgent/types.d.cts +380 -0
- package/dist/agents/middlewareAgent/types.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/types.d.ts +380 -0
- package/dist/agents/middlewareAgent/types.d.ts.map +1 -0
- package/dist/agents/nodes/AgentNode.cjs +4 -4
- package/dist/agents/nodes/AgentNode.cjs.map +1 -1
- package/dist/agents/nodes/AgentNode.js +4 -4
- package/dist/agents/nodes/AgentNode.js.map +1 -1
- package/dist/agents/nodes/ToolNode.cjs +3 -3
- package/dist/agents/nodes/ToolNode.cjs.map +1 -1
- package/dist/agents/nodes/ToolNode.d.cts +4 -5
- 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 +4 -4
- package/dist/agents/nodes/ToolNode.js.map +1 -1
- package/dist/agents/responses.cjs +1 -1
- package/dist/agents/responses.cjs.map +1 -1
- package/dist/agents/responses.d.cts.map +1 -1
- package/dist/agents/responses.d.ts.map +1 -1
- package/dist/agents/responses.js +1 -1
- package/dist/agents/responses.js.map +1 -1
- package/dist/agents/types.d.cts +5 -7
- package/dist/agents/types.d.cts.map +1 -1
- package/dist/agents/types.d.ts +1 -3
- package/dist/agents/types.d.ts.map +1 -1
- package/dist/agents/utils.cjs +6 -6
- package/dist/agents/utils.cjs.map +1 -1
- package/dist/agents/utils.js +7 -7
- 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/api_chain.d.cts +1 -1
- package/dist/chains/api/prompts.cjs.map +1 -1
- package/dist/chains/api/prompts.js.map +1 -1
- package/dist/chains/base.d.cts +1 -1
- package/dist/chains/combine_docs_chain.d.cts +1 -1
- package/dist/chains/combine_documents/stuff.d.cts +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/conversational_retrieval_chain.d.cts +1 -1
- package/dist/chains/graph_qa/cypher.d.cts +1 -1
- package/dist/chains/history_aware_retriever.d.cts +2 -2
- 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/llm_chain.d.cts +3 -3
- package/dist/chains/openai_functions/base.d.cts +3 -3
- 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 +2 -2
- 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 +2 -4
- 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 +5 -3
- 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/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/retrieval.d.cts +1 -1
- package/dist/chains/router/llm_router.d.cts +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_chain.d.cts +2 -2
- 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 +4 -4
- 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 +1 -1
- package/dist/embeddings/cache_backed.js +2 -2
- package/dist/embeddings/cache_backed.js.map +1 -1
- package/dist/evaluation/agents/trajectory.d.cts +3 -3
- package/dist/evaluation/agents/trajectory.d.cts.map +1 -1
- package/dist/evaluation/agents/trajectory.d.ts.map +1 -1
- package/dist/evaluation/comparison/pairwise.d.cts +1 -1
- package/dist/evaluation/comparison/pairwise.d.cts.map +1 -1
- package/dist/evaluation/criteria/criteria.d.cts +1 -1
- package/dist/evaluation/criteria/criteria.d.cts.map +1 -1
- package/dist/evaluation/criteria/criteria.d.ts.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/evaluation/qa/eval_chain.d.cts +1 -1
- package/dist/hub/base.cjs.map +1 -1
- package/dist/hub/base.js.map +1 -1
- package/dist/index.cjs +3 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -4
- package/dist/index.d.ts +3 -2
- package/dist/index.js +3 -1
- 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 +1 -1
- package/dist/langchain-core/dist/messages/content/index.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/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 +1 -1
- package/dist/libs/langchain-core/dist/messages/content/index.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 +2 -13
- package/dist/load/import_map.cjs.map +1 -1
- package/dist/load/import_map.js +2 -13
- 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/memory/summary.d.cts +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/fix.d.cts +1 -1
- package/dist/output_parsers/http_response.d.cts +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 +2 -2
- 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/json.d.cts +1 -1
- package/dist/tools/retriever.cjs +2 -2
- package/dist/tools/retriever.cjs.map +1 -1
- package/dist/tools/retriever.d.cts +2 -2
- 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/tools/vectorstore.d.cts +1 -1
- package/dist/tools/webbrowser.d.cts +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 +21 -16
- 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
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
import { JsonSchemaFormat, ProviderStrategy, ResponseFormat, ResponseFormatUndefined, ToolStrategy, TypedToolStrategy } from "../responses.js";
|
|
2
|
+
import { AnyAnnotationRoot, PreHookAnnotation, ToAnnotationRoot } from "../annotation.js";
|
|
3
|
+
import { ToolNode } from "../nodes/ToolNode.js";
|
|
4
|
+
import { AgentRuntime, ClientTool, ServerTool } from "../types.js";
|
|
5
|
+
import { BaseMessage, BaseMessageLike, SystemMessage } from "@langchain/core/messages";
|
|
6
|
+
import { Runnable } from "@langchain/core/runnables";
|
|
7
|
+
import { LangGraphRunnableConfig, START } from "@langchain/langgraph";
|
|
8
|
+
import { InferInteropZodInput, InteropZodObject, InteropZodType } from "@langchain/core/utils/types";
|
|
9
|
+
import { z } from "zod/v3";
|
|
10
|
+
import { LanguageModelLike } from "@langchain/core/language_models/base";
|
|
11
|
+
import { All, BaseCheckpointSaver, BaseStore } from "@langchain/langgraph-checkpoint";
|
|
12
|
+
|
|
13
|
+
//#region src/agents/middlewareAgent/types.d.ts
|
|
14
|
+
type N = typeof START | "model_request" | "tools";
|
|
15
|
+
interface BuiltInState {
|
|
16
|
+
messages: BaseMessage[];
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Information about a tool call that has been executed.
|
|
20
|
+
*/
|
|
21
|
+
interface ToolCall {
|
|
22
|
+
/**
|
|
23
|
+
* The ID of the tool call.
|
|
24
|
+
*/
|
|
25
|
+
id: string;
|
|
26
|
+
/**
|
|
27
|
+
* The name of the tool that was called.
|
|
28
|
+
*/
|
|
29
|
+
name: string;
|
|
30
|
+
/**
|
|
31
|
+
* The arguments that were passed to the tool.
|
|
32
|
+
*/
|
|
33
|
+
args: Record<string, any>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Information about a tool result from a tool execution.
|
|
37
|
+
*/
|
|
38
|
+
interface ToolResult {
|
|
39
|
+
/**
|
|
40
|
+
* The ID of the tool call.
|
|
41
|
+
*/
|
|
42
|
+
id: string;
|
|
43
|
+
/**
|
|
44
|
+
* The result of the tool call.
|
|
45
|
+
*/
|
|
46
|
+
result: any;
|
|
47
|
+
/**
|
|
48
|
+
* An optional error message if the tool call failed.
|
|
49
|
+
*/
|
|
50
|
+
error?: string;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Configuration for modifying a model call at runtime.
|
|
54
|
+
* All fields are optional and only provided fields will override defaults.
|
|
55
|
+
*/
|
|
56
|
+
interface ModelRequest {
|
|
57
|
+
/**
|
|
58
|
+
* The model to use for this step.
|
|
59
|
+
*/
|
|
60
|
+
model: LanguageModelLike;
|
|
61
|
+
/**
|
|
62
|
+
* The messages to send to the model.
|
|
63
|
+
*/
|
|
64
|
+
messages: BaseMessage[];
|
|
65
|
+
/**
|
|
66
|
+
* The system message for this step.
|
|
67
|
+
*/
|
|
68
|
+
systemMessage?: BaseMessage;
|
|
69
|
+
/**
|
|
70
|
+
* Tool choice configuration (model-specific format).
|
|
71
|
+
* Can be one of:
|
|
72
|
+
* - `"auto"`: means the model can pick between generating a message or calling one or more tools.
|
|
73
|
+
* - `"none"`: means the model will not call any tool and instead generates a message.
|
|
74
|
+
* - `"required"`: means the model must call one or more tools.
|
|
75
|
+
* - `{ type: "function", function: { name: string } }`: The model will use the specified function.
|
|
76
|
+
*/
|
|
77
|
+
toolChoice?: "auto" | "none" | "required" | {
|
|
78
|
+
type: "function";
|
|
79
|
+
function: {
|
|
80
|
+
name: string;
|
|
81
|
+
};
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* The tools to make available for this step.
|
|
85
|
+
* Can be tool names (strings) or tool instances.
|
|
86
|
+
*/
|
|
87
|
+
tools: (ClientTool | ServerTool)[];
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Runtime information available to middleware (readonly).
|
|
91
|
+
*/
|
|
92
|
+
interface Runtime<TContext = unknown> {
|
|
93
|
+
readonly toolCalls: ToolCall[];
|
|
94
|
+
readonly toolResults: ToolResult[];
|
|
95
|
+
// readonly tokenUsage: {
|
|
96
|
+
// readonly inputTokens: number;
|
|
97
|
+
// readonly outputTokens: number;
|
|
98
|
+
// readonly totalTokens: number;
|
|
99
|
+
// };
|
|
100
|
+
readonly context: TContext;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Control flow interface for middleware.
|
|
104
|
+
*/
|
|
105
|
+
interface Controls<TState = unknown> {
|
|
106
|
+
jumpTo(target: "model" | "tools", stateUpdate?: Partial<TState>): ControlAction<TState>;
|
|
107
|
+
terminate(result?: Partial<TState> | Error): ControlAction<TState>;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Control action type returned by control methods.
|
|
111
|
+
*/
|
|
112
|
+
type ControlAction<TStateSchema> = {
|
|
113
|
+
type: "jump" | "terminate" | "retry";
|
|
114
|
+
target?: string;
|
|
115
|
+
stateUpdate?: Partial<TStateSchema>;
|
|
116
|
+
result?: any;
|
|
117
|
+
error?: Error;
|
|
118
|
+
};
|
|
119
|
+
/**
|
|
120
|
+
* Result type for middleware functions.
|
|
121
|
+
*/
|
|
122
|
+
type MiddlewareResult<TState> = TState | void;
|
|
123
|
+
/**
|
|
124
|
+
* Type for the agent's built-in state properties.
|
|
125
|
+
*/
|
|
126
|
+
type AgentBuiltInState = {
|
|
127
|
+
messages: BaseMessage[];
|
|
128
|
+
};
|
|
129
|
+
/**
|
|
130
|
+
* Helper type to filter out properties that start with underscore (private properties)
|
|
131
|
+
*/
|
|
132
|
+
type FilterPrivateProps<T> = { [K in keyof T as K extends `_${string}` ? never : K]: T[K] };
|
|
133
|
+
/**
|
|
134
|
+
* Helper type to infer the state schema type from a middleware
|
|
135
|
+
* This filters out private properties (those starting with underscore)
|
|
136
|
+
*/
|
|
137
|
+
type InferMiddlewareState<T extends AgentMiddleware<any, any, any>> = T extends AgentMiddleware<infer S, any, any> ? S extends z.ZodObject<any> ? FilterPrivateProps<z.infer<S>> : {} : {};
|
|
138
|
+
/**
|
|
139
|
+
* Helper type to infer the input state schema type from a middleware (all properties optional)
|
|
140
|
+
* This filters out private properties (those starting with underscore)
|
|
141
|
+
*/
|
|
142
|
+
type InferMiddlewareInputState<T extends AgentMiddleware<any, any, any>> = T extends AgentMiddleware<infer S, any, any> ? S extends z.ZodObject<any> ? FilterPrivateProps<z.input<S>> : {} : {};
|
|
143
|
+
/**
|
|
144
|
+
* Helper type to infer merged state from an array of middleware (just the middleware states)
|
|
145
|
+
*/
|
|
146
|
+
type InferMiddlewareStates<T extends readonly AgentMiddleware<any, any, any>[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware<any, any, any> ? Rest extends readonly AgentMiddleware<any, any, any>[] ? InferMiddlewareState<First> & InferMiddlewareStates<Rest> : InferMiddlewareState<First> : {} : {};
|
|
147
|
+
/**
|
|
148
|
+
* Helper type to infer merged input state from an array of middleware (with optional defaults)
|
|
149
|
+
*/
|
|
150
|
+
type InferMiddlewareInputStates<T extends readonly AgentMiddleware<any, any, any>[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware<any, any, any> ? Rest extends readonly AgentMiddleware<any, any, any>[] ? InferMiddlewareInputState<First> & InferMiddlewareInputStates<Rest> : InferMiddlewareInputState<First> : {} : {};
|
|
151
|
+
/**
|
|
152
|
+
* Helper type to infer merged state from an array of middleware (includes built-in state)
|
|
153
|
+
*/
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Helper type to infer the input context schema type from a middleware (with optional defaults)
|
|
157
|
+
*/
|
|
158
|
+
type InferMiddlewareContextInput<T extends AgentMiddleware<any, any, any>> = T extends AgentMiddleware<any, infer C, any> ? C extends z.ZodObject<any> ? z.input<C> : {} : {};
|
|
159
|
+
/**
|
|
160
|
+
* Helper type to infer merged context from an array of middleware
|
|
161
|
+
*/
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Helper type to infer merged input context from an array of middleware (with optional defaults)
|
|
165
|
+
*/
|
|
166
|
+
type InferMiddlewareContextInputs<T extends readonly AgentMiddleware<any, any, any>[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware<any, any, any> ? Rest extends readonly AgentMiddleware<any, any, any>[] ? InferMiddlewareContextInput<First> & InferMiddlewareContextInputs<Rest> : InferMiddlewareContextInput<First> : {} : {};
|
|
167
|
+
/**
|
|
168
|
+
* Base middleware interface.
|
|
169
|
+
*/
|
|
170
|
+
interface AgentMiddleware<TSchema extends z.ZodObject<z.ZodRawShape> | undefined = undefined, TContextSchema extends z.ZodObject<z.ZodRawShape> | undefined = undefined, TFullContext = any> {
|
|
171
|
+
stateSchema?: TSchema;
|
|
172
|
+
contextSchema?: TContextSchema;
|
|
173
|
+
name: string;
|
|
174
|
+
/**
|
|
175
|
+
* Runs before each LLM call, can modify call parameters, changes are not persistent
|
|
176
|
+
* e.g. if you change `model`, it will only be changed for the next model call
|
|
177
|
+
*
|
|
178
|
+
* @param options - Current call options (can be modified by previous middleware)
|
|
179
|
+
* @param state - Current state (read-only in this phase)
|
|
180
|
+
* @param runtime - Runtime context and metadata
|
|
181
|
+
* @returns Modified options or undefined to pass through
|
|
182
|
+
*/
|
|
183
|
+
prepareModelRequest?(request: ModelRequest, state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) & AgentBuiltInState, runtime: Runtime<TFullContext>): Promise<Partial<ModelRequest> | void> | Partial<ModelRequest> | void;
|
|
184
|
+
beforeModel?(state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) & AgentBuiltInState, runtime: Runtime<TFullContext>, controls: Controls<(TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) & AgentBuiltInState>): Promise<MiddlewareResult<Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>>>;
|
|
185
|
+
afterModel?(state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) & AgentBuiltInState, runtime: Runtime<TFullContext>, controls: Controls<(TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) & AgentBuiltInState>): Promise<MiddlewareResult<Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>>>;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Information about a tool call that has been executed.
|
|
189
|
+
*/
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Duplicate of the Prompt type from ../types.ts
|
|
193
|
+
*/
|
|
194
|
+
type Prompt<ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = SystemMessage | string | ((state: AgentBuiltInState, config: LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>["State"]>) => BaseMessageLike[] | Promise<BaseMessageLike[]>) | Runnable;
|
|
195
|
+
type DynamicLLMFunction<ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = (state: AgentBuiltInState & PreHookAnnotation["State"], runtime: AgentRuntime<ToAnnotationRoot<ContextSchema>["State"]>) => Promise<LanguageModelLike> | LanguageModelLike;
|
|
196
|
+
type CreateAgentParams<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> = {
|
|
197
|
+
/** The chat model that can utilize OpenAI-style tool calling. */
|
|
198
|
+
llm?: LanguageModelLike | DynamicLLMFunction<ContextSchema>;
|
|
199
|
+
/**
|
|
200
|
+
* Initializes a ChatModel based on the provided model name and provider.
|
|
201
|
+
* It supports various model providers and allows for runtime configuration of model parameters.
|
|
202
|
+
*
|
|
203
|
+
* @uses {@link initChatModel}
|
|
204
|
+
* @example
|
|
205
|
+
* ```ts
|
|
206
|
+
* const agent = createAgent({
|
|
207
|
+
* model: "anthropic:claude-3-7-sonnet-latest",
|
|
208
|
+
* // ...
|
|
209
|
+
* });
|
|
210
|
+
* ```
|
|
211
|
+
*/
|
|
212
|
+
model?: string;
|
|
213
|
+
/** A list of tools or a ToolNode. */
|
|
214
|
+
tools?: ToolNode | (ServerTool | ClientTool)[];
|
|
215
|
+
/**
|
|
216
|
+
* An optional prompt for the LLM. This takes full graph state BEFORE the LLM is called and prepares the input to LLM.
|
|
217
|
+
*
|
|
218
|
+
* Can take a few different forms:
|
|
219
|
+
*
|
|
220
|
+
* - str: This is converted to a SystemMessage and added to the beginning of the list of messages in state["messages"].
|
|
221
|
+
* - SystemMessage: this is added to the beginning of the list of messages in state["messages"].
|
|
222
|
+
* - Function: This function should take in full graph state and the output is then passed to the language model.
|
|
223
|
+
* - Runnable: This runnable should take in full graph state and the output is then passed to the language model.
|
|
224
|
+
*
|
|
225
|
+
* Note:
|
|
226
|
+
* Prior to `v0.2.46`, the prompt was set using `stateModifier` / `messagesModifier` parameters.
|
|
227
|
+
* This is now deprecated and will be removed in a future release.
|
|
228
|
+
*
|
|
229
|
+
* Cannot be used together with `prepareModelRequest`.
|
|
230
|
+
*/
|
|
231
|
+
prompt?: Prompt<ContextSchema>;
|
|
232
|
+
/**
|
|
233
|
+
* An optional schema for the context. It allows to pass in a typed context object into the agent
|
|
234
|
+
* invocation and allows to access it in hooks such as `prompt` and middleware.
|
|
235
|
+
* As opposed to the agent state, defined in `stateSchema`, the context is not persisted between
|
|
236
|
+
* agent invocations.
|
|
237
|
+
*
|
|
238
|
+
* @example
|
|
239
|
+
* ```ts
|
|
240
|
+
* const agent = createAgent({
|
|
241
|
+
* llm: model,
|
|
242
|
+
* tools: [getWeather],
|
|
243
|
+
* contextSchema: z.object({
|
|
244
|
+
* capital: z.string(),
|
|
245
|
+
* }),
|
|
246
|
+
* prompt: (state, config) => {
|
|
247
|
+
* return [
|
|
248
|
+
* new SystemMessage(`You are a helpful assistant. The capital of France is ${config.context.capital}.`),
|
|
249
|
+
* ];
|
|
250
|
+
* },
|
|
251
|
+
* });
|
|
252
|
+
*
|
|
253
|
+
* const result = await agent.invoke({
|
|
254
|
+
* messages: [
|
|
255
|
+
* new SystemMessage("You are a helpful assistant."),
|
|
256
|
+
* new HumanMessage("What is the capital of France?"),
|
|
257
|
+
* ],
|
|
258
|
+
* }, {
|
|
259
|
+
* context: {
|
|
260
|
+
* capital: "Paris",
|
|
261
|
+
* },
|
|
262
|
+
* });
|
|
263
|
+
* ```
|
|
264
|
+
*/
|
|
265
|
+
contextSchema?: ContextSchema;
|
|
266
|
+
/** An optional checkpoint saver to persist the agent's state. */
|
|
267
|
+
checkpointSaver?: BaseCheckpointSaver | boolean;
|
|
268
|
+
/** An optional checkpoint saver to persist the agent's state. Alias of "checkpointSaver". */
|
|
269
|
+
checkpointer?: BaseCheckpointSaver | boolean;
|
|
270
|
+
/** An optional list of node names to interrupt before running. */
|
|
271
|
+
interruptBefore?: N[] | All;
|
|
272
|
+
/** An optional list of node names to interrupt after running. */
|
|
273
|
+
interruptAfter?: N[] | All;
|
|
274
|
+
store?: BaseStore;
|
|
275
|
+
/**
|
|
276
|
+
* An optional schema for the final agent output.
|
|
277
|
+
*
|
|
278
|
+
* If provided, output will be formatted to match the given schema and returned in the 'structuredResponse' state key.
|
|
279
|
+
* If not provided, `structuredResponse` will not be present in the output state.
|
|
280
|
+
*
|
|
281
|
+
* Can be passed in as:
|
|
282
|
+
* - Zod schema
|
|
283
|
+
* ```ts
|
|
284
|
+
* const agent = createAgent({
|
|
285
|
+
* responseFormat: z.object({
|
|
286
|
+
* capital: z.string(),
|
|
287
|
+
* }),
|
|
288
|
+
* // ...
|
|
289
|
+
* });
|
|
290
|
+
* ```
|
|
291
|
+
* - JSON schema
|
|
292
|
+
* ```ts
|
|
293
|
+
* const agent = createAgent({
|
|
294
|
+
* responseFormat: {
|
|
295
|
+
* type: "json_schema",
|
|
296
|
+
* schema: {
|
|
297
|
+
* type: "object",
|
|
298
|
+
* properties: {
|
|
299
|
+
* capital: { type: "string" },
|
|
300
|
+
* },
|
|
301
|
+
* required: ["capital"],
|
|
302
|
+
* },
|
|
303
|
+
* },
|
|
304
|
+
* // ...
|
|
305
|
+
* });
|
|
306
|
+
* ```
|
|
307
|
+
* - Create React Agent ResponseFormat
|
|
308
|
+
* ```ts
|
|
309
|
+
* import { providerStrategy, toolStrategy } from "langchain";
|
|
310
|
+
* const agent = createAgent({
|
|
311
|
+
* responseFormat: providerStrategy(
|
|
312
|
+
* z.object({
|
|
313
|
+
* capital: z.string(),
|
|
314
|
+
* })
|
|
315
|
+
* ),
|
|
316
|
+
* // or
|
|
317
|
+
* responseFormat: [
|
|
318
|
+
* toolStrategy({ ... }),
|
|
319
|
+
* toolStrategy({ ... }),
|
|
320
|
+
* ]
|
|
321
|
+
* // ...
|
|
322
|
+
* });
|
|
323
|
+
* ```
|
|
324
|
+
*
|
|
325
|
+
* **Note**: The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.
|
|
326
|
+
* 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/).
|
|
327
|
+
*/
|
|
328
|
+
responseFormat?: ResponseFormatType;
|
|
329
|
+
/**
|
|
330
|
+
* Middleware instances to run during agent execution.
|
|
331
|
+
* Each middleware can define its own state schema and hook into the agent lifecycle.
|
|
332
|
+
*/
|
|
333
|
+
middleware?: readonly AgentMiddleware<any, any, any>[];
|
|
334
|
+
/**
|
|
335
|
+
* An optional name for the agent.
|
|
336
|
+
*/
|
|
337
|
+
name?: string;
|
|
338
|
+
/**
|
|
339
|
+
* An optional description for the agent.
|
|
340
|
+
* This can be used to describe the agent to the underlying supervisor LLM.
|
|
341
|
+
*/
|
|
342
|
+
description?: string;
|
|
343
|
+
/**
|
|
344
|
+
* Use to specify how to expose the agent name to the underlying supervisor LLM.
|
|
345
|
+
* - `undefined`: Relies on the LLM provider {@link AIMessage#name}. Currently, only OpenAI supports this.
|
|
346
|
+
* - `"inline"`: Add the agent name directly into the content field of the {@link AIMessage} using XML-style tags.
|
|
347
|
+
* Example: `"How can I help you"` -> `"<name>agent_name</name><content>How can I help you?</content>"`
|
|
348
|
+
*/
|
|
349
|
+
includeAgentName?: "inline" | undefined;
|
|
350
|
+
/**
|
|
351
|
+
* An optional abort signal that indicates that the overall operation should be aborted.
|
|
352
|
+
*/
|
|
353
|
+
signal?: AbortSignal;
|
|
354
|
+
/**
|
|
355
|
+
* Determines the version of the graph to create.
|
|
356
|
+
*
|
|
357
|
+
* Can be one of
|
|
358
|
+
* - `"v1"`: The tool node processes a single message. All tool calls in the message are
|
|
359
|
+
* executed in parallel within the tool node.
|
|
360
|
+
* - `"v2"`: The tool node processes a single tool call. Tool calls are distributed across
|
|
361
|
+
* multiple instances of the tool node using the Send API.
|
|
362
|
+
*
|
|
363
|
+
* @default `"v2"`
|
|
364
|
+
*/
|
|
365
|
+
version?: "v1" | "v2";
|
|
366
|
+
};
|
|
367
|
+
/**
|
|
368
|
+
* Helper type to check if all properties of a type are optional
|
|
369
|
+
*/
|
|
370
|
+
type IsAllOptional<T> = T extends Record<string, any> ? {} extends T ? true : false : true;
|
|
371
|
+
/**
|
|
372
|
+
* Helper type to extract input type from context schema (with optional defaults)
|
|
373
|
+
*/
|
|
374
|
+
type InferContextInput<ContextSchema extends AnyAnnotationRoot | InteropZodObject> = ContextSchema extends InteropZodObject ? InferInteropZodInput<ContextSchema> : ContextSchema extends AnyAnnotationRoot ? ToAnnotationRoot<ContextSchema>["State"] : {};
|
|
375
|
+
/**
|
|
376
|
+
* Helper type to get the required config type based on context schema
|
|
377
|
+
*/
|
|
378
|
+
//#endregion
|
|
379
|
+
export { AgentBuiltInState, AgentMiddleware, BuiltInState, Controls, CreateAgentParams, InferContextInput, InferMiddlewareContextInputs, InferMiddlewareInputStates, InferMiddlewareStates, IsAllOptional, MiddlewareResult, ModelRequest, Runtime };
|
|
380
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","names":["z","InteropZodObject","InteropZodType","InferInteropZodInput","LangGraphRunnableConfig","START","LanguageModelLike","SystemMessage","BaseMessageLike","BaseMessage","All","BaseCheckpointSaver","BaseStore","Runnable","PreHookAnnotation","AnyAnnotationRoot","ToAnnotationRoot","ResponseFormat","ToolStrategy","TypedToolStrategy","ProviderStrategy","ResponseFormatUndefined","JsonSchemaFormat","ToolNode","ClientTool","ServerTool","AgentRuntime","N","BuiltInState","ToolCall","Record","ToolResult","ModelRequest","Runtime","TContext","Controls","TState","Partial","ControlAction","Error","TStateSchema","MiddlewareResult","AgentBuiltInState","FilterPrivateProps","T","K","InferMiddlewareState","AgentMiddleware","S","ZodObject","infer","InferMiddlewareInputState","input","InferMiddlewareStates","First","Rest","InferMiddlewareInputStates","InferMergedState","InferMergedInputState","InferMiddlewareContext","C","InferMiddlewareContextInput","InferMiddlewareContexts","InferMiddlewareContextInputs","ZodRawShape","TSchema","TContextSchema","TFullContext","Promise","ExecutedToolCall","LLMCall","Prompt","ContextSchema","DynamicLLMFunction","CreateAgentParams","StructuredResponseType","ResponseFormatType","AbortSignal","IsAllOptional","InferContextInput","InferAgentConfig","TMiddleware","InternalAgentState"],"sources":["../../../src/agents/middlewareAgent/types.d.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { z } from \"zod/v3\";\nimport type { InteropZodObject, InteropZodType, InferInteropZodInput } from \"@langchain/core/utils/types\";\nimport type { LangGraphRunnableConfig, START } 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 { Runnable } from \"@langchain/core/runnables\";\nimport type { PreHookAnnotation, AnyAnnotationRoot, ToAnnotationRoot } from \"../annotation.js\";\nimport type { ResponseFormat, ToolStrategy, TypedToolStrategy, ProviderStrategy, ResponseFormatUndefined, JsonSchemaFormat } from \"../responses.js\";\nimport type { ToolNode } from \"../nodes/ToolNode.js\";\nimport type { ClientTool, ServerTool, AgentRuntime } from \"../types.js\";\nexport type N = typeof START | \"model_request\" | \"tools\";\nexport interface BuiltInState {\n messages: BaseMessage[];\n}\n/**\n * Information about a tool call that has been executed.\n */\nexport interface ToolCall {\n /**\n * The ID of the tool call.\n */\n id: string;\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, any>;\n}\n/**\n * Information about a tool result from a tool execution.\n */\nexport interface ToolResult {\n /**\n * The ID of the tool call.\n */\n id: string;\n /**\n * The result of the tool call.\n */\n result: any;\n /**\n * An optional error message if the tool call failed.\n */\n error?: string;\n}\n/**\n * Configuration for modifying a model call at runtime.\n * All fields are optional and only provided fields will override defaults.\n */\nexport interface ModelRequest {\n /**\n * The model to use for this step.\n */\n model: LanguageModelLike;\n /**\n * The messages to send to the model.\n */\n messages: BaseMessage[];\n /**\n * The system message for this step.\n */\n systemMessage?: BaseMessage;\n /**\n * Tool choice configuration (model-specific format).\n * Can be one of:\n * - `\"auto\"`: means the model can pick between generating a message or calling one or more tools.\n * - `\"none\"`: means the model will not call any tool and instead generates a message.\n * - `\"required\"`: means the model must call one or more tools.\n * - `{ type: \"function\", function: { name: string } }`: The model will use the specified function.\n */\n toolChoice?: \"auto\" | \"none\" | \"required\" | {\n type: \"function\";\n function: {\n name: string;\n };\n };\n /**\n * The tools to make available for this step.\n * Can be tool names (strings) or tool instances.\n */\n tools: (ClientTool | ServerTool)[];\n}\n/**\n * Runtime information available to middleware (readonly).\n */\nexport interface Runtime<TContext = unknown> {\n readonly toolCalls: ToolCall[];\n readonly toolResults: ToolResult[];\n // readonly tokenUsage: {\n // readonly inputTokens: number;\n // readonly outputTokens: number;\n // readonly totalTokens: number;\n // };\n readonly context: TContext;\n}\n/**\n * Control flow interface for middleware.\n */\nexport interface Controls<TState = unknown> {\n jumpTo(target: \"model\" | \"tools\", stateUpdate?: Partial<TState>): ControlAction<TState>;\n terminate(result?: Partial<TState> | Error): ControlAction<TState>;\n}\n/**\n * Control action type returned by control methods.\n */\nexport type ControlAction<TStateSchema> = {\n type: \"jump\" | \"terminate\" | \"retry\";\n target?: string;\n stateUpdate?: Partial<TStateSchema>;\n result?: any;\n error?: Error;\n};\n/**\n * Result type for middleware functions.\n */\nexport type MiddlewareResult<TState> = TState | void;\n/**\n * Type for the agent's built-in state properties.\n */\nexport type AgentBuiltInState = {\n messages: BaseMessage[];\n};\n/**\n * Helper type to filter out properties that start with underscore (private properties)\n */\ntype FilterPrivateProps<T> = {\n [K in keyof T as K extends `_${string}` ? never : K]: T[K];\n};\n/**\n * Helper type to infer the state schema type from a middleware\n * This filters out private properties (those starting with underscore)\n */\nexport type InferMiddlewareState<T extends AgentMiddleware<any, any, any>> = T extends AgentMiddleware<infer S, any, any> ? S extends z.ZodObject<any> ? FilterPrivateProps<z.infer<S>> : {} : {};\n/**\n * Helper type to infer the input state schema type from a middleware (all properties optional)\n * This filters out private properties (those starting with underscore)\n */\nexport type InferMiddlewareInputState<T extends AgentMiddleware<any, any, any>> = T extends AgentMiddleware<infer S, any, any> ? S extends z.ZodObject<any> ? FilterPrivateProps<z.input<S>> : {} : {};\n/**\n * Helper type to infer merged state from an array of middleware (just the middleware states)\n */\nexport type InferMiddlewareStates<T extends readonly AgentMiddleware<any, any, any>[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware<any, any, any> ? Rest extends readonly AgentMiddleware<any, any, any>[] ? InferMiddlewareState<First> & InferMiddlewareStates<Rest> : InferMiddlewareState<First> : {} : {};\n/**\n * Helper type to infer merged input state from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareInputStates<T extends readonly AgentMiddleware<any, any, any>[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware<any, any, any> ? Rest extends readonly AgentMiddleware<any, any, any>[] ? InferMiddlewareInputState<First> & InferMiddlewareInputStates<Rest> : InferMiddlewareInputState<First> : {} : {};\n/**\n * Helper type to infer merged state from an array of middleware (includes built-in state)\n */\nexport type InferMergedState<T extends readonly AgentMiddleware<any, any, any>[]> = InferMiddlewareStates<T> & AgentBuiltInState;\n/**\n * Helper type to infer merged input state from an array of middleware (includes built-in state)\n */\nexport type InferMergedInputState<T extends readonly AgentMiddleware<any, any, any>[]> = InferMiddlewareInputStates<T> & AgentBuiltInState;\n/**\n * Helper type to infer the context schema type from a middleware\n */\nexport type InferMiddlewareContext<T extends AgentMiddleware<any, any, any>> = T extends AgentMiddleware<any, infer C, any> ? C extends z.ZodObject<any> ? z.infer<C> : {} : {};\n/**\n * Helper type to infer the input context schema type from a middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInput<T extends AgentMiddleware<any, any, any>> = T extends AgentMiddleware<any, infer C, any> ? C extends z.ZodObject<any> ? z.input<C> : {} : {};\n/**\n * Helper type to infer merged context from an array of middleware\n */\nexport type InferMiddlewareContexts<T extends readonly AgentMiddleware<any, any, any>[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware<any, any, any> ? Rest extends readonly AgentMiddleware<any, any, any>[] ? InferMiddlewareContext<First> & InferMiddlewareContexts<Rest> : InferMiddlewareContext<First> : {} : {};\n/**\n * Helper type to infer merged input context from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInputs<T extends readonly AgentMiddleware<any, any, any>[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware<any, any, any> ? Rest extends readonly AgentMiddleware<any, any, any>[] ? InferMiddlewareContextInput<First> & InferMiddlewareContextInputs<Rest> : InferMiddlewareContextInput<First> : {} : {};\n/**\n * Base middleware interface.\n */\nexport interface AgentMiddleware<TSchema extends z.ZodObject<z.ZodRawShape> | undefined = undefined, TContextSchema extends z.ZodObject<z.ZodRawShape> | undefined = undefined, TFullContext = any> {\n stateSchema?: TSchema;\n contextSchema?: TContextSchema;\n name: string;\n /**\n * Runs before each LLM call, can modify call parameters, changes are not persistent\n * e.g. if you change `model`, it will only be changed for the next model call\n *\n * @param options - Current call options (can be modified by previous middleware)\n * @param state - Current state (read-only in this phase)\n * @param runtime - Runtime context and metadata\n * @returns Modified options or undefined to pass through\n */\n prepareModelRequest?(request: ModelRequest, state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) & AgentBuiltInState, runtime: Runtime<TFullContext>): Promise<Partial<ModelRequest> | void> | Partial<ModelRequest> | void;\n beforeModel?(state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) & AgentBuiltInState, runtime: Runtime<TFullContext>, controls: Controls<(TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) & AgentBuiltInState>): Promise<MiddlewareResult<Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>>>;\n afterModel?(state: (TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) & AgentBuiltInState, runtime: Runtime<TFullContext>, controls: Controls<(TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}) & AgentBuiltInState>): Promise<MiddlewareResult<Partial<TSchema extends z.ZodObject<any> ? z.infer<TSchema> : {}>>>;\n}\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 * Duplicate of the Prompt type from ../types.ts\n */\nexport type Prompt<ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = SystemMessage | string | ((state: AgentBuiltInState, config: LangGraphRunnableConfig<ToAnnotationRoot<ContextSchema>[\"State\"]>) => BaseMessageLike[] | Promise<BaseMessageLike[]>) | Runnable;\nexport type DynamicLLMFunction<ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = (state: AgentBuiltInState & PreHookAnnotation[\"State\"], runtime: AgentRuntime<ToAnnotationRoot<ContextSchema>[\"State\"]>) => Promise<LanguageModelLike> | LanguageModelLike;\nexport type CreateAgentParams<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> = {\n /** The chat model that can utilize OpenAI-style tool calling. */\n llm?: LanguageModelLike | DynamicLLMFunction<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 `prepareModelRequest`.\n */\n prompt?: Prompt<ContextSchema>;\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` and middleware.\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 * Middleware instances to run during agent execution.\n * Each middleware can define its own state schema and hook into the agent lifecycle.\n */\n middleware?: readonly AgentMiddleware<any, any, any>[];\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 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};\n/**\n * Helper type to check if all properties of a type are optional\n */\nexport type IsAllOptional<T> = T extends Record<string, any> ? {} extends T ? true : false : true;\n/**\n * Helper type to extract input type from context schema (with optional defaults)\n */\nexport type InferContextInput<ContextSchema extends AnyAnnotationRoot | InteropZodObject> = ContextSchema extends InteropZodObject ? InferInteropZodInput<ContextSchema> : ContextSchema extends AnyAnnotationRoot ? ToAnnotationRoot<ContextSchema>[\"State\"] : {};\n/**\n * Helper type to get the required config type based on context schema\n */\nexport type InferAgentConfig<ContextSchema extends AnyAnnotationRoot | InteropZodObject, TMiddleware extends readonly AgentMiddleware<any, any, any>[]> = IsAllOptional<InferContextInput<ContextSchema> & InferMiddlewareContextInputs<TMiddleware>> extends true ? LangGraphRunnableConfig<{\n context?: InferContextInput<ContextSchema> & InferMiddlewareContextInputs<TMiddleware>;\n}> | undefined : LangGraphRunnableConfig<{\n context: InferContextInput<ContextSchema> & InferMiddlewareContextInputs<TMiddleware>;\n}>;\nexport type InternalAgentState<StructuredResponseType extends Record<string, unknown> | undefined = Record<string, unknown>> = {\n messages: BaseMessage[];\n __preparedModelOptions?: ModelRequest;\n} & (StructuredResponseType extends ResponseFormatUndefined ? Record<string, never> : {\n structuredResponse: StructuredResponseType;\n});\nexport {};\n"],"mappings":";;;;;;;;;;;;;KAYY2B,CAAAA,UAAWtB;AAAXsB,UACKC,YAAAA,CADW;EACXA,QAAAA,EACHnB,WADe,EAAA;AAM7B;AAiBA;AAkBA;;AAIWH,UAv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BwD"}
|
|
@@ -34,7 +34,7 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
|
|
|
34
34
|
* If so, we should generate structured response (if needed) and stop
|
|
35
35
|
*/
|
|
36
36
|
const lastMessage = state.messages[state.messages.length - 1];
|
|
37
|
-
if (
|
|
37
|
+
if (__langchain_core_messages.ToolMessage.isInstance(lastMessage) && lastMessage.name && this.#options.shouldReturnDirect.has(lastMessage.name))
|
|
38
38
|
/**
|
|
39
39
|
* return directly without invoking the model again
|
|
40
40
|
*/
|
|
@@ -53,9 +53,9 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
|
|
|
53
53
|
if (response instanceof __langchain_langgraph.Command) return response;
|
|
54
54
|
response.name = this.name;
|
|
55
55
|
response.lc_kwargs.name = this.name;
|
|
56
|
-
if (this.#areMoreStepsNeeded(state, response)) return { messages: [new __langchain_core_messages.AIMessage(
|
|
56
|
+
if (this.#areMoreStepsNeeded(state, response)) return { messages: [new __langchain_core_messages.AIMessage({
|
|
57
|
+
content: "Sorry, need more steps to process this request.",
|
|
57
58
|
name: this.name,
|
|
58
|
-
lc_kwargs: { name: this.name },
|
|
59
59
|
id: response.id
|
|
60
60
|
})] };
|
|
61
61
|
return { messages: [response] };
|
|
@@ -201,7 +201,7 @@ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
|
|
|
201
201
|
throw error;
|
|
202
202
|
}
|
|
203
203
|
#areMoreStepsNeeded(state, response) {
|
|
204
|
-
const allToolsReturnDirect =
|
|
204
|
+
const allToolsReturnDirect = __langchain_core_messages.AIMessage.isInstance(response) && response.tool_calls?.every((call) => this.#options.shouldReturnDirect.has(call.name));
|
|
205
205
|
const remainingSteps = "remainingSteps" in state ? state.remainingSteps : void 0;
|
|
206
206
|
return Boolean(remainingSteps && (remainingSteps < 1 && allToolsReturnDirect || remainingSteps < 2 && require_utils.hasToolCalls(state.messages)));
|
|
207
207
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AgentNode.cjs","names":["RunnableCallable","options: AgentNodeOptions<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >","#run","#options","#structuredToolInfo","transformResponseFormat","ToolStrategy","state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]","config: RunnableConfig","ToolMessage","#invokeModel","Command","#areMoreStepsNeeded","AIMessage","initChatModel","options: {\n lastMessage?: string;\n }","#deriveModel","validateLLMHasNoBoundTools","#bindTools","#getModelInputState","mergeAbortSignals","ProviderStrategy","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","response: AIMessage","toolCalls: ToolCall[]","MultipleStructuredOutputsError","#handleToolStrategyError","toolCall: ToolCall","lastMessage?: string","error: ToolStrategyError","response: BaseMessage","hasToolCalls","model: LanguageModelLike","options: Partial<BaseChatModelCallOptions>","hasSupportForJsonSchemaOutput","bindTools","getPromptRunnable","withAgentName"],"sources":["../../../src/agents/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport { BaseMessage, AIMessage, ToolMessage } from \"@langchain/core/messages\";\nimport { Command } from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n} from \"@langchain/core/utils/types\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\n\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError } from \"../errors.js\";\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport { PreHookAnnotation, AnyAnnotationRoot } from \"../annotation.js\";\nimport { mergeAbortSignals } from \"./utils.js\";\nimport {\n bindTools,\n getPromptRunnable,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n hasSupportForJsonSchemaOutput,\n} from \"../utils.js\";\nimport {\n InternalAgentState,\n ClientTool,\n ServerTool,\n CreateAgentParams,\n} from \"../types.js\";\nimport { withAgentName } from \"../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n} from \"../responses.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\nexport interface AgentNodeOptions<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends Pick<\n CreateAgentParams<StateSchema, StructuredResponseFormat, ContextSchema>,\n \"llm\" | \"model\" | \"prompt\" | \"includeAgentName\" | \"name\" | \"responseFormat\"\n > {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n}\n\nexport class AgentNode<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n { messages: BaseMessage[] } | { structuredResponse: StructuredResponseFormat }\n> {\n #options: AgentNodeOptions<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >;\n\n #structuredToolInfo: Record<string, ToolStrategy> = {};\n\n constructor(\n options: AgentNodeOptions<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) =>\n this.#run(input, config as RunnableConfig) as any,\n });\n\n this.#options = options;\n\n /**\n * Populate a list of structured tool info.\n */\n this.#structuredToolInfo = (\n transformResponseFormat(this.#options.responseFormat).filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce((acc, format) => {\n acc[format.name] = format;\n return acc;\n }, {} as Record<string, ToolStrategy>);\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages[state.messages.length - 1];\n if (\n lastMessage instanceof ToolMessage &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n /**\n * return directly without invoking the model again\n */\n return { messages: [] };\n }\n\n const response = await this.#invokeModel(state, config);\n\n /**\n * if we were able to generate a structured response, return it\n */\n if (\"structuredResponse\" in response) {\n return {\n messages: [...state.messages, ...(response.messages || [])],\n structuredResponse: response.structuredResponse,\n };\n }\n\n /**\n * if we need to direct the agent to the model, return the update\n */\n if (response instanceof Command) {\n return response;\n }\n\n response.name = this.name;\n response.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, response)) {\n return {\n messages: [\n new AIMessage(\"Sorry, need more steps to process this request.\", {\n name: this.name,\n lc_kwargs: { name: this.name },\n id: response.id,\n }),\n ],\n };\n }\n\n return { messages: [response] };\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n if (this.#options.model) {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n throw new Error(\"`model` option must be a string.\");\n }\n\n const model = this.#options.llm;\n\n /**\n * If the model is a function, call it to get the model.\n */\n if (typeof model === \"function\") {\n return model(state, config);\n }\n\n if (model) {\n return model;\n }\n\n throw new Error(\n \"No model option was provided, either via `model` or via `llm` option.\"\n );\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> {\n const model = await this.#deriveModel(state, config);\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(model);\n\n const modelWithTools = await this.#bindTools(model);\n const modelInput = this.#getModelInputState(state);\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const invokeConfig = {\n ...config,\n signal,\n };\n\n const response = (await modelWithTools.invoke(\n modelInput,\n invokeConfig\n )) as AIMessage;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n const structuredResponse = this.#options.responseFormat.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n }\n\n if (!response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in this.#structuredToolInfo\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(response, toolCalls);\n }\n\n const toolStrategy = this.#structuredToolInfo[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n toolMessageContent ?? options.lastMessage\n );\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[]\n ): Promise<Command> {\n /**\n * the following should never happen, let's throw an error if it does\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n throw new Error(\n \"Multiple structured outputs should not apply to native structured output responses\"\n );\n }\n\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0]\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = this.#structuredToolInfo[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(this.#structuredToolInfo).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided `true` as the `errorHandler` option, return a new AIMessage\n * with the error message and retry the tool call.\n */\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * throw otherwise, e.g. if `errorHandler` is not defined or set to `false`\n */\n throw error;\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n response instanceof AIMessage &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages)))\n );\n }\n\n #getModelInputState(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]\n ): Omit<InternalAgentState<StructuredResponseFormat>, \"llmInputMessages\"> {\n const { messages, llmInputMessages, ...rest } = state;\n if (llmInputMessages && llmInputMessages.length > 0) {\n return { messages: llmInputMessages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n return { messages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n\n async #bindTools(model: LanguageModelLike): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions> = {};\n const structuredTools = Object.values(this.#structuredToolInfo);\n const allTools = this.#options.toolClasses.concat(\n ...structuredTools.map((toolStrategy) => toolStrategy.tool)\n );\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice = structuredTools.length > 0 ? \"any\" : undefined;\n\n /**\n * check if the user requests a native schema output\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n /**\n * if the model does not support JSON schema output, throw an error\n */\n if (!hasSupportForJsonSchemaOutput(model)) {\n throw new Error(\n \"Model does not support native structured output responses. Please use a model that supports native structured output responses or use a tool output.\"\n );\n }\n\n const jsonSchemaParams = {\n name: this.#options.responseFormat.schema?.name ?? \"extract\",\n description: getSchemaDescription(this.#options.responseFormat.schema),\n schema: this.#options.responseFormat.schema,\n strict: true,\n };\n\n Object.assign(options, {\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: this.#options.responseFormat.schema,\n },\n strict: true,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n */\n const modelRunnable = getPromptRunnable(this.#options.prompt).pipe(\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools\n );\n\n return modelRunnable;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA6DA,IAAa,YAAb,cAOUA,0CAGR;CACA;CAMA,sBAAoD,CAAE;CAEtD,YACEC,SAKA;EACA,MAAM;GACJ,MAAM,QAAQ,QAAQ;GACtB,MAAM,CAAC,OAAO,WACZ,KAAKC,KAAK,OAAO,OAAyB;EAC7C,EAAC;EAEF,KAAKC,WAAW;;;;EAKhB,KAAKC,sBACHC,0CAAwB,KAAKF,SAAS,eAAe,CAAC,OACpD,CAAC,WAAW,kBAAkBG,+BAC/B,CACD,OAAO,CAAC,KAAK,WAAW;GACxB,IAAI,OAAO,QAAQ;AACnB,UAAO;EACR,GAAE,CAAE,EAAiC;CACvC;CAED,MAAMJ,KACJK,OAEAC,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,UAAU;GAAkB,GAAG;EAAM;AAKhD,SAAO;GAAE;GAAU,GAAG;EAAM;CAI7B;CAED,MAAMW,WAAWe,OAA6C;EAC5D,MAAMC,UAA6C,CAAE;EACrD,MAAM,kBAAkB,OAAO,OAAO,KAAK9B,oBAAoB;EAC/D,MAAM,WAAW,KAAKD,SAAS,YAAY,OACzC,GAAG,gBAAgB,IAAI,CAAC,iBAAiB,aAAa,KAAK,CAC5D;;;;;EAMD,MAAM,aAAa,gBAAgB,SAAS,IAAI,QAAQ;;;;AAKxD,MAAI,KAAKA,SAAS,0BAA0BkB,oCAAkB;;;;AAI5D,OAAI,CAACc,4CAA8B,MAAM,CACvC,OAAM,IAAI,MACR;GAIJ,MAAM,mBAAmB;IACvB,MAAM,KAAKhC,SAAS,eAAe,QAAQ,QAAQ;IACnD,oEAAkC,KAAKA,SAAS,eAAe,OAAO;IACtE,QAAQ,KAAKA,SAAS,eAAe;IACrC,QAAQ;GACT;GAED,OAAO,OAAO,SAAS;IACrB,iBAAiB;KACf,MAAM;KACN,aAAa;IACd;IACD,6BAA6B;KAC3B,QAAQ,EAAE,QAAQ,cAAe;KACjC,QAAQ,KAAKA,SAAS,eAAe;IACtC;IACD,QAAQ;GACT,EAAC;EACH;;;;EAKD,MAAM,iBAAiB,MAAMiC,wBAAU,OAAO,UAAU;GACtD,GAAG;GACH,aAAa;EACd,EAAC;;;;EAKF,MAAM,gBAAgBC,gCAAkB,KAAKlC,SAAS,OAAO,CAAC,KAC5D,KAAKA,SAAS,qBAAqB,WAC/BmC,oCAAc,gBAAgB,KAAKnC,SAAS,iBAAiB,GAC7D,eACL;AAED,SAAO;CACR;AACF"}
|
|
1
|
+
{"version":3,"file":"AgentNode.cjs","names":["RunnableCallable","options: AgentNodeOptions<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >","#run","#options","#structuredToolInfo","transformResponseFormat","ToolStrategy","state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]","config: RunnableConfig","ToolMessage","#invokeModel","Command","#areMoreStepsNeeded","AIMessage","initChatModel","options: {\n lastMessage?: string;\n }","#deriveModel","validateLLMHasNoBoundTools","#bindTools","#getModelInputState","mergeAbortSignals","ProviderStrategy","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","response: AIMessage","toolCalls: ToolCall[]","MultipleStructuredOutputsError","#handleToolStrategyError","toolCall: ToolCall","lastMessage?: string","error: ToolStrategyError","response: BaseMessage","hasToolCalls","model: LanguageModelLike","options: Partial<BaseChatModelCallOptions>","hasSupportForJsonSchemaOutput","bindTools","getPromptRunnable","withAgentName"],"sources":["../../../src/agents/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport { BaseMessage, AIMessage, ToolMessage } from \"@langchain/core/messages\";\nimport { Command } from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n} from \"@langchain/core/utils/types\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\n\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError } from \"../errors.js\";\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport { PreHookAnnotation, AnyAnnotationRoot } from \"../annotation.js\";\nimport { mergeAbortSignals } from \"./utils.js\";\nimport {\n bindTools,\n getPromptRunnable,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n hasSupportForJsonSchemaOutput,\n} from \"../utils.js\";\nimport {\n InternalAgentState,\n ClientTool,\n ServerTool,\n CreateAgentParams,\n} from \"../types.js\";\nimport { withAgentName } from \"../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n} from \"../responses.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\nexport interface AgentNodeOptions<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends Pick<\n CreateAgentParams<StateSchema, StructuredResponseFormat, ContextSchema>,\n \"llm\" | \"model\" | \"prompt\" | \"includeAgentName\" | \"name\" | \"responseFormat\"\n > {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n}\n\nexport class AgentNode<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n { messages: BaseMessage[] } | { structuredResponse: StructuredResponseFormat }\n> {\n #options: AgentNodeOptions<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >;\n\n #structuredToolInfo: Record<string, ToolStrategy> = {};\n\n constructor(\n options: AgentNodeOptions<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) =>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.#run(input, config as RunnableConfig) as any,\n });\n\n this.#options = options;\n\n /**\n * Populate a list of structured tool info.\n */\n this.#structuredToolInfo = (\n transformResponseFormat(this.#options.responseFormat).filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce((acc, format) => {\n acc[format.name] = format;\n return acc;\n }, {} as Record<string, ToolStrategy>);\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages[state.messages.length - 1];\n if (\n ToolMessage.isInstance(lastMessage) &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n /**\n * return directly without invoking the model again\n */\n return { messages: [] };\n }\n\n const response = await this.#invokeModel(state, config);\n\n /**\n * if we were able to generate a structured response, return it\n */\n if (\"structuredResponse\" in response) {\n return {\n messages: [...state.messages, ...(response.messages || [])],\n structuredResponse: response.structuredResponse,\n };\n }\n\n /**\n * if we need to direct the agent to the model, return the update\n */\n if (response instanceof Command) {\n return response;\n }\n\n response.name = this.name;\n response.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, response)) {\n return {\n messages: [\n new AIMessage({\n content: \"Sorry, need more steps to process this request.\",\n name: this.name,\n id: response.id,\n }),\n ],\n };\n }\n\n return { messages: [response] };\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n if (this.#options.model) {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n throw new Error(\"`model` option must be a string.\");\n }\n\n const model = this.#options.llm;\n\n /**\n * If the model is a function, call it to get the model.\n */\n if (typeof model === \"function\") {\n return model(state, config);\n }\n\n if (model) {\n return model;\n }\n\n throw new Error(\n \"No model option was provided, either via `model` or via `llm` option.\"\n );\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> {\n const model = await this.#deriveModel(state, config);\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(model);\n\n const modelWithTools = await this.#bindTools(model);\n const modelInput = this.#getModelInputState(state);\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const invokeConfig = {\n ...config,\n signal,\n };\n\n const response = (await modelWithTools.invoke(\n modelInput,\n invokeConfig\n )) as AIMessage;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n const structuredResponse = this.#options.responseFormat.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n }\n\n if (!response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in this.#structuredToolInfo\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(response, toolCalls);\n }\n\n const toolStrategy = this.#structuredToolInfo[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n toolMessageContent ?? options.lastMessage\n );\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[]\n ): Promise<Command> {\n /**\n * the following should never happen, let's throw an error if it does\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n throw new Error(\n \"Multiple structured outputs should not apply to native structured output responses\"\n );\n }\n\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0]\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = this.#structuredToolInfo[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(this.#structuredToolInfo).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided `true` as the `errorHandler` option, return a new AIMessage\n * with the error message and retry the tool call.\n */\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * throw otherwise, e.g. if `errorHandler` is not defined or set to `false`\n */\n throw error;\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n AIMessage.isInstance(response) &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages)))\n );\n }\n\n #getModelInputState(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]\n ): Omit<InternalAgentState<StructuredResponseFormat>, \"llmInputMessages\"> {\n const { messages, llmInputMessages, ...rest } = state;\n if (llmInputMessages && llmInputMessages.length > 0) {\n return { messages: llmInputMessages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n return { messages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n\n async #bindTools(model: LanguageModelLike): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions> = {};\n const structuredTools = Object.values(this.#structuredToolInfo);\n const allTools = this.#options.toolClasses.concat(\n ...structuredTools.map((toolStrategy) => toolStrategy.tool)\n );\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice = structuredTools.length > 0 ? \"any\" : undefined;\n\n /**\n * check if the user requests a native schema output\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n /**\n * if the model does not support JSON schema output, throw an error\n */\n if (!hasSupportForJsonSchemaOutput(model)) {\n throw new Error(\n \"Model does not support native structured output responses. Please use a model that supports native structured output responses or use a tool output.\"\n );\n }\n\n const jsonSchemaParams = {\n name: this.#options.responseFormat.schema?.name ?? \"extract\",\n description: getSchemaDescription(this.#options.responseFormat.schema),\n schema: this.#options.responseFormat.schema,\n strict: true,\n };\n\n Object.assign(options, {\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: this.#options.responseFormat.schema,\n },\n strict: true,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n */\n const modelRunnable = getPromptRunnable(this.#options.prompt).pipe(\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools\n );\n\n return modelRunnable;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA6DA,IAAa,YAAb,cAOUA,0CAGR;CACA;CAMA,sBAAoD,CAAE;CAEtD,YACEC,SAKA;EACA,MAAM;GACJ,MAAM,QAAQ,QAAQ;GACtB,MAAM,CAAC,OAAO,WAEZ,KAAKC,KAAK,OAAO,OAAyB;EAC7C,EAAC;EAEF,KAAKC,WAAW;;;;EAKhB,KAAKC,sBACHC,0CAAwB,KAAKF,SAAS,eAAe,CAAC,OACpD,CAAC,WAAW,kBAAkBG,+BAC/B,CACD,OAAO,CAAC,KAAK,WAAW;GACxB,IAAI,OAAO,QAAQ;AACnB,UAAO;EACR,GAAE,CAAE,EAAiC;CACvC;CAED,MAAMJ,KACJK,OAEAC,QACA;;;;;EAKA,MAAM,cAAc,MAAM,SAAS,MAAM,SAAS,SAAS;AAC3D,MACEC,sCAAY,WAAW,YAAY,IACnC,YAAY,QACZ,KAAKN,SAAS,mBAAmB,IAAI,YAAY,KAAK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B,oBAAoB;EAC/D,MAAM,WAAW,KAAKD,SAAS,YAAY,OACzC,GAAG,gBAAgB,IAAI,CAAC,iBAAiB,aAAa,KAAK,CAC5D;;;;;EAMD,MAAM,aAAa,gBAAgB,SAAS,IAAI,QAAQ;;;;AAKxD,MAAI,KAAKA,SAAS,0BAA0BkB,oCAAkB;;;;AAI5D,OAAI,CAACc,4CAA8B,MAAM,CACvC,OAAM,IAAI,MACR;GAIJ,MAAM,mBAAmB;IACvB,MAAM,KAAKhC,SAAS,eAAe,QAAQ,QAAQ;IACnD,oEAAkC,KAAKA,SAAS,eAAe,OAAO;IACtE,QAAQ,KAAKA,SAAS,eAAe;IACrC,QAAQ;GACT;GAED,OAAO,OAAO,SAAS;IACrB,iBAAiB;KACf,MAAM;KACN,aAAa;IACd;IACD,6BAA6B;KAC3B,QAAQ,EAAE,QAAQ,cAAe;KACjC,QAAQ,KAAKA,SAAS,eAAe;IACtC;IACD,QAAQ;GACT,EAAC;EACH;;;;EAKD,MAAM,iBAAiB,MAAMiC,wBAAU,OAAO,UAAU;GACtD,GAAG;GACH,aAAa;EACd,EAAC;;;;EAKF,MAAM,gBAAgBC,gCAAkB,KAAKlC,SAAS,OAAO,CAAC,KAC5D,KAAKA,SAAS,qBAAqB,WAC/BmC,oCAAc,gBAAgB,KAAKnC,SAAS,iBAAiB,GAC7D,eACL;AAED,SAAO;CACR;AACF"}
|
|
@@ -33,7 +33,7 @@ var AgentNode = class extends RunnableCallable {
|
|
|
33
33
|
* If so, we should generate structured response (if needed) and stop
|
|
34
34
|
*/
|
|
35
35
|
const lastMessage = state.messages[state.messages.length - 1];
|
|
36
|
-
if (lastMessage
|
|
36
|
+
if (ToolMessage.isInstance(lastMessage) && lastMessage.name && this.#options.shouldReturnDirect.has(lastMessage.name))
|
|
37
37
|
/**
|
|
38
38
|
* return directly without invoking the model again
|
|
39
39
|
*/
|
|
@@ -52,9 +52,9 @@ var AgentNode = class extends RunnableCallable {
|
|
|
52
52
|
if (response instanceof Command) return response;
|
|
53
53
|
response.name = this.name;
|
|
54
54
|
response.lc_kwargs.name = this.name;
|
|
55
|
-
if (this.#areMoreStepsNeeded(state, response)) return { messages: [new AIMessage(
|
|
55
|
+
if (this.#areMoreStepsNeeded(state, response)) return { messages: [new AIMessage({
|
|
56
|
+
content: "Sorry, need more steps to process this request.",
|
|
56
57
|
name: this.name,
|
|
57
|
-
lc_kwargs: { name: this.name },
|
|
58
58
|
id: response.id
|
|
59
59
|
})] };
|
|
60
60
|
return { messages: [response] };
|
|
@@ -200,7 +200,7 @@ var AgentNode = class extends RunnableCallable {
|
|
|
200
200
|
throw error;
|
|
201
201
|
}
|
|
202
202
|
#areMoreStepsNeeded(state, response) {
|
|
203
|
-
const allToolsReturnDirect = response
|
|
203
|
+
const allToolsReturnDirect = AIMessage.isInstance(response) && response.tool_calls?.every((call) => this.#options.shouldReturnDirect.has(call.name));
|
|
204
204
|
const remainingSteps = "remainingSteps" in state ? state.remainingSteps : void 0;
|
|
205
205
|
return Boolean(remainingSteps && (remainingSteps < 1 && allToolsReturnDirect || remainingSteps < 2 && hasToolCalls(state.messages)));
|
|
206
206
|
}
|