@langchain/core 0.2.18-rc.0 → 0.2.19

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 (128) hide show
  1. package/dist/callbacks/manager.cjs +94 -19
  2. package/dist/callbacks/manager.d.ts +3 -1
  3. package/dist/callbacks/manager.js +94 -19
  4. package/dist/messages/base.cjs +16 -1
  5. package/dist/messages/base.d.ts +9 -0
  6. package/dist/messages/base.js +14 -0
  7. package/dist/messages/tool.cjs +23 -0
  8. package/dist/messages/tool.d.ts +15 -0
  9. package/dist/messages/tool.js +24 -1
  10. package/dist/messages/utils.cjs +1 -1
  11. package/dist/messages/utils.js +1 -1
  12. package/dist/output_parsers/string.cjs +1 -0
  13. package/dist/output_parsers/string.js +1 -0
  14. package/dist/runnables/base.cjs +1 -3
  15. package/dist/runnables/base.js +1 -3
  16. package/dist/runnables/remote.cjs +3 -1
  17. package/dist/runnables/remote.js +3 -1
  18. package/dist/tools/index.cjs +15 -6
  19. package/dist/tools/index.d.ts +21 -12
  20. package/dist/tools/index.js +15 -6
  21. package/dist/utils/testing/index.cjs +161 -3
  22. package/dist/utils/testing/index.d.ts +94 -3
  23. package/dist/utils/testing/index.js +160 -3
  24. package/package.json +4 -3
  25. package/dist/caches/tests/in_memory_cache.test.d.ts +0 -1
  26. package/dist/caches/tests/in_memory_cache.test.js +0 -33
  27. package/dist/callbacks/tests/callbacks.test.d.ts +0 -1
  28. package/dist/callbacks/tests/callbacks.test.js +0 -495
  29. package/dist/callbacks/tests/manager.int.test.d.ts +0 -1
  30. package/dist/callbacks/tests/manager.int.test.js +0 -29
  31. package/dist/callbacks/tests/run_collector.test.d.ts +0 -1
  32. package/dist/callbacks/tests/run_collector.test.js +0 -58
  33. package/dist/language_models/tests/chat_models.test.d.ts +0 -1
  34. package/dist/language_models/tests/chat_models.test.js +0 -204
  35. package/dist/language_models/tests/count_tokens.test.d.ts +0 -1
  36. package/dist/language_models/tests/count_tokens.test.js +0 -19
  37. package/dist/language_models/tests/llms.test.d.ts +0 -1
  38. package/dist/language_models/tests/llms.test.js +0 -52
  39. package/dist/messages/tests/base_message.test.d.ts +0 -1
  40. package/dist/messages/tests/base_message.test.js +0 -245
  41. package/dist/messages/tests/message_utils.test.d.ts +0 -1
  42. package/dist/messages/tests/message_utils.test.js +0 -434
  43. package/dist/output_parsers/openai_tools/tests/json_output_tools_parser.test.d.ts +0 -1
  44. package/dist/output_parsers/openai_tools/tests/json_output_tools_parser.test.js +0 -81
  45. package/dist/output_parsers/tests/json.test.d.ts +0 -1
  46. package/dist/output_parsers/tests/json.test.js +0 -427
  47. package/dist/output_parsers/tests/output_parser.test.d.ts +0 -1
  48. package/dist/output_parsers/tests/output_parser.test.js +0 -78
  49. package/dist/output_parsers/tests/string.test.d.ts +0 -1
  50. package/dist/output_parsers/tests/string.test.js +0 -68
  51. package/dist/output_parsers/tests/structured.test.d.ts +0 -1
  52. package/dist/output_parsers/tests/structured.test.js +0 -166
  53. package/dist/output_parsers/tests/xml.test.d.ts +0 -1
  54. package/dist/output_parsers/tests/xml.test.js +0 -81
  55. package/dist/prompts/tests/chat.mustache.test.d.ts +0 -1
  56. package/dist/prompts/tests/chat.mustache.test.js +0 -129
  57. package/dist/prompts/tests/chat.test.d.ts +0 -1
  58. package/dist/prompts/tests/chat.test.js +0 -557
  59. package/dist/prompts/tests/few_shot.test.d.ts +0 -1
  60. package/dist/prompts/tests/few_shot.test.js +0 -224
  61. package/dist/prompts/tests/pipeline.test.d.ts +0 -1
  62. package/dist/prompts/tests/pipeline.test.js +0 -101
  63. package/dist/prompts/tests/prompt.mustache.test.d.ts +0 -1
  64. package/dist/prompts/tests/prompt.mustache.test.js +0 -105
  65. package/dist/prompts/tests/prompt.test.d.ts +0 -1
  66. package/dist/prompts/tests/prompt.test.js +0 -78
  67. package/dist/prompts/tests/structured.test.d.ts +0 -1
  68. package/dist/prompts/tests/structured.test.js +0 -37
  69. package/dist/prompts/tests/template.test.d.ts +0 -1
  70. package/dist/prompts/tests/template.test.js +0 -24
  71. package/dist/runnables/tests/runnable.test.d.ts +0 -1
  72. package/dist/runnables/tests/runnable.test.js +0 -491
  73. package/dist/runnables/tests/runnable_binding.test.d.ts +0 -1
  74. package/dist/runnables/tests/runnable_binding.test.js +0 -46
  75. package/dist/runnables/tests/runnable_branch.test.d.ts +0 -1
  76. package/dist/runnables/tests/runnable_branch.test.js +0 -116
  77. package/dist/runnables/tests/runnable_graph.test.d.ts +0 -1
  78. package/dist/runnables/tests/runnable_graph.test.js +0 -100
  79. package/dist/runnables/tests/runnable_history.test.d.ts +0 -1
  80. package/dist/runnables/tests/runnable_history.test.js +0 -177
  81. package/dist/runnables/tests/runnable_interface.test.d.ts +0 -1
  82. package/dist/runnables/tests/runnable_interface.test.js +0 -209
  83. package/dist/runnables/tests/runnable_map.test.d.ts +0 -1
  84. package/dist/runnables/tests/runnable_map.test.js +0 -238
  85. package/dist/runnables/tests/runnable_passthrough.test.d.ts +0 -1
  86. package/dist/runnables/tests/runnable_passthrough.test.js +0 -96
  87. package/dist/runnables/tests/runnable_remote.int.test.d.ts +0 -1
  88. package/dist/runnables/tests/runnable_remote.int.test.js +0 -138
  89. package/dist/runnables/tests/runnable_remote.test.d.ts +0 -1
  90. package/dist/runnables/tests/runnable_remote.test.js +0 -200
  91. package/dist/runnables/tests/runnable_retry.test.d.ts +0 -1
  92. package/dist/runnables/tests/runnable_retry.test.js +0 -125
  93. package/dist/runnables/tests/runnable_stream_events.test.d.ts +0 -1
  94. package/dist/runnables/tests/runnable_stream_events.test.js +0 -1013
  95. package/dist/runnables/tests/runnable_stream_events_v2.test.d.ts +0 -1
  96. package/dist/runnables/tests/runnable_stream_events_v2.test.js +0 -2022
  97. package/dist/runnables/tests/runnable_stream_log.test.d.ts +0 -1
  98. package/dist/runnables/tests/runnable_stream_log.test.js +0 -71
  99. package/dist/runnables/tests/runnable_tools.test.d.ts +0 -1
  100. package/dist/runnables/tests/runnable_tools.test.js +0 -149
  101. package/dist/runnables/tests/runnable_tracing.int.test.d.ts +0 -1
  102. package/dist/runnables/tests/runnable_tracing.int.test.js +0 -37
  103. package/dist/runnables/tests/runnable_with_fallbacks.test.d.ts +0 -1
  104. package/dist/runnables/tests/runnable_with_fallbacks.test.js +0 -36
  105. package/dist/singletons/tests/async_local_storage.test.d.ts +0 -1
  106. package/dist/singletons/tests/async_local_storage.test.js +0 -153
  107. package/dist/structured_query/tests/utils.test.d.ts +0 -1
  108. package/dist/structured_query/tests/utils.test.js +0 -47
  109. package/dist/tools/tests/tools.test.d.ts +0 -1
  110. package/dist/tools/tests/tools.test.js +0 -85
  111. package/dist/tracers/tests/langchain_tracer.int.test.d.ts +0 -1
  112. package/dist/tracers/tests/langchain_tracer.int.test.js +0 -74
  113. package/dist/tracers/tests/langsmith_interop.test.d.ts +0 -1
  114. package/dist/tracers/tests/langsmith_interop.test.js +0 -551
  115. package/dist/tracers/tests/tracer.test.d.ts +0 -1
  116. package/dist/tracers/tests/tracer.test.js +0 -378
  117. package/dist/utils/testing/tests/chatfake.test.d.ts +0 -1
  118. package/dist/utils/testing/tests/chatfake.test.js +0 -112
  119. package/dist/utils/tests/async_caller.test.d.ts +0 -1
  120. package/dist/utils/tests/async_caller.test.js +0 -27
  121. package/dist/utils/tests/enviroment.test.d.ts +0 -1
  122. package/dist/utils/tests/enviroment.test.js +0 -6
  123. package/dist/utils/tests/function_calling.test.d.ts +0 -1
  124. package/dist/utils/tests/function_calling.test.js +0 -107
  125. package/dist/utils/tests/math_utils.test.d.ts +0 -1
  126. package/dist/utils/tests/math_utils.test.js +0 -139
  127. package/dist/utils/tests/polyfill_stream.test.d.ts +0 -1
  128. package/dist/utils/tests/polyfill_stream.test.js +0 -15
@@ -1,4 +1,4 @@
1
- import { BaseMessage, BaseMessageChunk, mergeContent, _mergeDicts, _mergeObj, } from "./base.js";
1
+ import { BaseMessage, BaseMessageChunk, mergeContent, _mergeDicts, _mergeObj, _mergeStatus, } from "./base.js";
2
2
  /**
3
3
  * Represents a tool message in a conversation.
4
4
  */
@@ -16,6 +16,16 @@ export class ToolMessage extends BaseMessage {
16
16
  fields = { content: fields, name, tool_call_id: tool_call_id };
17
17
  }
18
18
  super(fields);
19
+ /**
20
+ * Status of the tool invocation.
21
+ * @version 0.2.19
22
+ */
23
+ Object.defineProperty(this, "status", {
24
+ enumerable: true,
25
+ configurable: true,
26
+ writable: true,
27
+ value: void 0
28
+ });
19
29
  Object.defineProperty(this, "tool_call_id", {
20
30
  enumerable: true,
21
31
  configurable: true,
@@ -38,6 +48,7 @@ export class ToolMessage extends BaseMessage {
38
48
  });
39
49
  this.tool_call_id = fields.tool_call_id;
40
50
  this.artifact = fields.artifact;
51
+ this.status = fields.status;
41
52
  }
42
53
  _getType() {
43
54
  return "tool";
@@ -66,6 +77,16 @@ export class ToolMessageChunk extends BaseMessageChunk {
66
77
  writable: true,
67
78
  value: void 0
68
79
  });
80
+ /**
81
+ * Status of the tool invocation.
82
+ * @version 0.2.19
83
+ */
84
+ Object.defineProperty(this, "status", {
85
+ enumerable: true,
86
+ configurable: true,
87
+ writable: true,
88
+ value: void 0
89
+ });
69
90
  /**
70
91
  * Artifact of the Tool execution which is not meant to be sent to the model.
71
92
  *
@@ -82,6 +103,7 @@ export class ToolMessageChunk extends BaseMessageChunk {
82
103
  });
83
104
  this.tool_call_id = fields.tool_call_id;
84
105
  this.artifact = fields.artifact;
106
+ this.status = fields.status;
85
107
  }
86
108
  static lc_name() {
87
109
  return "ToolMessageChunk";
@@ -97,6 +119,7 @@ export class ToolMessageChunk extends BaseMessageChunk {
97
119
  artifact: _mergeObj(this.artifact, chunk.artifact),
98
120
  tool_call_id: this.tool_call_id,
99
121
  id: this.id ?? chunk.id,
122
+ status: _mergeStatus(this.status, chunk.status),
100
123
  });
101
124
  }
102
125
  get _printableFields() {
@@ -121,7 +121,7 @@ function mapStoredMessageToChatMessage(message) {
121
121
  throw new Error("Tool call ID must be defined for tool messages");
122
122
  }
123
123
  return new tool_js_1.ToolMessage(storedMessage.data);
124
- case "chat": {
124
+ case "generic": {
125
125
  if (storedMessage.data.role === undefined) {
126
126
  throw new Error("Role must be defined for chat messages");
127
127
  }
@@ -116,7 +116,7 @@ export function mapStoredMessageToChatMessage(message) {
116
116
  throw new Error("Tool call ID must be defined for tool messages");
117
117
  }
118
118
  return new ToolMessage(storedMessage.data);
119
- case "chat": {
119
+ case "generic": {
120
120
  if (storedMessage.data.role === undefined) {
121
121
  throw new Error("Role must be defined for chat messages");
122
122
  }
@@ -62,6 +62,7 @@ class StringOutputParser extends transform_js_1.BaseTransformOutputParser {
62
62
  _messageContentComplexToString(content) {
63
63
  switch (content.type) {
64
64
  case "text":
65
+ case "text_delta":
65
66
  if ("text" in content) {
66
67
  // Type guard for MessageContentText
67
68
  return this._textContentToString(content);
@@ -59,6 +59,7 @@ export class StringOutputParser extends BaseTransformOutputParser {
59
59
  _messageContentComplexToString(content) {
60
60
  switch (content.type) {
61
61
  case "text":
62
+ case "text_delta":
62
63
  if ("text" in content) {
63
64
  // Type guard for MessageContentText
64
65
  return this._textContentToString(content);
@@ -834,9 +834,7 @@ class RunnableBinding extends Runnable {
834
834
  async stream(input, options) {
835
835
  return this.bound.stream(input, await this._mergeConfig((0, config_js_1.ensureConfig)(options), this.kwargs));
836
836
  }
837
- async *transform(
838
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
839
- generator, options) {
837
+ async *transform(generator, options) {
840
838
  yield* this.bound.transform(generator, await this._mergeConfig((0, config_js_1.ensureConfig)(options), this.kwargs));
841
839
  }
842
840
  streamEvents(input, options, streamOptions) {
@@ -826,9 +826,7 @@ export class RunnableBinding extends Runnable {
826
826
  async stream(input, options) {
827
827
  return this.bound.stream(input, await this._mergeConfig(ensureConfig(options), this.kwargs));
828
828
  }
829
- async *transform(
830
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
831
- generator, options) {
829
+ async *transform(generator, options) {
832
830
  yield* this.bound.transform(generator, await this._mergeConfig(ensureConfig(options), this.kwargs));
833
831
  }
834
832
  streamEvents(input, options, streamOptions) {
@@ -46,7 +46,7 @@ function revive(obj) {
46
46
  content: obj.content,
47
47
  });
48
48
  }
49
- if (obj.type === "ChatMessage" || obj.type === "chat") {
49
+ if (obj.type === "ChatMessage" || obj.type === "generic") {
50
50
  return new index_js_2.ChatMessage({
51
51
  content: obj.content,
52
52
  role: obj.role,
@@ -62,6 +62,7 @@ function revive(obj) {
62
62
  return new index_js_2.ToolMessage({
63
63
  content: obj.content,
64
64
  tool_call_id: obj.tool_call_id,
65
+ status: obj.status,
65
66
  });
66
67
  }
67
68
  if (obj.type === "AIMessage" || obj.type === "ai") {
@@ -95,6 +96,7 @@ function revive(obj) {
95
96
  return new index_js_2.ToolMessageChunk({
96
97
  content: obj.content,
97
98
  tool_call_id: obj.tool_call_id,
99
+ status: obj.status,
98
100
  });
99
101
  }
100
102
  if (obj.type === "AIMessageChunk") {
@@ -43,7 +43,7 @@ function revive(obj) {
43
43
  content: obj.content,
44
44
  });
45
45
  }
46
- if (obj.type === "ChatMessage" || obj.type === "chat") {
46
+ if (obj.type === "ChatMessage" || obj.type === "generic") {
47
47
  return new ChatMessage({
48
48
  content: obj.content,
49
49
  role: obj.role,
@@ -59,6 +59,7 @@ function revive(obj) {
59
59
  return new ToolMessage({
60
60
  content: obj.content,
61
61
  tool_call_id: obj.tool_call_id,
62
+ status: obj.status,
62
63
  });
63
64
  }
64
65
  if (obj.type === "AIMessage" || obj.type === "ai") {
@@ -92,6 +93,7 @@ function revive(obj) {
92
93
  return new ToolMessageChunk({
93
94
  content: obj.content,
94
95
  tool_call_id: obj.tool_call_id,
96
+ status: obj.status,
95
97
  });
96
98
  }
97
99
  if (obj.type === "AIMessageChunk") {
@@ -9,6 +9,7 @@ const tool_js_1 = require("../messages/tool.cjs");
9
9
  const index_js_1 = require("../singletons/index.cjs");
10
10
  const utils_js_1 = require("./utils.cjs");
11
11
  Object.defineProperty(exports, "ToolInputParsingException", { enumerable: true, get: function () { return utils_js_1.ToolInputParsingException; } });
12
+ const is_zod_schema_js_1 = require("../utils/types/is_zod_schema.cjs");
12
13
  /**
13
14
  * Base class for Tools that accept input of any shape defined by a Zod schema.
14
15
  */
@@ -94,6 +95,7 @@ class StructuredTool extends base_js_1.BaseLangChain {
94
95
  let result;
95
96
  try {
96
97
  result = await this._call(parsed, runManager, config);
98
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
97
99
  }
98
100
  catch (e) {
99
101
  await runManager?.handleToolError(e);
@@ -210,6 +212,9 @@ exports.DynamicTool = DynamicTool;
210
212
  * description, designed to work with structured data. It extends the
211
213
  * StructuredTool class and overrides the _call method to execute the
212
214
  * provided function when the tool is called.
215
+ *
216
+ * Schema can be passed as Zod or JSON schema. The tool will not validate
217
+ * input if JSON schema is passed.
213
218
  */
214
219
  class DynamicStructuredTool extends StructuredTool {
215
220
  static lc_name() {
@@ -245,7 +250,7 @@ class DynamicStructuredTool extends StructuredTool {
245
250
  this.description = fields.description;
246
251
  this.func = fields.func;
247
252
  this.returnDirect = fields.returnDirect ?? this.returnDirect;
248
- this.schema = fields.schema;
253
+ this.schema = ((0, is_zod_schema_js_1.isZodSchema)(fields.schema) ? fields.schema : zod_1.z.object({}));
249
254
  }
250
255
  /**
251
256
  * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
@@ -260,6 +265,7 @@ class DynamicStructuredTool extends StructuredTool {
260
265
  return super.call(arg, config, tags);
261
266
  }
262
267
  _call(arg, runManager, parentConfig) {
268
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
263
269
  return this.func(arg, runManager, parentConfig);
264
270
  }
265
271
  }
@@ -279,18 +285,20 @@ function tool(func, fields) {
279
285
  // If the schema is not provided, or it's a string schema, create a DynamicTool
280
286
  if (!fields.schema || !("shape" in fields.schema) || !fields.schema.shape) {
281
287
  return new DynamicTool({
282
- name: fields.name,
288
+ ...fields,
283
289
  description: fields.description ??
284
290
  fields.schema?.description ??
285
291
  `${fields.name} tool`,
286
- responseFormat: fields.responseFormat,
287
- func,
292
+ // TS doesn't restrict the type here based on the guard above
293
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
294
+ func: func,
288
295
  });
289
296
  }
290
297
  const description = fields.description ?? fields.schema.description ?? `${fields.name} tool`;
291
298
  return new DynamicStructuredTool({
292
- name: fields.name,
299
+ ...fields,
293
300
  description,
301
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
294
302
  schema: fields.schema,
295
303
  // TODO: Consider moving into DynamicStructuredTool constructor
296
304
  func: async (input, runManager, config) => {
@@ -300,6 +308,8 @@ function tool(func, fields) {
300
308
  });
301
309
  void index_js_1.AsyncLocalStorageProviderSingleton.getInstance().run(childConfig, async () => {
302
310
  try {
311
+ // TS doesn't restrict the type here based on the guard above
312
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
303
313
  resolve(func(input, childConfig));
304
314
  }
305
315
  catch (e) {
@@ -308,7 +318,6 @@ function tool(func, fields) {
308
318
  });
309
319
  });
310
320
  },
311
- responseFormat: fields.responseFormat,
312
321
  });
313
322
  }
314
323
  exports.tool = tool;
@@ -141,9 +141,9 @@ export interface DynamicToolInput extends BaseDynamicToolInput {
141
141
  /**
142
142
  * Interface for the input parameters of the DynamicStructuredTool class.
143
143
  */
144
- export interface DynamicStructuredToolInput<T extends ZodObjectAny = ZodObjectAny> extends BaseDynamicToolInput {
145
- func: (input: BaseDynamicToolInput["responseFormat"] extends "content_and_artifact" ? ToolCall : z.infer<T>, runManager?: CallbackManagerForToolRun, config?: RunnableConfig) => Promise<ToolReturnType>;
146
- schema: T;
144
+ export interface DynamicStructuredToolInput<T extends ZodObjectAny | Record<string, any> = ZodObjectAny> extends BaseDynamicToolInput {
145
+ func: (input: BaseDynamicToolInput["responseFormat"] extends "content_and_artifact" ? ToolCall : T extends ZodObjectAny ? z.infer<T> : T, runManager?: CallbackManagerForToolRun, config?: RunnableConfig) => Promise<ToolReturnType>;
146
+ schema: T extends ZodObjectAny ? T : T;
147
147
  }
148
148
  /**
149
149
  * A tool that can be created dynamically from a function, name, and description.
@@ -166,21 +166,24 @@ export declare class DynamicTool extends Tool {
166
166
  * description, designed to work with structured data. It extends the
167
167
  * StructuredTool class and overrides the _call method to execute the
168
168
  * provided function when the tool is called.
169
+ *
170
+ * Schema can be passed as Zod or JSON schema. The tool will not validate
171
+ * input if JSON schema is passed.
169
172
  */
170
- export declare class DynamicStructuredTool<T extends ZodObjectAny = ZodObjectAny> extends StructuredTool<T> {
173
+ export declare class DynamicStructuredTool<T extends ZodObjectAny | Record<string, any> = ZodObjectAny> extends StructuredTool<T extends ZodObjectAny ? T : ZodObjectAny> {
171
174
  static lc_name(): string;
172
175
  name: string;
173
176
  description: string;
174
177
  func: DynamicStructuredToolInput<T>["func"];
175
- schema: T;
178
+ schema: T extends ZodObjectAny ? T : ZodObjectAny;
176
179
  constructor(fields: DynamicStructuredToolInput<T>);
177
180
  /**
178
181
  * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
179
182
  */
180
- call(arg: z.output<T> | ToolCall, configArg?: RunnableConfig | Callbacks,
183
+ call(arg: (T extends ZodObjectAny ? z.output<T> : T) | ToolCall, configArg?: RunnableConfig | Callbacks,
181
184
  /** @deprecated */
182
185
  tags?: string[]): Promise<ToolReturnType>;
183
- protected _call(arg: z.output<T> | ToolCall, runManager?: CallbackManagerForToolRun, parentConfig?: RunnableConfig): Promise<ToolReturnType>;
186
+ protected _call(arg: (T extends ZodObjectAny ? z.output<T> : T) | ToolCall, runManager?: CallbackManagerForToolRun, parentConfig?: RunnableConfig): Promise<ToolReturnType>;
184
187
  }
185
188
  /**
186
189
  * Abstract base class for toolkits in LangChain. Toolkits are collections
@@ -193,9 +196,11 @@ export declare abstract class BaseToolkit {
193
196
  }
194
197
  /**
195
198
  * Parameters for the tool function.
196
- * @template {ZodObjectAny | z.ZodString = ZodObjectAny} RunInput The input schema for the tool. Either any Zod object, or a Zod string.
199
+ * Schema can be provided as Zod or JSON schema.
200
+ * If you pass JSON schema, tool inputs will not be validated.
201
+ * @template {ZodObjectAny | z.ZodString | Record<string, any> = ZodObjectAny} RunInput The input schema for the tool. Either any Zod object, a Zod string, or JSON schema.
197
202
  */
198
- interface ToolWrapperParams<RunInput extends ZodObjectAny | z.ZodString = ZodObjectAny> extends ToolParams {
203
+ interface ToolWrapperParams<RunInput extends ZodObjectAny | z.ZodString | Record<string, any> = ZodObjectAny> extends ToolParams {
199
204
  /**
200
205
  * The name of the tool. If using with an LLM, this
201
206
  * will be passed as the tool name.
@@ -226,8 +231,11 @@ interface ToolWrapperParams<RunInput extends ZodObjectAny | z.ZodString = ZodObj
226
231
  /**
227
232
  * Creates a new StructuredTool instance with the provided function, name, description, and schema.
228
233
  *
234
+ * Schema can be provided as Zod or JSON schema.
235
+ * If you pass JSON schema, tool inputs will not be validated.
236
+ *
229
237
  * @function
230
- * @template {ZodObjectAny | z.ZodString = ZodObjectAny} T The input schema for the tool. Either any Zod object, or a Zod string.
238
+ * @template {ZodObjectAny | z.ZodString | Record<string, any> = ZodObjectAny} T The input schema for the tool. Either any Zod object, a Zod string, or JSON schema instance.
231
239
  *
232
240
  * @param {RunnableFunc<z.output<T>, ToolReturnType>} func - The function to invoke when the tool is called.
233
241
  * @param {ToolWrapperParams<T>} fields - An object containing the following properties:
@@ -237,5 +245,6 @@ interface ToolWrapperParams<RunInput extends ZodObjectAny | z.ZodString = ZodObj
237
245
  *
238
246
  * @returns {DynamicStructuredTool<T>} A new StructuredTool instance.
239
247
  */
240
- export declare function tool<T extends z.ZodString = z.ZodString>(func: RunnableFunc<z.output<T>, ToolReturnType>, fields: ToolWrapperParams<T>): DynamicTool;
241
- export declare function tool<T extends ZodObjectAny = ZodObjectAny>(func: RunnableFunc<z.output<T>, ToolReturnType>, fields: ToolWrapperParams<T>): DynamicStructuredTool<T>;
248
+ export declare function tool<T extends z.ZodString>(func: RunnableFunc<z.output<T>, ToolReturnType>, fields: ToolWrapperParams<T>): DynamicTool;
249
+ export declare function tool<T extends ZodObjectAny>(func: RunnableFunc<z.output<T>, ToolReturnType>, fields: ToolWrapperParams<T>): DynamicStructuredTool<T>;
250
+ export declare function tool<T extends Record<string, any>>(func: RunnableFunc<T, ToolReturnType>, fields: ToolWrapperParams<T>): DynamicStructuredTool<T>;
@@ -5,6 +5,7 @@ import { ensureConfig, patchConfig, } from "../runnables/config.js";
5
5
  import { ToolMessage } from "../messages/tool.js";
6
6
  import { AsyncLocalStorageProviderSingleton } from "../singletons/index.js";
7
7
  import { _isToolCall, ToolInputParsingException } from "./utils.js";
8
+ import { isZodSchema } from "../utils/types/is_zod_schema.js";
8
9
  export { ToolInputParsingException };
9
10
  /**
10
11
  * Base class for Tools that accept input of any shape defined by a Zod schema.
@@ -91,6 +92,7 @@ export class StructuredTool extends BaseLangChain {
91
92
  let result;
92
93
  try {
93
94
  result = await this._call(parsed, runManager, config);
95
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
94
96
  }
95
97
  catch (e) {
96
98
  await runManager?.handleToolError(e);
@@ -204,6 +206,9 @@ export class DynamicTool extends Tool {
204
206
  * description, designed to work with structured data. It extends the
205
207
  * StructuredTool class and overrides the _call method to execute the
206
208
  * provided function when the tool is called.
209
+ *
210
+ * Schema can be passed as Zod or JSON schema. The tool will not validate
211
+ * input if JSON schema is passed.
207
212
  */
208
213
  export class DynamicStructuredTool extends StructuredTool {
209
214
  static lc_name() {
@@ -239,7 +244,7 @@ export class DynamicStructuredTool extends StructuredTool {
239
244
  this.description = fields.description;
240
245
  this.func = fields.func;
241
246
  this.returnDirect = fields.returnDirect ?? this.returnDirect;
242
- this.schema = fields.schema;
247
+ this.schema = (isZodSchema(fields.schema) ? fields.schema : z.object({}));
243
248
  }
244
249
  /**
245
250
  * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
@@ -254,6 +259,7 @@ export class DynamicStructuredTool extends StructuredTool {
254
259
  return super.call(arg, config, tags);
255
260
  }
256
261
  _call(arg, runManager, parentConfig) {
262
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
257
263
  return this.func(arg, runManager, parentConfig);
258
264
  }
259
265
  }
@@ -271,18 +277,20 @@ export function tool(func, fields) {
271
277
  // If the schema is not provided, or it's a string schema, create a DynamicTool
272
278
  if (!fields.schema || !("shape" in fields.schema) || !fields.schema.shape) {
273
279
  return new DynamicTool({
274
- name: fields.name,
280
+ ...fields,
275
281
  description: fields.description ??
276
282
  fields.schema?.description ??
277
283
  `${fields.name} tool`,
278
- responseFormat: fields.responseFormat,
279
- func,
284
+ // TS doesn't restrict the type here based on the guard above
285
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
286
+ func: func,
280
287
  });
281
288
  }
282
289
  const description = fields.description ?? fields.schema.description ?? `${fields.name} tool`;
283
290
  return new DynamicStructuredTool({
284
- name: fields.name,
291
+ ...fields,
285
292
  description,
293
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
286
294
  schema: fields.schema,
287
295
  // TODO: Consider moving into DynamicStructuredTool constructor
288
296
  func: async (input, runManager, config) => {
@@ -292,6 +300,8 @@ export function tool(func, fields) {
292
300
  });
293
301
  void AsyncLocalStorageProviderSingleton.getInstance().run(childConfig, async () => {
294
302
  try {
303
+ // TS doesn't restrict the type here based on the guard above
304
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
295
305
  resolve(func(input, childConfig));
296
306
  }
297
307
  catch (e) {
@@ -300,7 +310,6 @@ export function tool(func, fields) {
300
310
  });
301
311
  });
302
312
  },
303
- responseFormat: fields.responseFormat,
304
313
  });
305
314
  }
306
315
  function _formatToolOutput(params) {
@@ -3,7 +3,8 @@
3
3
  /* eslint-disable @typescript-eslint/no-explicit-any */
4
4
  /* eslint-disable @typescript-eslint/no-unused-vars */
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.SingleRunExtractor = exports.SyntheticEmbeddings = exports.FakeEmbeddings = exports.FakeTool = exports.FakeTracer = exports.FakeListChatMessageHistory = exports.FakeChatMessageHistory = exports.FakeListChatModel = exports.FakeRetriever = exports.FakeStreamingChatModel = exports.FakeChatModel = exports.FakeStreamingLLM = exports.FakeLLM = exports.FakeRunnable = exports.FakeSplitIntoListParser = void 0;
6
+ exports.FakeVectorStore = exports.SingleRunExtractor = exports.SyntheticEmbeddings = exports.FakeEmbeddings = exports.FakeTool = exports.FakeTracer = exports.FakeListChatMessageHistory = exports.FakeChatMessageHistory = exports.FakeListChatModel = exports.FakeRetriever = exports.FakeStreamingChatModel = exports.FakeChatModel = exports.FakeStreamingLLM = exports.FakeLLM = exports.FakeRunnable = exports.FakeSplitIntoListParser = void 0;
7
+ const ml_distance_1 = require("ml-distance");
7
8
  const chat_history_js_1 = require("../../chat_history.cjs");
8
9
  const document_js_1 = require("../../documents/document.cjs");
9
10
  const chat_models_js_1 = require("../../language_models/chat_models.cjs");
@@ -16,6 +17,7 @@ const base_js_2 = require("../../runnables/base.cjs");
16
17
  const index_js_3 = require("../../tools/index.cjs");
17
18
  const base_js_3 = require("../../tracers/base.cjs");
18
19
  const embeddings_js_1 = require("../../embeddings.cjs");
20
+ const vectorstores_js_1 = require("../../vectorstores.cjs");
19
21
  /**
20
22
  * Parser for comma-separated values. It splits the input text by commas
21
23
  * and trims the resulting values.
@@ -307,7 +309,7 @@ class FakeListChatModel extends chat_models_js_1.BaseChatModel {
307
309
  static lc_name() {
308
310
  return "FakeListChatModel";
309
311
  }
310
- constructor({ responses, sleep }) {
312
+ constructor({ responses, sleep, emitCustomEvent }) {
311
313
  super({});
312
314
  Object.defineProperty(this, "responses", {
313
315
  enumerable: true,
@@ -327,8 +329,15 @@ class FakeListChatModel extends chat_models_js_1.BaseChatModel {
327
329
  writable: true,
328
330
  value: void 0
329
331
  });
332
+ Object.defineProperty(this, "emitCustomEvent", {
333
+ enumerable: true,
334
+ configurable: true,
335
+ writable: true,
336
+ value: false
337
+ });
330
338
  this.responses = responses;
331
339
  this.sleep = sleep;
340
+ this.emitCustomEvent = emitCustomEvent ?? this.emitCustomEvent;
332
341
  }
333
342
  _combineLLMOutput() {
334
343
  return [];
@@ -336,8 +345,13 @@ class FakeListChatModel extends chat_models_js_1.BaseChatModel {
336
345
  _llmType() {
337
346
  return "fake-list";
338
347
  }
339
- async _generate(_messages, options) {
348
+ async _generate(_messages, options, runManager) {
340
349
  await this._sleepIfRequested();
350
+ if (this.emitCustomEvent) {
351
+ await runManager?.handleCustomEvent("some_test_event", {
352
+ someval: true,
353
+ });
354
+ }
341
355
  if (options?.stop?.length) {
342
356
  return {
343
357
  generations: [this._formatGeneration(options.stop[0])],
@@ -361,6 +375,11 @@ class FakeListChatModel extends chat_models_js_1.BaseChatModel {
361
375
  async *_streamResponseChunks(_messages, _options, runManager) {
362
376
  const response = this._currentResponse();
363
377
  this._incrementResponse();
378
+ if (this.emitCustomEvent) {
379
+ await runManager?.handleCustomEvent("some_test_event", {
380
+ someval: true,
381
+ });
382
+ }
364
383
  for await (const text of response) {
365
384
  await this._sleepIfRequested();
366
385
  const chunk = this._createResponseChunk(text);
@@ -636,3 +655,142 @@ class SingleRunExtractor extends base_js_3.BaseTracer {
636
655
  }
637
656
  }
638
657
  exports.SingleRunExtractor = SingleRunExtractor;
658
+ /**
659
+ * Class that extends `VectorStore` to store vectors in memory. Provides
660
+ * methods for adding documents, performing similarity searches, and
661
+ * creating instances from texts, documents, or an existing index.
662
+ */
663
+ class FakeVectorStore extends vectorstores_js_1.VectorStore {
664
+ _vectorstoreType() {
665
+ return "memory";
666
+ }
667
+ constructor(embeddings, { similarity, ...rest } = {}) {
668
+ super(embeddings, rest);
669
+ Object.defineProperty(this, "memoryVectors", {
670
+ enumerable: true,
671
+ configurable: true,
672
+ writable: true,
673
+ value: []
674
+ });
675
+ Object.defineProperty(this, "similarity", {
676
+ enumerable: true,
677
+ configurable: true,
678
+ writable: true,
679
+ value: void 0
680
+ });
681
+ this.similarity = similarity ?? ml_distance_1.similarity.cosine;
682
+ }
683
+ /**
684
+ * Method to add documents to the memory vector store. It extracts the
685
+ * text from each document, generates embeddings for them, and adds the
686
+ * resulting vectors to the store.
687
+ * @param documents Array of `Document` instances to be added to the store.
688
+ * @returns Promise that resolves when all documents have been added.
689
+ */
690
+ async addDocuments(documents) {
691
+ const texts = documents.map(({ pageContent }) => pageContent);
692
+ return this.addVectors(await this.embeddings.embedDocuments(texts), documents);
693
+ }
694
+ /**
695
+ * Method to add vectors to the memory vector store. It creates
696
+ * `MemoryVector` instances for each vector and document pair and adds
697
+ * them to the store.
698
+ * @param vectors Array of vectors to be added to the store.
699
+ * @param documents Array of `Document` instances corresponding to the vectors.
700
+ * @returns Promise that resolves when all vectors have been added.
701
+ */
702
+ async addVectors(vectors, documents) {
703
+ const memoryVectors = vectors.map((embedding, idx) => ({
704
+ content: documents[idx].pageContent,
705
+ embedding,
706
+ metadata: documents[idx].metadata,
707
+ }));
708
+ this.memoryVectors = this.memoryVectors.concat(memoryVectors);
709
+ }
710
+ /**
711
+ * Method to perform a similarity search in the memory vector store. It
712
+ * calculates the similarity between the query vector and each vector in
713
+ * the store, sorts the results by similarity, and returns the top `k`
714
+ * results along with their scores.
715
+ * @param query Query vector to compare against the vectors in the store.
716
+ * @param k Number of top results to return.
717
+ * @param filter Optional filter function to apply to the vectors before performing the search.
718
+ * @returns Promise that resolves with an array of tuples, each containing a `Document` and its similarity score.
719
+ */
720
+ async similaritySearchVectorWithScore(query, k, filter) {
721
+ const filterFunction = (memoryVector) => {
722
+ if (!filter) {
723
+ return true;
724
+ }
725
+ const doc = new document_js_1.Document({
726
+ metadata: memoryVector.metadata,
727
+ pageContent: memoryVector.content,
728
+ });
729
+ return filter(doc);
730
+ };
731
+ const filteredMemoryVectors = this.memoryVectors.filter(filterFunction);
732
+ const searches = filteredMemoryVectors
733
+ .map((vector, index) => ({
734
+ similarity: this.similarity(query, vector.embedding),
735
+ index,
736
+ }))
737
+ .sort((a, b) => (a.similarity > b.similarity ? -1 : 0))
738
+ .slice(0, k);
739
+ const result = searches.map((search) => [
740
+ new document_js_1.Document({
741
+ metadata: filteredMemoryVectors[search.index].metadata,
742
+ pageContent: filteredMemoryVectors[search.index].content,
743
+ }),
744
+ search.similarity,
745
+ ]);
746
+ return result;
747
+ }
748
+ /**
749
+ * Static method to create a `FakeVectorStore` instance from an array of
750
+ * texts. It creates a `Document` for each text and metadata pair, and
751
+ * adds them to the store.
752
+ * @param texts Array of texts to be added to the store.
753
+ * @param metadatas Array or single object of metadata corresponding to the texts.
754
+ * @param embeddings `Embeddings` instance used to generate embeddings for the texts.
755
+ * @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance.
756
+ * @returns Promise that resolves with a new `FakeVectorStore` instance.
757
+ */
758
+ static async fromTexts(texts, metadatas, embeddings, dbConfig) {
759
+ const docs = [];
760
+ for (let i = 0; i < texts.length; i += 1) {
761
+ const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas;
762
+ const newDoc = new document_js_1.Document({
763
+ pageContent: texts[i],
764
+ metadata,
765
+ });
766
+ docs.push(newDoc);
767
+ }
768
+ return FakeVectorStore.fromDocuments(docs, embeddings, dbConfig);
769
+ }
770
+ /**
771
+ * Static method to create a `FakeVectorStore` instance from an array of
772
+ * `Document` instances. It adds the documents to the store.
773
+ * @param docs Array of `Document` instances to be added to the store.
774
+ * @param embeddings `Embeddings` instance used to generate embeddings for the documents.
775
+ * @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance.
776
+ * @returns Promise that resolves with a new `FakeVectorStore` instance.
777
+ */
778
+ static async fromDocuments(docs, embeddings, dbConfig) {
779
+ const instance = new this(embeddings, dbConfig);
780
+ await instance.addDocuments(docs);
781
+ return instance;
782
+ }
783
+ /**
784
+ * Static method to create a `FakeVectorStore` instance from an existing
785
+ * index. It creates a new `FakeVectorStore` instance without adding any
786
+ * documents or vectors.
787
+ * @param embeddings `Embeddings` instance used to generate embeddings for the documents.
788
+ * @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance.
789
+ * @returns Promise that resolves with a new `FakeVectorStore` instance.
790
+ */
791
+ static async fromExistingIndex(embeddings, dbConfig) {
792
+ const instance = new this(embeddings, dbConfig);
793
+ return instance;
794
+ }
795
+ }
796
+ exports.FakeVectorStore = FakeVectorStore;