langchain 1.0.0-alpha.5 → 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/annotation.cjs.map +1 -1
- package/dist/agents/annotation.d.cts +4 -6
- 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.map +1 -1
- package/dist/agents/createAgent.js.map +1 -1
- package/dist/agents/index.cjs +2 -2
- package/dist/agents/index.cjs.map +1 -1
- package/dist/agents/index.d.cts +47 -47
- package/dist/agents/index.d.cts.map +1 -1
- package/dist/agents/index.d.ts +47 -47
- package/dist/agents/index.d.ts.map +1 -1
- package/dist/agents/index.js +2 -2
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/middlewareAgent/ReactAgent.cjs +18 -18
- package/dist/agents/middlewareAgent/ReactAgent.cjs.map +1 -1
- package/dist/agents/middlewareAgent/ReactAgent.d.cts +8 -9
- package/dist/agents/middlewareAgent/ReactAgent.d.cts.map +1 -1
- package/dist/agents/middlewareAgent/ReactAgent.d.ts +8 -9
- package/dist/agents/middlewareAgent/ReactAgent.d.ts.map +1 -1
- package/dist/agents/middlewareAgent/ReactAgent.js +18 -18
- package/dist/agents/middlewareAgent/ReactAgent.js.map +1 -1
- package/dist/agents/middlewareAgent/annotation.cjs +2 -2
- package/dist/agents/middlewareAgent/annotation.cjs.map +1 -1
- package/dist/agents/middlewareAgent/annotation.js +2 -2
- package/dist/agents/middlewareAgent/annotation.js.map +1 -1
- package/dist/agents/middlewareAgent/index.cjs.map +1 -1
- package/dist/agents/middlewareAgent/index.js.map +1 -1
- package/dist/agents/middlewareAgent/{middlewares → middleware}/hitl.cjs +8 -8
- package/dist/agents/middlewareAgent/middleware/hitl.cjs.map +1 -0
- package/dist/agents/middlewareAgent/{middlewares → middleware}/hitl.d.cts +3 -3
- package/dist/agents/middlewareAgent/middleware/hitl.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/{middlewares → middleware}/hitl.d.ts +3 -3
- package/dist/agents/middlewareAgent/middleware/hitl.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/{middlewares → middleware}/hitl.js +3 -3
- 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.js +17 -0
- package/dist/agents/middlewareAgent/middleware/index.js.map +1 -0
- package/dist/agents/middlewareAgent/{middlewares → middleware}/promptCaching.cjs +51 -22
- package/dist/agents/middlewareAgent/middleware/promptCaching.cjs.map +1 -0
- package/dist/agents/middlewareAgent/{middlewares → middleware}/promptCaching.d.cts +9 -9
- package/dist/agents/middlewareAgent/middleware/promptCaching.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/{middlewares → middleware}/promptCaching.d.ts +9 -9
- package/dist/agents/middlewareAgent/middleware/promptCaching.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/{middlewares → middleware}/promptCaching.js +50 -21
- package/dist/agents/middlewareAgent/middleware/promptCaching.js.map +1 -0
- package/dist/agents/middlewareAgent/{middlewares → middleware}/summarization.cjs +11 -11
- package/dist/agents/middlewareAgent/middleware/summarization.cjs.map +1 -0
- package/dist/agents/middlewareAgent/{middlewares → middleware}/summarization.d.cts +3 -3
- package/dist/agents/middlewareAgent/middleware/summarization.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/{middlewares → middleware}/summarization.d.ts +10 -10
- package/dist/agents/middlewareAgent/{middlewares/summarization.d.cts.map → middleware/summarization.d.ts.map} +1 -1
- package/dist/agents/middlewareAgent/{middlewares → middleware}/summarization.js +4 -4
- package/dist/agents/middlewareAgent/middleware/summarization.js.map +1 -0
- package/dist/agents/middlewareAgent/middleware.cjs.map +1 -1
- package/dist/agents/middlewareAgent/middleware.d.cts +1 -1
- package/dist/agents/middlewareAgent/middleware.d.cts.map +1 -1
- package/dist/agents/middlewareAgent/middleware.d.ts +1 -1
- package/dist/agents/middlewareAgent/middleware.d.ts.map +1 -1
- package/dist/agents/middlewareAgent/middleware.js.map +1 -1
- package/dist/agents/middlewareAgent/nodes/AfterModalNode.cjs.map +1 -1
- package/dist/agents/middlewareAgent/nodes/AfterModalNode.js.map +1 -1
- package/dist/agents/middlewareAgent/nodes/AgentNode.cjs +12 -19
- package/dist/agents/middlewareAgent/nodes/AgentNode.cjs.map +1 -1
- package/dist/agents/middlewareAgent/nodes/AgentNode.js +12 -19
- package/dist/agents/middlewareAgent/nodes/AgentNode.js.map +1 -1
- package/dist/agents/middlewareAgent/nodes/BeforeModalNode.cjs.map +1 -1
- package/dist/agents/middlewareAgent/nodes/BeforeModalNode.js.map +1 -1
- package/dist/agents/middlewareAgent/nodes/middleware.cjs.map +1 -1
- package/dist/agents/middlewareAgent/nodes/middleware.js.map +1 -1
- package/dist/agents/middlewareAgent/nodes/utils.cjs +7 -7
- package/dist/agents/middlewareAgent/nodes/utils.cjs.map +1 -1
- package/dist/agents/middlewareAgent/nodes/utils.js +3 -3
- package/dist/agents/middlewareAgent/nodes/utils.js.map +1 -1
- package/dist/agents/middlewareAgent/types.d.cts +10 -23
- package/dist/agents/middlewareAgent/types.d.cts.map +1 -1
- package/dist/agents/middlewareAgent/types.d.ts +10 -23
- package/dist/agents/middlewareAgent/types.d.ts.map +1 -1
- 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 +1 -2
- 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 +1 -3
- 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/prompts.cjs.map +1 -1
- package/dist/chains/api/prompts.js.map +1 -1
- package/dist/chains/constitutional_ai/constitutional_chain.cjs.map +1 -1
- package/dist/chains/constitutional_ai/constitutional_chain.js.map +1 -1
- package/dist/chains/index.cjs +0 -3
- package/dist/chains/index.cjs.map +1 -1
- package/dist/chains/index.d.cts +1 -2
- package/dist/chains/index.d.ts +1 -2
- package/dist/chains/index.js +1 -3
- package/dist/chains/index.js.map +1 -1
- package/dist/chains/openai_functions/extraction.cjs.map +1 -1
- package/dist/chains/openai_functions/extraction.d.cts +1 -3
- package/dist/chains/openai_functions/extraction.d.cts.map +1 -1
- package/dist/chains/openai_functions/extraction.d.ts +1 -3
- package/dist/chains/openai_functions/extraction.d.ts.map +1 -1
- package/dist/chains/openai_functions/extraction.js.map +1 -1
- package/dist/chains/openai_functions/index.cjs +0 -5
- package/dist/chains/openai_functions/index.cjs.map +1 -1
- package/dist/chains/openai_functions/index.d.cts +1 -2
- package/dist/chains/openai_functions/index.d.ts +1 -2
- package/dist/chains/openai_functions/index.js +1 -4
- package/dist/chains/openai_functions/index.js.map +1 -1
- package/dist/chains/openai_functions/openapi.cjs +4 -4
- package/dist/chains/openai_functions/openapi.cjs.map +1 -1
- package/dist/chains/openai_functions/openapi.d.cts +1 -1
- package/dist/chains/openai_functions/openapi.js +4 -4
- package/dist/chains/openai_functions/openapi.js.map +1 -1
- package/dist/chains/openai_functions/tagging.cjs.map +1 -1
- package/dist/chains/openai_functions/tagging.d.cts +1 -3
- package/dist/chains/openai_functions/tagging.d.cts.map +1 -1
- package/dist/chains/openai_functions/tagging.d.ts +1 -3
- package/dist/chains/openai_functions/tagging.d.ts.map +1 -1
- package/dist/chains/openai_functions/tagging.js.map +1 -1
- package/dist/chains/query_constructor/index.cjs +4 -4
- package/dist/chains/query_constructor/index.cjs.map +1 -1
- package/dist/chains/query_constructor/index.d.cts +4 -2
- package/dist/chains/query_constructor/index.d.cts.map +1 -1
- package/dist/chains/query_constructor/index.d.ts +4 -2
- package/dist/chains/query_constructor/index.d.ts.map +1 -1
- package/dist/chains/query_constructor/index.js +1 -1
- package/dist/chains/query_constructor/index.js.map +1 -1
- package/dist/chains/question_answering/load.d.ts +2 -2
- package/dist/chains/question_answering/load.d.ts.map +1 -1
- package/dist/chains/question_answering/map_reduce_prompts.cjs.map +1 -1
- package/dist/chains/question_answering/map_reduce_prompts.js.map +1 -1
- package/dist/chains/question_answering/refine_prompts.cjs.map +1 -1
- package/dist/chains/question_answering/refine_prompts.js.map +1 -1
- package/dist/chains/question_answering/stuff_prompts.cjs.map +1 -1
- package/dist/chains/question_answering/stuff_prompts.js.map +1 -1
- package/dist/chains/router/multi_prompt.cjs +4 -4
- package/dist/chains/router/multi_prompt.cjs.map +1 -1
- package/dist/chains/router/multi_prompt.js +1 -1
- package/dist/chains/router/multi_prompt.js.map +1 -1
- package/dist/chains/router/multi_retrieval_qa.cjs +4 -4
- package/dist/chains/router/multi_retrieval_qa.cjs.map +1 -1
- package/dist/chains/router/multi_retrieval_qa.js +1 -1
- package/dist/chains/router/multi_retrieval_qa.js.map +1 -1
- package/dist/chains/sql_db/sql_db_prompt.cjs.map +1 -1
- package/dist/chains/sql_db/sql_db_prompt.d.cts.map +1 -1
- package/dist/chains/sql_db/sql_db_prompt.d.ts.map +1 -1
- package/dist/chains/sql_db/sql_db_prompt.js.map +1 -1
- package/dist/chains/summarization/load.d.ts +2 -2
- package/dist/chains/summarization/load.d.ts.map +1 -1
- package/dist/chains/summarization/stuff_prompts.cjs.map +1 -1
- package/dist/chains/summarization/stuff_prompts.js.map +1 -1
- package/dist/chat_models/universal.cjs +8 -5
- package/dist/chat_models/universal.cjs.map +1 -1
- package/dist/chat_models/universal.d.cts +2 -2
- package/dist/chat_models/universal.d.cts.map +1 -1
- package/dist/chat_models/universal.d.ts +2 -2
- package/dist/chat_models/universal.d.ts.map +1 -1
- package/dist/chat_models/universal.js +8 -5
- package/dist/chat_models/universal.js.map +1 -1
- package/dist/document_loaders/fs/directory.cjs.map +1 -1
- package/dist/document_loaders/fs/directory.d.cts +0 -1
- package/dist/document_loaders/fs/directory.d.cts.map +1 -1
- package/dist/document_loaders/fs/directory.d.ts +0 -1
- package/dist/document_loaders/fs/directory.d.ts.map +1 -1
- package/dist/document_loaders/fs/directory.js.map +1 -1
- package/dist/document_loaders/fs/json.cjs +7 -1
- package/dist/document_loaders/fs/json.cjs.map +1 -1
- package/dist/document_loaders/fs/json.js +7 -1
- package/dist/document_loaders/fs/json.js.map +1 -1
- package/dist/embeddings/cache_backed.cjs +1 -1
- package/dist/embeddings/cache_backed.cjs.map +1 -1
- package/dist/embeddings/cache_backed.d.cts +1 -1
- package/dist/embeddings/cache_backed.d.ts +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.map +1 -1
- package/dist/evaluation/comparison/pairwise.d.ts.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/hub/base.cjs.map +1 -1
- package/dist/hub/base.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 +3 -14
- package/dist/load/import_map.cjs.map +1 -1
- package/dist/load/import_map.js +3 -14
- package/dist/load/import_map.js.map +1 -1
- package/dist/memory/prompt.cjs.map +1 -1
- package/dist/memory/prompt.d.cts.map +1 -1
- package/dist/memory/prompt.d.ts.map +1 -1
- package/dist/memory/prompt.js.map +1 -1
- package/dist/output_parsers/combining.cjs +1 -1
- package/dist/output_parsers/combining.cjs.map +1 -1
- package/dist/output_parsers/combining.js +1 -1
- package/dist/output_parsers/combining.js.map +1 -1
- package/dist/output_parsers/expression_type_handlers/array_literal_expression_handler.cjs.map +1 -1
- package/dist/output_parsers/expression_type_handlers/array_literal_expression_handler.js.map +1 -1
- package/dist/output_parsers/expression_type_handlers/base.cjs +1 -1
- package/dist/output_parsers/expression_type_handlers/base.cjs.map +1 -1
- package/dist/output_parsers/expression_type_handlers/base.js +1 -1
- package/dist/output_parsers/expression_type_handlers/base.js.map +1 -1
- package/dist/output_parsers/regex.cjs.map +1 -1
- package/dist/output_parsers/regex.js.map +1 -1
- package/dist/output_parsers/structured.cjs +4 -4
- package/dist/output_parsers/structured.cjs.map +1 -1
- package/dist/output_parsers/structured.d.cts +1 -1
- package/dist/output_parsers/structured.d.cts.map +1 -1
- package/dist/output_parsers/structured.d.ts +1 -1
- package/dist/output_parsers/structured.d.ts.map +1 -1
- package/dist/output_parsers/structured.js +2 -2
- package/dist/output_parsers/structured.js.map +1 -1
- package/dist/retrievers/ensemble.cjs.map +1 -1
- package/dist/retrievers/ensemble.js.map +1 -1
- package/dist/storage/file_system.cjs +1 -1
- package/dist/storage/file_system.cjs.map +1 -1
- package/dist/storage/file_system.js +1 -1
- package/dist/storage/file_system.js.map +1 -1
- package/dist/tools/fs.cjs +5 -5
- package/dist/tools/fs.cjs.map +1 -1
- package/dist/tools/fs.d.cts +1 -1
- package/dist/tools/fs.d.cts.map +1 -1
- package/dist/tools/fs.d.ts +1 -1
- package/dist/tools/fs.d.ts.map +1 -1
- package/dist/tools/fs.js +1 -1
- package/dist/tools/fs.js.map +1 -1
- package/dist/tools/retriever.cjs +2 -2
- package/dist/tools/retriever.cjs.map +1 -1
- package/dist/tools/retriever.d.cts +1 -1
- package/dist/tools/retriever.d.cts.map +1 -1
- package/dist/tools/retriever.d.ts +1 -1
- package/dist/tools/retriever.d.ts.map +1 -1
- package/dist/tools/retriever.js +1 -1
- package/dist/tools/retriever.js.map +1 -1
- package/dist/tools/sql.cjs +1 -2
- package/dist/tools/sql.cjs.map +1 -1
- package/dist/tools/sql.d.cts +1 -1
- package/dist/tools/sql.d.cts.map +1 -1
- package/dist/tools/sql.d.ts +1 -1
- package/dist/tools/sql.d.ts.map +1 -1
- package/dist/tools/sql.js +1 -2
- package/dist/tools/sql.js.map +1 -1
- package/dist/types/expression-parser.d.cts +2 -0
- package/dist/types/expression-parser.d.cts.map +1 -1
- package/dist/types/expression-parser.d.ts +2 -0
- package/dist/types/expression-parser.d.ts.map +1 -1
- package/dist/util/hub.cjs +1 -1
- package/dist/util/hub.js +1 -1
- package/dist/util/openapi.cjs +1 -1
- package/dist/util/openapi.cjs.map +1 -1
- package/dist/util/openapi.js +1 -1
- package/dist/util/openapi.js.map +1 -1
- package/package.json +15 -21
- package/dist/agents/middlewareAgent/middlewares/hitl.cjs.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/hitl.d.cts.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/hitl.d.ts.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/hitl.js.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/index.cjs +0 -8
- package/dist/agents/middlewareAgent/middlewares/index.js +0 -5
- package/dist/agents/middlewareAgent/middlewares/promptCaching.cjs.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/promptCaching.d.cts.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/promptCaching.d.ts.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/promptCaching.js.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/summarization.cjs.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/summarization.d.ts.map +0 -1
- package/dist/agents/middlewareAgent/middlewares/summarization.js.map +0 -1
- package/dist/chains/openai_functions/structured_output.cjs +0 -107
- package/dist/chains/openai_functions/structured_output.cjs.map +0 -1
- package/dist/chains/openai_functions/structured_output.d.cts +0 -38
- package/dist/chains/openai_functions/structured_output.d.cts.map +0 -1
- package/dist/chains/openai_functions/structured_output.d.ts +0 -38
- package/dist/chains/openai_functions/structured_output.d.ts.map +0 -1
- package/dist/chains/openai_functions/structured_output.js +0 -105
- package/dist/chains/openai_functions/structured_output.js.map +0 -1
- package/dist/chains/openai_moderation.cjs +0 -107
- package/dist/chains/openai_moderation.cjs.map +0 -1
- package/dist/chains/openai_moderation.d.cts +0 -74
- package/dist/chains/openai_moderation.d.cts.map +0 -1
- package/dist/chains/openai_moderation.d.ts +0 -74
- package/dist/chains/openai_moderation.d.ts.map +0 -1
- package/dist/chains/openai_moderation.js +0 -106
- package/dist/chains/openai_moderation.js.map +0 -1
- /package/dist/agents/middlewareAgent/{middlewares → middleware}/index.d.cts +0 -0
- /package/dist/agents/middlewareAgent/{middlewares → middleware}/index.d.ts +0 -0
|
@@ -2,7 +2,9 @@
|
|
|
2
2
|
interface ParseOptions {
|
|
3
3
|
filename?: string;
|
|
4
4
|
startRule?: "Start";
|
|
5
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
5
6
|
tracer?: any;
|
|
7
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
6
8
|
[key: string]: any;
|
|
7
9
|
}
|
|
8
10
|
type ParseFunction = <Options extends ParseOptions>(input: string, options?: Options) => Options extends {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"expression-parser.d.cts","names":["ParseOptions","ParseFunction","Options","StartRule","Start","Program","Identifier","IdentifierName","Literal","NullLiteral","BooleanLiteral","NumericLiteral","StringLiteral","DecimalLiteral","PrimaryExpression","ArrayExpression","ObjectExpression","Expression","ElementList","PropertyNameAndValueList","PropertyAssignment","PropertyName","MemberExpression","CallExpression","Arguments","ExpressionStatement","ExpressionNode"],"sources":["../../src/types/expression-parser.d.ts"],"sourcesContent":["export interface ParseOptions {\n filename?: string;\n startRule?: \"Start\";\n tracer?: any;\n [key: string]: any;\n}\nexport type ParseFunction = <Options extends ParseOptions>(input: string, options?: Options) => Options extends {\n startRule: infer StartRule;\n} ? StartRule extends \"Start\" ? Start : Start : Start;\n// These types were autogenerated by ts-pegjs\nexport type Start = Program;\nexport type Identifier = IdentifierName;\nexport type IdentifierName = {\n type: \"Identifier\";\n name: string;\n};\nexport type Literal = NullLiteral | BooleanLiteral | NumericLiteral | StringLiteral;\nexport type NullLiteral = {\n type: \"NullLiteral\";\n value: null;\n};\nexport type BooleanLiteral = {\n type: \"BooleanLiteral\";\n value: true;\n} | {\n type: \"BooleanLiteral\";\n value: false;\n};\nexport type NumericLiteral = DecimalLiteral;\nexport type DecimalLiteral = {\n type: \"NumericLiteral\";\n value: number;\n};\nexport type StringLiteral = {\n type: \"StringLiteral\";\n value: string;\n};\nexport type PrimaryExpression = Identifier | Literal | ArrayExpression | ObjectExpression | Expression;\nexport type ArrayExpression = {\n type: \"ArrayExpression\";\n elements: ElementList;\n};\nexport type ElementList = PrimaryExpression[];\nexport type ObjectExpression = {\n type: \"ObjectExpression\";\n properties: [];\n} | {\n type: \"ObjectExpression\";\n properties: PropertyNameAndValueList;\n};\nexport type PropertyNameAndValueList = PrimaryExpression[];\nexport type PropertyAssignment = {\n type: \"PropertyAssignment\";\n key: PropertyName;\n value: Expression;\n kind: \"init\";\n};\nexport type PropertyName = IdentifierName | StringLiteral | NumericLiteral;\nexport type MemberExpression = {\n type: \"MemberExpression\";\n property: StringLiteral;\n computed: true;\n object: MemberExpression | Identifier | StringLiteral;\n} | {\n type: \"MemberExpression\";\n property: Identifier;\n computed: false;\n object: MemberExpression | Identifier | StringLiteral;\n};\nexport type CallExpression = {\n type: \"CallExpression\";\n arguments: Arguments;\n callee: MemberExpression | Identifier;\n};\nexport type Arguments = PrimaryExpression[];\nexport type Expression = CallExpression | MemberExpression;\nexport type ExpressionStatement = {\n type: \"ExpressionStatement\";\n expression: Expression;\n};\nexport type Program = {\n type: \"Program\";\n body: ExpressionStatement;\n};\nexport type ExpressionNode = Program | ExpressionStatement | ArrayExpression | BooleanLiteral | CallExpression | Identifier | MemberExpression | NumericLiteral | ObjectExpression | PropertyAssignment | NullLiteral | StringLiteral;\n"],"mappings":";UAAiBA,YAAAA;EAAAA,QAAAA,CAAAA,EAAAA,MAAY;
|
|
1
|
+
{"version":3,"file":"expression-parser.d.cts","names":["ParseOptions","ParseFunction","Options","StartRule","Start","Program","Identifier","IdentifierName","Literal","NullLiteral","BooleanLiteral","NumericLiteral","StringLiteral","DecimalLiteral","PrimaryExpression","ArrayExpression","ObjectExpression","Expression","ElementList","PropertyNameAndValueList","PropertyAssignment","PropertyName","MemberExpression","CallExpression","Arguments","ExpressionStatement","ExpressionNode"],"sources":["../../src/types/expression-parser.d.ts"],"sourcesContent":["export interface ParseOptions {\n filename?: string;\n startRule?: \"Start\";\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n tracer?: any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n}\nexport type ParseFunction = <Options extends ParseOptions>(input: string, options?: Options) => Options extends {\n startRule: infer StartRule;\n} ? StartRule extends \"Start\" ? Start : Start : Start;\n// These types were autogenerated by ts-pegjs\nexport type Start = Program;\nexport type Identifier = IdentifierName;\nexport type IdentifierName = {\n type: \"Identifier\";\n name: string;\n};\nexport type Literal = NullLiteral | BooleanLiteral | NumericLiteral | StringLiteral;\nexport type NullLiteral = {\n type: \"NullLiteral\";\n value: null;\n};\nexport type BooleanLiteral = {\n type: \"BooleanLiteral\";\n value: true;\n} | {\n type: \"BooleanLiteral\";\n value: false;\n};\nexport type NumericLiteral = DecimalLiteral;\nexport type DecimalLiteral = {\n type: \"NumericLiteral\";\n value: number;\n};\nexport type StringLiteral = {\n type: \"StringLiteral\";\n value: string;\n};\nexport type PrimaryExpression = Identifier | Literal | ArrayExpression | ObjectExpression | Expression;\nexport type ArrayExpression = {\n type: \"ArrayExpression\";\n elements: ElementList;\n};\nexport type ElementList = PrimaryExpression[];\nexport type ObjectExpression = {\n type: \"ObjectExpression\";\n properties: [];\n} | {\n type: \"ObjectExpression\";\n properties: PropertyNameAndValueList;\n};\nexport type PropertyNameAndValueList = PrimaryExpression[];\nexport type PropertyAssignment = {\n type: \"PropertyAssignment\";\n key: PropertyName;\n value: Expression;\n kind: \"init\";\n};\nexport type PropertyName = IdentifierName | StringLiteral | NumericLiteral;\nexport type MemberExpression = {\n type: \"MemberExpression\";\n property: StringLiteral;\n computed: true;\n object: MemberExpression | Identifier | StringLiteral;\n} | {\n type: \"MemberExpression\";\n property: Identifier;\n computed: false;\n object: MemberExpression | Identifier | StringLiteral;\n};\nexport type CallExpression = {\n type: \"CallExpression\";\n arguments: Arguments;\n callee: MemberExpression | Identifier;\n};\nexport type Arguments = PrimaryExpression[];\nexport type Expression = CallExpression | MemberExpression;\nexport type ExpressionStatement = {\n type: \"ExpressionStatement\";\n expression: Expression;\n};\nexport type Program = {\n type: \"Program\";\n body: ExpressionStatement;\n};\nexport type ExpressionNode = Program | ExpressionStatement | ArrayExpression | BooleanLiteral | CallExpression | Identifier | MemberExpression | NumericLiteral | ObjectExpression | PropertyAssignment | NullLiteral | StringLiteral;\n"],"mappings":";UAAiBA,YAAAA;EAAAA,QAAAA,CAAAA,EAAAA,MAAY;EAQjBC,SAAAA,CAAAA,EAAAA,OAAa;EAAA;EAAA,MAAoBD,CAAAA,EAAAA,GAAAA;EAAY;EAAkC,CAAA,GAAKE,EAAAA,MAAAA,CAAAA,EAAAA,GAAAA;;AAEhEE,KAFpBH,aAAAA,GAEoBG,CAAAA,gBAFaJ,YAEbI,CAAAA,CAAAA,KAAAA,EAAAA,MAAAA,EAAAA,OAAAA,CAAAA,EAFoDF,OAEpDE,EAAAA,GAFgEF,OAEhEE,SAAAA;EAAK,SAAGA,EAAAA,KAAAA,UAAAA;CAAK,GAAzCD,SAA4CC,SAAAA,OAAAA,GAAhBA,KAAgBA,GAARA,KAAQA,GAAAA,KAAAA;AAAK;AAEzCA,KAAAA,KAAAA,GAAQC,OAAAA;AACRC,KAAAA,UAAAA,GAAaC,cAAAA;AACbA,KAAAA,cAAAA,GAAc;EAIdC,IAAAA,EAAAA,YAAO;EAAA,IAAA,EAAA,MAAA;CAAA;AAAiBE,KAAxBF,OAAAA,GAAUC,WAAcC,GAAAA,cAAAA,GAAiBC,cAAjBD,GAAkCE,aAAlCF;AAAiBC,KACzCF,WAAAA,GADyCE;EAAc,IAAGC,EAAAA,aAAAA;EAAa,KAAA,EAAA,IAAA;AACnF,CAAA;AAIYF,KAAAA,cAAAA,GAAc;EAOdC,IAAAA,EAAAA,gBAAc;EACdE,KAAAA,EAAAA,IAAAA;AAIZ,CAAA,GAAYD;EAIAE,IAAAA,EAAAA,gBAAiB;EAAA,KAAA,EAAA,KAAA;CAAA;AAAgBN,KATjCG,cAAAA,GAAiBE,cASgBL;AAAUO,KAR3CF,cAAAA,GAQ2CE;EAAe,IAAGC,EAAAA,gBAAAA;EAAgB,KAAGC,EAAAA,MAAAA;AAAU,CAA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AAA;AAA0B,KAVdD,SAAAA,GAAYV,iBAUE,EAAA;AAAGT,KATjBY,UAAAA,GAAaM,cASIlB,GATaiB,gBASbjB;AAAUoB,KAR3BA,mBAAAA,GAQ2BA;EAAmB,IAAGV,EAAAA,qBAAAA;EAAe,UAAGL,EAN/DO,UAM+DP;CAAc;AAAoBJ,KAJrGD,OAAAA,GAIqGC;EAAU,IAAGgB,EAAAA,SAAAA;EAAgB,IAAGX,EAFvIc,mBAEuId;CAAc;AAAsBS,KAAzKM,cAAAA,GAAiBrB,OAAwJe,GAA9IK,mBAA8IL,GAAxHL,eAAwHK,GAAtGV,cAAsGU,GAArFG,cAAqFH,GAApEd,UAAoEc,GAAvDE,gBAAuDF,GAApCT,cAAoCS,GAAnBJ,gBAAmBI,GAAAA,kBAAAA,GAAqBX,WAArBW,GAAmCR,aAAnCQ"}
|
|
@@ -2,7 +2,9 @@
|
|
|
2
2
|
interface ParseOptions {
|
|
3
3
|
filename?: string;
|
|
4
4
|
startRule?: "Start";
|
|
5
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
5
6
|
tracer?: any;
|
|
7
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
6
8
|
[key: string]: any;
|
|
7
9
|
}
|
|
8
10
|
type ParseFunction = <Options extends ParseOptions>(input: string, options?: Options) => Options extends {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"expression-parser.d.ts","names":["ParseOptions","ParseFunction","Options","StartRule","Start","Program","Identifier","IdentifierName","Literal","NullLiteral","BooleanLiteral","NumericLiteral","StringLiteral","DecimalLiteral","PrimaryExpression","ArrayExpression","ObjectExpression","Expression","ElementList","PropertyNameAndValueList","PropertyAssignment","PropertyName","MemberExpression","CallExpression","Arguments","ExpressionStatement","ExpressionNode"],"sources":["../../src/types/expression-parser.d.ts"],"sourcesContent":["export interface ParseOptions {\n filename?: string;\n startRule?: \"Start\";\n tracer?: any;\n [key: string]: any;\n}\nexport type ParseFunction = <Options extends ParseOptions>(input: string, options?: Options) => Options extends {\n startRule: infer StartRule;\n} ? StartRule extends \"Start\" ? Start : Start : Start;\n// These types were autogenerated by ts-pegjs\nexport type Start = Program;\nexport type Identifier = IdentifierName;\nexport type IdentifierName = {\n type: \"Identifier\";\n name: string;\n};\nexport type Literal = NullLiteral | BooleanLiteral | NumericLiteral | StringLiteral;\nexport type NullLiteral = {\n type: \"NullLiteral\";\n value: null;\n};\nexport type BooleanLiteral = {\n type: \"BooleanLiteral\";\n value: true;\n} | {\n type: \"BooleanLiteral\";\n value: false;\n};\nexport type NumericLiteral = DecimalLiteral;\nexport type DecimalLiteral = {\n type: \"NumericLiteral\";\n value: number;\n};\nexport type StringLiteral = {\n type: \"StringLiteral\";\n value: string;\n};\nexport type PrimaryExpression = Identifier | Literal | ArrayExpression | ObjectExpression | Expression;\nexport type ArrayExpression = {\n type: \"ArrayExpression\";\n elements: ElementList;\n};\nexport type ElementList = PrimaryExpression[];\nexport type ObjectExpression = {\n type: \"ObjectExpression\";\n properties: [];\n} | {\n type: \"ObjectExpression\";\n properties: PropertyNameAndValueList;\n};\nexport type PropertyNameAndValueList = PrimaryExpression[];\nexport type PropertyAssignment = {\n type: \"PropertyAssignment\";\n key: PropertyName;\n value: Expression;\n kind: \"init\";\n};\nexport type PropertyName = IdentifierName | StringLiteral | NumericLiteral;\nexport type MemberExpression = {\n type: \"MemberExpression\";\n property: StringLiteral;\n computed: true;\n object: MemberExpression | Identifier | StringLiteral;\n} | {\n type: \"MemberExpression\";\n property: Identifier;\n computed: false;\n object: MemberExpression | Identifier | StringLiteral;\n};\nexport type CallExpression = {\n type: \"CallExpression\";\n arguments: Arguments;\n callee: MemberExpression | Identifier;\n};\nexport type Arguments = PrimaryExpression[];\nexport type Expression = CallExpression | MemberExpression;\nexport type ExpressionStatement = {\n type: \"ExpressionStatement\";\n expression: Expression;\n};\nexport type Program = {\n type: \"Program\";\n body: ExpressionStatement;\n};\nexport type ExpressionNode = Program | ExpressionStatement | ArrayExpression | BooleanLiteral | CallExpression | Identifier | MemberExpression | NumericLiteral | ObjectExpression | PropertyAssignment | NullLiteral | StringLiteral;\n"],"mappings":";UAAiBA,YAAAA;EAAAA,QAAAA,CAAAA,EAAAA,MAAY;
|
|
1
|
+
{"version":3,"file":"expression-parser.d.ts","names":["ParseOptions","ParseFunction","Options","StartRule","Start","Program","Identifier","IdentifierName","Literal","NullLiteral","BooleanLiteral","NumericLiteral","StringLiteral","DecimalLiteral","PrimaryExpression","ArrayExpression","ObjectExpression","Expression","ElementList","PropertyNameAndValueList","PropertyAssignment","PropertyName","MemberExpression","CallExpression","Arguments","ExpressionStatement","ExpressionNode"],"sources":["../../src/types/expression-parser.d.ts"],"sourcesContent":["export interface ParseOptions {\n filename?: string;\n startRule?: \"Start\";\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n tracer?: any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any;\n}\nexport type ParseFunction = <Options extends ParseOptions>(input: string, options?: Options) => Options extends {\n startRule: infer StartRule;\n} ? StartRule extends \"Start\" ? Start : Start : Start;\n// These types were autogenerated by ts-pegjs\nexport type Start = Program;\nexport type Identifier = IdentifierName;\nexport type IdentifierName = {\n type: \"Identifier\";\n name: string;\n};\nexport type Literal = NullLiteral | BooleanLiteral | NumericLiteral | StringLiteral;\nexport type NullLiteral = {\n type: \"NullLiteral\";\n value: null;\n};\nexport type BooleanLiteral = {\n type: \"BooleanLiteral\";\n value: true;\n} | {\n type: \"BooleanLiteral\";\n value: false;\n};\nexport type NumericLiteral = DecimalLiteral;\nexport type DecimalLiteral = {\n type: \"NumericLiteral\";\n value: number;\n};\nexport type StringLiteral = {\n type: \"StringLiteral\";\n value: string;\n};\nexport type PrimaryExpression = Identifier | Literal | ArrayExpression | ObjectExpression | Expression;\nexport type ArrayExpression = {\n type: \"ArrayExpression\";\n elements: ElementList;\n};\nexport type ElementList = PrimaryExpression[];\nexport type ObjectExpression = {\n type: \"ObjectExpression\";\n properties: [];\n} | {\n type: \"ObjectExpression\";\n properties: PropertyNameAndValueList;\n};\nexport type PropertyNameAndValueList = PrimaryExpression[];\nexport type PropertyAssignment = {\n type: \"PropertyAssignment\";\n key: PropertyName;\n value: Expression;\n kind: \"init\";\n};\nexport type PropertyName = IdentifierName | StringLiteral | NumericLiteral;\nexport type MemberExpression = {\n type: \"MemberExpression\";\n property: StringLiteral;\n computed: true;\n object: MemberExpression | Identifier | StringLiteral;\n} | {\n type: \"MemberExpression\";\n property: Identifier;\n computed: false;\n object: MemberExpression | Identifier | StringLiteral;\n};\nexport type CallExpression = {\n type: \"CallExpression\";\n arguments: Arguments;\n callee: MemberExpression | Identifier;\n};\nexport type Arguments = PrimaryExpression[];\nexport type Expression = CallExpression | MemberExpression;\nexport type ExpressionStatement = {\n type: \"ExpressionStatement\";\n expression: Expression;\n};\nexport type Program = {\n type: \"Program\";\n body: ExpressionStatement;\n};\nexport type ExpressionNode = Program | ExpressionStatement | ArrayExpression | BooleanLiteral | CallExpression | Identifier | MemberExpression | NumericLiteral | ObjectExpression | PropertyAssignment | NullLiteral | StringLiteral;\n"],"mappings":";UAAiBA,YAAAA;EAAAA,QAAAA,CAAAA,EAAAA,MAAY;EAQjBC,SAAAA,CAAAA,EAAAA,OAAa;EAAA;EAAA,MAAoBD,CAAAA,EAAAA,GAAAA;EAAY;EAAkC,CAAA,GAAKE,EAAAA,MAAAA,CAAAA,EAAAA,GAAAA;;AAEhEE,KAFpBH,aAAAA,GAEoBG,CAAAA,gBAFaJ,YAEbI,CAAAA,CAAAA,KAAAA,EAAAA,MAAAA,EAAAA,OAAAA,CAAAA,EAFoDF,OAEpDE,EAAAA,GAFgEF,OAEhEE,SAAAA;EAAK,SAAGA,EAAAA,KAAAA,UAAAA;CAAK,GAAzCD,SAA4CC,SAAAA,OAAAA,GAAhBA,KAAgBA,GAARA,KAAQA,GAAAA,KAAAA;AAAK;AAEzCA,KAAAA,KAAAA,GAAQC,OAAAA;AACRC,KAAAA,UAAAA,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name = require('./extname.cjs');
|
|
3
|
-
const __langchain_core_utils_env = require_rolldown_runtime.__toESM(require("@langchain/core/utils/env"));
|
|
4
3
|
const p_retry = require_rolldown_runtime.__toESM(require("p-retry"));
|
|
4
|
+
const __langchain_core_utils_env = require_rolldown_runtime.__toESM(require("@langchain/core/utils/env"));
|
|
5
5
|
|
|
6
6
|
//#region src/util/hub.ts
|
|
7
7
|
const fetchWithTimeout = async (url, init) => {
|
package/dist/util/hub.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { extname } from "./extname.js";
|
|
2
|
-
import { getEnvironmentVariable } from "@langchain/core/utils/env";
|
|
3
2
|
import pRetry from "p-retry";
|
|
3
|
+
import { getEnvironmentVariable } from "@langchain/core/utils/env";
|
|
4
4
|
|
|
5
5
|
//#region src/util/hub.ts
|
|
6
6
|
const fetchWithTimeout = async (url, init) => {
|
package/dist/util/openapi.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openapi.cjs","names":["document: OpenAPIV3_1.Document","path: string","ref: OpenAPIV3_1.ReferenceObject","schema: OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.SchemaObject","method: OpenAPIV3.HttpMethods","operation: OpenAPIV3_1.OperationObject","method: OpenAPIV3_1.HttpMethods","document: Record<string, any>","rawString: string","yaml","url: string"],"sources":["../../src/util/openapi.ts"],"sourcesContent":["import * as yaml from \"js-yaml\";\nimport { OpenAPIV3, OpenAPIV3_1 } from \"openapi-types\";\n\nexport class OpenAPISpec {\n constructor(public document: OpenAPIV3_1.Document) {}\n\n get baseUrl() {\n return this.document.servers ? this.document.servers[0].url : undefined;\n }\n\n getPathsStrict() {\n if (!this.document.paths) {\n throw new Error(\"No paths found in spec\");\n }\n return this.document.paths;\n }\n\n getParametersStrict() {\n if (!this.document.components?.parameters) {\n throw new Error(\"No parameters found in spec\");\n }\n return this.document.components.parameters;\n }\n\n getSchemasStrict() {\n if (!this.document.components?.schemas) {\n throw new Error(\"No schemas found in spec.\");\n }\n return this.document.components.schemas;\n }\n\n getRequestBodiesStrict() {\n if (!this.document.components?.requestBodies) {\n throw new Error(\"No request body found in spec.\");\n }\n return this.document.components.requestBodies;\n }\n\n getPathStrict(path: string) {\n const pathItem = this.getPathsStrict()[path];\n if (pathItem === undefined) {\n throw new Error(`No path found for \"${path}\".`);\n }\n return pathItem;\n }\n\n getReferencedParameter(ref: OpenAPIV3_1.ReferenceObject) {\n const refComponents = ref.$ref.split(\"/\");\n const refName = refComponents[refComponents.length - 1];\n if (this.getParametersStrict()[refName] === undefined) {\n throw new Error(`No parameter found for \"${refName}\".`);\n }\n return this.getParametersStrict()[refName];\n }\n\n getRootReferencedParameter(\n ref: OpenAPIV3_1.ReferenceObject\n ): OpenAPIV3_1.ParameterObject {\n let parameter = this.getReferencedParameter(ref);\n while ((parameter as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n parameter = this.getReferencedParameter(\n parameter as OpenAPIV3_1.ReferenceObject\n );\n }\n return parameter as OpenAPIV3_1.ParameterObject;\n }\n\n getReferencedSchema(\n ref: OpenAPIV3_1.ReferenceObject\n ): OpenAPIV3_1.SchemaObject {\n const refComponents = ref.$ref.split(\"/\");\n const refName = refComponents[refComponents.length - 1];\n const schema = this.getSchemasStrict()[refName];\n if (schema === undefined) {\n throw new Error(`No schema found for \"${refName}\".`);\n }\n return schema;\n }\n\n getSchema(\n schema: OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.SchemaObject\n ): OpenAPIV3_1.SchemaObject {\n if ((schema as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n return this.getReferencedSchema(schema as OpenAPIV3_1.ReferenceObject);\n }\n return schema;\n }\n\n getRootReferencedSchema(ref: OpenAPIV3_1.ReferenceObject) {\n let schema = this.getReferencedSchema(ref);\n while ((schema as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n schema = this.getReferencedSchema(schema as OpenAPIV3_1.ReferenceObject);\n }\n return schema as OpenAPIV3_1.ParameterObject;\n }\n\n getReferencedRequestBody(ref: OpenAPIV3_1.ReferenceObject) {\n const refComponents = ref.$ref.split(\"/\");\n const refName = refComponents[refComponents.length - 1];\n const requestBodies = this.getRequestBodiesStrict();\n if (requestBodies[refName] === undefined) {\n throw new Error(`No request body found for \"${refName}\"`);\n }\n return requestBodies[refName];\n }\n\n getRootReferencedRequestBody(ref: OpenAPIV3_1.ReferenceObject) {\n let requestBody = this.getReferencedRequestBody(ref);\n while ((requestBody as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n requestBody = this.getReferencedRequestBody(\n requestBody as OpenAPIV3_1.ReferenceObject\n );\n }\n return requestBody as OpenAPIV3_1.RequestBodyObject;\n }\n\n getMethodsForPath(path: string): OpenAPIV3.HttpMethods[] {\n const pathItem = this.getPathStrict(path);\n // This is an enum in the underlying package.\n // Werestate here to allow \"import type\" above and not cause warnings in certain envs.\n const possibleMethods = [\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"options\",\n \"head\",\n \"patch\",\n \"trace\",\n ];\n return possibleMethods.filter(\n (possibleMethod) =>\n pathItem[possibleMethod as OpenAPIV3.HttpMethods] !== undefined\n ) as OpenAPIV3.HttpMethods[];\n }\n\n getParametersForPath(path: string) {\n const pathItem = this.getPathStrict(path);\n if (pathItem.parameters === undefined) {\n return [];\n }\n return pathItem.parameters.map((parameter) => {\n if ((parameter as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n return this.getRootReferencedParameter(\n parameter as OpenAPIV3_1.ReferenceObject\n );\n }\n return parameter as OpenAPIV3_1.ParameterObject;\n });\n }\n\n getOperation(path: string, method: OpenAPIV3.HttpMethods) {\n const pathItem = this.getPathStrict(path);\n if (pathItem[method] === undefined) {\n throw new Error(`No ${method} method found for \"path\".`);\n }\n return pathItem[method];\n }\n\n getParametersForOperation(operation: OpenAPIV3_1.OperationObject) {\n if (operation.parameters === undefined) {\n return [];\n }\n return operation.parameters.map((parameter) => {\n if ((parameter as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n return this.getRootReferencedParameter(\n parameter as OpenAPIV3_1.ReferenceObject\n );\n }\n return parameter as OpenAPIV3_1.ParameterObject;\n });\n }\n\n getRequestBodyForOperation(\n operation: OpenAPIV3_1.OperationObject\n ): OpenAPIV3_1.RequestBodyObject {\n const { requestBody } = operation;\n if ((requestBody as OpenAPIV3_1.ReferenceObject)?.$ref !== undefined) {\n return this.getRootReferencedRequestBody(\n requestBody as OpenAPIV3_1.ReferenceObject\n );\n }\n return requestBody as OpenAPIV3_1.RequestBodyObject;\n }\n\n static getCleanedOperationId(\n operation: OpenAPIV3_1.OperationObject,\n path: string,\n method: OpenAPIV3_1.HttpMethods\n ) {\n let { operationId } = operation;\n if (operationId === undefined) {\n const updatedPath = path.replaceAll(/[^a-zA-Z0-9]/g, \"_\");\n operationId = `${\n updatedPath.startsWith(\"/\") ? updatedPath.slice(1) : updatedPath\n }_${method}`;\n }\n return operationId\n .replaceAll(/-/g, \"_\")\n .replaceAll(/\\./g, \"_\")\n .replaceAll(/\\//g, \"_\");\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static alertUnsupportedSpec(document: Record<string, any>) {\n const warningMessage =\n \"This may result in degraded performance. Convert your OpenAPI spec to 3.1.0 for better support.\";\n const swaggerVersion = document.swagger;\n const openAPIVersion = document.openapi;\n if (openAPIVersion !== undefined && openAPIVersion !== \"3.1.0\") {\n console.warn(\n `Attempting to load an OpenAPI ${openAPIVersion} spec. ${warningMessage}`\n );\n } else if (swaggerVersion !== undefined) {\n console.warn(\n `Attempting to load a Swagger ${swaggerVersion} spec. ${warningMessage}`\n );\n } else {\n throw new Error(\n `Attempting to load an unsupported spec:\\n\\n${JSON.stringify(\n document,\n null,\n 2\n )}.`\n );\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static fromObject(document: Record<string, any>) {\n OpenAPISpec.alertUnsupportedSpec(document);\n return new OpenAPISpec(document as OpenAPIV3_1.Document);\n }\n\n static fromString(rawString: string) {\n let document;\n try {\n document = JSON.parse(rawString);\n } catch (e) {\n document = yaml.load(rawString);\n }\n return OpenAPISpec.fromObject(document);\n }\n\n static async fromURL(url: string) {\n const response = await fetch(url);\n const rawDocument = await response.text();\n return OpenAPISpec.fromString(rawDocument);\n }\n}\n"],"mappings":";;;;AAGA,IAAa,cAAb,MAAa,YAAY;CACvB,YAAmBA,UAAgC;EAAhC;CAAkC;CAErD,IAAI,UAAU;AACZ,SAAO,KAAK,SAAS,UAAU,KAAK,SAAS,QAAQ,GAAG,MAAM;CAC/D;CAED,iBAAiB;AACf,MAAI,CAAC,KAAK,SAAS,MACjB,OAAM,IAAI,MAAM;AAElB,SAAO,KAAK,SAAS;CACtB;CAED,sBAAsB;AACpB,MAAI,CAAC,KAAK,SAAS,YAAY,WAC7B,OAAM,IAAI,MAAM;AAElB,SAAO,KAAK,SAAS,WAAW;CACjC;CAED,mBAAmB;AACjB,MAAI,CAAC,KAAK,SAAS,YAAY,QAC7B,OAAM,IAAI,MAAM;AAElB,SAAO,KAAK,SAAS,WAAW;CACjC;CAED,yBAAyB;AACvB,MAAI,CAAC,KAAK,SAAS,YAAY,cAC7B,OAAM,IAAI,MAAM;AAElB,SAAO,KAAK,SAAS,WAAW;CACjC;CAED,cAAcC,MAAc;EAC1B,MAAM,WAAW,KAAK,gBAAgB,CAAC;AACvC,MAAI,aAAa,OACf,OAAM,IAAI,MAAM,CAAC,mBAAmB,EAAE,KAAK,EAAE,CAAC;AAEhD,SAAO;CACR;CAED,uBAAuBC,KAAkC;EACvD,MAAM,gBAAgB,IAAI,KAAK,MAAM,IAAI;EACzC,MAAM,UAAU,cAAc,cAAc,SAAS;AACrD,MAAI,KAAK,qBAAqB,CAAC,aAAa,OAC1C,OAAM,IAAI,MAAM,CAAC,wBAAwB,EAAE,QAAQ,EAAE,CAAC;AAExD,SAAO,KAAK,qBAAqB,CAAC;CACnC;CAED,2BACEA,KAC6B;EAC7B,IAAI,YAAY,KAAK,uBAAuB,IAAI;AAChD,SAA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2CAA2C,EAAE,KAAK,UACjD,UACA,MACA,EACD,CAAC,CAAC,CAAC;CAGT;CAGD,OAAO,WAAWA,UAA+B;EAC/C,YAAY,qBAAqB,SAAS;AAC1C,SAAO,IAAI,YAAY;CACxB;CAED,OAAO,WAAWC,WAAmB;EACnC,IAAI;AACJ,MAAI;GACF,WAAW,KAAK,MAAM,UAAU;EACjC,SAAQ,GAAG;GACV,WAAWC,QAAK,KAAK,UAAU;EAChC;AACD,SAAO,YAAY,WAAW,SAAS;CACxC;CAED,aAAa,QAAQC,KAAa;EAChC,MAAM,WAAW,MAAM,MAAM,IAAI;EACjC,MAAM,cAAc,MAAM,SAAS,MAAM;AACzC,SAAO,YAAY,WAAW,YAAY;CAC3C;AACF"}
|
|
1
|
+
{"version":3,"file":"openapi.cjs","names":["document: OpenAPIV3_1.Document","path: string","ref: OpenAPIV3_1.ReferenceObject","schema: OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.SchemaObject","method: OpenAPIV3.HttpMethods","operation: OpenAPIV3_1.OperationObject","method: OpenAPIV3_1.HttpMethods","document: Record<string, any>","rawString: string","yaml","url: string"],"sources":["../../src/util/openapi.ts"],"sourcesContent":["import * as yaml from \"js-yaml\";\nimport { OpenAPIV3, OpenAPIV3_1 } from \"openapi-types\";\n\nexport class OpenAPISpec {\n constructor(public document: OpenAPIV3_1.Document) {}\n\n get baseUrl() {\n return this.document.servers ? this.document.servers[0].url : undefined;\n }\n\n getPathsStrict() {\n if (!this.document.paths) {\n throw new Error(\"No paths found in spec\");\n }\n return this.document.paths;\n }\n\n getParametersStrict() {\n if (!this.document.components?.parameters) {\n throw new Error(\"No parameters found in spec\");\n }\n return this.document.components.parameters;\n }\n\n getSchemasStrict() {\n if (!this.document.components?.schemas) {\n throw new Error(\"No schemas found in spec.\");\n }\n return this.document.components.schemas;\n }\n\n getRequestBodiesStrict() {\n if (!this.document.components?.requestBodies) {\n throw new Error(\"No request body found in spec.\");\n }\n return this.document.components.requestBodies;\n }\n\n getPathStrict(path: string) {\n const pathItem = this.getPathsStrict()[path];\n if (pathItem === undefined) {\n throw new Error(`No path found for \"${path}\".`);\n }\n return pathItem;\n }\n\n getReferencedParameter(ref: OpenAPIV3_1.ReferenceObject) {\n const refComponents = ref.$ref.split(\"/\");\n const refName = refComponents[refComponents.length - 1];\n if (this.getParametersStrict()[refName] === undefined) {\n throw new Error(`No parameter found for \"${refName}\".`);\n }\n return this.getParametersStrict()[refName];\n }\n\n getRootReferencedParameter(\n ref: OpenAPIV3_1.ReferenceObject\n ): OpenAPIV3_1.ParameterObject {\n let parameter = this.getReferencedParameter(ref);\n while ((parameter as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n parameter = this.getReferencedParameter(\n parameter as OpenAPIV3_1.ReferenceObject\n );\n }\n return parameter as OpenAPIV3_1.ParameterObject;\n }\n\n getReferencedSchema(\n ref: OpenAPIV3_1.ReferenceObject\n ): OpenAPIV3_1.SchemaObject {\n const refComponents = ref.$ref.split(\"/\");\n const refName = refComponents[refComponents.length - 1];\n const schema = this.getSchemasStrict()[refName];\n if (schema === undefined) {\n throw new Error(`No schema found for \"${refName}\".`);\n }\n return schema;\n }\n\n getSchema(\n schema: OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.SchemaObject\n ): OpenAPIV3_1.SchemaObject {\n if ((schema as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n return this.getReferencedSchema(schema as OpenAPIV3_1.ReferenceObject);\n }\n return schema;\n }\n\n getRootReferencedSchema(ref: OpenAPIV3_1.ReferenceObject) {\n let schema = this.getReferencedSchema(ref);\n while ((schema as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n schema = this.getReferencedSchema(schema as OpenAPIV3_1.ReferenceObject);\n }\n return schema as OpenAPIV3_1.ParameterObject;\n }\n\n getReferencedRequestBody(ref: OpenAPIV3_1.ReferenceObject) {\n const refComponents = ref.$ref.split(\"/\");\n const refName = refComponents[refComponents.length - 1];\n const requestBodies = this.getRequestBodiesStrict();\n if (requestBodies[refName] === undefined) {\n throw new Error(`No request body found for \"${refName}\"`);\n }\n return requestBodies[refName];\n }\n\n getRootReferencedRequestBody(ref: OpenAPIV3_1.ReferenceObject) {\n let requestBody = this.getReferencedRequestBody(ref);\n while ((requestBody as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n requestBody = this.getReferencedRequestBody(\n requestBody as OpenAPIV3_1.ReferenceObject\n );\n }\n return requestBody as OpenAPIV3_1.RequestBodyObject;\n }\n\n getMethodsForPath(path: string): OpenAPIV3.HttpMethods[] {\n const pathItem = this.getPathStrict(path);\n // This is an enum in the underlying package.\n // Werestate here to allow \"import type\" above and not cause warnings in certain envs.\n const possibleMethods = [\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"options\",\n \"head\",\n \"patch\",\n \"trace\",\n ];\n return possibleMethods.filter(\n (possibleMethod) =>\n pathItem[possibleMethod as OpenAPIV3.HttpMethods] !== undefined\n ) as OpenAPIV3.HttpMethods[];\n }\n\n getParametersForPath(path: string) {\n const pathItem = this.getPathStrict(path);\n if (pathItem.parameters === undefined) {\n return [];\n }\n return pathItem.parameters.map((parameter) => {\n if ((parameter as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n return this.getRootReferencedParameter(\n parameter as OpenAPIV3_1.ReferenceObject\n );\n }\n return parameter as OpenAPIV3_1.ParameterObject;\n });\n }\n\n getOperation(path: string, method: OpenAPIV3.HttpMethods) {\n const pathItem = this.getPathStrict(path);\n if (pathItem[method] === undefined) {\n throw new Error(`No ${method} method found for \"path\".`);\n }\n return pathItem[method];\n }\n\n getParametersForOperation(operation: OpenAPIV3_1.OperationObject) {\n if (operation.parameters === undefined) {\n return [];\n }\n return operation.parameters.map((parameter) => {\n if ((parameter as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n return this.getRootReferencedParameter(\n parameter as OpenAPIV3_1.ReferenceObject\n );\n }\n return parameter as OpenAPIV3_1.ParameterObject;\n });\n }\n\n getRequestBodyForOperation(\n operation: OpenAPIV3_1.OperationObject\n ): OpenAPIV3_1.RequestBodyObject {\n const { requestBody } = operation;\n if ((requestBody as OpenAPIV3_1.ReferenceObject)?.$ref !== undefined) {\n return this.getRootReferencedRequestBody(\n requestBody as OpenAPIV3_1.ReferenceObject\n );\n }\n return requestBody as OpenAPIV3_1.RequestBodyObject;\n }\n\n static getCleanedOperationId(\n operation: OpenAPIV3_1.OperationObject,\n path: string,\n method: OpenAPIV3_1.HttpMethods\n ) {\n let { operationId } = operation;\n if (operationId === undefined) {\n const updatedPath = path.replaceAll(/[^a-zA-Z0-9]/g, \"_\");\n operationId = `${\n updatedPath.startsWith(\"/\") ? updatedPath.slice(1) : updatedPath\n }_${method}`;\n }\n return operationId\n .replaceAll(/-/g, \"_\")\n .replaceAll(/\\./g, \"_\")\n .replaceAll(/\\//g, \"_\");\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static alertUnsupportedSpec(document: Record<string, any>) {\n const warningMessage =\n \"This may result in degraded performance. Convert your OpenAPI spec to 3.1.0 for better support.\";\n const swaggerVersion = document.swagger;\n const openAPIVersion = document.openapi;\n if (openAPIVersion !== undefined && openAPIVersion !== \"3.1.0\") {\n console.warn(\n `Attempting to load an OpenAPI ${openAPIVersion} spec. ${warningMessage}`\n );\n } else if (swaggerVersion !== undefined) {\n console.warn(\n `Attempting to load a Swagger ${swaggerVersion} spec. ${warningMessage}`\n );\n } else {\n throw new Error(\n `Attempting to load an unsupported spec:\\n\\n${JSON.stringify(\n document,\n null,\n 2\n )}.`\n );\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static fromObject(document: Record<string, any>) {\n OpenAPISpec.alertUnsupportedSpec(document);\n return new OpenAPISpec(document as OpenAPIV3_1.Document);\n }\n\n static fromString(rawString: string) {\n let document;\n try {\n document = JSON.parse(rawString);\n } catch {\n document = yaml.load(rawString);\n }\n return OpenAPISpec.fromObject(document);\n }\n\n static async fromURL(url: string) {\n const response = await fetch(url);\n const rawDocument = await response.text();\n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I,YAAY;CACxB;CAED,OAAO,WAAWC,WAAmB;EACnC,IAAI;AACJ,MAAI;GACF,WAAW,KAAK,MAAM,UAAU;EACjC,QAAO;GACN,WAAWC,QAAK,KAAK,UAAU;EAChC;AACD,SAAO,YAAY,WAAW,SAAS;CACxC;CAED,aAAa,QAAQC,KAAa;EAChC,MAAM,WAAW,MAAM,MAAM,IAAI;EACjC,MAAM,cAAc,MAAM,SAAS,MAAM;AACzC,SAAO,YAAY,WAAW,YAAY;CAC3C;AACF"}
|
package/dist/util/openapi.js
CHANGED
package/dist/util/openapi.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openapi.js","names":["document: OpenAPIV3_1.Document","path: string","ref: OpenAPIV3_1.ReferenceObject","schema: OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.SchemaObject","method: OpenAPIV3.HttpMethods","operation: OpenAPIV3_1.OperationObject","method: OpenAPIV3_1.HttpMethods","document: Record<string, any>","rawString: string","url: string"],"sources":["../../src/util/openapi.ts"],"sourcesContent":["import * as yaml from \"js-yaml\";\nimport { OpenAPIV3, OpenAPIV3_1 } from \"openapi-types\";\n\nexport class OpenAPISpec {\n constructor(public document: OpenAPIV3_1.Document) {}\n\n get baseUrl() {\n return this.document.servers ? this.document.servers[0].url : undefined;\n }\n\n getPathsStrict() {\n if (!this.document.paths) {\n throw new Error(\"No paths found in spec\");\n }\n return this.document.paths;\n }\n\n getParametersStrict() {\n if (!this.document.components?.parameters) {\n throw new Error(\"No parameters found in spec\");\n }\n return this.document.components.parameters;\n }\n\n getSchemasStrict() {\n if (!this.document.components?.schemas) {\n throw new Error(\"No schemas found in spec.\");\n }\n return this.document.components.schemas;\n }\n\n getRequestBodiesStrict() {\n if (!this.document.components?.requestBodies) {\n throw new Error(\"No request body found in spec.\");\n }\n return this.document.components.requestBodies;\n }\n\n getPathStrict(path: string) {\n const pathItem = this.getPathsStrict()[path];\n if (pathItem === undefined) {\n throw new Error(`No path found for \"${path}\".`);\n }\n return pathItem;\n }\n\n getReferencedParameter(ref: OpenAPIV3_1.ReferenceObject) {\n const refComponents = ref.$ref.split(\"/\");\n const refName = refComponents[refComponents.length - 1];\n if (this.getParametersStrict()[refName] === undefined) {\n throw new Error(`No parameter found for \"${refName}\".`);\n }\n return this.getParametersStrict()[refName];\n }\n\n getRootReferencedParameter(\n ref: OpenAPIV3_1.ReferenceObject\n ): OpenAPIV3_1.ParameterObject {\n let parameter = this.getReferencedParameter(ref);\n while ((parameter as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n parameter = this.getReferencedParameter(\n parameter as OpenAPIV3_1.ReferenceObject\n );\n }\n return parameter as OpenAPIV3_1.ParameterObject;\n }\n\n getReferencedSchema(\n ref: OpenAPIV3_1.ReferenceObject\n ): OpenAPIV3_1.SchemaObject {\n const refComponents = ref.$ref.split(\"/\");\n const refName = refComponents[refComponents.length - 1];\n const schema = this.getSchemasStrict()[refName];\n if (schema === undefined) {\n throw new Error(`No schema found for \"${refName}\".`);\n }\n return schema;\n }\n\n getSchema(\n schema: OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.SchemaObject\n ): OpenAPIV3_1.SchemaObject {\n if ((schema as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n return this.getReferencedSchema(schema as OpenAPIV3_1.ReferenceObject);\n }\n return schema;\n }\n\n getRootReferencedSchema(ref: OpenAPIV3_1.ReferenceObject) {\n let schema = this.getReferencedSchema(ref);\n while ((schema as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n schema = this.getReferencedSchema(schema as OpenAPIV3_1.ReferenceObject);\n }\n return schema as OpenAPIV3_1.ParameterObject;\n }\n\n getReferencedRequestBody(ref: OpenAPIV3_1.ReferenceObject) {\n const refComponents = ref.$ref.split(\"/\");\n const refName = refComponents[refComponents.length - 1];\n const requestBodies = this.getRequestBodiesStrict();\n if (requestBodies[refName] === undefined) {\n throw new Error(`No request body found for \"${refName}\"`);\n }\n return requestBodies[refName];\n }\n\n getRootReferencedRequestBody(ref: OpenAPIV3_1.ReferenceObject) {\n let requestBody = this.getReferencedRequestBody(ref);\n while ((requestBody as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n requestBody = this.getReferencedRequestBody(\n requestBody as OpenAPIV3_1.ReferenceObject\n );\n }\n return requestBody as OpenAPIV3_1.RequestBodyObject;\n }\n\n getMethodsForPath(path: string): OpenAPIV3.HttpMethods[] {\n const pathItem = this.getPathStrict(path);\n // This is an enum in the underlying package.\n // Werestate here to allow \"import type\" above and not cause warnings in certain envs.\n const possibleMethods = [\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"options\",\n \"head\",\n \"patch\",\n \"trace\",\n ];\n return possibleMethods.filter(\n (possibleMethod) =>\n pathItem[possibleMethod as OpenAPIV3.HttpMethods] !== undefined\n ) as OpenAPIV3.HttpMethods[];\n }\n\n getParametersForPath(path: string) {\n const pathItem = this.getPathStrict(path);\n if (pathItem.parameters === undefined) {\n return [];\n }\n return pathItem.parameters.map((parameter) => {\n if ((parameter as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n return this.getRootReferencedParameter(\n parameter as OpenAPIV3_1.ReferenceObject\n );\n }\n return parameter as OpenAPIV3_1.ParameterObject;\n });\n }\n\n getOperation(path: string, method: OpenAPIV3.HttpMethods) {\n const pathItem = this.getPathStrict(path);\n if (pathItem[method] === undefined) {\n throw new Error(`No ${method} method found for \"path\".`);\n }\n return pathItem[method];\n }\n\n getParametersForOperation(operation: OpenAPIV3_1.OperationObject) {\n if (operation.parameters === undefined) {\n return [];\n }\n return operation.parameters.map((parameter) => {\n if ((parameter as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n return this.getRootReferencedParameter(\n parameter as OpenAPIV3_1.ReferenceObject\n );\n }\n return parameter as OpenAPIV3_1.ParameterObject;\n });\n }\n\n getRequestBodyForOperation(\n operation: OpenAPIV3_1.OperationObject\n ): OpenAPIV3_1.RequestBodyObject {\n const { requestBody } = operation;\n if ((requestBody as OpenAPIV3_1.ReferenceObject)?.$ref !== undefined) {\n return this.getRootReferencedRequestBody(\n requestBody as OpenAPIV3_1.ReferenceObject\n );\n }\n return requestBody as OpenAPIV3_1.RequestBodyObject;\n }\n\n static getCleanedOperationId(\n operation: OpenAPIV3_1.OperationObject,\n path: string,\n method: OpenAPIV3_1.HttpMethods\n ) {\n let { operationId } = operation;\n if (operationId === undefined) {\n const updatedPath = path.replaceAll(/[^a-zA-Z0-9]/g, \"_\");\n operationId = `${\n updatedPath.startsWith(\"/\") ? updatedPath.slice(1) : updatedPath\n }_${method}`;\n }\n return operationId\n .replaceAll(/-/g, \"_\")\n .replaceAll(/\\./g, \"_\")\n .replaceAll(/\\//g, \"_\");\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static alertUnsupportedSpec(document: Record<string, any>) {\n const warningMessage =\n \"This may result in degraded performance. Convert your OpenAPI spec to 3.1.0 for better support.\";\n const swaggerVersion = document.swagger;\n const openAPIVersion = document.openapi;\n if (openAPIVersion !== undefined && openAPIVersion !== \"3.1.0\") {\n console.warn(\n `Attempting to load an OpenAPI ${openAPIVersion} spec. ${warningMessage}`\n );\n } else if (swaggerVersion !== undefined) {\n console.warn(\n `Attempting to load a Swagger ${swaggerVersion} spec. ${warningMessage}`\n );\n } else {\n throw new Error(\n `Attempting to load an unsupported spec:\\n\\n${JSON.stringify(\n document,\n null,\n 2\n )}.`\n );\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static fromObject(document: Record<string, any>) {\n OpenAPISpec.alertUnsupportedSpec(document);\n return new OpenAPISpec(document as OpenAPIV3_1.Document);\n }\n\n static fromString(rawString: string) {\n let document;\n try {\n document = JSON.parse(rawString);\n } catch (e) {\n document = yaml.load(rawString);\n }\n return OpenAPISpec.fromObject(document);\n }\n\n static async fromURL(url: string) {\n const response = await fetch(url);\n const rawDocument = await response.text();\n return OpenAPISpec.fromString(rawDocument);\n }\n}\n"],"mappings":";;;AAGA,IAAa,cAAb,MAAa,YAAY;C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K,MAAM,UAAU;EACjC,SAAQ,GAAG;GACV,WAAW,KAAK,KAAK,UAAU;EAChC;AACD,SAAO,YAAY,WAAW,SAAS;CACxC;CAED,aAAa,QAAQC,KAAa;EAChC,MAAM,WAAW,MAAM,MAAM,IAAI;EACjC,MAAM,cAAc,MAAM,SAAS,MAAM;AACzC,SAAO,YAAY,WAAW,YAAY;CAC3C;AACF"}
|
|
1
|
+
{"version":3,"file":"openapi.js","names":["document: OpenAPIV3_1.Document","path: string","ref: OpenAPIV3_1.ReferenceObject","schema: OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.SchemaObject","method: OpenAPIV3.HttpMethods","operation: OpenAPIV3_1.OperationObject","method: OpenAPIV3_1.HttpMethods","document: Record<string, any>","rawString: string","url: string"],"sources":["../../src/util/openapi.ts"],"sourcesContent":["import * as yaml from \"js-yaml\";\nimport { OpenAPIV3, OpenAPIV3_1 } from \"openapi-types\";\n\nexport class OpenAPISpec {\n constructor(public document: OpenAPIV3_1.Document) {}\n\n get baseUrl() {\n return this.document.servers ? this.document.servers[0].url : undefined;\n }\n\n getPathsStrict() {\n if (!this.document.paths) {\n throw new Error(\"No paths found in spec\");\n }\n return this.document.paths;\n }\n\n getParametersStrict() {\n if (!this.document.components?.parameters) {\n throw new Error(\"No parameters found in spec\");\n }\n return this.document.components.parameters;\n }\n\n getSchemasStrict() {\n if (!this.document.components?.schemas) {\n throw new Error(\"No schemas found in spec.\");\n }\n return this.document.components.schemas;\n }\n\n getRequestBodiesStrict() {\n if (!this.document.components?.requestBodies) {\n throw new Error(\"No request body found in spec.\");\n }\n return this.document.components.requestBodies;\n }\n\n getPathStrict(path: string) {\n const pathItem = this.getPathsStrict()[path];\n if (pathItem === undefined) {\n throw new Error(`No path found for \"${path}\".`);\n }\n return pathItem;\n }\n\n getReferencedParameter(ref: OpenAPIV3_1.ReferenceObject) {\n const refComponents = ref.$ref.split(\"/\");\n const refName = refComponents[refComponents.length - 1];\n if (this.getParametersStrict()[refName] === undefined) {\n throw new Error(`No parameter found for \"${refName}\".`);\n }\n return this.getParametersStrict()[refName];\n }\n\n getRootReferencedParameter(\n ref: OpenAPIV3_1.ReferenceObject\n ): OpenAPIV3_1.ParameterObject {\n let parameter = this.getReferencedParameter(ref);\n while ((parameter as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n parameter = this.getReferencedParameter(\n parameter as OpenAPIV3_1.ReferenceObject\n );\n }\n return parameter as OpenAPIV3_1.ParameterObject;\n }\n\n getReferencedSchema(\n ref: OpenAPIV3_1.ReferenceObject\n ): OpenAPIV3_1.SchemaObject {\n const refComponents = ref.$ref.split(\"/\");\n const refName = refComponents[refComponents.length - 1];\n const schema = this.getSchemasStrict()[refName];\n if (schema === undefined) {\n throw new Error(`No schema found for \"${refName}\".`);\n }\n return schema;\n }\n\n getSchema(\n schema: OpenAPIV3_1.ReferenceObject | OpenAPIV3_1.SchemaObject\n ): OpenAPIV3_1.SchemaObject {\n if ((schema as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n return this.getReferencedSchema(schema as OpenAPIV3_1.ReferenceObject);\n }\n return schema;\n }\n\n getRootReferencedSchema(ref: OpenAPIV3_1.ReferenceObject) {\n let schema = this.getReferencedSchema(ref);\n while ((schema as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n schema = this.getReferencedSchema(schema as OpenAPIV3_1.ReferenceObject);\n }\n return schema as OpenAPIV3_1.ParameterObject;\n }\n\n getReferencedRequestBody(ref: OpenAPIV3_1.ReferenceObject) {\n const refComponents = ref.$ref.split(\"/\");\n const refName = refComponents[refComponents.length - 1];\n const requestBodies = this.getRequestBodiesStrict();\n if (requestBodies[refName] === undefined) {\n throw new Error(`No request body found for \"${refName}\"`);\n }\n return requestBodies[refName];\n }\n\n getRootReferencedRequestBody(ref: OpenAPIV3_1.ReferenceObject) {\n let requestBody = this.getReferencedRequestBody(ref);\n while ((requestBody as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n requestBody = this.getReferencedRequestBody(\n requestBody as OpenAPIV3_1.ReferenceObject\n );\n }\n return requestBody as OpenAPIV3_1.RequestBodyObject;\n }\n\n getMethodsForPath(path: string): OpenAPIV3.HttpMethods[] {\n const pathItem = this.getPathStrict(path);\n // This is an enum in the underlying package.\n // Werestate here to allow \"import type\" above and not cause warnings in certain envs.\n const possibleMethods = [\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"options\",\n \"head\",\n \"patch\",\n \"trace\",\n ];\n return possibleMethods.filter(\n (possibleMethod) =>\n pathItem[possibleMethod as OpenAPIV3.HttpMethods] !== undefined\n ) as OpenAPIV3.HttpMethods[];\n }\n\n getParametersForPath(path: string) {\n const pathItem = this.getPathStrict(path);\n if (pathItem.parameters === undefined) {\n return [];\n }\n return pathItem.parameters.map((parameter) => {\n if ((parameter as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n return this.getRootReferencedParameter(\n parameter as OpenAPIV3_1.ReferenceObject\n );\n }\n return parameter as OpenAPIV3_1.ParameterObject;\n });\n }\n\n getOperation(path: string, method: OpenAPIV3.HttpMethods) {\n const pathItem = this.getPathStrict(path);\n if (pathItem[method] === undefined) {\n throw new Error(`No ${method} method found for \"path\".`);\n }\n return pathItem[method];\n }\n\n getParametersForOperation(operation: OpenAPIV3_1.OperationObject) {\n if (operation.parameters === undefined) {\n return [];\n }\n return operation.parameters.map((parameter) => {\n if ((parameter as OpenAPIV3_1.ReferenceObject).$ref !== undefined) {\n return this.getRootReferencedParameter(\n parameter as OpenAPIV3_1.ReferenceObject\n );\n }\n return parameter as OpenAPIV3_1.ParameterObject;\n });\n }\n\n getRequestBodyForOperation(\n operation: OpenAPIV3_1.OperationObject\n ): OpenAPIV3_1.RequestBodyObject {\n const { requestBody } = operation;\n if ((requestBody as OpenAPIV3_1.ReferenceObject)?.$ref !== undefined) {\n return this.getRootReferencedRequestBody(\n requestBody as OpenAPIV3_1.ReferenceObject\n );\n }\n return requestBody as OpenAPIV3_1.RequestBodyObject;\n }\n\n static getCleanedOperationId(\n operation: OpenAPIV3_1.OperationObject,\n path: string,\n method: OpenAPIV3_1.HttpMethods\n ) {\n let { operationId } = operation;\n if (operationId === undefined) {\n const updatedPath = path.replaceAll(/[^a-zA-Z0-9]/g, \"_\");\n operationId = `${\n updatedPath.startsWith(\"/\") ? updatedPath.slice(1) : updatedPath\n }_${method}`;\n }\n return operationId\n .replaceAll(/-/g, \"_\")\n .replaceAll(/\\./g, \"_\")\n .replaceAll(/\\//g, \"_\");\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static alertUnsupportedSpec(document: Record<string, any>) {\n const warningMessage =\n \"This may result in degraded performance. Convert your OpenAPI spec to 3.1.0 for better support.\";\n const swaggerVersion = document.swagger;\n const openAPIVersion = document.openapi;\n if (openAPIVersion !== undefined && openAPIVersion !== \"3.1.0\") {\n console.warn(\n `Attempting to load an OpenAPI ${openAPIVersion} spec. ${warningMessage}`\n );\n } else if (swaggerVersion !== undefined) {\n console.warn(\n `Attempting to load a Swagger ${swaggerVersion} spec. ${warningMessage}`\n );\n } else {\n throw new Error(\n `Attempting to load an unsupported spec:\\n\\n${JSON.stringify(\n document,\n null,\n 2\n )}.`\n );\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static fromObject(document: Record<string, any>) {\n OpenAPISpec.alertUnsupportedSpec(document);\n return new OpenAPISpec(document as OpenAPIV3_1.Document);\n }\n\n static fromString(rawString: string) {\n let document;\n try {\n document = JSON.parse(rawString);\n } catch {\n document = yaml.load(rawString);\n }\n return OpenAPISpec.fromObject(document);\n }\n\n static async fromURL(url: string) {\n const response = await fetch(url);\n const rawDocument = await response.text();\n return OpenAPISpec.fromString(rawDocument);\n }\n}\n"],"mappings":";;;AAGA,IAAa,cAAb,MAAa,YAAY;CACvB,YAAmBA,UAAgC;EAAhC;CAAkC;CAErD,IAAI,UAAU;AACZ,SAAO,KAAK,SAAS,UAAU,KAAK,SAAS,QAAQ,GAAG,MAAM;CAC/D;CAED,iBAAiB;AACf,MAAI,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AAM,IAAI;EACjC,MAAM,cAAc,MAAM,SAAS,MAAM;AACzC,SAAO,YAAY,WAAW,YAAY;CAC3C;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "langchain",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.6",
|
|
4
4
|
"description": "Typescript bindings for langchain",
|
|
5
5
|
"author": "LangChain",
|
|
6
6
|
"license": "MIT",
|
|
@@ -22,18 +22,11 @@
|
|
|
22
22
|
"@types/jsdom": "^21.1.1",
|
|
23
23
|
"@types/uuid": "^9",
|
|
24
24
|
"@types/ws": "^8",
|
|
25
|
-
"@typescript-eslint/eslint-plugin": "^5.58.0",
|
|
26
|
-
"@typescript-eslint/parser": "^5.58.0",
|
|
27
25
|
"@vitest/coverage-v8": "^3.2.4",
|
|
28
26
|
"cheerio": "1.0.0-rc.12",
|
|
29
27
|
"dotenv": "^16.0.3",
|
|
30
28
|
"dpdm": "^3.14.0",
|
|
31
|
-
"eslint": "^
|
|
32
|
-
"eslint-config-airbnb-base": "^15.0.0",
|
|
33
|
-
"eslint-config-prettier": "^8.6.0",
|
|
34
|
-
"eslint-plugin-import": "^2.27.5",
|
|
35
|
-
"eslint-plugin-no-instanceof": "^1.0.1",
|
|
36
|
-
"eslint-plugin-prettier": "^4.2.1",
|
|
29
|
+
"eslint": "^9.34.0",
|
|
37
30
|
"langsmith": "^0.3.64",
|
|
38
31
|
"openai": "^5.1.0",
|
|
39
32
|
"peggy": "^3.0.2",
|
|
@@ -46,12 +39,14 @@
|
|
|
46
39
|
"typeorm": "^0.3.20",
|
|
47
40
|
"typescript": "~5.8.3",
|
|
48
41
|
"vitest": "^3.2.4",
|
|
49
|
-
"@langchain/core": "1.0.0-alpha.
|
|
50
|
-
"@langchain/
|
|
51
|
-
"@langchain/cohere": "0.3.4"
|
|
42
|
+
"@langchain/core": "1.0.0-alpha.4",
|
|
43
|
+
"@langchain/openai": "1.0.0-alpha.1",
|
|
44
|
+
"@langchain/cohere": "0.3.4",
|
|
45
|
+
"@langchain/eslint": "0.1.0",
|
|
46
|
+
"@langchain/anthropic": "1.0.0-alpha.1"
|
|
52
47
|
},
|
|
53
48
|
"peerDependencies": {
|
|
54
|
-
"@langchain/core": "^1.0.0-alpha.
|
|
49
|
+
"@langchain/core": "^1.0.0-alpha.3 <2.0.0",
|
|
55
50
|
"cheerio": "*",
|
|
56
51
|
"peggy": "^3.0.2",
|
|
57
52
|
"typeorm": "*"
|
|
@@ -76,8 +71,7 @@
|
|
|
76
71
|
"p-retry": "4",
|
|
77
72
|
"uuid": "^10.0.0",
|
|
78
73
|
"yaml": "^2.2.1",
|
|
79
|
-
"zod": "^3.25.
|
|
80
|
-
"@langchain/openai": "1.0.0-alpha.1",
|
|
74
|
+
"zod": "^3.25.76 || ^4",
|
|
81
75
|
"@langchain/textsplitters": "1.0.0-alpha.1"
|
|
82
76
|
},
|
|
83
77
|
"optionalDependencies": {
|
|
@@ -402,14 +396,14 @@
|
|
|
402
396
|
},
|
|
403
397
|
"./middleware": {
|
|
404
398
|
"import": {
|
|
405
|
-
"types": "./dist/agents/middlewareAgent/
|
|
406
|
-
"default": "./dist/agents/middlewareAgent/
|
|
399
|
+
"types": "./dist/agents/middlewareAgent/middleware/index.d.ts",
|
|
400
|
+
"default": "./dist/agents/middlewareAgent/middleware/index.js"
|
|
407
401
|
},
|
|
408
402
|
"require": {
|
|
409
|
-
"types": "./dist/agents/middlewareAgent/
|
|
410
|
-
"default": "./dist/agents/middlewareAgent/
|
|
403
|
+
"types": "./dist/agents/middlewareAgent/middleware/index.d.cts",
|
|
404
|
+
"default": "./dist/agents/middlewareAgent/middleware/index.cjs"
|
|
411
405
|
},
|
|
412
|
-
"input": "./src/agents/middlewareAgent/
|
|
406
|
+
"input": "./src/agents/middlewareAgent/middleware/index.ts"
|
|
413
407
|
},
|
|
414
408
|
"./document": {
|
|
415
409
|
"import": {
|
|
@@ -833,7 +827,7 @@
|
|
|
833
827
|
},
|
|
834
828
|
"scripts": {
|
|
835
829
|
"build": "pnpm --filter @langchain/build compile langchain",
|
|
836
|
-
"lint:eslint": "
|
|
830
|
+
"lint:eslint": "eslint --cache src/",
|
|
837
831
|
"lint:dpdm": "dpdm --skip-dynamic-imports circular --exit-code circular:1 --no-warning --no-tree src/*.ts src/**/*.ts",
|
|
838
832
|
"lint": "pnpm lint:eslint && pnpm lint:dpdm",
|
|
839
833
|
"lint:fix": "pnpm lint:eslint --fix && pnpm lint:dpdm",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"hitl.cjs","names":["z","options: z.input<typeof contextSchema>","createMiddleware","interruptToolCalls: ToolCall[]","autoApprovedToolCalls: ToolCall[]","normalizedToolCall: ToolCall","requests: ToolApprovalRequest[]","ToolMessage","AIMessage"],"sources":["../../../../src/agents/middlewareAgent/middlewares/hitl.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { v4 as uuid } from \"uuid\";\nimport { AIMessage, ToolMessage, isAIMessage } from \"@langchain/core/messages\";\nimport { interrupt } from \"@langchain/langgraph\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport type { ToolCall } from \"../types.js\";\nimport { HumanResponse } from \"../../interrupt.js\";\n\n/**\n * Interrupt request for tool approval\n */\ninterface ToolApprovalRequest {\n action: string;\n args: Record<string, any>;\n toolCallId: string;\n description?: string;\n}\n\nconst contextSchema = z.object({\n toolConfigs: z\n .record(\n z.object({\n requireApproval: z.boolean().optional(),\n description: z.string().optional(),\n })\n )\n .default({}),\n messagePrefix: z.string().default(\"Tool execution requires approval\"),\n});\n\n/**\n * Creates a Human-in-the-Loop (HITL) middleware for tool approval and oversight.\n *\n * This middleware intercepts tool calls made by an AI agent and provides human oversight\n * capabilities before execution. It enables selective approval workflows where certain tools\n * require human intervention while others can execute automatically.\n *\n * ## Features\n *\n * - **Selective Tool Approval**: Configure which tools require human approval\n * - **Multiple Response Types**: Accept, edit, ignore, or manually respond to tool calls\n * - **Asynchronous Workflow**: Uses LangGraph's interrupt mechanism for non-blocking approval\n * - **Custom Approval Messages**: Provide context-specific descriptions for approval requests\n *\n * ## Response Types\n *\n * When a tool requires approval, the human operator can respond with:\n * - `accept`: Execute the tool with original arguments\n * - `edit`: Modify the tool arguments before execution\n * - `ignore`: Skip the tool and terminate the agent\n * - `response`: Provide a manual response instead of executing the tool\n *\n * @param options - Configuration options for the middleware\n * @param options.toolConfigs - Per-tool configuration mapping tool names to their settings\n * @param options.toolConfigs[toolName].requireApproval - Whether the tool requires human approval\n * @param options.toolConfigs[toolName].description - Custom approval message for the tool\n * @param options.messagePrefix - Default prefix for approval messages (default: \"Tool execution requires approval\")\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @example\n * Basic usage with selective tool approval\n * ```typescript\n * import { humanInTheLoopMiddleware } from \"langchain/middleware\";\n * import { createAgent } from \"langchain\";\n *\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * toolConfigs: {\n * \"write_file\": {\n * requireApproval: true,\n * description: \"⚠️ File write operation requires approval\"\n * },\n * \"read_file\": {\n * requireApproval: false // Safe operation, no approval needed\n * }\n * }\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4\",\n * tools: [writeFileTool, readFileTool],\n * middlewares: [hitlMiddleware]\n * });\n * ```\n *\n * @example\n * Handling approval requests\n * ```typescript\n * import { Command } from \"@langchain/langgraph\";\n *\n * // Initial agent invocation\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Write 'Hello' to output.txt\")]\n * }, config);\n *\n * // Check if agent is paused for approval\n * const state = await agent.graph.getState(config);\n * if (state.next?.length > 0) {\n * // Get interrupt details\n * const task = state.tasks?.[0];\n * const requests = task?.interrupts?.[0]?.value;\n *\n * // Show tool call details to user\n * console.log(\"Tool:\", requests[0].action);\n * console.log(\"Args:\", requests[0].args);\n *\n * // Resume with approval\n * await agent.invoke(\n * new Command({ resume: [{ type: \"accept\" }] }),\n * config\n * );\n * }\n * ```\n *\n * @example\n * Different response types\n * ```typescript\n * // Accept the tool call as-is\n * new Command({ resume: [{ type: \"accept\" }] })\n *\n * // Edit the tool arguments\n * new Command({\n * resume: [{\n * type: \"edit\",\n * args: { action: \"write_file\", args: { filename: \"safe.txt\", content: \"Modified\" } }\n * }]\n * })\n *\n * // Skip tool and terminate agent\n * new Command({ resume: [{ type: \"ignore\" }] })\n *\n * // Provide manual response\n * new Command({\n * resume: [{\n * type: \"response\",\n * args: \"File operation not allowed in demo mode\"\n * }]\n * })\n * ```\n *\n * @example\n * Production use case with database operations\n * ```typescript\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * toolConfigs: {\n * \"execute_sql\": {\n * requireApproval: true,\n * description: \"🚨 SQL query requires DBA approval\\nPlease review for safety and performance\"\n * },\n * \"read_schema\": {\n * requireApproval: false // Reading metadata is safe\n * },\n * \"delete_records\": {\n * requireApproval: true,\n * description: \"⛔ DESTRUCTIVE OPERATION - Requires manager approval\"\n * }\n * },\n * messagePrefix: \"Database operation pending approval\"\n * });\n * ```\n *\n * @remarks\n * - Tool calls are processed in the order they appear in the AI message\n * - Auto-approved tools execute immediately without interruption\n * - Multiple tools requiring approval are bundled into a single interrupt\n * - The middleware operates in the `afterModel` phase, intercepting before tool execution\n * - Requires a checkpointer to maintain state across interruptions\n *\n * @see {@link createAgent} for agent creation\n * @see {@link Command} for resuming interrupted execution\n * @public\n */\nexport function humanInTheLoopMiddleware(\n options: z.input<typeof contextSchema> = {}\n) {\n return createMiddleware({\n name: \"HumanInTheLoopMiddleware\",\n contextSchema,\n afterModel: async (state, runtime, controls) => {\n const config = { ...contextSchema.parse(options), ...runtime.context };\n const { messages } = state;\n\n if (!messages.length) {\n return;\n }\n\n const lastMessage = messages[messages.length - 1];\n\n // Check if it's an AI message with tool calls\n if (!isAIMessage(lastMessage) || !lastMessage.tool_calls?.length) {\n return;\n }\n\n // Separate tool calls that need interrupts from those that don't\n const interruptToolCalls: ToolCall[] = [];\n const autoApprovedToolCalls: ToolCall[] = [];\n\n for (const toolCall of lastMessage.tool_calls) {\n // Ensure tool call has an ID\n const normalizedToolCall: ToolCall = {\n id: toolCall.id || uuid(),\n name: toolCall.name,\n args: toolCall.args,\n };\n\n const toolConfig = config.toolConfigs[normalizedToolCall.name];\n\n if (toolConfig?.requireApproval) {\n interruptToolCalls.push(normalizedToolCall);\n } else {\n autoApprovedToolCalls.push(normalizedToolCall);\n }\n }\n\n // If no interrupts needed, return early\n if (!interruptToolCalls.length) {\n return;\n }\n\n const approvedToolCalls = [...autoApprovedToolCalls];\n\n // Process tool calls that need interrupts\n const requests: ToolApprovalRequest[] = interruptToolCalls.map(\n (toolCall) => {\n const toolConfig = config.toolConfigs[toolCall.name];\n const description =\n toolConfig?.description ||\n `${config.messagePrefix}\\n\\nTool: ${\n toolCall.name\n }\\nArgs: ${JSON.stringify(toolCall.args, null, 2)}`;\n\n return {\n action: toolCall.name,\n args: toolCall.args,\n toolCallId: toolCall.id,\n description,\n };\n }\n );\n\n // Interrupt and wait for human responses\n const responses = (await interrupt(requests)) as HumanResponse[];\n\n // Process responses\n for (let i = 0; i < responses.length; i++) {\n const response = responses[i];\n const toolCall = interruptToolCalls[i];\n\n switch (response.type) {\n case \"accept\":\n approvedToolCalls.push(toolCall);\n break;\n\n case \"edit\":\n // For edit, args is an ActionRequest with updated args\n if (\n response.args &&\n typeof response.args === \"object\" &&\n \"args\" in response.args\n ) {\n approvedToolCalls.push({\n ...toolCall,\n args: (\n response.args as { action: string; args: Record<string, any> }\n ).args,\n });\n }\n break;\n\n case \"ignore\":\n // Skip to end - terminate the agent\n return controls.terminate();\n\n case \"response\": {\n // Return manual tool response and jump back to model\n // For response, args is a string\n const toolMessage = new ToolMessage({\n content: typeof response.args === \"string\" ? response.args : \"\",\n tool_call_id: toolCall.id,\n });\n return {\n messages: [...state.messages, toolMessage],\n jump_to: \"model\",\n };\n }\n default:\n throw new Error(`Unknown response type: ${(response as any).type}`);\n }\n }\n\n // Update the last message with approved tool calls\n const updatedMessage = new AIMessage({\n content: lastMessage.content,\n tool_calls: approvedToolCalls,\n id: lastMessage.id,\n });\n\n // Replace the last message with the updated one\n return {\n messages: [...state.messages.slice(0, -1), updatedMessage],\n };\n },\n });\n}\n"],"mappings":";;;;;;;;AAmBA,MAAM,gBAAgBA,MAAE,OAAO;CAC7B,aAAaA,MACV,OACCA,MAAE,OAAO;EACP,iBAAiBA,MAAE,SAAS,CAAC,UAAU;EACvC,aAAaA,MAAE,QAAQ,CAAC,UAAU;CACnC,EAAC,CACH,CACA,QAAQ,CAAE,EAAC;CACd,eAAeA,MAAE,QAAQ,CAAC,QAAQ,mCAAmC;AACtE,EAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgJF,SAAgB,yBACdC,UAAyC,CAAE,GAC3C;AACA,QAAOC,oCAAiB;EACtB,MAAM;EACN;EACA,YAAY,OAAO,OAAO,SAAS,aAAa;GAC9C,MAAM,SAAS;IAAE,GAAG,cAAc,MAAM,QAAQ;IAAE,GAAG,QAAQ;GAAS;GACtE,MAAM,EAAE,UAAU,GAAG;AAErB,OAAI,CAAC,SAAS,OACZ;GAGF,MAAM,cAAc,SAAS,SAAS,SAAS;AAG/C,OAAI,4CAAa,YAAY,IAAI,CAAC,YAAY,YAAY,OACxD;GAIF,MAAMC,qBAAiC,CAAE;GACzC,MAAMC,wBAAoC,CAAE;AAE5C,QAAK,MAAM,YAAY,YAAY,YAAY;IAE7C,MAAMC,qBAA+B;KACnC,IAAI,SAAS,oBAAY;KACzB,MAAM,SAAS;KACf,MAAM,SAAS;IAChB;IAED,MAAM,aAAa,OAAO,YAAY,mBAAmB;AAEzD,QAAI,YAAY,iBACd,mBAAmB,KAAK,mBAAmB;SAE3C,sBAAsB,KAAK,mBAAmB;GAEjD;AAGD,O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+0,0 @@
|
|
|
1
|
-
{"version":3,"file":"hitl.d.cts","names":["z","contextSchema","ZodString","ZodBoolean","ZodOptional","ZodTypeAny","ZodObject","ZodRecord","ZodDefault","Record","humanInTheLoopMiddleware","input","___types_js1","AgentMiddleware"],"sources":["../../../../src/agents/middlewareAgent/middlewares/hitl.d.ts"],"sourcesContent":["import { z } from \"zod\";\ndeclare const contextSchema: z.ZodObject<{\n toolConfigs: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{\n requireApproval: z.ZodOptional<z.ZodBoolean>;\n description: z.ZodOptional<z.ZodString>;\n }, \"strip\", z.ZodTypeAny, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }>>>;\n messagePrefix: z.ZodDefault<z.ZodString>;\n}, \"strip\", z.ZodTypeAny, {\n toolConfigs: Record<string, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }>;\n messagePrefix: string;\n}, {\n toolConfigs?: Record<string, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }> | undefined;\n messagePrefix?: string | undefined;\n}>;\n/**\n * Creates a Human-in-the-Loop (HITL) middleware for tool approval and oversight.\n *\n * This middleware intercepts tool calls made by an AI agent and provides human oversight\n * capabilities before execution. It enables selective approval workflows where certain tools\n * require human intervention while others can execute automatically.\n *\n * ## Features\n *\n * - **Selective Tool Approval**: Configure which tools require human approval\n * - **Multiple Response Types**: Accept, edit, ignore, or manually respond to tool calls\n * - **Asynchronous Workflow**: Uses LangGraph's interrupt mechanism for non-blocking approval\n * - **Custom Approval Messages**: Provide context-specific descriptions for approval requests\n *\n * ## Response Types\n *\n * When a tool requires approval, the human operator can respond with:\n * - `accept`: Execute the tool with original arguments\n * - `edit`: Modify the tool arguments before execution\n * - `ignore`: Skip the tool and terminate the agent\n * - `response`: Provide a manual response instead of executing the tool\n *\n * @param options - Configuration options for the middleware\n * @param options.toolConfigs - Per-tool configuration mapping tool names to their settings\n * @param options.toolConfigs[toolName].requireApproval - Whether the tool requires human approval\n * @param options.toolConfigs[toolName].description - Custom approval message for the tool\n * @param options.messagePrefix - Default prefix for approval messages (default: \"Tool execution requires approval\")\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @example\n * Basic usage with selective tool approval\n * ```typescript\n * import { humanInTheLoopMiddleware } from \"langchain/middleware\";\n * import { createAgent } from \"langchain\";\n *\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * toolConfigs: {\n * \"write_file\": {\n * requireApproval: true,\n * description: \"⚠️ File write operation requires approval\"\n * },\n * \"read_file\": {\n * requireApproval: false // Safe operation, no approval needed\n * }\n * }\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4\",\n * tools: [writeFileTool, readFileTool],\n * middlewares: [hitlMiddleware]\n * });\n * ```\n *\n * @example\n * Handling approval requests\n * ```typescript\n * import { Command } from \"@langchain/langgraph\";\n *\n * // Initial agent invocation\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Write 'Hello' to output.txt\")]\n * }, config);\n *\n * // Check if agent is paused for approval\n * const state = await agent.graph.getState(config);\n * if (state.next?.length > 0) {\n * // Get interrupt details\n * const task = state.tasks?.[0];\n * const requests = task?.interrupts?.[0]?.value;\n *\n * // Show tool call details to user\n * console.log(\"Tool:\", requests[0].action);\n * console.log(\"Args:\", requests[0].args);\n *\n * // Resume with approval\n * await agent.invoke(\n * new Command({ resume: [{ type: \"accept\" }] }),\n * config\n * );\n * }\n * ```\n *\n * @example\n * Different response types\n * ```typescript\n * // Accept the tool call as-is\n * new Command({ resume: [{ type: \"accept\" }] })\n *\n * // Edit the tool arguments\n * new Command({\n * resume: [{\n * type: \"edit\",\n * args: { action: \"write_file\", args: { filename: \"safe.txt\", content: \"Modified\" } }\n * }]\n * })\n *\n * // Skip tool and terminate agent\n * new Command({ resume: [{ type: \"ignore\" }] })\n *\n * // Provide manual response\n * new Command({\n * resume: [{\n * type: \"response\",\n * args: \"File operation not allowed in demo mode\"\n * }]\n * })\n * ```\n *\n * @example\n * Production use case with database operations\n * ```typescript\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * toolConfigs: {\n * \"execute_sql\": {\n * requireApproval: true,\n * description: \"🚨 SQL query requires DBA approval\\nPlease review for safety and performance\"\n * },\n * \"read_schema\": {\n * requireApproval: false // Reading metadata is safe\n * },\n * \"delete_records\": {\n * requireApproval: true,\n * description: \"⛔ DESTRUCTIVE OPERATION - Requires manager approval\"\n * }\n * },\n * messagePrefix: \"Database operation pending approval\"\n * });\n * ```\n *\n * @remarks\n * - Tool calls are processed in the order they appear in the AI message\n * - Auto-approved tools execute immediately without interruption\n * - Multiple tools requiring approval are bundled into a single interrupt\n * - The middleware operates in the `afterModel` phase, intercepting before tool execution\n * - Requires a checkpointer to maintain state across interruptions\n *\n * @see {@link createAgent} for agent creation\n * @see {@link Command} for resuming interrupted execution\n * @public\n */\nexport declare function humanInTheLoopMiddleware(options?: z.input<typeof contextSchema>): import(\"../types.js\").AgentMiddleware<undefined, z.ZodObject<{\n toolConfigs: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{\n requireApproval: z.ZodOptional<z.ZodBoolean>;\n description: z.ZodOptional<z.ZodString>;\n }, \"strip\", z.ZodTypeAny, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }>>>;\n messagePrefix: z.ZodDefault<z.ZodString>;\n}, \"strip\", z.ZodTypeAny, {\n toolConfigs: Record<string, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }>;\n messagePrefix: string;\n}, {\n toolConfigs?: Record<string, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }> | undefined;\n messagePrefix?: string | undefined;\n}>, any>;\nexport {};\n"],"mappings":";;;;cACcC,eAAeD,CAAAA,CAAEM;eACdN,CAAAA,CAAEQ,WAAWR,CAAAA,CAAEO,UAAUP,CAAAA,CAAEE,WAAWF,CAAAA,CAAEM;qBAChCN,CAAA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CV,CAAAA,CAAEW,aAAaV,iBAA6E,2BAAXD,CAAAA,CAAEM;eAC7HN,CAAAA,CAAEQ,WAAWR,CAAAA,CAAEO,UAAUP,CAAAA,CAAEE,WAAWF,CAAAA,CAAEM;qBAChCN,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEG;iBACpBH,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEE;cACrBF,CAAAA,CAAEK;;;;;;;iBAOCL,CAAAA,CAAEQ,WAAWR,CAAAA,CAAEE;YACtBF,CAAAA,CAAEK;eACGI;;;;;;gBAMCA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"hitl.d.ts","names":["z","contextSchema","ZodString","ZodBoolean","ZodOptional","ZodTypeAny","ZodObject","ZodRecord","ZodDefault","Record","humanInTheLoopMiddleware","input","___types_js1","AgentMiddleware"],"sources":["../../../../src/agents/middlewareAgent/middlewares/hitl.d.ts"],"sourcesContent":["import { z } from \"zod\";\ndeclare const contextSchema: z.ZodObject<{\n toolConfigs: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{\n requireApproval: z.ZodOptional<z.ZodBoolean>;\n description: z.ZodOptional<z.ZodString>;\n }, \"strip\", z.ZodTypeAny, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }>>>;\n messagePrefix: z.ZodDefault<z.ZodString>;\n}, \"strip\", z.ZodTypeAny, {\n toolConfigs: Record<string, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }>;\n messagePrefix: string;\n}, {\n toolConfigs?: Record<string, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }> | undefined;\n messagePrefix?: string | undefined;\n}>;\n/**\n * Creates a Human-in-the-Loop (HITL) middleware for tool approval and oversight.\n *\n * This middleware intercepts tool calls made by an AI agent and provides human oversight\n * capabilities before execution. It enables selective approval workflows where certain tools\n * require human intervention while others can execute automatically.\n *\n * ## Features\n *\n * - **Selective Tool Approval**: Configure which tools require human approval\n * - **Multiple Response Types**: Accept, edit, ignore, or manually respond to tool calls\n * - **Asynchronous Workflow**: Uses LangGraph's interrupt mechanism for non-blocking approval\n * - **Custom Approval Messages**: Provide context-specific descriptions for approval requests\n *\n * ## Response Types\n *\n * When a tool requires approval, the human operator can respond with:\n * - `accept`: Execute the tool with original arguments\n * - `edit`: Modify the tool arguments before execution\n * - `ignore`: Skip the tool and terminate the agent\n * - `response`: Provide a manual response instead of executing the tool\n *\n * @param options - Configuration options for the middleware\n * @param options.toolConfigs - Per-tool configuration mapping tool names to their settings\n * @param options.toolConfigs[toolName].requireApproval - Whether the tool requires human approval\n * @param options.toolConfigs[toolName].description - Custom approval message for the tool\n * @param options.messagePrefix - Default prefix for approval messages (default: \"Tool execution requires approval\")\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @example\n * Basic usage with selective tool approval\n * ```typescript\n * import { humanInTheLoopMiddleware } from \"langchain/middleware\";\n * import { createAgent } from \"langchain\";\n *\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * toolConfigs: {\n * \"write_file\": {\n * requireApproval: true,\n * description: \"⚠️ File write operation requires approval\"\n * },\n * \"read_file\": {\n * requireApproval: false // Safe operation, no approval needed\n * }\n * }\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4\",\n * tools: [writeFileTool, readFileTool],\n * middlewares: [hitlMiddleware]\n * });\n * ```\n *\n * @example\n * Handling approval requests\n * ```typescript\n * import { Command } from \"@langchain/langgraph\";\n *\n * // Initial agent invocation\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Write 'Hello' to output.txt\")]\n * }, config);\n *\n * // Check if agent is paused for approval\n * const state = await agent.graph.getState(config);\n * if (state.next?.length > 0) {\n * // Get interrupt details\n * const task = state.tasks?.[0];\n * const requests = task?.interrupts?.[0]?.value;\n *\n * // Show tool call details to user\n * console.log(\"Tool:\", requests[0].action);\n * console.log(\"Args:\", requests[0].args);\n *\n * // Resume with approval\n * await agent.invoke(\n * new Command({ resume: [{ type: \"accept\" }] }),\n * config\n * );\n * }\n * ```\n *\n * @example\n * Different response types\n * ```typescript\n * // Accept the tool call as-is\n * new Command({ resume: [{ type: \"accept\" }] })\n *\n * // Edit the tool arguments\n * new Command({\n * resume: [{\n * type: \"edit\",\n * args: { action: \"write_file\", args: { filename: \"safe.txt\", content: \"Modified\" } }\n * }]\n * })\n *\n * // Skip tool and terminate agent\n * new Command({ resume: [{ type: \"ignore\" }] })\n *\n * // Provide manual response\n * new Command({\n * resume: [{\n * type: \"response\",\n * args: \"File operation not allowed in demo mode\"\n * }]\n * })\n * ```\n *\n * @example\n * Production use case with database operations\n * ```typescript\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * toolConfigs: {\n * \"execute_sql\": {\n * requireApproval: true,\n * description: \"🚨 SQL query requires DBA approval\\nPlease review for safety and performance\"\n * },\n * \"read_schema\": {\n * requireApproval: false // Reading metadata is safe\n * },\n * \"delete_records\": {\n * requireApproval: true,\n * description: \"⛔ DESTRUCTIVE OPERATION - Requires manager approval\"\n * }\n * },\n * messagePrefix: \"Database operation pending approval\"\n * });\n * ```\n *\n * @remarks\n * - Tool calls are processed in the order they appear in the AI message\n * - Auto-approved tools execute immediately without interruption\n * - Multiple tools requiring approval are bundled into a single interrupt\n * - The middleware operates in the `afterModel` phase, intercepting before tool execution\n * - Requires a checkpointer to maintain state across interruptions\n *\n * @see {@link createAgent} for agent creation\n * @see {@link Command} for resuming interrupted execution\n * @public\n */\nexport declare function humanInTheLoopMiddleware(options?: z.input<typeof contextSchema>): import(\"../types.js\").AgentMiddleware<undefined, z.ZodObject<{\n toolConfigs: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{\n requireApproval: z.ZodOptional<z.ZodBoolean>;\n description: z.ZodOptional<z.ZodString>;\n }, \"strip\", z.ZodTypeAny, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }>>>;\n messagePrefix: z.ZodDefault<z.ZodString>;\n}, \"strip\", z.ZodTypeAny, {\n toolConfigs: Record<string, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }>;\n messagePrefix: string;\n}, {\n toolConfigs?: Record<string, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }> | undefined;\n messagePrefix?: string | undefined;\n}>, any>;\nexport {};\n"],"mappings":";;;;cACcC,eAAeD,CAAAA,CAAEM;eACdN,CAAAA,CAAEQ,WAAWR,CAAAA,CAAEO,UAAUP,CAAAA,CAAEE,WAAWF,CAAAA,CAAEM;qBAChCN,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEG;IAF3BF,WAAAA,EAGOD,CAAAA,CAAEI,WAqBrB,CArBiCJ,CAAAA,CAAEE,SAqBnC,CAAA;EAAA,CAAA,EAAA,OAAA,EApBcF,CAAAA,CAAEK,UAoBhB,EAAA;IAvBwCL,eAAEE,CAAAA,EAAAA,OAAAA,GAAAA,SAAAA;IACLF,WAAEG,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAU,CAAA,EAA1BH;IACUA,eAAEE,CAAAA,EAAAA,OAAAA,GAAAA,SAAAA;IAAhBF,WAAEI,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAW,CAAA,CAAA,CAClBJ,CAAAA;EAAY,aAH6BM,EAUtCN,CAAAA,CAAEQ,UAVoCF,CAUzBN,CAAAA,CAAEE,SAVuBI,CAAAA;CAAS,EAAA,OAAlCC,EAWpBP,CAAAA,CAAEK,UAXkBE,EAAAA;EAAS,WAAtBC,EAYFC,MAZED,CAAAA,MAAAA,EAAAA;IAUaR,eAAEE,CAAAA,EAAAA,OAAAA,GAAAA,SAAAA;IAAfF,WAAEQ,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAU,CAAA,CAAA;EACP,aACPC,EAAAA,MAAAA;CAAM,EAAA;EAMC,WAnBOH,CAAAA,EAmBbG,MAnBaH,CAAAA,MAAAA,EAAAA;IAAS,eAAA,CAAA,EAAA,OAAA,GAAA,SAAA;IAuKhBI,WAAAA,CAAAA,EAAAA,MAAAA,GAAwB,SAAA;EAAA,CAAA,CAAA,GAAA,SAAA;EAAA,aAA0BT,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;CAAa,CAAA;;;;;;;;;;;;;;;;;AAAyC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAxGS,wBAAAA,WAAmCV,CAAAA,CAAEW,aAAaV,iBAA6E,2BAAXD,CAAAA,CAAEM;eAC7HN,CAAAA,CAAEQ,WAAWR,CAAAA,CAAEO,UAAUP,CAAAA,CAAEE,WAAWF,CAAAA,CAAEM;qBAChCN,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEG;iBACpBH,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEE;cACrBF,CAAAA,CAAEK;;;;;;;iBAOCL,CAAAA,CAAEQ,WAAWR,CAAAA,CAAEE;YACtBF,CAAAA,CAAEK;eACGI;;;;;;gBAMCA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"hitl.js","names":["options: z.input<typeof contextSchema>","interruptToolCalls: ToolCall[]","autoApprovedToolCalls: ToolCall[]","normalizedToolCall: ToolCall","uuid","requests: ToolApprovalRequest[]"],"sources":["../../../../src/agents/middlewareAgent/middlewares/hitl.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { v4 as uuid } from \"uuid\";\nimport { AIMessage, ToolMessage, isAIMessage } from \"@langchain/core/messages\";\nimport { interrupt } from \"@langchain/langgraph\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport type { ToolCall } from \"../types.js\";\nimport { HumanResponse } from \"../../interrupt.js\";\n\n/**\n * Interrupt request for tool approval\n */\ninterface ToolApprovalRequest {\n action: string;\n args: Record<string, any>;\n toolCallId: string;\n description?: string;\n}\n\nconst contextSchema = z.object({\n toolConfigs: z\n .record(\n z.object({\n requireApproval: z.boolean().optional(),\n description: z.string().optional(),\n })\n )\n .default({}),\n messagePrefix: z.string().default(\"Tool execution requires approval\"),\n});\n\n/**\n * Creates a Human-in-the-Loop (HITL) middleware for tool approval and oversight.\n *\n * This middleware intercepts tool calls made by an AI agent and provides human oversight\n * capabilities before execution. It enables selective approval workflows where certain tools\n * require human intervention while others can execute automatically.\n *\n * ## Features\n *\n * - **Selective Tool Approval**: Configure which tools require human approval\n * - **Multiple Response Types**: Accept, edit, ignore, or manually respond to tool calls\n * - **Asynchronous Workflow**: Uses LangGraph's interrupt mechanism for non-blocking approval\n * - **Custom Approval Messages**: Provide context-specific descriptions for approval requests\n *\n * ## Response Types\n *\n * When a tool requires approval, the human operator can respond with:\n * - `accept`: Execute the tool with original arguments\n * - `edit`: Modify the tool arguments before execution\n * - `ignore`: Skip the tool and terminate the agent\n * - `response`: Provide a manual response instead of executing the tool\n *\n * @param options - Configuration options for the middleware\n * @param options.toolConfigs - Per-tool configuration mapping tool names to their settings\n * @param options.toolConfigs[toolName].requireApproval - Whether the tool requires human approval\n * @param options.toolConfigs[toolName].description - Custom approval message for the tool\n * @param options.messagePrefix - Default prefix for approval messages (default: \"Tool execution requires approval\")\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @example\n * Basic usage with selective tool approval\n * ```typescript\n * import { humanInTheLoopMiddleware } from \"langchain/middleware\";\n * import { createAgent } from \"langchain\";\n *\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * toolConfigs: {\n * \"write_file\": {\n * requireApproval: true,\n * description: \"⚠️ File write operation requires approval\"\n * },\n * \"read_file\": {\n * requireApproval: false // Safe operation, no approval needed\n * }\n * }\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4\",\n * tools: [writeFileTool, readFileTool],\n * middlewares: [hitlMiddleware]\n * });\n * ```\n *\n * @example\n * Handling approval requests\n * ```typescript\n * import { Command } from \"@langchain/langgraph\";\n *\n * // Initial agent invocation\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Write 'Hello' to output.txt\")]\n * }, config);\n *\n * // Check if agent is paused for approval\n * const state = await agent.graph.getState(config);\n * if (state.next?.length > 0) {\n * // Get interrupt details\n * const task = state.tasks?.[0];\n * const requests = task?.interrupts?.[0]?.value;\n *\n * // Show tool call details to user\n * console.log(\"Tool:\", requests[0].action);\n * console.log(\"Args:\", requests[0].args);\n *\n * // Resume with approval\n * await agent.invoke(\n * new Command({ resume: [{ type: \"accept\" }] }),\n * config\n * );\n * }\n * ```\n *\n * @example\n * Different response types\n * ```typescript\n * // Accept the tool call as-is\n * new Command({ resume: [{ type: \"accept\" }] })\n *\n * // Edit the tool arguments\n * new Command({\n * resume: [{\n * type: \"edit\",\n * args: { action: \"write_file\", args: { filename: \"safe.txt\", content: \"Modified\" } }\n * }]\n * })\n *\n * // Skip tool and terminate agent\n * new Command({ resume: [{ type: \"ignore\" }] })\n *\n * // Provide manual response\n * new Command({\n * resume: [{\n * type: \"response\",\n * args: \"File operation not allowed in demo mode\"\n * }]\n * })\n * ```\n *\n * @example\n * Production use case with database operations\n * ```typescript\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * toolConfigs: {\n * \"execute_sql\": {\n * requireApproval: true,\n * description: \"🚨 SQL query requires DBA approval\\nPlease review for safety and performance\"\n * },\n * \"read_schema\": {\n * requireApproval: false // Reading metadata is safe\n * },\n * \"delete_records\": {\n * requireApproval: true,\n * description: \"⛔ DESTRUCTIVE OPERATION - Requires manager approval\"\n * }\n * },\n * messagePrefix: \"Database operation pending approval\"\n * });\n * ```\n *\n * @remarks\n * - Tool calls are processed in the order they appear in the AI message\n * - Auto-approved tools execute immediately without interruption\n * - Multiple tools requiring approval are bundled into a single interrupt\n * - The middleware operates in the `afterModel` phase, intercepting before tool execution\n * - Requires a checkpointer to maintain state across interruptions\n *\n * @see {@link createAgent} for agent creation\n * @see {@link Command} for resuming interrupted execution\n * @public\n */\nexport function humanInTheLoopMiddleware(\n options: z.input<typeof contextSchema> = {}\n) {\n return createMiddleware({\n name: \"HumanInTheLoopMiddleware\",\n contextSchema,\n afterModel: async (state, runtime, controls) => {\n const config = { ...contextSchema.parse(options), ...runtime.context };\n const { messages } = state;\n\n if (!messages.length) {\n return;\n }\n\n const lastMessage = messages[messages.length - 1];\n\n // Check if it's an AI message with tool calls\n if (!isAIMessage(lastMessage) || !lastMessage.tool_calls?.length) {\n return;\n }\n\n // Separate tool calls that need interrupts from those that don't\n const interruptToolCalls: ToolCall[] = [];\n const autoApprovedToolCalls: ToolCall[] = [];\n\n for (const toolCall of lastMessage.tool_calls) {\n // Ensure tool call has an ID\n const normalizedToolCall: ToolCall = {\n id: toolCall.id || uuid(),\n name: toolCall.name,\n args: toolCall.args,\n };\n\n const toolConfig = config.toolConfigs[normalizedToolCall.name];\n\n if (toolConfig?.requireApproval) {\n interruptToolCalls.push(normalizedToolCall);\n } else {\n autoApprovedToolCalls.push(normalizedToolCall);\n }\n }\n\n // If no interrupts needed, return early\n if (!interruptToolCalls.length) {\n return;\n }\n\n const approvedToolCalls = [...autoApprovedToolCalls];\n\n // Process tool calls that need interrupts\n const requests: ToolApprovalRequest[] = interruptToolCalls.map(\n (toolCall) => {\n const toolConfig = config.toolConfigs[toolCall.name];\n const description =\n toolConfig?.description ||\n `${config.messagePrefix}\\n\\nTool: ${\n toolCall.name\n }\\nArgs: ${JSON.stringify(toolCall.args, null, 2)}`;\n\n return {\n action: toolCall.name,\n args: toolCall.args,\n toolCallId: toolCall.id,\n description,\n };\n }\n );\n\n // Interrupt and wait for human responses\n const responses = (await interrupt(requests)) as HumanResponse[];\n\n // Process responses\n for (let i = 0; i < responses.length; i++) {\n const response = responses[i];\n const toolCall = interruptToolCalls[i];\n\n switch (response.type) {\n case \"accept\":\n approvedToolCalls.push(toolCall);\n break;\n\n case \"edit\":\n // For edit, args is an ActionRequest with updated args\n if (\n response.args &&\n typeof response.args === \"object\" &&\n \"args\" in response.args\n ) {\n approvedToolCalls.push({\n ...toolCall,\n args: (\n response.args as { action: string; args: Record<string, any> }\n ).args,\n });\n }\n break;\n\n case \"ignore\":\n // Skip to end - terminate the agent\n return controls.terminate();\n\n case \"response\": {\n // Return manual tool response and jump back to model\n // For response, args is a string\n const toolMessage = new ToolMessage({\n content: typeof response.args === \"string\" ? response.args : \"\",\n tool_call_id: toolCall.id,\n });\n return {\n messages: [...state.messages, toolMessage],\n jump_to: \"model\",\n };\n }\n default:\n throw new Error(`Unknown response type: ${(response as any).type}`);\n }\n }\n\n // Update the last message with approved tool calls\n const updatedMessage = new AIMessage({\n content: lastMessage.content,\n tool_calls: approvedToolCalls,\n id: lastMessage.id,\n });\n\n // Replace the last message with the updated one\n return {\n messages: [...state.messages.slice(0, -1), updatedMessage],\n };\n },\n });\n}\n"],"mappings":";;;;;;;AAmBA,MAAM,gBAAgB,EAAE,OAAO;CAC7B,aAAa,EACV,OACC,EAAE,OAAO;EACP,iBAAiB,EAAE,SAAS,CAAC,UAAU;EACvC,aAAa,EAAE,QAAQ,CAAC,UAAU;CACnC,EAAC,CACH,CACA,QAAQ,CAAE,EAAC;CACd,eAAe,EAAE,QAAQ,CAAC,QAAQ,mCAAmC;AACtE,EAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgJF,SAAgB,yBACdA,UAAyC,CAAE,GAC3C;AACA,QAAO,iBAAiB;EACtB,MAAM;EACN;EACA,YAAY,OAAO,OAAO,SAAS,aAAa;GAC9C,MAAM,SAAS;IAAE,GAAG,cAAc,MAAM,QAAQ;IAAE,GAAG,QAAQ;GAAS;GACtE,MAAM,EAAE,UAAU,GAAG;AAErB,OAAI,CAAC,SAAS,OACZ;GAGF,MAAM,cAAc,SAAS,SAAS,SAAS;AAG/C,OAAI,CA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AS;MACxB;AACD,aAAO;OACL,UAAU,CAAC,GAAG,MAAM,UAAU,WAAY;OAC1C,SAAS;MACV;KACF;KACD,QACE,OAAM,IAAI,MAAM,CAAC,uBAAuB,EAAG,SAAiB,MAAM;IACrE;GACF;GAGD,MAAM,iBAAiB,IAAI,UAAU;IACnC,SAAS,YAAY;IACrB,YAAY;IACZ,IAAI,YAAY;GACjB;AAGD,UAAO,EACL,UAAU,CAAC,GAAG,MAAM,SAAS,MAAM,GAAG,GAAG,EAAE,cAAe,EAC3D;EACF;CACF,EAAC;AACH"}
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
const require_summarization = require('./summarization.cjs');
|
|
2
|
-
const require_hitl = require('./hitl.cjs');
|
|
3
|
-
const require_promptCaching = require('./promptCaching.cjs');
|
|
4
|
-
|
|
5
|
-
exports.anthropicPromptCachingMiddleware = require_promptCaching.anthropicPromptCachingMiddleware;
|
|
6
|
-
exports.countTokensApproximately = require_summarization.countTokensApproximately;
|
|
7
|
-
exports.humanInTheLoopMiddleware = require_hitl.humanInTheLoopMiddleware;
|
|
8
|
-
exports.summarizationMiddleware = require_summarization.summarizationMiddleware;
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import { countTokensApproximately, summarizationMiddleware } from "./summarization.js";
|
|
2
|
-
import { humanInTheLoopMiddleware } from "./hitl.js";
|
|
3
|
-
import { anthropicPromptCachingMiddleware } from "./promptCaching.js";
|
|
4
|
-
|
|
5
|
-
export { anthropicPromptCachingMiddleware, countTokensApproximately, humanInTheLoopMiddleware, summarizationMiddleware };
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"promptCaching.cjs","names":["z","middlewareOptions?: Partial<z.infer<typeof contextSchema>>","createMiddleware"],"sources":["../../../../src/agents/middlewareAgent/middlewares/promptCaching.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { createMiddleware } from \"../middleware.js\";\n\nconst contextSchema = z.object({\n // Configuration options\n enableCaching: z.boolean().default(true),\n ttl: z.enum([\"5m\", \"1h\"]).default(\"5m\"),\n minMessagesToCache: z.number().default(3),\n});\n\n/**\n * Creates a prompt caching middleware for Anthropic models to optimize API usage.\n *\n * This middleware automatically adds cache control headers to messages when using Anthropic models,\n * enabling their prompt caching feature. This can significantly reduce costs and latency for\n * applications with repetitive prompts, long system messages, or extensive conversation histories.\n *\n * ## How It Works\n *\n * The middleware intercepts model requests and adds cache control metadata that tells Anthropic's\n * API to cache processed prompt prefixes. On subsequent requests with matching prefixes, the\n * cached representations are reused, skipping redundant token processing.\n *\n * ## Benefits\n *\n * - **Cost Reduction**: Avoid reprocessing the same tokens repeatedly (up to 90% savings on cached portions)\n * - **Lower Latency**: Cached prompts are processed faster as embeddings are pre-computed\n * - **Better Scalability**: Reduced computational load enables handling more requests\n * - **Consistent Performance**: Stable response times for repetitive queries\n *\n * @param middlewareOptions - Configuration options for the caching behavior\n * @param middlewareOptions.enableCaching - Whether to enable prompt caching (default: `true`)\n * @param middlewareOptions.ttl - Cache time-to-live: `\"5m\"` for 5 minutes or `\"1h\"` for 1 hour (default: `\"5m\"`)\n * @param middlewareOptions.minMessagesToCache - Minimum number of messages required before caching is applied (default: `3`)\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @throws {Error} If used with non-Anthropic models\n *\n * @example\n * Basic usage with default settings\n * ```typescript\n * import { createAgent } from \"langchain\";\n * import { anthropicPromptCachingMiddleware } from \"langchain/middleware\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * middlewares: [\n * anthropicPromptCachingMiddleware()\n * ]\n * });\n * ```\n *\n * @example\n * Custom configuration for longer conversations\n * ```typescript\n * const cachingMiddleware = anthropicPromptCachingMiddleware({\n * ttl: \"1h\", // Cache for 1 hour instead of default 5 minutes\n * minMessagesToCache: 5 // Only cache after 5 messages\n * });\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemMessage: \"You are a helpful assistant with deep knowledge of...\", // Long system prompt\n * middlewares: [cachingMiddleware]\n * });\n * ```\n *\n * @example\n * Conditional caching based on runtime context\n * ```typescript\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * middlewares: [\n * anthropicPromptCachingMiddleware({\n * enableCaching: true,\n * ttl: \"5m\"\n * })\n * ]\n * });\n *\n * // Disable caching for specific requests\n * await agent.invoke(\n * { messages: [new HumanMessage(\"Process this without caching\")] },\n * {\n * configurable: {\n * middleware_context: { enableCaching: false }\n * }\n * }\n * );\n * ```\n *\n * @example\n * Optimal setup for customer support chatbot\n * ```typescript\n * const supportAgent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemMessage: `You are a customer support agent for ACME Corp.\n *\n * Company policies:\n * - Always be polite and professional\n * - Refer to knowledge base for product information\n * - Escalate billing issues to human agents\n * ... (extensive policies and guidelines)\n * `,\n * tools: [searchKnowledgeBase, createTicket, checkOrderStatus],\n * middlewares: [\n * anthropicPromptCachingMiddleware({\n * ttl: \"1h\", // Long TTL for stable system prompt\n * minMessagesToCache: 1 // Cache immediately due to large system prompt\n * })\n * ]\n * });\n * ```\n *\n * @remarks\n * - **Anthropic Only**: This middleware only works with Anthropic models and will throw an error if used with other providers\n * - **Automatic Application**: Caching is applied automatically when message count exceeds `minMessagesToCache`\n * - **Cache Scope**: Caches are isolated per API key and cannot be shared across different keys\n * - **TTL Options**: Only supports \"5m\" (5 minutes) and \"1h\" (1 hour) as TTL values per Anthropic's API\n * - **Best Use Cases**: Long system prompts, multi-turn conversations, repetitive queries, RAG applications\n * - **Cost Impact**: Cached tokens are billed at 10% of the base input token price, cache writes are billed at 25% of the base\n *\n * @see {@link createAgent} for agent creation\n * @see {@link https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching} Anthropic's prompt caching documentation\n * @public\n */\nexport function anthropicPromptCachingMiddleware(\n middlewareOptions?: Partial<z.infer<typeof contextSchema>>\n) {\n return createMiddleware({\n name: \"PromptCachingMiddleware\",\n contextSchema,\n prepareModelRequest: (options, state, runtime) => {\n const enableCaching =\n runtime.context.enableCaching ?? middlewareOptions?.enableCaching;\n const ttl = runtime.context.ttl ?? middlewareOptions?.ttl;\n const minMessagesToCache =\n runtime.context.minMessagesToCache ??\n middlewareOptions?.minMessagesToCache;\n\n // Skip if caching is disabled\n if (!enableCaching) {\n return undefined;\n }\n\n if (options.model?.getName() !== \"anthropic\") {\n throw new Error(\n \"Prompt caching is only supported for Anthropic models\"\n );\n }\n\n const messagesCount =\n state.messages.length + (options.systemMessage ? 1 : 0);\n\n if (messagesCount < minMessagesToCache) {\n return options;\n }\n\n return {\n ...options,\n modelSettings: {\n cache_control: {\n type: \"ephemeral\",\n ttl,\n },\n },\n };\n },\n });\n}\n"],"mappings":";;;;;AAGA,MAAM,gBAAgBA,MAAE,OAAO;CAE7B,eAAeA,MAAE,SAAS,CAAC,QAAQ,KAAK;CACxC,KAAKA,MAAE,KAAK,CAAC,MAAM,IAAK,EAAC,CAAC,QAAQ,KAAK;CACvC,oBAAoBA,MAAE,QAAQ,CAAC,QAAQ,EAAE;AAC1C,EAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuHF,SAAgB,iCACdC,mBACA;AACA,QAAOC,oCAAiB;EACtB,MAAM;EACN;EACA,qBAAqB,CAAC,SAAS,OAAO,YAAY;GAChD,MAAM,gBACJ,QAAQ,QAAQ,iBAAiB,mBAAmB;GACtD,MAAM,MAAM,QAAQ,QAAQ,OAAO,mBAAmB;GACtD,MAAM,qBACJ,QAAQ,QAAQ,sBAChB,mBAAmB;AAGrB,OAAI,CAAC,cACH,QAAO;AAGT,OAAI,QAAQ,OAAO,SAAS,KAAK,YAC/B,OAAM,IAAI,MACR;GAIJ,MAAM,gBACJ,MAAM,SAAS,UAAU,QAAQ,gBAAgB,IAAI;AAEvD,OAAI,gBAAgB,mBAClB,QAAO;AAGT,UAAO;IACL,GAAG;IACH,eAAe,EACb,eAAe;KACb,MAAM;KACN;IACD,EACF;GACF;EACF;CACF,EAAC;AACH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"promptCaching.d.cts","names":["z","contextSchema","ZodBoolean","ZodDefault","ZodEnum","ZodNumber","ZodTypeAny","ZodObject","anthropicPromptCachingMiddleware","infer","Partial","___types_js0","AgentMiddleware"],"sources":["../../../../src/agents/middlewareAgent/middlewares/promptCaching.d.ts"],"sourcesContent":["import { z } from \"zod\";\ndeclare const contextSchema: z.ZodObject<{\n // Configuration options\n enableCaching: z.ZodDefault<z.ZodBoolean>;\n ttl: z.ZodDefault<z.ZodEnum<[\"5m\", \"1h\"]>>;\n minMessagesToCache: z.ZodDefault<z.ZodNumber>;\n}, \"strip\", z.ZodTypeAny, {\n enableCaching: boolean;\n ttl: \"1h\" | \"5m\";\n minMessagesToCache: number;\n}, {\n enableCaching?: boolean | undefined;\n ttl?: \"1h\" | \"5m\" | undefined;\n minMessagesToCache?: number | undefined;\n}>;\n/**\n * Creates a prompt caching middleware for Anthropic models to optimize API usage.\n *\n * This middleware automatically adds cache control headers to messages when using Anthropic models,\n * enabling their prompt caching feature. This can significantly reduce costs and latency for\n * applications with repetitive prompts, long system messages, or extensive conversation histories.\n *\n * ## How It Works\n *\n * The middleware intercepts model requests and adds cache control metadata that tells Anthropic's\n * API to cache processed prompt prefixes. On subsequent requests with matching prefixes, the\n * cached representations are reused, skipping redundant token processing.\n *\n * ## Benefits\n *\n * - **Cost Reduction**: Avoid reprocessing the same tokens repeatedly (up to 90% savings on cached portions)\n * - **Lower Latency**: Cached prompts are processed faster as embeddings are pre-computed\n * - **Better Scalability**: Reduced computational load enables handling more requests\n * - **Consistent Performance**: Stable response times for repetitive queries\n *\n * @param middlewareOptions - Configuration options for the caching behavior\n * @param middlewareOptions.enableCaching - Whether to enable prompt caching (default: `true`)\n * @param middlewareOptions.ttl - Cache time-to-live: `\"5m\"` for 5 minutes or `\"1h\"` for 1 hour (default: `\"5m\"`)\n * @param middlewareOptions.minMessagesToCache - Minimum number of messages required before caching is applied (default: `3`)\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @throws {Error} If used with non-Anthropic models\n *\n * @example\n * Basic usage with default settings\n * ```typescript\n * import { createAgent } from \"langchain\";\n * import { anthropicPromptCachingMiddleware } from \"langchain/middleware\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * middlewares: [\n * anthropicPromptCachingMiddleware()\n * ]\n * });\n * ```\n *\n * @example\n * Custom configuration for longer conversations\n * ```typescript\n * const cachingMiddleware = anthropicPromptCachingMiddleware({\n * ttl: \"1h\", // Cache for 1 hour instead of default 5 minutes\n * minMessagesToCache: 5 // Only cache after 5 messages\n * });\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemMessage: \"You are a helpful assistant with deep knowledge of...\", // Long system prompt\n * middlewares: [cachingMiddleware]\n * });\n * ```\n *\n * @example\n * Conditional caching based on runtime context\n * ```typescript\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * middlewares: [\n * anthropicPromptCachingMiddleware({\n * enableCaching: true,\n * ttl: \"5m\"\n * })\n * ]\n * });\n *\n * // Disable caching for specific requests\n * await agent.invoke(\n * { messages: [new HumanMessage(\"Process this without caching\")] },\n * {\n * configurable: {\n * middleware_context: { enableCaching: false }\n * }\n * }\n * );\n * ```\n *\n * @example\n * Optimal setup for customer support chatbot\n * ```typescript\n * const supportAgent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemMessage: `You are a customer support agent for ACME Corp.\n *\n * Company policies:\n * - Always be polite and professional\n * - Refer to knowledge base for product information\n * - Escalate billing issues to human agents\n * ... (extensive policies and guidelines)\n * `,\n * tools: [searchKnowledgeBase, createTicket, checkOrderStatus],\n * middlewares: [\n * anthropicPromptCachingMiddleware({\n * ttl: \"1h\", // Long TTL for stable system prompt\n * minMessagesToCache: 1 // Cache immediately due to large system prompt\n * })\n * ]\n * });\n * ```\n *\n * @remarks\n * - **Anthropic Only**: This middleware only works with Anthropic models and will throw an error if used with other providers\n * - **Automatic Application**: Caching is applied automatically when message count exceeds `minMessagesToCache`\n * - **Cache Scope**: Caches are isolated per API key and cannot be shared across different keys\n * - **TTL Options**: Only supports \"5m\" (5 minutes) and \"1h\" (1 hour) as TTL values per Anthropic's API\n * - **Best Use Cases**: Long system prompts, multi-turn conversations, repetitive queries, RAG applications\n * - **Cost Impact**: Cached tokens are billed at 10% of the base input token price, cache writes are billed at 25% of the base\n *\n * @see {@link createAgent} for agent creation\n * @see {@link https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching} Anthropic's prompt caching documentation\n * @public\n */\nexport declare function anthropicPromptCachingMiddleware(middlewareOptions?: Partial<z.infer<typeof contextSchema>>): import(\"../types.js\").AgentMiddleware<undefined, z.ZodObject<{\n // Configuration options\n enableCaching: z.ZodDefault<z.ZodBoolean>;\n ttl: z.ZodDefault<z.ZodEnum<[\"5m\", \"1h\"]>>;\n minMessagesToCache: z.ZodDefault<z.ZodNumber>;\n}, \"strip\", z.ZodTypeAny, {\n enableCaching: boolean;\n ttl: \"1h\" | \"5m\";\n minMessagesToCache: number;\n}, {\n enableCaching?: boolean | undefined;\n ttl?: \"1h\" | \"5m\" | undefined;\n minMessagesToCache?: number | undefined;\n}>, any>;\nexport {};\n"],"mappings":";;;;cACcC,eAAeD,CAAAA,CAAEO;;iBAEZP,CAAAA,CAAEG,WAAWH,CAAAA,CAAEE;EAFpBD,GAAAA,EAGLD,CAAAA,CAAEG,UAUT,CAVoBH,CAAAA,CAAEI,OAUtB,CAAA,CAAA,IAAA,EAAA,IAAA,CAAA,CAAA,CAAA;EAAA,kBAAA,EATsBJ,CAAAA,CAAEG,UASxB,CATmCH,CAAAA,CAAEK,SASrC,CAAA;CAAA,EAAA,OAXgCH,EAGtBF,CAAAA,CAAEM,UAHoBJ,EAAAA;EAAU,aAAvBC,EAAAA,OAAAA;EAAU,GACTH,EAAEI,IAAAA,GAAAA,IAAAA;EAAO,kBAApBD,EAAAA,MAAAA;CAAU,EAAA;EAC2B,aAAtBA,CAAAA,EAAAA,OAAAA,GAAAA,SAAAA;EAAU,GACxBH,CAAAA,EAAEM,IAAAA,GAAAA,IAAAA,GAAAA,SAAAA;EAAU,kBALOC,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;AAAS,CAAA,CAAA;AAmIxC;;;;;;;;;;;;;;AAA2J;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAnIC,gCAAAA,qBAAqDE,QAAQV,CAAAA,CAAES,aAAaR,kBAA8E,2BAAXD,CAAAA,CAAEO;;iBAEtJP,CAAAA,CAAEG,WAAWH,CAAAA,CAAEE;OACzBF,CAAAA,CAAEG,WAAWH,CAAAA,CAAEI;sBACAJ,CAAAA,CAAEG,WAAWH,CAAAA,CAAEK;YAC3BL,CAAAA,CAAEM"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"promptCaching.d.ts","names":["z","contextSchema","ZodBoolean","ZodDefault","ZodEnum","ZodNumber","ZodTypeAny","ZodObject","anthropicPromptCachingMiddleware","infer","Partial","___types_js0","AgentMiddleware"],"sources":["../../../../src/agents/middlewareAgent/middlewares/promptCaching.d.ts"],"sourcesContent":["import { z } from \"zod\";\ndeclare const contextSchema: z.ZodObject<{\n // Configuration options\n enableCaching: z.ZodDefault<z.ZodBoolean>;\n ttl: z.ZodDefault<z.ZodEnum<[\"5m\", \"1h\"]>>;\n minMessagesToCache: z.ZodDefault<z.ZodNumber>;\n}, \"strip\", z.ZodTypeAny, {\n enableCaching: boolean;\n ttl: \"1h\" | \"5m\";\n minMessagesToCache: number;\n}, {\n enableCaching?: boolean | undefined;\n ttl?: \"1h\" | \"5m\" | undefined;\n minMessagesToCache?: number | undefined;\n}>;\n/**\n * Creates a prompt caching middleware for Anthropic models to optimize API usage.\n *\n * This middleware automatically adds cache control headers to messages when using Anthropic models,\n * enabling their prompt caching feature. This can significantly reduce costs and latency for\n * applications with repetitive prompts, long system messages, or extensive conversation histories.\n *\n * ## How It Works\n *\n * The middleware intercepts model requests and adds cache control metadata that tells Anthropic's\n * API to cache processed prompt prefixes. On subsequent requests with matching prefixes, the\n * cached representations are reused, skipping redundant token processing.\n *\n * ## Benefits\n *\n * - **Cost Reduction**: Avoid reprocessing the same tokens repeatedly (up to 90% savings on cached portions)\n * - **Lower Latency**: Cached prompts are processed faster as embeddings are pre-computed\n * - **Better Scalability**: Reduced computational load enables handling more requests\n * - **Consistent Performance**: Stable response times for repetitive queries\n *\n * @param middlewareOptions - Configuration options for the caching behavior\n * @param middlewareOptions.enableCaching - Whether to enable prompt caching (default: `true`)\n * @param middlewareOptions.ttl - Cache time-to-live: `\"5m\"` for 5 minutes or `\"1h\"` for 1 hour (default: `\"5m\"`)\n * @param middlewareOptions.minMessagesToCache - Minimum number of messages required before caching is applied (default: `3`)\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @throws {Error} If used with non-Anthropic models\n *\n * @example\n * Basic usage with default settings\n * ```typescript\n * import { createAgent } from \"langchain\";\n * import { anthropicPromptCachingMiddleware } from \"langchain/middleware\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * middlewares: [\n * anthropicPromptCachingMiddleware()\n * ]\n * });\n * ```\n *\n * @example\n * Custom configuration for longer conversations\n * ```typescript\n * const cachingMiddleware = anthropicPromptCachingMiddleware({\n * ttl: \"1h\", // Cache for 1 hour instead of default 5 minutes\n * minMessagesToCache: 5 // Only cache after 5 messages\n * });\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemMessage: \"You are a helpful assistant with deep knowledge of...\", // Long system prompt\n * middlewares: [cachingMiddleware]\n * });\n * ```\n *\n * @example\n * Conditional caching based on runtime context\n * ```typescript\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * middlewares: [\n * anthropicPromptCachingMiddleware({\n * enableCaching: true,\n * ttl: \"5m\"\n * })\n * ]\n * });\n *\n * // Disable caching for specific requests\n * await agent.invoke(\n * { messages: [new HumanMessage(\"Process this without caching\")] },\n * {\n * configurable: {\n * middleware_context: { enableCaching: false }\n * }\n * }\n * );\n * ```\n *\n * @example\n * Optimal setup for customer support chatbot\n * ```typescript\n * const supportAgent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemMessage: `You are a customer support agent for ACME Corp.\n *\n * Company policies:\n * - Always be polite and professional\n * - Refer to knowledge base for product information\n * - Escalate billing issues to human agents\n * ... (extensive policies and guidelines)\n * `,\n * tools: [searchKnowledgeBase, createTicket, checkOrderStatus],\n * middlewares: [\n * anthropicPromptCachingMiddleware({\n * ttl: \"1h\", // Long TTL for stable system prompt\n * minMessagesToCache: 1 // Cache immediately due to large system prompt\n * })\n * ]\n * });\n * ```\n *\n * @remarks\n * - **Anthropic Only**: This middleware only works with Anthropic models and will throw an error if used with other providers\n * - **Automatic Application**: Caching is applied automatically when message count exceeds `minMessagesToCache`\n * - **Cache Scope**: Caches are isolated per API key and cannot be shared across different keys\n * - **TTL Options**: Only supports \"5m\" (5 minutes) and \"1h\" (1 hour) as TTL values per Anthropic's API\n * - **Best Use Cases**: Long system prompts, multi-turn conversations, repetitive queries, RAG applications\n * - **Cost Impact**: Cached tokens are billed at 10% of the base input token price, cache writes are billed at 25% of the base\n *\n * @see {@link createAgent} for agent creation\n * @see {@link https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching} Anthropic's prompt caching documentation\n * @public\n */\nexport declare function anthropicPromptCachingMiddleware(middlewareOptions?: Partial<z.infer<typeof contextSchema>>): import(\"../types.js\").AgentMiddleware<undefined, z.ZodObject<{\n // Configuration options\n enableCaching: z.ZodDefault<z.ZodBoolean>;\n ttl: z.ZodDefault<z.ZodEnum<[\"5m\", \"1h\"]>>;\n minMessagesToCache: z.ZodDefault<z.ZodNumber>;\n}, \"strip\", z.ZodTypeAny, {\n enableCaching: boolean;\n ttl: \"1h\" | \"5m\";\n minMessagesToCache: number;\n}, {\n enableCaching?: boolean | undefined;\n ttl?: \"1h\" | \"5m\" | undefined;\n minMessagesToCache?: number | undefined;\n}>, any>;\nexport {};\n"],"mappings":";;;;cACcC,eAAeD,CAAAA,CAAEO;;iBAEZP,CAAAA,CAAEG,WAAWH,CAAAA,CAAEE;EAFpBD,GAAAA,EAGLD,CAAAA,CAAEG,UAUT,CAVoBH,CAAAA,CAAEI,OAUtB,CAAA,CAAA,IAAA,EAAA,IAAA,CAAA,CAAA,CAAA;EAAA,kBAAA,EATsBJ,CAAAA,CAAEG,UASxB,CATmCH,CAAAA,CAAEK,SASrC,CAAA;CAAA,EAAA,OAXgCH,EAGtBF,CAAAA,CAAEM,UAHoBJ,EAAAA;EAAU,aAAvBC,EAAAA,OAAAA;EAAU,GACTH,EAAEI,IAAAA,GAAAA,IAAAA;EAAO,kBAApBD,EAAAA,MAAAA;CAAU,EAAA;EAC2B,aAAtBA,CAAAA,EAAAA,OAAAA,GAAAA,SAAAA;EAAU,GACxBH,CAAAA,EAAEM,IAAAA,GAAAA,IAAAA,GAAAA,SAAAA;EAAU,kBALOC,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;AAAS,CAAA,CAAA;AAmIxC;;;;;;;;;;;;;;AAA2J;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAnIC,gCAAAA,qBAAqDE,QAAQV,CAAAA,CAAES,aAAaR,kBAA8E,2BAAXD,CAAAA,CAAEO;;iBAEtJP,CAAAA,CAAEG,WAAWH,CAAAA,CAAEE;OACzBF,CAAAA,CAAEG,WAAWH,CAAAA,CAAEI;sBACAJ,CAAAA,CAAEG,WAAWH,CAAAA,CAAEK;YAC3BL,CAAAA,CAAEM"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"promptCaching.js","names":["middlewareOptions?: Partial<z.infer<typeof contextSchema>>"],"sources":["../../../../src/agents/middlewareAgent/middlewares/promptCaching.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { createMiddleware } from \"../middleware.js\";\n\nconst contextSchema = z.object({\n // Configuration options\n enableCaching: z.boolean().default(true),\n ttl: z.enum([\"5m\", \"1h\"]).default(\"5m\"),\n minMessagesToCache: z.number().default(3),\n});\n\n/**\n * Creates a prompt caching middleware for Anthropic models to optimize API usage.\n *\n * This middleware automatically adds cache control headers to messages when using Anthropic models,\n * enabling their prompt caching feature. This can significantly reduce costs and latency for\n * applications with repetitive prompts, long system messages, or extensive conversation histories.\n *\n * ## How It Works\n *\n * The middleware intercepts model requests and adds cache control metadata that tells Anthropic's\n * API to cache processed prompt prefixes. On subsequent requests with matching prefixes, the\n * cached representations are reused, skipping redundant token processing.\n *\n * ## Benefits\n *\n * - **Cost Reduction**: Avoid reprocessing the same tokens repeatedly (up to 90% savings on cached portions)\n * - **Lower Latency**: Cached prompts are processed faster as embeddings are pre-computed\n * - **Better Scalability**: Reduced computational load enables handling more requests\n * - **Consistent Performance**: Stable response times for repetitive queries\n *\n * @param middlewareOptions - Configuration options for the caching behavior\n * @param middlewareOptions.enableCaching - Whether to enable prompt caching (default: `true`)\n * @param middlewareOptions.ttl - Cache time-to-live: `\"5m\"` for 5 minutes or `\"1h\"` for 1 hour (default: `\"5m\"`)\n * @param middlewareOptions.minMessagesToCache - Minimum number of messages required before caching is applied (default: `3`)\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @throws {Error} If used with non-Anthropic models\n *\n * @example\n * Basic usage with default settings\n * ```typescript\n * import { createAgent } from \"langchain\";\n * import { anthropicPromptCachingMiddleware } from \"langchain/middleware\";\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * middlewares: [\n * anthropicPromptCachingMiddleware()\n * ]\n * });\n * ```\n *\n * @example\n * Custom configuration for longer conversations\n * ```typescript\n * const cachingMiddleware = anthropicPromptCachingMiddleware({\n * ttl: \"1h\", // Cache for 1 hour instead of default 5 minutes\n * minMessagesToCache: 5 // Only cache after 5 messages\n * });\n *\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemMessage: \"You are a helpful assistant with deep knowledge of...\", // Long system prompt\n * middlewares: [cachingMiddleware]\n * });\n * ```\n *\n * @example\n * Conditional caching based on runtime context\n * ```typescript\n * const agent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * middlewares: [\n * anthropicPromptCachingMiddleware({\n * enableCaching: true,\n * ttl: \"5m\"\n * })\n * ]\n * });\n *\n * // Disable caching for specific requests\n * await agent.invoke(\n * { messages: [new HumanMessage(\"Process this without caching\")] },\n * {\n * configurable: {\n * middleware_context: { enableCaching: false }\n * }\n * }\n * );\n * ```\n *\n * @example\n * Optimal setup for customer support chatbot\n * ```typescript\n * const supportAgent = createAgent({\n * model: \"anthropic:claude-3-5-sonnet\",\n * systemMessage: `You are a customer support agent for ACME Corp.\n *\n * Company policies:\n * - Always be polite and professional\n * - Refer to knowledge base for product information\n * - Escalate billing issues to human agents\n * ... (extensive policies and guidelines)\n * `,\n * tools: [searchKnowledgeBase, createTicket, checkOrderStatus],\n * middlewares: [\n * anthropicPromptCachingMiddleware({\n * ttl: \"1h\", // Long TTL for stable system prompt\n * minMessagesToCache: 1 // Cache immediately due to large system prompt\n * })\n * ]\n * });\n * ```\n *\n * @remarks\n * - **Anthropic Only**: This middleware only works with Anthropic models and will throw an error if used with other providers\n * - **Automatic Application**: Caching is applied automatically when message count exceeds `minMessagesToCache`\n * - **Cache Scope**: Caches are isolated per API key and cannot be shared across different keys\n * - **TTL Options**: Only supports \"5m\" (5 minutes) and \"1h\" (1 hour) as TTL values per Anthropic's API\n * - **Best Use Cases**: Long system prompts, multi-turn conversations, repetitive queries, RAG applications\n * - **Cost Impact**: Cached tokens are billed at 10% of the base input token price, cache writes are billed at 25% of the base\n *\n * @see {@link createAgent} for agent creation\n * @see {@link https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching} Anthropic's prompt caching documentation\n * @public\n */\nexport function anthropicPromptCachingMiddleware(\n middlewareOptions?: Partial<z.infer<typeof contextSchema>>\n) {\n return createMiddleware({\n name: \"PromptCachingMiddleware\",\n contextSchema,\n prepareModelRequest: (options, state, runtime) => {\n const enableCaching =\n runtime.context.enableCaching ?? middlewareOptions?.enableCaching;\n const ttl = runtime.context.ttl ?? middlewareOptions?.ttl;\n const minMessagesToCache =\n runtime.context.minMessagesToCache ??\n middlewareOptions?.minMessagesToCache;\n\n // Skip if caching is disabled\n if (!enableCaching) {\n return undefined;\n }\n\n if (options.model?.getName() !== \"anthropic\") {\n throw new Error(\n \"Prompt caching is only supported for Anthropic models\"\n );\n }\n\n const messagesCount =\n state.messages.length + (options.systemMessage ? 1 : 0);\n\n if (messagesCount < minMessagesToCache) {\n return options;\n }\n\n return {\n ...options,\n modelSettings: {\n cache_control: {\n type: \"ephemeral\",\n ttl,\n },\n },\n };\n },\n });\n}\n"],"mappings":";;;;AAGA,MAAM,gBAAgB,EAAE,OAAO;CAE7B,eAAe,EAAE,SAAS,CAAC,QAAQ,KAAK;CACxC,KAAK,EAAE,KAAK,CAAC,MAAM,IAAK,EAAC,CAAC,QAAQ,KAAK;CACvC,oBAAoB,EAAE,QAAQ,CAAC,QAAQ,EAAE;AAC1C,EAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuHF,SAAgB,iCACdA,mBACA;AACA,QAAO,iBAAiB;EACtB,MAAM;EACN;EACA,qBAAqB,CAAC,SAAS,OAAO,YAAY;GAChD,MAAM,gBACJ,QAAQ,QAAQ,iBAAiB,mBAAmB;GACtD,MAAM,MAAM,QAAQ,QAAQ,OAAO,mBAAmB;GACtD,MAAM,qBACJ,QAAQ,QAAQ,sBAChB,mBAAmB;AAGrB,OAAI,CAAC,cACH,QAAO;AAGT,OAAI,QAAQ,OAAO,SAAS,KAAK,YAC/B,OAAM,IAAI,MACR;GAIJ,MAAM,gBACJ,MAAM,SAAS,UAAU,QAAQ,gBAAgB,IAAI;AAEvD,OAAI,gBAAgB,mBAClB,QAAO;AAGT,UAAO;IACL,GAAG;IACH,eAAe,EACb,eAAe;KACb,MAAM;KACN;IACD,EACF;GACF;EACF;CACF,EAAC;AACH"}
|