@langchain/core 1.0.3 → 1.0.5

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/agents.d.cts.map +1 -1
  3. package/dist/agents.d.ts.map +1 -1
  4. package/dist/errors/index.cjs +1 -1
  5. package/dist/errors/index.cjs.map +1 -1
  6. package/dist/errors/index.js +1 -1
  7. package/dist/errors/index.js.map +1 -1
  8. package/dist/language_models/base.cjs +68 -9
  9. package/dist/language_models/base.cjs.map +1 -1
  10. package/dist/language_models/base.d.cts +18 -0
  11. package/dist/language_models/base.d.cts.map +1 -1
  12. package/dist/language_models/base.d.ts +18 -0
  13. package/dist/language_models/base.d.ts.map +1 -1
  14. package/dist/language_models/base.js +68 -9
  15. package/dist/language_models/base.js.map +1 -1
  16. package/dist/language_models/profile.cjs +12 -0
  17. package/dist/language_models/profile.cjs.map +1 -0
  18. package/dist/language_models/profile.d.cts +174 -0
  19. package/dist/language_models/profile.d.cts.map +1 -0
  20. package/dist/language_models/profile.d.ts +174 -0
  21. package/dist/language_models/profile.d.ts.map +1 -0
  22. package/dist/language_models/profile.js +6 -0
  23. package/dist/language_models/profile.js.map +1 -0
  24. package/dist/load/import_map.cjs +5 -1
  25. package/dist/load/import_map.cjs.map +1 -1
  26. package/dist/load/import_map.js +5 -1
  27. package/dist/load/import_map.js.map +1 -1
  28. package/dist/tools/index.cjs +17 -4
  29. package/dist/tools/index.cjs.map +1 -1
  30. package/dist/tools/index.js +17 -4
  31. package/dist/tools/index.js.map +1 -1
  32. package/dist/utils/async_caller.cjs +10 -4
  33. package/dist/utils/async_caller.cjs.map +1 -1
  34. package/dist/utils/async_caller.js +10 -4
  35. package/dist/utils/async_caller.js.map +1 -1
  36. package/dist/utils/format.cjs +12 -0
  37. package/dist/utils/format.cjs.map +1 -0
  38. package/dist/utils/format.d.cts +58 -0
  39. package/dist/utils/format.d.cts.map +1 -0
  40. package/dist/utils/format.d.ts +58 -0
  41. package/dist/utils/format.d.ts.map +1 -0
  42. package/dist/utils/format.js +6 -0
  43. package/dist/utils/format.js.map +1 -0
  44. package/dist/utils/types/zod.cjs +21 -14
  45. package/dist/utils/types/zod.cjs.map +1 -1
  46. package/dist/utils/types/zod.js +21 -14
  47. package/dist/utils/types/zod.js.map +1 -1
  48. package/package.json +25 -2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"profile.js","names":[],"sources":["../../src/language_models/profile.ts"],"sourcesContent":["/**\n * Represents the capabilities and constraints of a language model.\n *\n * This interface defines the various features and limitations that a model may have,\n * including input/output constraints, multimodal support, and advanced capabilities\n * like tool calling and structured output.\n */\nexport interface ModelProfile {\n /**\n * Maximum number of tokens that can be included in the input context window.\n *\n * This represents the total token budget for the model's input, including\n * the prompt, system messages, conversation history, and any other context.\n *\n * @example\n * ```typescript\n * const profile: ModelProfile = {\n * maxInputTokens: 128000 // Model supports up to 128k tokens\n * };\n * ```\n */\n maxInputTokens?: number;\n\n /**\n * Whether the model supports image inputs.\n *\n * When `true`, the model can process images as part of its input, enabling\n * multimodal interactions where visual content can be analyzed alongside text.\n *\n * @see {@link imageUrlInputs} for URL-based image input support\n */\n imageInputs?: boolean;\n\n /**\n * Whether the model supports image URL inputs.\n *\n * When `true`, the model can accept URLs pointing to images rather than\n * requiring the image data to be embedded directly in the request. This can\n * be more efficient for large images or when images are already hosted.\n *\n * @see {@link imageInputs} for direct image input support\n */\n imageUrlInputs?: boolean;\n\n /**\n * Whether the model supports PDF document inputs.\n *\n * When `true`, the model can process PDF files as input, allowing it to\n * analyze document content, extract information, or answer questions about\n * PDF documents.\n */\n pdfInputs?: boolean;\n\n /**\n * Whether the model supports audio inputs.\n *\n * When `true`, the model can process audio data as input, enabling\n * capabilities like speech recognition, audio analysis, or multimodal\n * interactions involving sound.\n */\n audioInputs?: boolean;\n\n /**\n * Whether the model supports video inputs.\n *\n * When `true`, the model can process video data as input, enabling\n * capabilities like video analysis, scene understanding, or multimodal\n * interactions involving moving images.\n */\n videoInputs?: boolean;\n\n /**\n * Whether the model supports image content in tool messages.\n *\n * When `true`, tool responses can include images that the model can process\n * and reason about. This enables workflows where tools return visual data\n * that the model needs to interpret.\n */\n imageToolMessage?: boolean;\n\n /**\n * Whether the model supports PDF content in tool messages.\n *\n * When `true`, tool responses can include PDF documents that the model can\n * process and reason about. This enables workflows where tools return\n * document data that the model needs to interpret.\n */\n pdfToolMessage?: boolean;\n\n /**\n * Maximum number of tokens the model can generate in its output.\n *\n * This represents the upper limit on the length of the model's response.\n * The actual output may be shorter depending on the completion criteria\n * (e.g., natural stopping point, stop sequences).\n *\n * @example\n * ```typescript\n * const profile: ModelProfile = {\n * maxOutputTokens: 4096 // Model can generate up to 4k tokens\n * };\n * ```\n */\n maxOutputTokens?: number;\n\n /**\n * Whether the model supports reasoning or chain-of-thought output.\n *\n * When `true`, the model can produce explicit reasoning steps or\n * chain-of-thought explanations as part of its output. This is useful\n * for understanding the model's decision-making process and improving\n * transparency in complex reasoning tasks.\n */\n reasoningOutput?: boolean;\n\n /**\n * Whether the model can generate image outputs.\n *\n * When `true`, the model can produce images as part of its response,\n * enabling capabilities like image generation, editing, or visual\n * content creation.\n */\n imageOutputs?: boolean;\n\n /**\n * Whether the model can generate audio outputs.\n *\n * When `true`, the model can produce audio data as part of its response,\n * enabling capabilities like text-to-speech, audio generation, or\n * sound synthesis.\n */\n audioOutputs?: boolean;\n\n /**\n * Whether the model can generate video outputs.\n *\n * When `true`, the model can produce video data as part of its response,\n * enabling capabilities like video generation, editing, or visual\n * content creation with motion.\n */\n videoOutputs?: boolean;\n\n /**\n * Whether the model supports tool calling (function calling).\n *\n * When `true`, the model can invoke external tools or functions during\n * its reasoning process. The model can decide which tools to call,\n * with what arguments, and can incorporate the tool results into its\n * final response.\n *\n * @see {@link toolChoice} for controlling tool selection behavior\n * @see {@link https://docs.langchain.com/oss/javascript/langchain/models#tool-calling}\n */\n toolCalling?: boolean;\n\n /**\n * Whether the model supports tool choice control.\n *\n * When `true`, the caller can specify how the model should select tools,\n * such as forcing the use of a specific tool, allowing any tool, or\n * preventing tool use entirely. This provides fine-grained control over\n * the model's tool-calling behavior.\n *\n * @see {@link toolCalling} for basic tool calling support\n */\n toolChoice?: boolean;\n\n /**\n * Whether the model supports structured output generation.\n *\n * When `true`, the model can generate responses that conform to a\n * specified schema or structure (e.g., JSON with a particular format).\n * This is useful for ensuring the model's output can be reliably parsed\n * and processed programmatically.\n *\n * @example\n * ```typescript\n * // Model can be instructed to return JSON matching a schema\n * const profile: ModelProfile = {\n * structuredOutput: true\n * };\n * ```\n */\n structuredOutput?: boolean;\n}\n"],"mappings":""}
@@ -30,12 +30,13 @@ const require_caches_base = require('../caches/base.cjs');
30
30
  const require_document_loaders_base = require('../document_loaders/base.cjs');
31
31
  const require_document_loaders_langsmith = require('../document_loaders/langsmith.cjs');
32
32
  const require_documents_index = require('../documents/index.cjs');
33
- const require_example_selectors_index = require('../example_selectors/index.cjs');
34
33
  const require_indexing_index = require('../indexing/index.cjs');
34
+ const require_example_selectors_index = require('../example_selectors/index.cjs');
35
35
  const require_utils_tiktoken = require('../utils/tiktoken.cjs');
36
36
  const require_language_models_base = require('../language_models/base.cjs');
37
37
  const require_language_models_chat_models = require('../language_models/chat_models.cjs');
38
38
  const require_language_models_llms = require('../language_models/llms.cjs');
39
+ const require_language_models_profile = require('../language_models/profile.cjs');
39
40
  const require_runnables_index = require('../runnables/index.cjs');
40
41
  const require_utils_json_patch = require('../utils/json_patch.cjs');
41
42
  const require_output_parsers_index = require('../output_parsers/index.cjs');
@@ -49,6 +50,7 @@ const require_tracers_run_collector = require('../tracers/run_collector.cjs');
49
50
  const require_types_stream = require('../types/stream.cjs');
50
51
  const require_utils_chunk_array = require('../utils/chunk_array.cjs');
51
52
  const require_utils_event_source_parse = require('../utils/event_source_parse.cjs');
53
+ const require_utils_format = require('../utils/format.cjs');
52
54
  const require_utils_function_calling = require('../utils/function_calling.cjs');
53
55
  const require_utils_math = require('../utils/math.cjs');
54
56
  const require_utils_testing_index = require('../utils/testing/index.cjs');
@@ -73,6 +75,7 @@ require_rolldown_runtime.__export(import_map_exports, {
73
75
  language_models__base: () => require_language_models_base.base_exports,
74
76
  language_models__chat_models: () => require_language_models_chat_models.chat_models_exports,
75
77
  language_models__llms: () => require_language_models_llms.llms_exports,
78
+ language_models__profile: () => require_language_models_profile.profile_exports,
76
79
  load__serializable: () => require_load_serializable.serializable_exports,
77
80
  memory: () => require_memory.memory_exports,
78
81
  messages: () => require_messages_index.messages_exports,
@@ -101,6 +104,7 @@ require_rolldown_runtime.__export(import_map_exports, {
101
104
  utils__chunk_array: () => require_utils_chunk_array.chunk_array_exports,
102
105
  utils__env: () => require_utils_env.env_exports,
103
106
  utils__event_source_parse: () => require_utils_event_source_parse.event_source_parse_exports,
107
+ utils__format: () => require_utils_format.format_exports,
104
108
  utils__function_calling: () => require_utils_function_calling.function_calling_exports,
105
109
  utils__hash: () => require_utils_hash.hash_exports,
106
110
  utils__json_patch: () => require_utils_json_patch.json_patch_exports,
@@ -1 +1 @@
1
- {"version":3,"file":"import_map.cjs","names":[],"sources":["../../src/load/import_map.ts"],"sourcesContent":["// Auto-generated by import-map plugin. Do not edit manually.\n\nexport * as index from \"../index.js\";\nexport * as agents from \"../agents.js\";\nexport * as caches from \"../caches/base.js\";\nexport * as callbacks__base from \"../callbacks/base.js\";\nexport * as callbacks__manager from \"../callbacks/manager.js\";\nexport * as callbacks__promises from \"../callbacks/promises.js\";\nexport * as chat_history from \"../chat_history.js\";\nexport * as documents from \"../documents/index.js\";\nexport * as document_loaders__base from \"../document_loaders/base.js\";\nexport * as document_loaders__langsmith from \"../document_loaders/langsmith.js\";\nexport * as embeddings from \"../embeddings.js\";\nexport * as example_selectors from \"../example_selectors/index.js\";\nexport * as indexing from \"../indexing/index.js\";\nexport * as language_models__base from \"../language_models/base.js\";\nexport * as language_models__chat_models from \"../language_models/chat_models.js\";\nexport * as language_models__llms from \"../language_models/llms.js\";\nexport * as load__serializable from \"../load/serializable.js\";\nexport * as memory from \"../memory.js\";\nexport * as messages from \"../messages/index.js\";\nexport * as messages__tool from \"../messages/tool.js\";\nexport * as output_parsers from \"../output_parsers/index.js\";\nexport * as output_parsers__openai_tools from \"../output_parsers/openai_tools/index.js\";\nexport * as output_parsers__openai_functions from \"../output_parsers/openai_functions/index.js\";\nexport * as outputs from \"../outputs.js\";\nexport * as prompts from \"../prompts/index.js\";\nexport * as prompt_values from \"../prompt_values.js\";\nexport * as runnables from \"../runnables/index.js\";\nexport * as runnables__graph from \"../runnables/graph.js\";\nexport * as retrievers from \"../retrievers/index.js\";\nexport * as retrievers__document_compressors from \"../retrievers/document_compressors/base.js\";\nexport * as singletons from \"../singletons/index.js\";\nexport * as stores from \"../stores.js\";\nexport * as structured_query from \"../structured_query/index.js\";\nexport * as tools from \"../tools/index.js\";\nexport * as tracers__base from \"../tracers/base.js\";\nexport * as tracers__console from \"../tracers/console.js\";\nexport * as tracers__log_stream from \"../tracers/log_stream.js\";\nexport * as tracers__run_collector from \"../tracers/run_collector.js\";\nexport * as tracers__tracer_langchain from \"../tracers/tracer_langchain.js\";\nexport * as types__stream from \"../types/stream.js\";\nexport * as utils__async_caller from \"../utils/async_caller.js\";\nexport * as utils__chunk_array from \"../utils/chunk_array.js\";\nexport * as utils__env from \"../utils/env.js\";\nexport * as utils__event_source_parse from \"../utils/event_source_parse.js\";\nexport * as utils__function_calling from \"../utils/function_calling.js\";\nexport * as utils__hash from \"../utils/hash.js\";\nexport * as utils__json_patch from \"../utils/json_patch.js\";\nexport * as utils__json_schema from \"../utils/json_schema.js\";\nexport * as utils__math from \"../utils/math.js\";\nexport * as utils__stream from \"../utils/stream.js\";\nexport * as utils__testing from \"../utils/testing/index.js\";\nexport * as utils__tiktoken from \"../utils/tiktoken.js\";\nexport * as utils__types from \"../utils/types/index.js\";\nexport * as vectorstores from \"../vectorstores.js\";\n"],"mappings":""}
1
+ {"version":3,"file":"import_map.cjs","names":[],"sources":["../../src/load/import_map.ts"],"sourcesContent":["// Auto-generated by import-map plugin. Do not edit manually.\n\nexport * as index from \"../index.js\";\nexport * as agents from \"../agents.js\";\nexport * as caches from \"../caches/base.js\";\nexport * as callbacks__base from \"../callbacks/base.js\";\nexport * as callbacks__manager from \"../callbacks/manager.js\";\nexport * as callbacks__promises from \"../callbacks/promises.js\";\nexport * as chat_history from \"../chat_history.js\";\nexport * as documents from \"../documents/index.js\";\nexport * as document_loaders__base from \"../document_loaders/base.js\";\nexport * as document_loaders__langsmith from \"../document_loaders/langsmith.js\";\nexport * as embeddings from \"../embeddings.js\";\nexport * as example_selectors from \"../example_selectors/index.js\";\nexport * as indexing from \"../indexing/index.js\";\nexport * as language_models__base from \"../language_models/base.js\";\nexport * as language_models__chat_models from \"../language_models/chat_models.js\";\nexport * as language_models__llms from \"../language_models/llms.js\";\nexport * as language_models__profile from \"../language_models/profile.js\";\nexport * as load__serializable from \"../load/serializable.js\";\nexport * as memory from \"../memory.js\";\nexport * as messages from \"../messages/index.js\";\nexport * as messages__tool from \"../messages/tool.js\";\nexport * as output_parsers from \"../output_parsers/index.js\";\nexport * as output_parsers__openai_tools from \"../output_parsers/openai_tools/index.js\";\nexport * as output_parsers__openai_functions from \"../output_parsers/openai_functions/index.js\";\nexport * as outputs from \"../outputs.js\";\nexport * as prompts from \"../prompts/index.js\";\nexport * as prompt_values from \"../prompt_values.js\";\nexport * as runnables from \"../runnables/index.js\";\nexport * as runnables__graph from \"../runnables/graph.js\";\nexport * as retrievers from \"../retrievers/index.js\";\nexport * as retrievers__document_compressors from \"../retrievers/document_compressors/base.js\";\nexport * as singletons from \"../singletons/index.js\";\nexport * as stores from \"../stores.js\";\nexport * as structured_query from \"../structured_query/index.js\";\nexport * as tools from \"../tools/index.js\";\nexport * as tracers__base from \"../tracers/base.js\";\nexport * as tracers__console from \"../tracers/console.js\";\nexport * as tracers__log_stream from \"../tracers/log_stream.js\";\nexport * as tracers__run_collector from \"../tracers/run_collector.js\";\nexport * as tracers__tracer_langchain from \"../tracers/tracer_langchain.js\";\nexport * as types__stream from \"../types/stream.js\";\nexport * as utils__async_caller from \"../utils/async_caller.js\";\nexport * as utils__chunk_array from \"../utils/chunk_array.js\";\nexport * as utils__env from \"../utils/env.js\";\nexport * as utils__event_source_parse from \"../utils/event_source_parse.js\";\nexport * as utils__format from \"../utils/format.js\";\nexport * as utils__function_calling from \"../utils/function_calling.js\";\nexport * as utils__hash from \"../utils/hash.js\";\nexport * as utils__json_patch from \"../utils/json_patch.js\";\nexport * as utils__json_schema from \"../utils/json_schema.js\";\nexport * as utils__math from \"../utils/math.js\";\nexport * as utils__stream from \"../utils/stream.js\";\nexport * as utils__testing from \"../utils/testing/index.js\";\nexport * as utils__tiktoken from \"../utils/tiktoken.js\";\nexport * as utils__types from \"../utils/types/index.js\";\nexport * as vectorstores from \"../vectorstores.js\";\n"],"mappings":""}
@@ -30,12 +30,13 @@ import { base_exports as base_exports$2 } from "../caches/base.js";
30
30
  import { base_exports as base_exports$3 } from "../document_loaders/base.js";
31
31
  import { langsmith_exports } from "../document_loaders/langsmith.js";
32
32
  import { documents_exports } from "../documents/index.js";
33
- import { example_selectors_exports } from "../example_selectors/index.js";
34
33
  import { indexing_exports } from "../indexing/index.js";
34
+ import { example_selectors_exports } from "../example_selectors/index.js";
35
35
  import { tiktoken_exports } from "../utils/tiktoken.js";
36
36
  import { base_exports as base_exports$4 } from "../language_models/base.js";
37
37
  import { chat_models_exports } from "../language_models/chat_models.js";
38
38
  import { llms_exports } from "../language_models/llms.js";
39
+ import { profile_exports } from "../language_models/profile.js";
39
40
  import { runnables_exports } from "../runnables/index.js";
40
41
  import { json_patch_exports } from "../utils/json_patch.js";
41
42
  import { output_parsers_exports } from "../output_parsers/index.js";
@@ -49,6 +50,7 @@ import { run_collector_exports } from "../tracers/run_collector.js";
49
50
  import { stream_exports as stream_exports$1 } from "../types/stream.js";
50
51
  import { chunk_array_exports } from "../utils/chunk_array.js";
51
52
  import { event_source_parse_exports } from "../utils/event_source_parse.js";
53
+ import { format_exports } from "../utils/format.js";
52
54
  import { function_calling_exports } from "../utils/function_calling.js";
53
55
  import { math_exports } from "../utils/math.js";
54
56
  import { testing_exports } from "../utils/testing/index.js";
@@ -73,6 +75,7 @@ __export(import_map_exports, {
73
75
  language_models__base: () => base_exports$4,
74
76
  language_models__chat_models: () => chat_models_exports,
75
77
  language_models__llms: () => llms_exports,
78
+ language_models__profile: () => profile_exports,
76
79
  load__serializable: () => serializable_exports,
77
80
  memory: () => memory_exports,
78
81
  messages: () => messages_exports,
@@ -101,6 +104,7 @@ __export(import_map_exports, {
101
104
  utils__chunk_array: () => chunk_array_exports,
102
105
  utils__env: () => env_exports,
103
106
  utils__event_source_parse: () => event_source_parse_exports,
107
+ utils__format: () => format_exports,
104
108
  utils__function_calling: () => function_calling_exports,
105
109
  utils__hash: () => hash_exports,
106
110
  utils__json_patch: () => json_patch_exports,
@@ -1 +1 @@
1
- {"version":3,"file":"import_map.js","names":[],"sources":["../../src/load/import_map.ts"],"sourcesContent":["// Auto-generated by import-map plugin. Do not edit manually.\n\nexport * as index from \"../index.js\";\nexport * as agents from \"../agents.js\";\nexport * as caches from \"../caches/base.js\";\nexport * as callbacks__base from \"../callbacks/base.js\";\nexport * as callbacks__manager from \"../callbacks/manager.js\";\nexport * as callbacks__promises from \"../callbacks/promises.js\";\nexport * as chat_history from \"../chat_history.js\";\nexport * as documents from \"../documents/index.js\";\nexport * as document_loaders__base from \"../document_loaders/base.js\";\nexport * as document_loaders__langsmith from \"../document_loaders/langsmith.js\";\nexport * as embeddings from \"../embeddings.js\";\nexport * as example_selectors from \"../example_selectors/index.js\";\nexport * as indexing from \"../indexing/index.js\";\nexport * as language_models__base from \"../language_models/base.js\";\nexport * as language_models__chat_models from \"../language_models/chat_models.js\";\nexport * as language_models__llms from \"../language_models/llms.js\";\nexport * as load__serializable from \"../load/serializable.js\";\nexport * as memory from \"../memory.js\";\nexport * as messages from \"../messages/index.js\";\nexport * as messages__tool from \"../messages/tool.js\";\nexport * as output_parsers from \"../output_parsers/index.js\";\nexport * as output_parsers__openai_tools from \"../output_parsers/openai_tools/index.js\";\nexport * as output_parsers__openai_functions from \"../output_parsers/openai_functions/index.js\";\nexport * as outputs from \"../outputs.js\";\nexport * as prompts from \"../prompts/index.js\";\nexport * as prompt_values from \"../prompt_values.js\";\nexport * as runnables from \"../runnables/index.js\";\nexport * as runnables__graph from \"../runnables/graph.js\";\nexport * as retrievers from \"../retrievers/index.js\";\nexport * as retrievers__document_compressors from \"../retrievers/document_compressors/base.js\";\nexport * as singletons from \"../singletons/index.js\";\nexport * as stores from \"../stores.js\";\nexport * as structured_query from \"../structured_query/index.js\";\nexport * as tools from \"../tools/index.js\";\nexport * as tracers__base from \"../tracers/base.js\";\nexport * as tracers__console from \"../tracers/console.js\";\nexport * as tracers__log_stream from \"../tracers/log_stream.js\";\nexport * as tracers__run_collector from \"../tracers/run_collector.js\";\nexport * as tracers__tracer_langchain from \"../tracers/tracer_langchain.js\";\nexport * as types__stream from \"../types/stream.js\";\nexport * as utils__async_caller from \"../utils/async_caller.js\";\nexport * as utils__chunk_array from \"../utils/chunk_array.js\";\nexport * as utils__env from \"../utils/env.js\";\nexport * as utils__event_source_parse from \"../utils/event_source_parse.js\";\nexport * as utils__function_calling from \"../utils/function_calling.js\";\nexport * as utils__hash from \"../utils/hash.js\";\nexport * as utils__json_patch from \"../utils/json_patch.js\";\nexport * as utils__json_schema from \"../utils/json_schema.js\";\nexport * as utils__math from \"../utils/math.js\";\nexport * as utils__stream from \"../utils/stream.js\";\nexport * as utils__testing from \"../utils/testing/index.js\";\nexport * as utils__tiktoken from \"../utils/tiktoken.js\";\nexport * as utils__types from \"../utils/types/index.js\";\nexport * as vectorstores from \"../vectorstores.js\";\n"],"mappings":""}
1
+ {"version":3,"file":"import_map.js","names":[],"sources":["../../src/load/import_map.ts"],"sourcesContent":["// Auto-generated by import-map plugin. Do not edit manually.\n\nexport * as index from \"../index.js\";\nexport * as agents from \"../agents.js\";\nexport * as caches from \"../caches/base.js\";\nexport * as callbacks__base from \"../callbacks/base.js\";\nexport * as callbacks__manager from \"../callbacks/manager.js\";\nexport * as callbacks__promises from \"../callbacks/promises.js\";\nexport * as chat_history from \"../chat_history.js\";\nexport * as documents from \"../documents/index.js\";\nexport * as document_loaders__base from \"../document_loaders/base.js\";\nexport * as document_loaders__langsmith from \"../document_loaders/langsmith.js\";\nexport * as embeddings from \"../embeddings.js\";\nexport * as example_selectors from \"../example_selectors/index.js\";\nexport * as indexing from \"../indexing/index.js\";\nexport * as language_models__base from \"../language_models/base.js\";\nexport * as language_models__chat_models from \"../language_models/chat_models.js\";\nexport * as language_models__llms from \"../language_models/llms.js\";\nexport * as language_models__profile from \"../language_models/profile.js\";\nexport * as load__serializable from \"../load/serializable.js\";\nexport * as memory from \"../memory.js\";\nexport * as messages from \"../messages/index.js\";\nexport * as messages__tool from \"../messages/tool.js\";\nexport * as output_parsers from \"../output_parsers/index.js\";\nexport * as output_parsers__openai_tools from \"../output_parsers/openai_tools/index.js\";\nexport * as output_parsers__openai_functions from \"../output_parsers/openai_functions/index.js\";\nexport * as outputs from \"../outputs.js\";\nexport * as prompts from \"../prompts/index.js\";\nexport * as prompt_values from \"../prompt_values.js\";\nexport * as runnables from \"../runnables/index.js\";\nexport * as runnables__graph from \"../runnables/graph.js\";\nexport * as retrievers from \"../retrievers/index.js\";\nexport * as retrievers__document_compressors from \"../retrievers/document_compressors/base.js\";\nexport * as singletons from \"../singletons/index.js\";\nexport * as stores from \"../stores.js\";\nexport * as structured_query from \"../structured_query/index.js\";\nexport * as tools from \"../tools/index.js\";\nexport * as tracers__base from \"../tracers/base.js\";\nexport * as tracers__console from \"../tracers/console.js\";\nexport * as tracers__log_stream from \"../tracers/log_stream.js\";\nexport * as tracers__run_collector from \"../tracers/run_collector.js\";\nexport * as tracers__tracer_langchain from \"../tracers/tracer_langchain.js\";\nexport * as types__stream from \"../types/stream.js\";\nexport * as utils__async_caller from \"../utils/async_caller.js\";\nexport * as utils__chunk_array from \"../utils/chunk_array.js\";\nexport * as utils__env from \"../utils/env.js\";\nexport * as utils__event_source_parse from \"../utils/event_source_parse.js\";\nexport * as utils__format from \"../utils/format.js\";\nexport * as utils__function_calling from \"../utils/function_calling.js\";\nexport * as utils__hash from \"../utils/hash.js\";\nexport * as utils__json_patch from \"../utils/json_patch.js\";\nexport * as utils__json_schema from \"../utils/json_schema.js\";\nexport * as utils__math from \"../utils/math.js\";\nexport * as utils__stream from \"../utils/stream.js\";\nexport * as utils__testing from \"../utils/testing/index.js\";\nexport * as utils__tiktoken from \"../utils/tiktoken.js\";\nexport * as utils__types from \"../utils/types/index.js\";\nexport * as vectorstores from \"../vectorstores.js\";\n"],"mappings":""}
@@ -270,9 +270,17 @@ function tool(func, fields) {
270
270
  schema,
271
271
  func: async (input, runManager, config) => {
272
272
  return new Promise((resolve, reject) => {
273
- if (config?.signal) config.signal.addEventListener("abort", () => {
274
- return reject(require_signal.getAbortSignalError(config.signal));
275
- });
273
+ let listener;
274
+ const cleanup = () => {
275
+ if (config?.signal && listener) config.signal.removeEventListener("abort", listener);
276
+ };
277
+ if (config?.signal) {
278
+ listener = () => {
279
+ cleanup();
280
+ reject(require_signal.getAbortSignalError(config.signal));
281
+ };
282
+ config.signal.addEventListener("abort", listener);
283
+ }
276
284
  const childConfig = require_config.patchConfig(config, { callbacks: runManager?.getChild() });
277
285
  require_index.AsyncLocalStorageProviderSingleton.runWithConfig(require_config.pickRunnableConfigKeys(childConfig), async () => {
278
286
  try {
@@ -281,9 +289,14 @@ function tool(func, fields) {
281
289
  * If the signal is aborted, we don't want to resolve the promise
282
290
  * as the promise is already rejected.
283
291
  */
284
- if (config?.signal?.aborted) return;
292
+ if (config?.signal?.aborted) {
293
+ cleanup();
294
+ return;
295
+ }
296
+ cleanup();
285
297
  resolve(result);
286
298
  } catch (e) {
299
+ cleanup();
287
300
  reject(e);
288
301
  }
289
302
  });
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["BaseLangChain","fields?: ToolParams","input: TInput","config?: TConfig","toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >","enrichedConfig: ToolRunnableConfig","ensureConfig","mergeConfigs","_isToolCall","arg: TArg","configArg?: TConfig","tags?: string[]","parsed: SchemaOutputT","isInteropZodSchema","interopParseAsync","z4","ToolInputParsingException","result","parseCallbackConfigArg","CallbackManager","toolCallId: string | undefined","_configHasToolCallId","z","callbacks?: TConfig","fields: DynamicToolInput<ToolOutputT>","input: string","runManager?: CallbackManagerForToolRun","parentConfig?: ToolRunnableConfig","fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>","arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0]","parentConfig?: RunnableConfig","func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>","fields: ToolWrapperParams<SchemaT>","isSimpleStringZodSchema","validatesOnlyStrings","patchConfig","AsyncLocalStorageProviderSingleton","pickRunnableConfigKeys","getAbortSignalError","params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}","isDirectToolOutput","ToolMessage","content: unknown"],"sources":["../../src/tools/index.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { z as z4, ZodError } from \"zod/v4\";\nimport {\n validate,\n type Schema as ValidationSchema,\n} from \"@cfworker/json-schema\";\nimport {\n CallbackManager,\n CallbackManagerForToolRun,\n parseCallbackConfigArg,\n} from \"../callbacks/manager.js\";\nimport { BaseLangChain } from \"../language_models/base.js\";\nimport {\n mergeConfigs,\n ensureConfig,\n patchConfig,\n pickRunnableConfigKeys,\n type RunnableConfig,\n} from \"../runnables/config.js\";\nimport type { RunnableFunc } from \"../runnables/base.js\";\nimport { isDirectToolOutput, ToolCall, ToolMessage } from \"../messages/tool.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../singletons/index.js\";\nimport type { RunnableToolLike } from \"../runnables/base.js\";\nimport {\n _configHasToolCallId,\n _isToolCall,\n ToolInputParsingException,\n} from \"./utils.js\";\nimport {\n type InferInteropZodInput,\n type InferInteropZodOutput,\n type InteropZodObject,\n type InteropZodType,\n interopParseAsync,\n isSimpleStringZodSchema,\n isInteropZodSchema,\n type ZodStringV3,\n type ZodStringV4,\n type ZodObjectV3,\n type ZodObjectV4,\n} from \"../utils/types/zod.js\";\nimport { getAbortSignalError } from \"../utils/signal.js\";\nimport type {\n StructuredToolCallInput,\n ToolInputSchemaBase,\n ToolReturnType,\n ResponseFormat,\n ToolInputSchemaInputType,\n ToolInputSchemaOutputType,\n ToolParams,\n ToolRunnableConfig,\n StructuredToolInterface,\n DynamicToolInput,\n DynamicStructuredToolInput,\n StringInputToolSchema,\n ToolInterface,\n ToolOutputType,\n ToolRuntime,\n} from \"./types.js\";\nimport { type JSONSchema, validatesOnlyStrings } from \"../utils/json_schema.js\";\n\nexport type {\n BaseDynamicToolInput,\n ContentAndArtifact,\n DynamicToolInput,\n DynamicStructuredToolInput,\n ResponseFormat,\n StructuredToolCallInput,\n StructuredToolInterface,\n StructuredToolParams,\n ToolInterface,\n ToolParams,\n ToolReturnType,\n ToolRunnableConfig,\n ToolInputSchemaBase as ToolSchemaBase,\n} from \"./types.js\";\n\nexport {\n isLangChainTool,\n isRunnableToolLike,\n isStructuredTool,\n isStructuredToolParams,\n type ToolRuntime,\n} from \"./types.js\";\n\nexport { ToolInputParsingException };\n/**\n * Base class for Tools that accept input of any shape defined by a Zod schema.\n */\nexport abstract class StructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n >\n extends BaseLangChain<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolOutputT | ToolMessage\n >\n implements StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT>\n{\n abstract name: string;\n\n abstract description: string;\n\n abstract schema: SchemaT;\n\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect = false;\n\n verboseParsingErrors = false;\n\n get lc_namespace() {\n return [\"langchain\", \"tools\"];\n }\n\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat = \"content\";\n\n /**\n * Default config object for the tool runnable.\n */\n defaultConfig?: ToolRunnableConfig;\n\n constructor(fields?: ToolParams) {\n super(fields ?? {});\n\n this.verboseParsingErrors =\n fields?.verboseParsingErrors ?? this.verboseParsingErrors;\n this.responseFormat = fields?.responseFormat ?? this.responseFormat;\n this.defaultConfig = fields?.defaultConfig ?? this.defaultConfig;\n this.metadata = fields?.metadata ?? this.metadata;\n }\n\n protected abstract _call(\n arg: SchemaOutputT,\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT>;\n\n /**\n * Invokes the tool with the provided input and configuration.\n * @param input The input for the tool.\n * @param config Optional configuration for the tool.\n * @returns A Promise that resolves with the tool's output.\n */\n async invoke<\n TInput extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined\n >(\n input: TInput,\n config?: TConfig\n ): Promise<ToolReturnType<TInput, TConfig, ToolOutputT>> {\n let toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n\n let enrichedConfig: ToolRunnableConfig = ensureConfig(\n mergeConfigs(this.defaultConfig, config)\n );\n if (_isToolCall(input)) {\n toolInput = input.args as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n enrichedConfig = {\n ...enrichedConfig,\n toolCall: input,\n };\n } else {\n toolInput = input as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n }\n\n return this.call(toolInput, enrichedConfig) as Promise<\n ToolReturnType<TInput, TConfig, ToolOutputT>\n >;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument, configuration, and tags. It\n * parses the input according to the schema, handles any errors, and\n * manages callbacks.\n * @param arg The input argument for the tool.\n * @param configArg Optional configuration or callbacks for the tool.\n * @param tags Optional tags for the tool.\n * @returns A Promise that resolves with a string.\n */\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>> {\n // Determine the actual input that needs parsing/validation.\n // If arg is a ToolCall, use its args; otherwise, use arg directly.\n const inputForValidation = _isToolCall(arg) ? arg.args : arg;\n\n let parsed: SchemaOutputT; // This will hold the successfully parsed input of the expected output type.\n if (isInteropZodSchema(this.schema)) {\n try {\n // Validate the inputForValidation - TS needs help here as it can't exclude ToolCall based on the check\n parsed = await interopParseAsync(\n this.schema as InteropZodType,\n inputForValidation as Exclude<TArg, ToolCall>\n );\n } catch (e) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${(e as Error).message}`;\n }\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (e instanceof Error && e.constructor.name === \"ZodError\") {\n message = `${message}\\n\\n${z4.prettifyError(e as ZodError)}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n } else {\n const result = validate(\n inputForValidation,\n this.schema as ValidationSchema\n );\n if (!result.valid) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${result.errors\n .map((e) => `${e.keywordLocation}: ${e.error}`)\n .join(\"\\n\")}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n // Assign the validated input to parsed\n // We cast here because validate() doesn't narrow the type sufficiently for TS, but we know it's valid.\n parsed = inputForValidation as SchemaOutputT;\n }\n\n const config = parseCallbackConfigArg(configArg);\n const callbackManager_ = CallbackManager.configure(\n config.callbacks,\n this.callbacks,\n config.tags || tags,\n this.tags,\n config.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n const runManager = await callbackManager_?.handleToolStart(\n this.toJSON(),\n // Log the original raw input arg\n typeof arg === \"string\" ? arg : JSON.stringify(arg),\n config.runId,\n undefined,\n undefined,\n undefined,\n config.runName\n );\n delete config.runId;\n let result;\n try {\n // Pass the correctly typed parsed input to _call\n result = await this._call(parsed, runManager, config);\n } catch (e) {\n await runManager?.handleToolError(e);\n throw e;\n }\n let content;\n let artifact;\n if (this.responseFormat === \"content_and_artifact\") {\n if (Array.isArray(result) && result.length === 2) {\n [content, artifact] = result;\n } else {\n throw new Error(\n `Tool response format is \"content_and_artifact\" but the output was not a two-tuple.\\nResult: ${JSON.stringify(\n result\n )}`\n );\n }\n } else {\n content = result;\n }\n\n let toolCallId: string | undefined;\n // Extract toolCallId ONLY if the original arg was a ToolCall\n if (_isToolCall(arg)) {\n toolCallId = arg.id;\n }\n // Or if it was provided in the config's toolCall property\n if (!toolCallId && _configHasToolCallId(config)) {\n toolCallId = config.toolCall.id;\n }\n\n const formattedOutput = _formatToolOutput<ToolOutputT>({\n content,\n artifact,\n toolCallId,\n name: this.name,\n metadata: this.metadata,\n });\n await runManager?.handleToolEnd(formattedOutput);\n return formattedOutput as ToolReturnType<TArg, TConfig, ToolOutputT>;\n }\n}\n\n/**\n * Base class for Tools that accept input as a string.\n */\nexport abstract class Tool<ToolOutputT = ToolOutputType>\n extends StructuredTool<\n StringInputToolSchema,\n ToolInputSchemaOutputType<StringInputToolSchema>,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n implements\n ToolInterface<\n StringInputToolSchema,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n{\n schema = z\n .object({ input: z.string().optional() })\n .transform((obj) => obj.input);\n\n constructor(fields?: ToolParams) {\n super(fields);\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument and callbacks. It handles\n * string inputs specifically.\n * @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema.\n * @param callbacks Optional callbacks for the tool.\n * @returns A Promise that resolves with a string.\n */\n // Match the base class signature including the generics and conditional return type\n call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n callbacks?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n // Prepare the input for the base class call method.\n // If arg is string or undefined, wrap it; otherwise, pass ToolCall or { input: ... } directly.\n const structuredArg =\n typeof arg === \"string\" || arg == null ? { input: arg } : arg;\n\n // Ensure TConfig is passed to super.call\n return super.call(structuredArg, callbacks);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and description.\n */\nexport class DynamicTool<\n ToolOutputT = ToolOutputType\n> extends Tool<ToolOutputT> {\n static lc_name() {\n return \"DynamicTool\";\n }\n\n name: string;\n\n description: string;\n\n func: DynamicToolInput<ToolOutputT>[\"func\"];\n\n constructor(fields: DynamicToolInput<ToolOutputT>) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n async call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n configArg?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n // Call the Tool class's call method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig);\n }\n\n /** @ignore */\n async _call(\n input: string, // DynamicTool's _call specifically expects a string after schema transformation\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT> {\n return this.func(input, runManager, parentConfig);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and\n * description, designed to work with structured data. It extends the\n * StructuredTool class and overrides the _call method to execute the\n * provided function when the tool is called.\n *\n * Schema can be passed as Zod or JSON schema. The tool will not validate\n * input if JSON schema is passed.\n */\nexport class DynamicStructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n> extends StructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT> {\n static lc_name() {\n return \"DynamicStructuredTool\";\n }\n\n name: string;\n\n description: string;\n\n func: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>[\"func\"];\n\n schema: SchemaT;\n\n constructor(\n fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>\n ) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n this.schema = fields.schema;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n // Match the base class signature\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n\n // Call the base class method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig, tags);\n }\n\n protected _call(\n arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0],\n runManager?: CallbackManagerForToolRun,\n parentConfig?: RunnableConfig\n ): Promise<ToolOutputT> {\n return this.func(arg, runManager, parentConfig);\n }\n}\n\n/**\n * Abstract base class for toolkits in LangChain. Toolkits are collections\n * of tools that agents can use. Subclasses must implement the `tools`\n * property to provide the specific tools for the toolkit.\n */\nexport abstract class BaseToolkit {\n abstract tools: StructuredToolInterface[];\n\n getTools(): StructuredToolInterface[] {\n return this.tools;\n }\n}\n\n/**\n * Parameters for the tool function.\n * Schema can be provided as Zod or JSON schema.\n * Both schema types will be validated.\n * @template {ToolInputSchemaBase} RunInput The input schema for the tool.\n */\ninterface ToolWrapperParams<RunInput = ToolInputSchemaBase | undefined>\n extends ToolParams {\n /**\n * The name of the tool. If using with an LLM, this\n * will be passed as the tool name.\n */\n name: string;\n /**\n * The description of the tool.\n * @default `${fields.name} tool`\n */\n description?: string;\n /**\n * The input schema for the tool. If using an LLM, this\n * will be passed as the tool schema to generate arguments\n * for.\n */\n schema?: RunInput;\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat;\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect?: boolean;\n}\n\n/**\n * Creates a new StructuredTool instance with the provided function, name, description, and schema.\n *\n * Schema can be provided as Zod or JSON schema, and both will be validated.\n *\n * @function\n * @template {ToolInputSchemaBase} SchemaT The input schema for the tool.\n * @template {ToolReturnType} ToolOutputT The output type of the tool.\n *\n * @param {RunnableFunc<z.output<SchemaT>, ToolOutputT>} func - The function to invoke when the tool is called.\n * @param {ToolWrapperParams<SchemaT>} fields - An object containing the following properties:\n * @param {string} fields.name The name of the tool.\n * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.\n * @param {z.AnyZodObject | z.ZodString | undefined} fields.schema The Zod schema defining the input for the tool. If undefined, it will default to a Zod string schema.\n *\n * @returns {DynamicStructuredTool<SchemaT>} A new StructuredTool instance.\n */\nexport function tool<SchemaT extends ZodStringV3, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<SchemaT extends ZodStringV4, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<\n Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends\n | InteropZodObject\n | InteropZodType<string>\n | JSONSchema = InteropZodObject,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT>\n):\n | DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>\n | DynamicTool<ToolOutputT>;\n\n// Overloads with ToolRuntime as CallOptions\nexport function tool<\n SchemaT extends ZodStringV3,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodStringV4,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends\n | InteropZodObject\n | InteropZodType<string>\n | JSONSchema = InteropZodObject,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n):\n | DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>\n | DynamicTool<ToolOutputT> {\n const isSimpleStringSchema = isSimpleStringZodSchema(fields.schema);\n const isStringJSONSchema = validatesOnlyStrings(fields.schema);\n\n // If the schema is not provided, or it's a simple string schema, create a DynamicTool\n if (!fields.schema || isSimpleStringSchema || isStringJSONSchema) {\n return new DynamicTool<ToolOutputT>({\n ...fields,\n description:\n fields.description ??\n (fields.schema as { description?: string } | undefined)?.description ??\n `${fields.name} tool`,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n resolve(func(input as any, childConfig as any));\n } catch (e) {\n reject(e);\n }\n }\n );\n });\n },\n });\n }\n\n const schema = fields.schema as InteropZodObject | JSONSchema;\n\n const description =\n fields.description ??\n (fields.schema as { description?: string }).description ??\n `${fields.name} tool`;\n\n return new DynamicStructuredTool<\n typeof schema,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT\n >({\n ...fields,\n description,\n schema,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n if (config?.signal) {\n config.signal.addEventListener(\"abort\", () => {\n return reject(getAbortSignalError(config.signal));\n });\n }\n\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await func(input as any, childConfig as any);\n\n /**\n * If the signal is aborted, we don't want to resolve the promise\n * as the promise is already rejected.\n */\n if (config?.signal?.aborted) {\n return;\n }\n\n resolve(result);\n } catch (e) {\n reject(e);\n }\n }\n );\n });\n },\n }) as DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT\n >;\n}\n\nfunction _formatToolOutput<TOutput extends ToolOutputType>(params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}): ToolMessage | TOutput {\n const { content, artifact, toolCallId, metadata } = params;\n if (toolCallId && !isDirectToolOutput(content)) {\n if (\n typeof content === \"string\" ||\n (Array.isArray(content) &&\n content.every((item) => typeof item === \"object\"))\n ) {\n return new ToolMessage({\n status: \"success\",\n content,\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n } else {\n return new ToolMessage({\n status: \"success\",\n content: _stringify(content),\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n }\n } else {\n return content;\n }\n}\n\nfunction _stringify(content: unknown): string {\n try {\n return JSON.stringify(content, null, 2) ?? \"\";\n } catch (_noOp) {\n return `${content}`;\n }\n}\n\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool =\n | StructuredToolInterface\n | DynamicTool\n | RunnableToolLike;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyFA,IAAsB,iBAAtB,cAMUA,2CAKV;;;;;;;CAaE,eAAe;CAEf,uBAAuB;CAEvB,IAAI,eAAe;AACjB,SAAO,CAAC,aAAa,OAAQ;CAC9B;;;;;;;;;;CAWD,iBAAkC;;;;CAKlC;CAEA,YAAYC,QAAqB;EAC/B,MAAM,UAAU,CAAE,EAAC;EAEnB,KAAK,uBACH,QAAQ,wBAAwB,KAAK;EACvC,KAAK,iBAAiB,QAAQ,kBAAkB,KAAK;EACrD,KAAK,gBAAgB,QAAQ,iBAAiB,KAAK;EACnD,KAAK,WAAW,QAAQ,YAAY,KAAK;CAC1C;;;;;;;CAcD,MAAM,OAIJC,OACAC,QACuD;EACvD,IAAIC;EAKJ,IAAIC,iBAAqCC,4BACvCC,4BAAa,KAAK,eAAe,OAAO,CACzC;AACD,MAAIC,0BAAY,MAAM,EAAE;GACtB,YAAY,MAAM;GAIlB,iBAAiB;IACf,GAAG;IACH,UAAU;GACX;EACF,OACC,YAAY;AAMd,SAAO,KAAK,KAAK,WAAW,eAAe;CAG5C;;;;;;;;;;;;CAaD,MAAM,KAIJC,KACAC,WAEAC,MACqD;EAGrD,MAAM,qBAAqBH,0BAAY,IAAI,GAAG,IAAI,OAAO;EAEzD,IAAII;AACJ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B;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["BaseLangChain","fields?: ToolParams","input: TInput","config?: TConfig","toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >","enrichedConfig: ToolRunnableConfig","ensureConfig","mergeConfigs","_isToolCall","arg: TArg","configArg?: TConfig","tags?: string[]","parsed: SchemaOutputT","isInteropZodSchema","interopParseAsync","z4","ToolInputParsingException","result","parseCallbackConfigArg","CallbackManager","toolCallId: string | undefined","_configHasToolCallId","z","callbacks?: TConfig","fields: DynamicToolInput<ToolOutputT>","input: string","runManager?: CallbackManagerForToolRun","parentConfig?: ToolRunnableConfig","fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>","arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0]","parentConfig?: RunnableConfig","func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>","fields: ToolWrapperParams<SchemaT>","isSimpleStringZodSchema","validatesOnlyStrings","patchConfig","AsyncLocalStorageProviderSingleton","pickRunnableConfigKeys","listener: (() => void) | undefined","getAbortSignalError","params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}","isDirectToolOutput","ToolMessage","content: unknown"],"sources":["../../src/tools/index.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { z as z4, ZodError } from \"zod/v4\";\nimport {\n validate,\n type Schema as ValidationSchema,\n} from \"@cfworker/json-schema\";\nimport {\n CallbackManager,\n CallbackManagerForToolRun,\n parseCallbackConfigArg,\n} from \"../callbacks/manager.js\";\nimport { BaseLangChain } from \"../language_models/base.js\";\nimport {\n mergeConfigs,\n ensureConfig,\n patchConfig,\n pickRunnableConfigKeys,\n type RunnableConfig,\n} from \"../runnables/config.js\";\nimport type { RunnableFunc } from \"../runnables/base.js\";\nimport { isDirectToolOutput, ToolCall, ToolMessage } from \"../messages/tool.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../singletons/index.js\";\nimport type { RunnableToolLike } from \"../runnables/base.js\";\nimport {\n _configHasToolCallId,\n _isToolCall,\n ToolInputParsingException,\n} from \"./utils.js\";\nimport {\n type InferInteropZodInput,\n type InferInteropZodOutput,\n type InteropZodObject,\n type InteropZodType,\n interopParseAsync,\n isSimpleStringZodSchema,\n isInteropZodSchema,\n type ZodStringV3,\n type ZodStringV4,\n type ZodObjectV3,\n type ZodObjectV4,\n} from \"../utils/types/zod.js\";\nimport { getAbortSignalError } from \"../utils/signal.js\";\nimport type {\n StructuredToolCallInput,\n ToolInputSchemaBase,\n ToolReturnType,\n ResponseFormat,\n ToolInputSchemaInputType,\n ToolInputSchemaOutputType,\n ToolParams,\n ToolRunnableConfig,\n StructuredToolInterface,\n DynamicToolInput,\n DynamicStructuredToolInput,\n StringInputToolSchema,\n ToolInterface,\n ToolOutputType,\n ToolRuntime,\n} from \"./types.js\";\nimport { type JSONSchema, validatesOnlyStrings } from \"../utils/json_schema.js\";\n\nexport type {\n BaseDynamicToolInput,\n ContentAndArtifact,\n DynamicToolInput,\n DynamicStructuredToolInput,\n ResponseFormat,\n StructuredToolCallInput,\n StructuredToolInterface,\n StructuredToolParams,\n ToolInterface,\n ToolParams,\n ToolReturnType,\n ToolRunnableConfig,\n ToolInputSchemaBase as ToolSchemaBase,\n} from \"./types.js\";\n\nexport {\n isLangChainTool,\n isRunnableToolLike,\n isStructuredTool,\n isStructuredToolParams,\n type ToolRuntime,\n} from \"./types.js\";\n\nexport { ToolInputParsingException };\n/**\n * Base class for Tools that accept input of any shape defined by a Zod schema.\n */\nexport abstract class StructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n >\n extends BaseLangChain<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolOutputT | ToolMessage\n >\n implements StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT>\n{\n abstract name: string;\n\n abstract description: string;\n\n abstract schema: SchemaT;\n\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect = false;\n\n verboseParsingErrors = false;\n\n get lc_namespace() {\n return [\"langchain\", \"tools\"];\n }\n\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat = \"content\";\n\n /**\n * Default config object for the tool runnable.\n */\n defaultConfig?: ToolRunnableConfig;\n\n constructor(fields?: ToolParams) {\n super(fields ?? {});\n\n this.verboseParsingErrors =\n fields?.verboseParsingErrors ?? this.verboseParsingErrors;\n this.responseFormat = fields?.responseFormat ?? this.responseFormat;\n this.defaultConfig = fields?.defaultConfig ?? this.defaultConfig;\n this.metadata = fields?.metadata ?? this.metadata;\n }\n\n protected abstract _call(\n arg: SchemaOutputT,\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT>;\n\n /**\n * Invokes the tool with the provided input and configuration.\n * @param input The input for the tool.\n * @param config Optional configuration for the tool.\n * @returns A Promise that resolves with the tool's output.\n */\n async invoke<\n TInput extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined\n >(\n input: TInput,\n config?: TConfig\n ): Promise<ToolReturnType<TInput, TConfig, ToolOutputT>> {\n let toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n\n let enrichedConfig: ToolRunnableConfig = ensureConfig(\n mergeConfigs(this.defaultConfig, config)\n );\n if (_isToolCall(input)) {\n toolInput = input.args as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n enrichedConfig = {\n ...enrichedConfig,\n toolCall: input,\n };\n } else {\n toolInput = input as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n }\n\n return this.call(toolInput, enrichedConfig) as Promise<\n ToolReturnType<TInput, TConfig, ToolOutputT>\n >;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument, configuration, and tags. It\n * parses the input according to the schema, handles any errors, and\n * manages callbacks.\n * @param arg The input argument for the tool.\n * @param configArg Optional configuration or callbacks for the tool.\n * @param tags Optional tags for the tool.\n * @returns A Promise that resolves with a string.\n */\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>> {\n // Determine the actual input that needs parsing/validation.\n // If arg is a ToolCall, use its args; otherwise, use arg directly.\n const inputForValidation = _isToolCall(arg) ? arg.args : arg;\n\n let parsed: SchemaOutputT; // This will hold the successfully parsed input of the expected output type.\n if (isInteropZodSchema(this.schema)) {\n try {\n // Validate the inputForValidation - TS needs help here as it can't exclude ToolCall based on the check\n parsed = await interopParseAsync(\n this.schema as InteropZodType,\n inputForValidation as Exclude<TArg, ToolCall>\n );\n } catch (e) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${(e as Error).message}`;\n }\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (e instanceof Error && e.constructor.name === \"ZodError\") {\n message = `${message}\\n\\n${z4.prettifyError(e as ZodError)}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n } else {\n const result = validate(\n inputForValidation,\n this.schema as ValidationSchema\n );\n if (!result.valid) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${result.errors\n .map((e) => `${e.keywordLocation}: ${e.error}`)\n .join(\"\\n\")}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n // Assign the validated input to parsed\n // We cast here because validate() doesn't narrow the type sufficiently for TS, but we know it's valid.\n parsed = inputForValidation as SchemaOutputT;\n }\n\n const config = parseCallbackConfigArg(configArg);\n const callbackManager_ = CallbackManager.configure(\n config.callbacks,\n this.callbacks,\n config.tags || tags,\n this.tags,\n config.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n const runManager = await callbackManager_?.handleToolStart(\n this.toJSON(),\n // Log the original raw input arg\n typeof arg === \"string\" ? arg : JSON.stringify(arg),\n config.runId,\n undefined,\n undefined,\n undefined,\n config.runName\n );\n delete config.runId;\n let result;\n try {\n // Pass the correctly typed parsed input to _call\n result = await this._call(parsed, runManager, config);\n } catch (e) {\n await runManager?.handleToolError(e);\n throw e;\n }\n let content;\n let artifact;\n if (this.responseFormat === \"content_and_artifact\") {\n if (Array.isArray(result) && result.length === 2) {\n [content, artifact] = result;\n } else {\n throw new Error(\n `Tool response format is \"content_and_artifact\" but the output was not a two-tuple.\\nResult: ${JSON.stringify(\n result\n )}`\n );\n }\n } else {\n content = result;\n }\n\n let toolCallId: string | undefined;\n // Extract toolCallId ONLY if the original arg was a ToolCall\n if (_isToolCall(arg)) {\n toolCallId = arg.id;\n }\n // Or if it was provided in the config's toolCall property\n if (!toolCallId && _configHasToolCallId(config)) {\n toolCallId = config.toolCall.id;\n }\n\n const formattedOutput = _formatToolOutput<ToolOutputT>({\n content,\n artifact,\n toolCallId,\n name: this.name,\n metadata: this.metadata,\n });\n await runManager?.handleToolEnd(formattedOutput);\n return formattedOutput as ToolReturnType<TArg, TConfig, ToolOutputT>;\n }\n}\n\n/**\n * Base class for Tools that accept input as a string.\n */\nexport abstract class Tool<ToolOutputT = ToolOutputType>\n extends StructuredTool<\n StringInputToolSchema,\n ToolInputSchemaOutputType<StringInputToolSchema>,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n implements\n ToolInterface<\n StringInputToolSchema,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n{\n schema = z\n .object({ input: z.string().optional() })\n .transform((obj) => obj.input);\n\n constructor(fields?: ToolParams) {\n super(fields);\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument and callbacks. It handles\n * string inputs specifically.\n * @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema.\n * @param callbacks Optional callbacks for the tool.\n * @returns A Promise that resolves with a string.\n */\n // Match the base class signature including the generics and conditional return type\n call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n callbacks?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n // Prepare the input for the base class call method.\n // If arg is string or undefined, wrap it; otherwise, pass ToolCall or { input: ... } directly.\n const structuredArg =\n typeof arg === \"string\" || arg == null ? { input: arg } : arg;\n\n // Ensure TConfig is passed to super.call\n return super.call(structuredArg, callbacks);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and description.\n */\nexport class DynamicTool<\n ToolOutputT = ToolOutputType\n> extends Tool<ToolOutputT> {\n static lc_name() {\n return \"DynamicTool\";\n }\n\n name: string;\n\n description: string;\n\n func: DynamicToolInput<ToolOutputT>[\"func\"];\n\n constructor(fields: DynamicToolInput<ToolOutputT>) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n async call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n configArg?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n // Call the Tool class's call method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig);\n }\n\n /** @ignore */\n async _call(\n input: string, // DynamicTool's _call specifically expects a string after schema transformation\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT> {\n return this.func(input, runManager, parentConfig);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and\n * description, designed to work with structured data. It extends the\n * StructuredTool class and overrides the _call method to execute the\n * provided function when the tool is called.\n *\n * Schema can be passed as Zod or JSON schema. The tool will not validate\n * input if JSON schema is passed.\n */\nexport class DynamicStructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n> extends StructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT> {\n static lc_name() {\n return \"DynamicStructuredTool\";\n }\n\n name: string;\n\n description: string;\n\n func: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>[\"func\"];\n\n schema: SchemaT;\n\n constructor(\n fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>\n ) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n this.schema = fields.schema;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n // Match the base class signature\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n\n // Call the base class method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig, tags);\n }\n\n protected _call(\n arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0],\n runManager?: CallbackManagerForToolRun,\n parentConfig?: RunnableConfig\n ): Promise<ToolOutputT> {\n return this.func(arg, runManager, parentConfig);\n }\n}\n\n/**\n * Abstract base class for toolkits in LangChain. Toolkits are collections\n * of tools that agents can use. Subclasses must implement the `tools`\n * property to provide the specific tools for the toolkit.\n */\nexport abstract class BaseToolkit {\n abstract tools: StructuredToolInterface[];\n\n getTools(): StructuredToolInterface[] {\n return this.tools;\n }\n}\n\n/**\n * Parameters for the tool function.\n * Schema can be provided as Zod or JSON schema.\n * Both schema types will be validated.\n * @template {ToolInputSchemaBase} RunInput The input schema for the tool.\n */\ninterface ToolWrapperParams<RunInput = ToolInputSchemaBase | undefined>\n extends ToolParams {\n /**\n * The name of the tool. If using with an LLM, this\n * will be passed as the tool name.\n */\n name: string;\n /**\n * The description of the tool.\n * @default `${fields.name} tool`\n */\n description?: string;\n /**\n * The input schema for the tool. If using an LLM, this\n * will be passed as the tool schema to generate arguments\n * for.\n */\n schema?: RunInput;\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat;\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect?: boolean;\n}\n\n/**\n * Creates a new StructuredTool instance with the provided function, name, description, and schema.\n *\n * Schema can be provided as Zod or JSON schema, and both will be validated.\n *\n * @function\n * @template {ToolInputSchemaBase} SchemaT The input schema for the tool.\n * @template {ToolReturnType} ToolOutputT The output type of the tool.\n *\n * @param {RunnableFunc<z.output<SchemaT>, ToolOutputT>} func - The function to invoke when the tool is called.\n * @param {ToolWrapperParams<SchemaT>} fields - An object containing the following properties:\n * @param {string} fields.name The name of the tool.\n * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.\n * @param {z.AnyZodObject | z.ZodString | undefined} fields.schema The Zod schema defining the input for the tool. If undefined, it will default to a Zod string schema.\n *\n * @returns {DynamicStructuredTool<SchemaT>} A new StructuredTool instance.\n */\nexport function tool<SchemaT extends ZodStringV3, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<SchemaT extends ZodStringV4, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<\n Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends\n | InteropZodObject\n | InteropZodType<string>\n | JSONSchema = InteropZodObject,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT>\n):\n | DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>\n | DynamicTool<ToolOutputT>;\n\n// Overloads with ToolRuntime as CallOptions\nexport function tool<\n SchemaT extends ZodStringV3,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodStringV4,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends\n | InteropZodObject\n | InteropZodType<string>\n | JSONSchema = InteropZodObject,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n):\n | DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>\n | DynamicTool<ToolOutputT> {\n const isSimpleStringSchema = isSimpleStringZodSchema(fields.schema);\n const isStringJSONSchema = validatesOnlyStrings(fields.schema);\n\n // If the schema is not provided, or it's a simple string schema, create a DynamicTool\n if (!fields.schema || isSimpleStringSchema || isStringJSONSchema) {\n return new DynamicTool<ToolOutputT>({\n ...fields,\n description:\n fields.description ??\n (fields.schema as { description?: string } | undefined)?.description ??\n `${fields.name} tool`,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n resolve(func(input as any, childConfig as any));\n } catch (e) {\n reject(e);\n }\n }\n );\n });\n },\n });\n }\n\n const schema = fields.schema as InteropZodObject | JSONSchema;\n\n const description =\n fields.description ??\n (fields.schema as { description?: string }).description ??\n `${fields.name} tool`;\n\n return new DynamicStructuredTool<\n typeof schema,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT\n >({\n ...fields,\n description,\n schema,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n let listener: (() => void) | undefined;\n const cleanup = () => {\n if (config?.signal && listener) {\n config.signal.removeEventListener(\"abort\", listener);\n }\n };\n\n if (config?.signal) {\n listener = () => {\n cleanup();\n reject(getAbortSignalError(config.signal));\n };\n config.signal.addEventListener(\"abort\", listener);\n }\n\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await func(input as any, childConfig as any);\n\n /**\n * If the signal is aborted, we don't want to resolve the promise\n * as the promise is already rejected.\n */\n if (config?.signal?.aborted) {\n cleanup();\n return;\n }\n\n cleanup();\n resolve(result);\n } catch (e) {\n cleanup();\n reject(e);\n }\n }\n );\n });\n },\n }) as DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT\n >;\n}\n\nfunction _formatToolOutput<TOutput extends ToolOutputType>(params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}): ToolMessage | TOutput {\n const { content, artifact, toolCallId, metadata } = params;\n if (toolCallId && !isDirectToolOutput(content)) {\n if (\n typeof content === \"string\" ||\n (Array.isArray(content) &&\n content.every((item) => typeof item === \"object\"))\n ) {\n return new ToolMessage({\n status: \"success\",\n content,\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n } else {\n return new ToolMessage({\n status: \"success\",\n content: _stringify(content),\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n }\n } else {\n return content;\n }\n}\n\nfunction _stringify(content: unknown): string {\n try {\n return JSON.stringify(content, null, 2) ?? \"\";\n } catch (_noOp) {\n return `${content}`;\n }\n}\n\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool =\n | StructuredToolInterface\n | DynamicTool\n | RunnableToolLike;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyFA,IAAsB,iBAAtB,cAMUA,2CAKV;;;;;;;CAaE,eAAe;CAEf,uBAAuB;CAEvB,IAAI,eAAe;AACjB,SAAO,CAAC,aAAa,OAAQ;CAC9B;;;;;;;;;;CAWD,iBAAkC;;;;CAKlC;CAEA,YAAYC,QAAqB;EAC/B,MAAM,UAAU,CAAE,EAAC;EAEnB,KAAK,uBACH,QAAQ,wBAAwB,KAAK;EACvC,KAAK,iBAAiB,QAAQ,kBAAkB,KAAK;EACrD,KAAK,gBAAgB,QAAQ,iBAAiB,KAAK;EACnD,KAAK,WAAW,QAAQ,YAAY,KAAK;CAC1C;;;;;;;CAcD,MAAM,OAIJC,OACAC,QACuD;EACvD,IAAIC;EAKJ,IAAIC,iBAAqCC,4BACvCC,4BAAa,KAAK,eAAe,OAAO,CACzC;AACD,MAAIC,0BAAY,MAAM,EAAE;GACtB,YAAY,MAAM;GAIlB,iBAAiB;IACf,GAAG;IACH,UAAU;GACX;EACF,OACC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,SAAS,CAEnD,QAAO,IAAIC,kCAAY;EACrB,QAAQ;EACR;EACA;EACA,cAAc;EACd,MAAM,OAAO;EACb;CACD;KAED,QAAO,IAAIA,kCAAY;EACrB,QAAQ;EACR,SAAS,WAAW,QAAQ;EAC5B;EACA,cAAc;EACd,MAAM,OAAO;EACb;CACD;KAGH,QAAO;AAEV;AAED,SAAS,WAAWC,SAA0B;AAC5C,KAAI;AACF,SAAO,KAAK,UAAU,SAAS,MAAM,EAAE,IAAI;CAC5C,SAAQ,OAAO;AACd,SAAO,GAAG,SAAS;CACpB;AACF"}
@@ -270,9 +270,17 @@ function tool(func, fields) {
270
270
  schema,
271
271
  func: async (input, runManager, config) => {
272
272
  return new Promise((resolve, reject) => {
273
- if (config?.signal) config.signal.addEventListener("abort", () => {
274
- return reject(getAbortSignalError(config.signal));
275
- });
273
+ let listener;
274
+ const cleanup = () => {
275
+ if (config?.signal && listener) config.signal.removeEventListener("abort", listener);
276
+ };
277
+ if (config?.signal) {
278
+ listener = () => {
279
+ cleanup();
280
+ reject(getAbortSignalError(config.signal));
281
+ };
282
+ config.signal.addEventListener("abort", listener);
283
+ }
276
284
  const childConfig = patchConfig(config, { callbacks: runManager?.getChild() });
277
285
  AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => {
278
286
  try {
@@ -281,9 +289,14 @@ function tool(func, fields) {
281
289
  * If the signal is aborted, we don't want to resolve the promise
282
290
  * as the promise is already rejected.
283
291
  */
284
- if (config?.signal?.aborted) return;
292
+ if (config?.signal?.aborted) {
293
+ cleanup();
294
+ return;
295
+ }
296
+ cleanup();
285
297
  resolve(result);
286
298
  } catch (e) {
299
+ cleanup();
287
300
  reject(e);
288
301
  }
289
302
  });
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["fields?: ToolParams","input: TInput","config?: TConfig","toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >","enrichedConfig: ToolRunnableConfig","arg: TArg","configArg?: TConfig","tags?: string[]","parsed: SchemaOutputT","z4","result","toolCallId: string | undefined","callbacks?: TConfig","fields: DynamicToolInput<ToolOutputT>","input: string","runManager?: CallbackManagerForToolRun","parentConfig?: ToolRunnableConfig","fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>","arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0]","parentConfig?: RunnableConfig","func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>","fields: ToolWrapperParams<SchemaT>","params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}","content: unknown"],"sources":["../../src/tools/index.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { z as z4, ZodError } from \"zod/v4\";\nimport {\n validate,\n type Schema as ValidationSchema,\n} from \"@cfworker/json-schema\";\nimport {\n CallbackManager,\n CallbackManagerForToolRun,\n parseCallbackConfigArg,\n} from \"../callbacks/manager.js\";\nimport { BaseLangChain } from \"../language_models/base.js\";\nimport {\n mergeConfigs,\n ensureConfig,\n patchConfig,\n pickRunnableConfigKeys,\n type RunnableConfig,\n} from \"../runnables/config.js\";\nimport type { RunnableFunc } from \"../runnables/base.js\";\nimport { isDirectToolOutput, ToolCall, ToolMessage } from \"../messages/tool.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../singletons/index.js\";\nimport type { RunnableToolLike } from \"../runnables/base.js\";\nimport {\n _configHasToolCallId,\n _isToolCall,\n ToolInputParsingException,\n} from \"./utils.js\";\nimport {\n type InferInteropZodInput,\n type InferInteropZodOutput,\n type InteropZodObject,\n type InteropZodType,\n interopParseAsync,\n isSimpleStringZodSchema,\n isInteropZodSchema,\n type ZodStringV3,\n type ZodStringV4,\n type ZodObjectV3,\n type ZodObjectV4,\n} from \"../utils/types/zod.js\";\nimport { getAbortSignalError } from \"../utils/signal.js\";\nimport type {\n StructuredToolCallInput,\n ToolInputSchemaBase,\n ToolReturnType,\n ResponseFormat,\n ToolInputSchemaInputType,\n ToolInputSchemaOutputType,\n ToolParams,\n ToolRunnableConfig,\n StructuredToolInterface,\n DynamicToolInput,\n DynamicStructuredToolInput,\n StringInputToolSchema,\n ToolInterface,\n ToolOutputType,\n ToolRuntime,\n} from \"./types.js\";\nimport { type JSONSchema, validatesOnlyStrings } from \"../utils/json_schema.js\";\n\nexport type {\n BaseDynamicToolInput,\n ContentAndArtifact,\n DynamicToolInput,\n DynamicStructuredToolInput,\n ResponseFormat,\n StructuredToolCallInput,\n StructuredToolInterface,\n StructuredToolParams,\n ToolInterface,\n ToolParams,\n ToolReturnType,\n ToolRunnableConfig,\n ToolInputSchemaBase as ToolSchemaBase,\n} from \"./types.js\";\n\nexport {\n isLangChainTool,\n isRunnableToolLike,\n isStructuredTool,\n isStructuredToolParams,\n type ToolRuntime,\n} from \"./types.js\";\n\nexport { ToolInputParsingException };\n/**\n * Base class for Tools that accept input of any shape defined by a Zod schema.\n */\nexport abstract class StructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n >\n extends BaseLangChain<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolOutputT | ToolMessage\n >\n implements StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT>\n{\n abstract name: string;\n\n abstract description: string;\n\n abstract schema: SchemaT;\n\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect = false;\n\n verboseParsingErrors = false;\n\n get lc_namespace() {\n return [\"langchain\", \"tools\"];\n }\n\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat = \"content\";\n\n /**\n * Default config object for the tool runnable.\n */\n defaultConfig?: ToolRunnableConfig;\n\n constructor(fields?: ToolParams) {\n super(fields ?? {});\n\n this.verboseParsingErrors =\n fields?.verboseParsingErrors ?? this.verboseParsingErrors;\n this.responseFormat = fields?.responseFormat ?? this.responseFormat;\n this.defaultConfig = fields?.defaultConfig ?? this.defaultConfig;\n this.metadata = fields?.metadata ?? this.metadata;\n }\n\n protected abstract _call(\n arg: SchemaOutputT,\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT>;\n\n /**\n * Invokes the tool with the provided input and configuration.\n * @param input The input for the tool.\n * @param config Optional configuration for the tool.\n * @returns A Promise that resolves with the tool's output.\n */\n async invoke<\n TInput extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined\n >(\n input: TInput,\n config?: TConfig\n ): Promise<ToolReturnType<TInput, TConfig, ToolOutputT>> {\n let toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n\n let enrichedConfig: ToolRunnableConfig = ensureConfig(\n mergeConfigs(this.defaultConfig, config)\n );\n if (_isToolCall(input)) {\n toolInput = input.args as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n enrichedConfig = {\n ...enrichedConfig,\n toolCall: input,\n };\n } else {\n toolInput = input as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n }\n\n return this.call(toolInput, enrichedConfig) as Promise<\n ToolReturnType<TInput, TConfig, ToolOutputT>\n >;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument, configuration, and tags. It\n * parses the input according to the schema, handles any errors, and\n * manages callbacks.\n * @param arg The input argument for the tool.\n * @param configArg Optional configuration or callbacks for the tool.\n * @param tags Optional tags for the tool.\n * @returns A Promise that resolves with a string.\n */\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>> {\n // Determine the actual input that needs parsing/validation.\n // If arg is a ToolCall, use its args; otherwise, use arg directly.\n const inputForValidation = _isToolCall(arg) ? arg.args : arg;\n\n let parsed: SchemaOutputT; // This will hold the successfully parsed input of the expected output type.\n if (isInteropZodSchema(this.schema)) {\n try {\n // Validate the inputForValidation - TS needs help here as it can't exclude ToolCall based on the check\n parsed = await interopParseAsync(\n this.schema as InteropZodType,\n inputForValidation as Exclude<TArg, ToolCall>\n );\n } catch (e) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${(e as Error).message}`;\n }\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (e instanceof Error && e.constructor.name === \"ZodError\") {\n message = `${message}\\n\\n${z4.prettifyError(e as ZodError)}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n } else {\n const result = validate(\n inputForValidation,\n this.schema as ValidationSchema\n );\n if (!result.valid) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${result.errors\n .map((e) => `${e.keywordLocation}: ${e.error}`)\n .join(\"\\n\")}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n // Assign the validated input to parsed\n // We cast here because validate() doesn't narrow the type sufficiently for TS, but we know it's valid.\n parsed = inputForValidation as SchemaOutputT;\n }\n\n const config = parseCallbackConfigArg(configArg);\n const callbackManager_ = CallbackManager.configure(\n config.callbacks,\n this.callbacks,\n config.tags || tags,\n this.tags,\n config.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n const runManager = await callbackManager_?.handleToolStart(\n this.toJSON(),\n // Log the original raw input arg\n typeof arg === \"string\" ? arg : JSON.stringify(arg),\n config.runId,\n undefined,\n undefined,\n undefined,\n config.runName\n );\n delete config.runId;\n let result;\n try {\n // Pass the correctly typed parsed input to _call\n result = await this._call(parsed, runManager, config);\n } catch (e) {\n await runManager?.handleToolError(e);\n throw e;\n }\n let content;\n let artifact;\n if (this.responseFormat === \"content_and_artifact\") {\n if (Array.isArray(result) && result.length === 2) {\n [content, artifact] = result;\n } else {\n throw new Error(\n `Tool response format is \"content_and_artifact\" but the output was not a two-tuple.\\nResult: ${JSON.stringify(\n result\n )}`\n );\n }\n } else {\n content = result;\n }\n\n let toolCallId: string | undefined;\n // Extract toolCallId ONLY if the original arg was a ToolCall\n if (_isToolCall(arg)) {\n toolCallId = arg.id;\n }\n // Or if it was provided in the config's toolCall property\n if (!toolCallId && _configHasToolCallId(config)) {\n toolCallId = config.toolCall.id;\n }\n\n const formattedOutput = _formatToolOutput<ToolOutputT>({\n content,\n artifact,\n toolCallId,\n name: this.name,\n metadata: this.metadata,\n });\n await runManager?.handleToolEnd(formattedOutput);\n return formattedOutput as ToolReturnType<TArg, TConfig, ToolOutputT>;\n }\n}\n\n/**\n * Base class for Tools that accept input as a string.\n */\nexport abstract class Tool<ToolOutputT = ToolOutputType>\n extends StructuredTool<\n StringInputToolSchema,\n ToolInputSchemaOutputType<StringInputToolSchema>,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n implements\n ToolInterface<\n StringInputToolSchema,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n{\n schema = z\n .object({ input: z.string().optional() })\n .transform((obj) => obj.input);\n\n constructor(fields?: ToolParams) {\n super(fields);\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument and callbacks. It handles\n * string inputs specifically.\n * @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema.\n * @param callbacks Optional callbacks for the tool.\n * @returns A Promise that resolves with a string.\n */\n // Match the base class signature including the generics and conditional return type\n call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n callbacks?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n // Prepare the input for the base class call method.\n // If arg is string or undefined, wrap it; otherwise, pass ToolCall or { input: ... } directly.\n const structuredArg =\n typeof arg === \"string\" || arg == null ? { input: arg } : arg;\n\n // Ensure TConfig is passed to super.call\n return super.call(structuredArg, callbacks);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and description.\n */\nexport class DynamicTool<\n ToolOutputT = ToolOutputType\n> extends Tool<ToolOutputT> {\n static lc_name() {\n return \"DynamicTool\";\n }\n\n name: string;\n\n description: string;\n\n func: DynamicToolInput<ToolOutputT>[\"func\"];\n\n constructor(fields: DynamicToolInput<ToolOutputT>) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n async call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n configArg?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n // Call the Tool class's call method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig);\n }\n\n /** @ignore */\n async _call(\n input: string, // DynamicTool's _call specifically expects a string after schema transformation\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT> {\n return this.func(input, runManager, parentConfig);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and\n * description, designed to work with structured data. It extends the\n * StructuredTool class and overrides the _call method to execute the\n * provided function when the tool is called.\n *\n * Schema can be passed as Zod or JSON schema. The tool will not validate\n * input if JSON schema is passed.\n */\nexport class DynamicStructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n> extends StructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT> {\n static lc_name() {\n return \"DynamicStructuredTool\";\n }\n\n name: string;\n\n description: string;\n\n func: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>[\"func\"];\n\n schema: SchemaT;\n\n constructor(\n fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>\n ) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n this.schema = fields.schema;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n // Match the base class signature\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n\n // Call the base class method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig, tags);\n }\n\n protected _call(\n arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0],\n runManager?: CallbackManagerForToolRun,\n parentConfig?: RunnableConfig\n ): Promise<ToolOutputT> {\n return this.func(arg, runManager, parentConfig);\n }\n}\n\n/**\n * Abstract base class for toolkits in LangChain. Toolkits are collections\n * of tools that agents can use. Subclasses must implement the `tools`\n * property to provide the specific tools for the toolkit.\n */\nexport abstract class BaseToolkit {\n abstract tools: StructuredToolInterface[];\n\n getTools(): StructuredToolInterface[] {\n return this.tools;\n }\n}\n\n/**\n * Parameters for the tool function.\n * Schema can be provided as Zod or JSON schema.\n * Both schema types will be validated.\n * @template {ToolInputSchemaBase} RunInput The input schema for the tool.\n */\ninterface ToolWrapperParams<RunInput = ToolInputSchemaBase | undefined>\n extends ToolParams {\n /**\n * The name of the tool. If using with an LLM, this\n * will be passed as the tool name.\n */\n name: string;\n /**\n * The description of the tool.\n * @default `${fields.name} tool`\n */\n description?: string;\n /**\n * The input schema for the tool. If using an LLM, this\n * will be passed as the tool schema to generate arguments\n * for.\n */\n schema?: RunInput;\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat;\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect?: boolean;\n}\n\n/**\n * Creates a new StructuredTool instance with the provided function, name, description, and schema.\n *\n * Schema can be provided as Zod or JSON schema, and both will be validated.\n *\n * @function\n * @template {ToolInputSchemaBase} SchemaT The input schema for the tool.\n * @template {ToolReturnType} ToolOutputT The output type of the tool.\n *\n * @param {RunnableFunc<z.output<SchemaT>, ToolOutputT>} func - The function to invoke when the tool is called.\n * @param {ToolWrapperParams<SchemaT>} fields - An object containing the following properties:\n * @param {string} fields.name The name of the tool.\n * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.\n * @param {z.AnyZodObject | z.ZodString | undefined} fields.schema The Zod schema defining the input for the tool. If undefined, it will default to a Zod string schema.\n *\n * @returns {DynamicStructuredTool<SchemaT>} A new StructuredTool instance.\n */\nexport function tool<SchemaT extends ZodStringV3, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<SchemaT extends ZodStringV4, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<\n Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends\n | InteropZodObject\n | InteropZodType<string>\n | JSONSchema = InteropZodObject,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT>\n):\n | DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>\n | DynamicTool<ToolOutputT>;\n\n// Overloads with ToolRuntime as CallOptions\nexport function tool<\n SchemaT extends ZodStringV3,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodStringV4,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends\n | InteropZodObject\n | InteropZodType<string>\n | JSONSchema = InteropZodObject,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n):\n | DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>\n | DynamicTool<ToolOutputT> {\n const isSimpleStringSchema = isSimpleStringZodSchema(fields.schema);\n const isStringJSONSchema = validatesOnlyStrings(fields.schema);\n\n // If the schema is not provided, or it's a simple string schema, create a DynamicTool\n if (!fields.schema || isSimpleStringSchema || isStringJSONSchema) {\n return new DynamicTool<ToolOutputT>({\n ...fields,\n description:\n fields.description ??\n (fields.schema as { description?: string } | undefined)?.description ??\n `${fields.name} tool`,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n resolve(func(input as any, childConfig as any));\n } catch (e) {\n reject(e);\n }\n }\n );\n });\n },\n });\n }\n\n const schema = fields.schema as InteropZodObject | JSONSchema;\n\n const description =\n fields.description ??\n (fields.schema as { description?: string }).description ??\n `${fields.name} tool`;\n\n return new DynamicStructuredTool<\n typeof schema,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT\n >({\n ...fields,\n description,\n schema,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n if (config?.signal) {\n config.signal.addEventListener(\"abort\", () => {\n return reject(getAbortSignalError(config.signal));\n });\n }\n\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await func(input as any, childConfig as any);\n\n /**\n * If the signal is aborted, we don't want to resolve the promise\n * as the promise is already rejected.\n */\n if (config?.signal?.aborted) {\n return;\n }\n\n resolve(result);\n } catch (e) {\n reject(e);\n }\n }\n );\n });\n },\n }) as DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT\n >;\n}\n\nfunction _formatToolOutput<TOutput extends ToolOutputType>(params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}): ToolMessage | TOutput {\n const { content, artifact, toolCallId, metadata } = params;\n if (toolCallId && !isDirectToolOutput(content)) {\n if (\n typeof content === \"string\" ||\n (Array.isArray(content) &&\n content.every((item) => typeof item === \"object\"))\n ) {\n return new ToolMessage({\n status: \"success\",\n content,\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n } else {\n return new ToolMessage({\n status: \"success\",\n content: _stringify(content),\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n }\n } else {\n return content;\n }\n}\n\nfunction _stringify(content: unknown): string {\n try {\n return JSON.stringify(content, null, 2) ?? \"\";\n } catch (_noOp) {\n return `${content}`;\n }\n}\n\nexport type ServerT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AC;IAGJ,MAAM,cAAc,YAAY,QAAQ,EACtC,WAAW,YAAY,UAAU,CAClC,EAAC;IAEG,mCAAmC,cACtC,uBAAuB,YAAY,EACnC,YAAY;AACV,SAAI;MAEF,MAAM,SAAS,MAAM,KAAK,OAAc,YAAmB;;;;;AAM3D,UAAI,QAAQ,QAAQ,QAClB;MAGF,QAAQ,OAAO;KAChB,SAAQ,GAAG;MACV,OAAO,EAAE;KACV;IACF,EACF;GACF;EACF;CACF;AAMF;AAED,SAAS,kBAAkDC,QAMjC;CACxB,MAAM,EAAE,SAAS,UAAU,YAAY,UAAU,GAAG;AACpD,KAAI,cAAc,CAAC,mBAAmB,QAAQ,CAC5C,KACE,OAAO,YAAY,YAClB,MAAM,QAAQ,QAAQ,IACrB,QAAQ,MAAM,CAAC,SAAS,OAAO,SAAS,SAAS,CAEnD,QAAO,IAAI,YAAY;EACrB,QAAQ;EACR;EACA;EACA,cAAc;EACd,MAAM,OAAO;EACb;CACD;KAED,QAAO,IAAI,YAAY;EACrB,QAAQ;EACR,SAAS,WAAW,QAAQ;EAC5B;EACA,cAAc;EACd,MAAM,OAAO;EACb;CACD;KAGH,QAAO;AAEV;AAED,SAAS,WAAWC,SAA0B;AAC5C,KAAI;AACF,SAAO,KAAK,UAAU,SAAS,MAAM,EAAE,IAAI;CAC5C,SAAQ,OAAO;AACd,SAAO,GAAG,SAAS;CACpB;AACF"}
1
+ {"version":3,"file":"index.js","names":["fields?: ToolParams","input: TInput","config?: TConfig","toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >","enrichedConfig: ToolRunnableConfig","arg: TArg","configArg?: TConfig","tags?: string[]","parsed: SchemaOutputT","z4","result","toolCallId: string | undefined","callbacks?: TConfig","fields: DynamicToolInput<ToolOutputT>","input: string","runManager?: CallbackManagerForToolRun","parentConfig?: ToolRunnableConfig","fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>","arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0]","parentConfig?: RunnableConfig","func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>","fields: ToolWrapperParams<SchemaT>","listener: (() => void) | undefined","params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}","content: unknown"],"sources":["../../src/tools/index.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { z as z4, ZodError } from \"zod/v4\";\nimport {\n validate,\n type Schema as ValidationSchema,\n} from \"@cfworker/json-schema\";\nimport {\n CallbackManager,\n CallbackManagerForToolRun,\n parseCallbackConfigArg,\n} from \"../callbacks/manager.js\";\nimport { BaseLangChain } from \"../language_models/base.js\";\nimport {\n mergeConfigs,\n ensureConfig,\n patchConfig,\n pickRunnableConfigKeys,\n type RunnableConfig,\n} from \"../runnables/config.js\";\nimport type { RunnableFunc } from \"../runnables/base.js\";\nimport { isDirectToolOutput, ToolCall, ToolMessage } from \"../messages/tool.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../singletons/index.js\";\nimport type { RunnableToolLike } from \"../runnables/base.js\";\nimport {\n _configHasToolCallId,\n _isToolCall,\n ToolInputParsingException,\n} from \"./utils.js\";\nimport {\n type InferInteropZodInput,\n type InferInteropZodOutput,\n type InteropZodObject,\n type InteropZodType,\n interopParseAsync,\n isSimpleStringZodSchema,\n isInteropZodSchema,\n type ZodStringV3,\n type ZodStringV4,\n type ZodObjectV3,\n type ZodObjectV4,\n} from \"../utils/types/zod.js\";\nimport { getAbortSignalError } from \"../utils/signal.js\";\nimport type {\n StructuredToolCallInput,\n ToolInputSchemaBase,\n ToolReturnType,\n ResponseFormat,\n ToolInputSchemaInputType,\n ToolInputSchemaOutputType,\n ToolParams,\n ToolRunnableConfig,\n StructuredToolInterface,\n DynamicToolInput,\n DynamicStructuredToolInput,\n StringInputToolSchema,\n ToolInterface,\n ToolOutputType,\n ToolRuntime,\n} from \"./types.js\";\nimport { type JSONSchema, validatesOnlyStrings } from \"../utils/json_schema.js\";\n\nexport type {\n BaseDynamicToolInput,\n ContentAndArtifact,\n DynamicToolInput,\n DynamicStructuredToolInput,\n ResponseFormat,\n StructuredToolCallInput,\n StructuredToolInterface,\n StructuredToolParams,\n ToolInterface,\n ToolParams,\n ToolReturnType,\n ToolRunnableConfig,\n ToolInputSchemaBase as ToolSchemaBase,\n} from \"./types.js\";\n\nexport {\n isLangChainTool,\n isRunnableToolLike,\n isStructuredTool,\n isStructuredToolParams,\n type ToolRuntime,\n} from \"./types.js\";\n\nexport { ToolInputParsingException };\n/**\n * Base class for Tools that accept input of any shape defined by a Zod schema.\n */\nexport abstract class StructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n >\n extends BaseLangChain<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolOutputT | ToolMessage\n >\n implements StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT>\n{\n abstract name: string;\n\n abstract description: string;\n\n abstract schema: SchemaT;\n\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect = false;\n\n verboseParsingErrors = false;\n\n get lc_namespace() {\n return [\"langchain\", \"tools\"];\n }\n\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat = \"content\";\n\n /**\n * Default config object for the tool runnable.\n */\n defaultConfig?: ToolRunnableConfig;\n\n constructor(fields?: ToolParams) {\n super(fields ?? {});\n\n this.verboseParsingErrors =\n fields?.verboseParsingErrors ?? this.verboseParsingErrors;\n this.responseFormat = fields?.responseFormat ?? this.responseFormat;\n this.defaultConfig = fields?.defaultConfig ?? this.defaultConfig;\n this.metadata = fields?.metadata ?? this.metadata;\n }\n\n protected abstract _call(\n arg: SchemaOutputT,\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT>;\n\n /**\n * Invokes the tool with the provided input and configuration.\n * @param input The input for the tool.\n * @param config Optional configuration for the tool.\n * @returns A Promise that resolves with the tool's output.\n */\n async invoke<\n TInput extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined\n >(\n input: TInput,\n config?: TConfig\n ): Promise<ToolReturnType<TInput, TConfig, ToolOutputT>> {\n let toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n\n let enrichedConfig: ToolRunnableConfig = ensureConfig(\n mergeConfigs(this.defaultConfig, config)\n );\n if (_isToolCall(input)) {\n toolInput = input.args as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n enrichedConfig = {\n ...enrichedConfig,\n toolCall: input,\n };\n } else {\n toolInput = input as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n }\n\n return this.call(toolInput, enrichedConfig) as Promise<\n ToolReturnType<TInput, TConfig, ToolOutputT>\n >;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument, configuration, and tags. It\n * parses the input according to the schema, handles any errors, and\n * manages callbacks.\n * @param arg The input argument for the tool.\n * @param configArg Optional configuration or callbacks for the tool.\n * @param tags Optional tags for the tool.\n * @returns A Promise that resolves with a string.\n */\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>> {\n // Determine the actual input that needs parsing/validation.\n // If arg is a ToolCall, use its args; otherwise, use arg directly.\n const inputForValidation = _isToolCall(arg) ? arg.args : arg;\n\n let parsed: SchemaOutputT; // This will hold the successfully parsed input of the expected output type.\n if (isInteropZodSchema(this.schema)) {\n try {\n // Validate the inputForValidation - TS needs help here as it can't exclude ToolCall based on the check\n parsed = await interopParseAsync(\n this.schema as InteropZodType,\n inputForValidation as Exclude<TArg, ToolCall>\n );\n } catch (e) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${(e as Error).message}`;\n }\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (e instanceof Error && e.constructor.name === \"ZodError\") {\n message = `${message}\\n\\n${z4.prettifyError(e as ZodError)}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n } else {\n const result = validate(\n inputForValidation,\n this.schema as ValidationSchema\n );\n if (!result.valid) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${result.errors\n .map((e) => `${e.keywordLocation}: ${e.error}`)\n .join(\"\\n\")}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n // Assign the validated input to parsed\n // We cast here because validate() doesn't narrow the type sufficiently for TS, but we know it's valid.\n parsed = inputForValidation as SchemaOutputT;\n }\n\n const config = parseCallbackConfigArg(configArg);\n const callbackManager_ = CallbackManager.configure(\n config.callbacks,\n this.callbacks,\n config.tags || tags,\n this.tags,\n config.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n const runManager = await callbackManager_?.handleToolStart(\n this.toJSON(),\n // Log the original raw input arg\n typeof arg === \"string\" ? arg : JSON.stringify(arg),\n config.runId,\n undefined,\n undefined,\n undefined,\n config.runName\n );\n delete config.runId;\n let result;\n try {\n // Pass the correctly typed parsed input to _call\n result = await this._call(parsed, runManager, config);\n } catch (e) {\n await runManager?.handleToolError(e);\n throw e;\n }\n let content;\n let artifact;\n if (this.responseFormat === \"content_and_artifact\") {\n if (Array.isArray(result) && result.length === 2) {\n [content, artifact] = result;\n } else {\n throw new Error(\n `Tool response format is \"content_and_artifact\" but the output was not a two-tuple.\\nResult: ${JSON.stringify(\n result\n )}`\n );\n }\n } else {\n content = result;\n }\n\n let toolCallId: string | undefined;\n // Extract toolCallId ONLY if the original arg was a ToolCall\n if (_isToolCall(arg)) {\n toolCallId = arg.id;\n }\n // Or if it was provided in the config's toolCall property\n if (!toolCallId && _configHasToolCallId(config)) {\n toolCallId = config.toolCall.id;\n }\n\n const formattedOutput = _formatToolOutput<ToolOutputT>({\n content,\n artifact,\n toolCallId,\n name: this.name,\n metadata: this.metadata,\n });\n await runManager?.handleToolEnd(formattedOutput);\n return formattedOutput as ToolReturnType<TArg, TConfig, ToolOutputT>;\n }\n}\n\n/**\n * Base class for Tools that accept input as a string.\n */\nexport abstract class Tool<ToolOutputT = ToolOutputType>\n extends StructuredTool<\n StringInputToolSchema,\n ToolInputSchemaOutputType<StringInputToolSchema>,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n implements\n ToolInterface<\n StringInputToolSchema,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n{\n schema = z\n .object({ input: z.string().optional() })\n .transform((obj) => obj.input);\n\n constructor(fields?: ToolParams) {\n super(fields);\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument and callbacks. It handles\n * string inputs specifically.\n * @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema.\n * @param callbacks Optional callbacks for the tool.\n * @returns A Promise that resolves with a string.\n */\n // Match the base class signature including the generics and conditional return type\n call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n callbacks?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n // Prepare the input for the base class call method.\n // If arg is string or undefined, wrap it; otherwise, pass ToolCall or { input: ... } directly.\n const structuredArg =\n typeof arg === \"string\" || arg == null ? { input: arg } : arg;\n\n // Ensure TConfig is passed to super.call\n return super.call(structuredArg, callbacks);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and description.\n */\nexport class DynamicTool<\n ToolOutputT = ToolOutputType\n> extends Tool<ToolOutputT> {\n static lc_name() {\n return \"DynamicTool\";\n }\n\n name: string;\n\n description: string;\n\n func: DynamicToolInput<ToolOutputT>[\"func\"];\n\n constructor(fields: DynamicToolInput<ToolOutputT>) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n async call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n configArg?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n // Call the Tool class's call method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig);\n }\n\n /** @ignore */\n async _call(\n input: string, // DynamicTool's _call specifically expects a string after schema transformation\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT> {\n return this.func(input, runManager, parentConfig);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and\n * description, designed to work with structured data. It extends the\n * StructuredTool class and overrides the _call method to execute the\n * provided function when the tool is called.\n *\n * Schema can be passed as Zod or JSON schema. The tool will not validate\n * input if JSON schema is passed.\n */\nexport class DynamicStructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n> extends StructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT> {\n static lc_name() {\n return \"DynamicStructuredTool\";\n }\n\n name: string;\n\n description: string;\n\n func: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>[\"func\"];\n\n schema: SchemaT;\n\n constructor(\n fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>\n ) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n this.schema = fields.schema;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n // Match the base class signature\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n\n // Call the base class method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig, tags);\n }\n\n protected _call(\n arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0],\n runManager?: CallbackManagerForToolRun,\n parentConfig?: RunnableConfig\n ): Promise<ToolOutputT> {\n return this.func(arg, runManager, parentConfig);\n }\n}\n\n/**\n * Abstract base class for toolkits in LangChain. Toolkits are collections\n * of tools that agents can use. Subclasses must implement the `tools`\n * property to provide the specific tools for the toolkit.\n */\nexport abstract class BaseToolkit {\n abstract tools: StructuredToolInterface[];\n\n getTools(): StructuredToolInterface[] {\n return this.tools;\n }\n}\n\n/**\n * Parameters for the tool function.\n * Schema can be provided as Zod or JSON schema.\n * Both schema types will be validated.\n * @template {ToolInputSchemaBase} RunInput The input schema for the tool.\n */\ninterface ToolWrapperParams<RunInput = ToolInputSchemaBase | undefined>\n extends ToolParams {\n /**\n * The name of the tool. If using with an LLM, this\n * will be passed as the tool name.\n */\n name: string;\n /**\n * The description of the tool.\n * @default `${fields.name} tool`\n */\n description?: string;\n /**\n * The input schema for the tool. If using an LLM, this\n * will be passed as the tool schema to generate arguments\n * for.\n */\n schema?: RunInput;\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat;\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect?: boolean;\n}\n\n/**\n * Creates a new StructuredTool instance with the provided function, name, description, and schema.\n *\n * Schema can be provided as Zod or JSON schema, and both will be validated.\n *\n * @function\n * @template {ToolInputSchemaBase} SchemaT The input schema for the tool.\n * @template {ToolReturnType} ToolOutputT The output type of the tool.\n *\n * @param {RunnableFunc<z.output<SchemaT>, ToolOutputT>} func - The function to invoke when the tool is called.\n * @param {ToolWrapperParams<SchemaT>} fields - An object containing the following properties:\n * @param {string} fields.name The name of the tool.\n * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.\n * @param {z.AnyZodObject | z.ZodString | undefined} fields.schema The Zod schema defining the input for the tool. If undefined, it will default to a Zod string schema.\n *\n * @returns {DynamicStructuredTool<SchemaT>} A new StructuredTool instance.\n */\nexport function tool<SchemaT extends ZodStringV3, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<SchemaT extends ZodStringV4, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<\n Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends\n | InteropZodObject\n | InteropZodType<string>\n | JSONSchema = InteropZodObject,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT>\n):\n | DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>\n | DynamicTool<ToolOutputT>;\n\n// Overloads with ToolRuntime as CallOptions\nexport function tool<\n SchemaT extends ZodStringV3,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodStringV4,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;\n\nexport function tool<\n SchemaT extends\n | InteropZodObject\n | InteropZodType<string>\n | JSONSchema = InteropZodObject,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n):\n | DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>\n | DynamicTool<ToolOutputT> {\n const isSimpleStringSchema = isSimpleStringZodSchema(fields.schema);\n const isStringJSONSchema = validatesOnlyStrings(fields.schema);\n\n // If the schema is not provided, or it's a simple string schema, create a DynamicTool\n if (!fields.schema || isSimpleStringSchema || isStringJSONSchema) {\n return new DynamicTool<ToolOutputT>({\n ...fields,\n description:\n fields.description ??\n (fields.schema as { description?: string } | undefined)?.description ??\n `${fields.name} tool`,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n resolve(func(input as any, childConfig as any));\n } catch (e) {\n reject(e);\n }\n }\n );\n });\n },\n });\n }\n\n const schema = fields.schema as InteropZodObject | JSONSchema;\n\n const description =\n fields.description ??\n (fields.schema as { description?: string }).description ??\n `${fields.name} tool`;\n\n return new DynamicStructuredTool<\n typeof schema,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT\n >({\n ...fields,\n description,\n schema,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n let listener: (() => void) | undefined;\n const cleanup = () => {\n if (config?.signal && listener) {\n config.signal.removeEventListener(\"abort\", listener);\n }\n };\n\n if (config?.signal) {\n listener = () => {\n cleanup();\n reject(getAbortSignalError(config.signal));\n };\n config.signal.addEventListener(\"abort\", listener);\n }\n\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await func(input as any, childConfig as any);\n\n /**\n * If the signal is aborted, we don't want to resolve the promise\n * as the promise is already rejected.\n */\n if (config?.signal?.aborted) {\n cleanup();\n return;\n }\n\n cleanup();\n resolve(result);\n } catch (e) {\n cleanup();\n reject(e);\n }\n }\n );\n });\n },\n }) as DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT\n >;\n}\n\nfunction _formatToolOutput<TOutput extends ToolOutputType>(params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}): ToolMessage | TOutput {\n const { content, artifact, toolCallId, metadata } = params;\n if (toolCallId && !isDirectToolOutput(content)) {\n if (\n typeof content === \"string\" ||\n (Array.isArray(content) &&\n content.every((item) => typeof item === \"object\"))\n ) {\n return new ToolMessage({\n status: \"success\",\n content,\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n } else {\n return new ToolMessage({\n status: \"success\",\n content: _stringify(content),\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n }\n } else {\n return content;\n }\n}\n\nfunction _stringify(content: unknown): string {\n try {\n return JSON.stringify(content, null, 2) ?? \"\";\n } catch (_noOp) {\n return `${content}`;\n }\n}\n\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool =\n | StructuredToolInterface\n | DynamicTool\n | RunnableToolLike;\n"],"mappings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OAAO,CAAC;KAC3C;KACD,OAAO,OAAO,iBAAiB,SAAS,SAAS;IAClD;IAED,MAAM,cAAc,YAAY,QAAQ,EACtC,WAAW,YAAY,UAAU,CAClC,EAAC;IAEG,mCAAmC,cACtC,uBAAuB,YAAY,EACnC,YAAY;AACV,SAAI;MAEF,MAAM,SAAS,MAAM,KAAK,OAAc,YAAmB;;;;;AAM3D,UAAI,QAAQ,QAAQ,SAAS;OAC3B,SAAS;AACT;MACD;MAED,SAAS;MACT,QAAQ,OAAO;KAChB,SAAQ,GAAG;MACV,SAAS;MACT,OAAO,EAAE;KACV;IACF,EACF;GACF;EACF;CACF;AAMF;AAED,SAAS,kBAAkDC,QAMjC;CACxB,MAAM,EAAE,SAAS,UAAU,YAAY,UAAU,GAAG;AACpD,KAAI,cAAc,CAAC,mBAAmB,QAAQ,CAC5C,KACE,OAAO,YAAY,YAClB,MAAM,QAAQ,QAAQ,IACrB,QAAQ,MAAM,CAAC,SAAS,OAAO,SAAS,SAAS,CAEnD,QAAO,IAAI,YAAY;EACrB,QAAQ;EACR;EACA;EACA,cAAc;EACd,MAAM,OAAO;EACb;CACD;KAED,QAAO,IAAI,YAAY;EACrB,QAAQ;EACR,SAAS,WAAW,QAAQ;EAC5B;EACA,cAAc;EACd,MAAM,OAAO;EACb;CACD;KAGH,QAAO;AAEV;AAED,SAAS,WAAWC,SAA0B;AAC5C,KAAI;AACF,SAAO,KAAK,UAAU,SAAS,MAAM,EAAE,IAAI;CAC5C,SAAQ,OAAO;AACd,SAAO,GAAG,SAAS;CACpB;AACF"}
@@ -64,11 +64,17 @@ var AsyncCaller = class {
64
64
  }), { throwOnTimeout: true });
65
65
  }
66
66
  callWithOptions(options, callable, ...args) {
67
- if (options.signal) return Promise.race([this.call(callable, ...args), new Promise((_, reject) => {
68
- options.signal?.addEventListener("abort", () => {
69
- reject(require_signal.getAbortSignalError(options.signal));
67
+ if (options.signal) {
68
+ let listener;
69
+ return Promise.race([this.call(callable, ...args), new Promise((_, reject) => {
70
+ listener = () => {
71
+ reject(require_signal.getAbortSignalError(options.signal));
72
+ };
73
+ options.signal?.addEventListener("abort", listener);
74
+ })]).finally(() => {
75
+ if (options.signal && listener) options.signal.removeEventListener("abort", listener);
70
76
  });
71
- })]);
77
+ }
72
78
  return this.call(callable, ...args);
73
79
  }
74
80
  fetch(...args) {