@langchain/core 0.2.14 → 0.2.16

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 (111) hide show
  1. package/README.md +1 -1
  2. package/caches.cjs +1 -1
  3. package/caches.d.cts +1 -1
  4. package/caches.d.ts +1 -1
  5. package/caches.js +1 -1
  6. package/callbacks/dispatch/web.cjs +1 -0
  7. package/callbacks/dispatch/web.d.cts +1 -0
  8. package/callbacks/dispatch/web.d.ts +1 -0
  9. package/callbacks/dispatch/web.js +1 -0
  10. package/callbacks/dispatch.cjs +1 -0
  11. package/callbacks/dispatch.d.cts +1 -0
  12. package/callbacks/dispatch.d.ts +1 -0
  13. package/callbacks/dispatch.js +1 -0
  14. package/dist/{caches.cjs → caches/base.cjs} +6 -6
  15. package/dist/{caches.d.ts → caches/base.d.ts} +7 -7
  16. package/dist/{caches.js → caches/base.js} +6 -6
  17. package/dist/caches/tests/in_memory_cache.test.d.ts +1 -0
  18. package/dist/caches/tests/in_memory_cache.test.js +33 -0
  19. package/dist/callbacks/base.cjs +8 -0
  20. package/dist/callbacks/base.d.ts +16 -10
  21. package/dist/callbacks/base.js +8 -0
  22. package/dist/callbacks/dispatch/index.cjs +49 -0
  23. package/dist/callbacks/dispatch/index.d.ts +35 -0
  24. package/dist/callbacks/dispatch/index.js +45 -0
  25. package/dist/callbacks/dispatch/web.cjs +61 -0
  26. package/dist/callbacks/dispatch/web.d.ts +32 -0
  27. package/dist/callbacks/dispatch/web.js +57 -0
  28. package/dist/callbacks/manager.cjs +32 -5
  29. package/dist/callbacks/manager.d.ts +5 -2
  30. package/dist/callbacks/manager.js +31 -5
  31. package/dist/language_models/base.cjs +4 -4
  32. package/dist/language_models/base.d.ts +2 -2
  33. package/dist/language_models/base.js +1 -1
  34. package/dist/language_models/chat_models.d.ts +4 -4
  35. package/dist/language_models/llms.d.ts +1 -1
  36. package/dist/language_models/tests/chat_models.test.js +33 -0
  37. package/dist/load/import_map.cjs +2 -2
  38. package/dist/load/import_map.d.ts +2 -2
  39. package/dist/load/import_map.js +2 -2
  40. package/dist/messages/ai.cjs +2 -0
  41. package/dist/messages/ai.js +2 -0
  42. package/dist/messages/base.cjs +45 -5
  43. package/dist/messages/base.d.ts +1 -0
  44. package/dist/messages/base.js +43 -4
  45. package/dist/messages/index.d.ts +1 -1
  46. package/dist/messages/tests/base_message.test.js +134 -2
  47. package/dist/messages/tests/message_utils.test.js +54 -2
  48. package/dist/messages/tool.cjs +31 -0
  49. package/dist/messages/tool.d.ts +27 -0
  50. package/dist/messages/tool.js +32 -1
  51. package/dist/messages/transformers.cjs +1 -0
  52. package/dist/messages/transformers.js +1 -0
  53. package/dist/messages/utils.cjs +5 -1
  54. package/dist/messages/utils.js +5 -1
  55. package/dist/output_parsers/openai_tools/json_output_tools_parsers.cjs +2 -0
  56. package/dist/output_parsers/openai_tools/json_output_tools_parsers.js +2 -0
  57. package/dist/runnables/base.cjs +89 -16
  58. package/dist/runnables/base.d.ts +51 -0
  59. package/dist/runnables/base.js +86 -15
  60. package/dist/runnables/config.cjs +30 -8
  61. package/dist/runnables/config.js +30 -8
  62. package/dist/runnables/history.cjs +1 -1
  63. package/dist/runnables/history.d.ts +1 -3
  64. package/dist/runnables/history.js +1 -1
  65. package/dist/runnables/index.cjs +2 -1
  66. package/dist/runnables/index.d.ts +1 -1
  67. package/dist/runnables/index.js +1 -1
  68. package/dist/runnables/tests/runnable.test.js +3 -3
  69. package/dist/runnables/tests/runnable_stream_events.test.js +1 -1
  70. package/dist/runnables/tests/runnable_stream_events_v2.test.js +124 -19
  71. package/dist/runnables/tests/runnable_tools.test.d.ts +1 -0
  72. package/dist/runnables/tests/runnable_tools.test.js +111 -0
  73. package/dist/singletons/tests/async_local_storage.test.js +38 -4
  74. package/dist/{tools.cjs → tools/index.cjs} +130 -14
  75. package/dist/{tools.d.ts → tools/index.d.ts} +69 -31
  76. package/dist/{tools.js → tools/index.js} +130 -14
  77. package/dist/tools/tests/tools.test.d.ts +1 -0
  78. package/dist/tools/tests/tools.test.js +74 -0
  79. package/dist/tracers/base.cjs +1 -0
  80. package/dist/tracers/base.d.ts +1 -1
  81. package/dist/tracers/base.js +1 -0
  82. package/dist/tracers/event_stream.cjs +15 -0
  83. package/dist/tracers/event_stream.d.ts +1 -0
  84. package/dist/tracers/event_stream.js +15 -0
  85. package/dist/tracers/initialize.cjs +2 -0
  86. package/dist/tracers/initialize.d.ts +2 -0
  87. package/dist/tracers/initialize.js +2 -0
  88. package/dist/types/zod.cjs +2 -0
  89. package/dist/types/zod.d.ts +2 -0
  90. package/dist/types/zod.js +1 -0
  91. package/dist/utils/callbacks.cjs +17 -0
  92. package/dist/utils/callbacks.d.ts +1 -0
  93. package/dist/utils/callbacks.js +13 -0
  94. package/dist/utils/function_calling.cjs +38 -10
  95. package/dist/utils/function_calling.d.ts +32 -11
  96. package/dist/utils/function_calling.js +36 -9
  97. package/dist/utils/testing/index.cjs +10 -3
  98. package/dist/utils/testing/index.d.ts +1 -1
  99. package/dist/utils/testing/index.js +9 -2
  100. package/package.json +28 -14
  101. package/tools.cjs +1 -1
  102. package/tools.d.cts +1 -1
  103. package/tools.d.ts +1 -1
  104. package/tools.js +1 -1
  105. package/dist/utils/beta_warning.cjs +0 -11
  106. package/dist/utils/beta_warning.d.ts +0 -5
  107. package/dist/utils/beta_warning.js +0 -7
  108. package/utils/beta_warning.cjs +0 -1
  109. package/utils/beta_warning.d.cts +0 -1
  110. package/utils/beta_warning.d.ts +0 -1
  111. package/utils/beta_warning.js +0 -1
@@ -1,13 +1,28 @@
1
1
  import { z } from "zod";
2
- import { CallbackManagerForToolRun, Callbacks } from "./callbacks/manager.js";
3
- import { BaseLangChain, type BaseLangChainParams } from "./language_models/base.js";
4
- import { type RunnableConfig } from "./runnables/config.js";
5
- import type { RunnableFunc, RunnableInterface } from "./runnables/base.js";
6
- type ZodAny = z.ZodObject<any, any, any, any>;
2
+ import { CallbackManagerForToolRun, Callbacks } from "../callbacks/manager.js";
3
+ import { BaseLangChain, type BaseLangChainParams } from "../language_models/base.js";
4
+ import { type RunnableConfig } from "../runnables/config.js";
5
+ import type { RunnableFunc, RunnableInterface } from "../runnables/base.js";
6
+ import { ToolCall } from "../messages/tool.js";
7
+ import { ZodAny } from "../types/zod.js";
8
+ import { MessageContent } from "../messages/base.js";
9
+ export type ResponseFormat = "content" | "content_and_artifact" | string;
10
+ type ToolReturnType = any;
11
+ export type ContentAndArtifact = [MessageContent, any];
7
12
  /**
8
13
  * Parameters for the Tool classes.
9
14
  */
10
15
  export interface ToolParams extends BaseLangChainParams {
16
+ /**
17
+ * The tool response format.
18
+ *
19
+ * If "content" then the output of the tool is interpreted as the contents of a
20
+ * ToolMessage. If "content_and_artifact" then the output is expected to be a
21
+ * two-tuple corresponding to the (content, artifact) of a ToolMessage.
22
+ *
23
+ * @default "content"
24
+ */
25
+ responseFormat?: ResponseFormat;
11
26
  }
12
27
  /**
13
28
  * Custom error class used to handle exceptions related to tool input parsing.
@@ -18,7 +33,7 @@ export declare class ToolInputParsingException extends Error {
18
33
  output?: string;
19
34
  constructor(message: string, output?: string);
20
35
  }
21
- export interface StructuredToolInterface<T extends ZodAny = ZodAny> extends RunnableInterface<(z.output<T> extends string ? string : never) | z.input<T>, string> {
36
+ export interface StructuredToolInterface<T extends ZodAny = ZodAny> extends RunnableInterface<(z.output<T> extends string ? string : never) | z.input<T> | ToolCall, ToolReturnType> {
22
37
  lc_namespace: string[];
23
38
  schema: T | z.ZodEffects<T>;
24
39
  /**
@@ -32,9 +47,9 @@ export interface StructuredToolInterface<T extends ZodAny = ZodAny> extends Runn
32
47
  * @param tags Optional tags for the tool.
33
48
  * @returns A Promise that resolves with a string.
34
49
  */
35
- call(arg: (z.output<T> extends string ? string : never) | z.input<T>, configArg?: Callbacks | RunnableConfig,
50
+ call(arg: (z.output<T> extends string ? string : never) | z.input<T> | ToolCall, configArg?: Callbacks | RunnableConfig,
36
51
  /** @deprecated */
37
- tags?: string[]): Promise<string>;
52
+ tags?: string[]): Promise<ToolReturnType>;
38
53
  name: string;
39
54
  description: string;
40
55
  returnDirect: boolean;
@@ -42,18 +57,31 @@ export interface StructuredToolInterface<T extends ZodAny = ZodAny> extends Runn
42
57
  /**
43
58
  * Base class for Tools that accept input of any shape defined by a Zod schema.
44
59
  */
45
- export declare abstract class StructuredTool<T extends ZodAny = ZodAny> extends BaseLangChain<(z.output<T> extends string ? string : never) | z.input<T>, string> {
60
+ export declare abstract class StructuredTool<T extends ZodAny = ZodAny> extends BaseLangChain<(z.output<T> extends string ? string : never) | z.input<T> | ToolCall, ToolReturnType> {
61
+ abstract name: string;
62
+ abstract description: string;
46
63
  abstract schema: T | z.ZodEffects<T>;
64
+ returnDirect: boolean;
47
65
  get lc_namespace(): string[];
66
+ /**
67
+ * The tool response format.
68
+ *
69
+ * If "content" then the output of the tool is interpreted as the contents of a
70
+ * ToolMessage. If "content_and_artifact" then the output is expected to be a
71
+ * two-tuple corresponding to the (content, artifact) of a ToolMessage.
72
+ *
73
+ * @default "content"
74
+ */
75
+ responseFormat?: ResponseFormat;
48
76
  constructor(fields?: ToolParams);
49
- protected abstract _call(arg: z.output<T>, runManager?: CallbackManagerForToolRun, config?: RunnableConfig): Promise<string>;
77
+ protected abstract _call(arg: z.output<T>, runManager?: CallbackManagerForToolRun, parentConfig?: RunnableConfig): Promise<ToolReturnType>;
50
78
  /**
51
79
  * Invokes the tool with the provided input and configuration.
52
80
  * @param input The input for the tool.
53
81
  * @param config Optional configuration for the tool.
54
82
  * @returns A Promise that resolves with a string.
55
83
  */
56
- invoke(input: (z.output<T> extends string ? string : never) | z.input<T>, config?: RunnableConfig): Promise<string>;
84
+ invoke(input: (z.output<T> extends string ? string : never) | z.input<T> | ToolCall, config?: RunnableConfig): Promise<ToolReturnType>;
57
85
  /**
58
86
  * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
59
87
  *
@@ -65,14 +93,11 @@ export declare abstract class StructuredTool<T extends ZodAny = ZodAny> extends
65
93
  * @param tags Optional tags for the tool.
66
94
  * @returns A Promise that resolves with a string.
67
95
  */
68
- call(arg: (z.output<T> extends string ? string : never) | z.input<T>, configArg?: Callbacks | RunnableConfig,
96
+ call(arg: (z.output<T> extends string ? string : never) | z.input<T> | ToolCall, configArg?: Callbacks | RunnableConfig,
69
97
  /** @deprecated */
70
- tags?: string[]): Promise<string>;
71
- abstract name: string;
72
- abstract description: string;
73
- returnDirect: boolean;
98
+ tags?: string[]): Promise<ToolReturnType>;
74
99
  }
75
- export interface ToolInterface extends StructuredToolInterface {
100
+ export interface ToolInterface<T extends ZodAny = ZodAny> extends StructuredToolInterface<T> {
76
101
  /**
77
102
  * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
78
103
  *
@@ -82,12 +107,12 @@ export interface ToolInterface extends StructuredToolInterface {
82
107
  * @param callbacks Optional callbacks for the tool.
83
108
  * @returns A Promise that resolves with a string.
84
109
  */
85
- call(arg: string | undefined | z.input<this["schema"]>, callbacks?: Callbacks | RunnableConfig): Promise<string>;
110
+ call(arg: string | undefined | z.input<this["schema"]> | ToolCall, callbacks?: Callbacks | RunnableConfig): Promise<ToolReturnType>;
86
111
  }
87
112
  /**
88
113
  * Base class for Tools that accept input as a string.
89
114
  */
90
- export declare abstract class Tool extends StructuredTool {
115
+ export declare abstract class Tool extends StructuredTool<ZodAny> {
91
116
  schema: z.ZodEffects<z.ZodObject<{
92
117
  input: z.ZodOptional<z.ZodString>;
93
118
  }, "strip", z.ZodTypeAny, {
@@ -107,7 +132,7 @@ export declare abstract class Tool extends StructuredTool {
107
132
  * @param callbacks Optional callbacks for the tool.
108
133
  * @returns A Promise that resolves with a string.
109
134
  */
110
- call(arg: string | undefined | z.input<this["schema"]>, callbacks?: Callbacks | RunnableConfig): Promise<string>;
135
+ call(arg: string | undefined | z.input<this["schema"]> | ToolCall, callbacks?: Callbacks | RunnableConfig): Promise<ToolReturnType>;
111
136
  }
112
137
  export interface BaseDynamicToolInput extends ToolParams {
113
138
  name: string;
@@ -118,13 +143,13 @@ export interface BaseDynamicToolInput extends ToolParams {
118
143
  * Interface for the input parameters of the DynamicTool class.
119
144
  */
120
145
  export interface DynamicToolInput extends BaseDynamicToolInput {
121
- func: (input: string, runManager?: CallbackManagerForToolRun, config?: RunnableConfig) => Promise<string>;
146
+ func: (input: string, runManager?: CallbackManagerForToolRun, config?: RunnableConfig) => Promise<ToolReturnType>;
122
147
  }
123
148
  /**
124
149
  * Interface for the input parameters of the DynamicStructuredTool class.
125
150
  */
126
151
  export interface DynamicStructuredToolInput<T extends ZodAny = ZodAny> extends BaseDynamicToolInput {
127
- func: (input: z.infer<T>, runManager?: CallbackManagerForToolRun, config?: RunnableConfig) => Promise<string>;
152
+ func: (input: BaseDynamicToolInput["responseFormat"] extends "content_and_artifact" ? ToolCall : z.infer<T>, runManager?: CallbackManagerForToolRun, config?: RunnableConfig) => Promise<ToolReturnType>;
128
153
  schema: T;
129
154
  }
130
155
  /**
@@ -139,9 +164,9 @@ export declare class DynamicTool extends Tool {
139
164
  /**
140
165
  * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
141
166
  */
142
- call(arg: string | undefined | z.input<this["schema"]>, configArg?: RunnableConfig | Callbacks): Promise<string>;
167
+ call(arg: string | undefined | z.input<this["schema"]> | ToolCall, configArg?: RunnableConfig | Callbacks): Promise<ToolReturnType>;
143
168
  /** @ignore */
144
- _call(input: string, runManager?: CallbackManagerForToolRun, config?: RunnableConfig): Promise<string>;
169
+ _call(input: string, runManager?: CallbackManagerForToolRun, parentConfig?: RunnableConfig): Promise<ToolReturnType>;
145
170
  }
146
171
  /**
147
172
  * A tool that can be created dynamically from a function, name, and
@@ -159,10 +184,10 @@ export declare class DynamicStructuredTool<T extends ZodAny = ZodAny> extends St
159
184
  /**
160
185
  * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
161
186
  */
162
- call(arg: z.output<T>, configArg?: RunnableConfig | Callbacks,
187
+ call(arg: z.output<T> | ToolCall, configArg?: RunnableConfig | Callbacks,
163
188
  /** @deprecated */
164
- tags?: string[]): Promise<string>;
165
- protected _call(arg: z.output<T>, runManager?: CallbackManagerForToolRun, config?: RunnableConfig): Promise<string>;
189
+ tags?: string[]): Promise<ToolReturnType>;
190
+ protected _call(arg: z.output<T> | ToolCall, runManager?: CallbackManagerForToolRun, parentConfig?: RunnableConfig): Promise<ToolReturnType>;
166
191
  }
167
192
  /**
168
193
  * Abstract base class for toolkits in LangChain. Toolkits are collections
@@ -176,6 +201,7 @@ export declare abstract class BaseToolkit {
176
201
  /**
177
202
  * Parameters for the tool function.
178
203
  * @template {ZodAny} RunInput The input schema for the tool.
204
+ * @template {any} RunOutput The output type for the tool.
179
205
  */
180
206
  interface ToolWrapperParams<RunInput extends ZodAny = ZodAny> extends ToolParams {
181
207
  /**
@@ -194,19 +220,31 @@ interface ToolWrapperParams<RunInput extends ZodAny = ZodAny> extends ToolParams
194
220
  * for.
195
221
  */
196
222
  schema?: RunInput;
223
+ /**
224
+ * The tool response format.
225
+ *
226
+ * If "content" then the output of the tool is interpreted as the contents of a
227
+ * ToolMessage. If "content_and_artifact" then the output is expected to be a
228
+ * two-tuple corresponding to the (content, artifact) of a ToolMessage.
229
+ *
230
+ * @default "content"
231
+ */
232
+ responseFormat?: ResponseFormat;
197
233
  }
198
234
  /**
199
235
  * Creates a new StructuredTool instance with the provided function, name, description, and schema.
200
236
  * @function
201
- * @template {ZodAny} RunInput The input schema for the tool.
237
+ * @template {RunInput extends ZodAny = ZodAny} RunInput The input schema for the tool. This corresponds to the input type when the tool is invoked.
238
+ * @template {RunOutput = any} RunOutput The output type for the tool. This corresponds to the output type when the tool is invoked.
239
+ * @template {FuncInput extends z.infer<RunInput> | ToolCall = z.infer<RunInput>} FuncInput The input type for the function.
202
240
  *
203
- * @param {RunnableFunc<RunInput, string>} func - The function to invoke when the tool is called.
241
+ * @param {RunnableFunc<z.infer<RunInput> | ToolCall, RunOutput>} func - The function to invoke when the tool is called.
204
242
  * @param fields - An object containing the following properties:
205
243
  * @param {string} fields.name The name of the tool.
206
244
  * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.
207
245
  * @param {z.ZodObject<any, any, any, any>} fields.schema The Zod schema defining the input for the tool.
208
246
  *
209
- * @returns {StructuredTool<RunInput, string>} A new StructuredTool instance.
247
+ * @returns {DynamicStructuredTool<RunInput, RunOutput>} A new StructuredTool instance.
210
248
  */
211
- export declare function tool<RunInput extends ZodAny = ZodAny>(func: RunnableFunc<z.infer<RunInput>, string>, fields: ToolWrapperParams<RunInput>): DynamicStructuredTool<RunInput>;
249
+ export declare function tool<T extends ZodAny = ZodAny>(func: RunnableFunc<z.output<T>, ToolReturnType>, fields: ToolWrapperParams<T>): DynamicStructuredTool<T>;
212
250
  export {};
@@ -1,7 +1,9 @@
1
1
  import { z } from "zod";
2
- import { CallbackManager, parseCallbackConfigArg, } from "./callbacks/manager.js";
3
- import { BaseLangChain, } from "./language_models/base.js";
4
- import { ensureConfig } from "./runnables/config.js";
2
+ import { CallbackManager, parseCallbackConfigArg, } from "../callbacks/manager.js";
3
+ import { BaseLangChain, } from "../language_models/base.js";
4
+ import { ensureConfig, patchConfig, } from "../runnables/config.js";
5
+ import { ToolMessage } from "../messages/tool.js";
6
+ import { AsyncLocalStorageProviderSingleton } from "../singletons/index.js";
5
7
  /**
6
8
  * Custom error class used to handle exceptions related to tool input parsing.
7
9
  * It extends the built-in `Error` class and adds an optional `output`
@@ -34,6 +36,22 @@ export class StructuredTool extends BaseLangChain {
34
36
  writable: true,
35
37
  value: false
36
38
  });
39
+ /**
40
+ * The tool response format.
41
+ *
42
+ * If "content" then the output of the tool is interpreted as the contents of a
43
+ * ToolMessage. If "content_and_artifact" then the output is expected to be a
44
+ * two-tuple corresponding to the (content, artifact) of a ToolMessage.
45
+ *
46
+ * @default "content"
47
+ */
48
+ Object.defineProperty(this, "responseFormat", {
49
+ enumerable: true,
50
+ configurable: true,
51
+ writable: true,
52
+ value: "content"
53
+ });
54
+ this.responseFormat = fields?.responseFormat ?? this.responseFormat;
37
55
  }
38
56
  /**
39
57
  * Invokes the tool with the provided input and configuration.
@@ -42,7 +60,23 @@ export class StructuredTool extends BaseLangChain {
42
60
  * @returns A Promise that resolves with a string.
43
61
  */
44
62
  async invoke(input, config) {
45
- return this.call(input, ensureConfig(config));
63
+ let tool_call_id;
64
+ let toolInput;
65
+ if (_isToolCall(input)) {
66
+ tool_call_id = input.id;
67
+ toolInput = input.args;
68
+ }
69
+ else {
70
+ toolInput = input;
71
+ }
72
+ const ensuredConfig = ensureConfig(config);
73
+ return this.call(toolInput, {
74
+ ...ensuredConfig,
75
+ configurable: {
76
+ ...ensuredConfig.configurable,
77
+ tool_call_id,
78
+ },
79
+ });
46
80
  }
47
81
  /**
48
82
  * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
@@ -77,8 +111,32 @@ export class StructuredTool extends BaseLangChain {
77
111
  await runManager?.handleToolError(e);
78
112
  throw e;
79
113
  }
80
- await runManager?.handleToolEnd(result);
81
- return result;
114
+ let content;
115
+ let artifact;
116
+ if (this.responseFormat === "content_and_artifact") {
117
+ if (Array.isArray(result) && result.length === 2) {
118
+ [content, artifact] = result;
119
+ }
120
+ else {
121
+ throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(result)}`);
122
+ }
123
+ }
124
+ else {
125
+ content = result;
126
+ }
127
+ let toolCallId;
128
+ if (config && "configurable" in config) {
129
+ toolCallId = config.configurable
130
+ .tool_call_id;
131
+ }
132
+ const formattedOutput = _formatToolOutput({
133
+ content,
134
+ artifact,
135
+ toolCallId,
136
+ name: this.name,
137
+ });
138
+ await runManager?.handleToolEnd(formattedOutput);
139
+ return formattedOutput;
82
140
  }
83
141
  }
84
142
  /**
@@ -152,8 +210,8 @@ export class DynamicTool extends Tool {
152
210
  return super.call(arg, config);
153
211
  }
154
212
  /** @ignore */
155
- async _call(input, runManager, config) {
156
- return this.func(input, runManager, config);
213
+ async _call(input, runManager, parentConfig) {
214
+ return this.func(input, runManager, parentConfig);
157
215
  }
158
216
  }
159
217
  /**
@@ -210,8 +268,8 @@ export class DynamicStructuredTool extends StructuredTool {
210
268
  }
211
269
  return super.call(arg, config, tags);
212
270
  }
213
- _call(arg, runManager, config) {
214
- return this.func(arg, runManager, config);
271
+ _call(arg, runManager, parentConfig) {
272
+ return this.func(arg, runManager, parentConfig);
215
273
  }
216
274
  }
217
275
  /**
@@ -227,15 +285,17 @@ export class BaseToolkit {
227
285
  /**
228
286
  * Creates a new StructuredTool instance with the provided function, name, description, and schema.
229
287
  * @function
230
- * @template {ZodAny} RunInput The input schema for the tool.
288
+ * @template {RunInput extends ZodAny = ZodAny} RunInput The input schema for the tool. This corresponds to the input type when the tool is invoked.
289
+ * @template {RunOutput = any} RunOutput The output type for the tool. This corresponds to the output type when the tool is invoked.
290
+ * @template {FuncInput extends z.infer<RunInput> | ToolCall = z.infer<RunInput>} FuncInput The input type for the function.
231
291
  *
232
- * @param {RunnableFunc<RunInput, string>} func - The function to invoke when the tool is called.
292
+ * @param {RunnableFunc<z.infer<RunInput> | ToolCall, RunOutput>} func - The function to invoke when the tool is called.
233
293
  * @param fields - An object containing the following properties:
234
294
  * @param {string} fields.name The name of the tool.
235
295
  * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.
236
296
  * @param {z.ZodObject<any, any, any, any>} fields.schema The Zod schema defining the input for the tool.
237
297
  *
238
- * @returns {StructuredTool<RunInput, string>} A new StructuredTool instance.
298
+ * @returns {DynamicStructuredTool<RunInput, RunOutput>} A new StructuredTool instance.
239
299
  */
240
300
  export function tool(func, fields) {
241
301
  const schema = fields.schema ??
@@ -245,6 +305,62 @@ export function tool(func, fields) {
245
305
  name: fields.name,
246
306
  description,
247
307
  schema: schema,
248
- func: async (input, _runManager, config) => func(input, config),
308
+ // TODO: Consider moving into DynamicStructuredTool constructor
309
+ func: async (input, runManager, config) => {
310
+ return new Promise((resolve, reject) => {
311
+ const childConfig = patchConfig(config, {
312
+ callbacks: runManager?.getChild(),
313
+ });
314
+ void AsyncLocalStorageProviderSingleton.getInstance().run(childConfig, async () => {
315
+ try {
316
+ resolve(func(input, childConfig));
317
+ }
318
+ catch (e) {
319
+ reject(e);
320
+ }
321
+ });
322
+ });
323
+ },
324
+ responseFormat: fields.responseFormat,
249
325
  });
250
326
  }
327
+ function _isToolCall(toolCall) {
328
+ return !!(toolCall &&
329
+ typeof toolCall === "object" &&
330
+ "type" in toolCall &&
331
+ toolCall.type === "tool_call");
332
+ }
333
+ function _formatToolOutput(params) {
334
+ const { content, artifact, toolCallId } = params;
335
+ if (toolCallId) {
336
+ if (typeof content === "string" ||
337
+ (Array.isArray(content) &&
338
+ content.every((item) => typeof item === "object"))) {
339
+ return new ToolMessage({
340
+ content,
341
+ artifact,
342
+ tool_call_id: toolCallId,
343
+ name: params.name,
344
+ });
345
+ }
346
+ else {
347
+ return new ToolMessage({
348
+ content: _stringify(content),
349
+ artifact,
350
+ tool_call_id: toolCallId,
351
+ name: params.name,
352
+ });
353
+ }
354
+ }
355
+ else {
356
+ return content;
357
+ }
358
+ }
359
+ function _stringify(content) {
360
+ try {
361
+ return JSON.stringify(content, null, 2);
362
+ }
363
+ catch (_noOp) {
364
+ return `${content}`;
365
+ }
366
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,74 @@
1
+ import { test, expect } from "@jest/globals";
2
+ import { z } from "zod";
3
+ import { tool } from "../index.js";
4
+ import { ToolMessage } from "../../messages/tool.js";
5
+ test("Tool should error if responseFormat is content_and_artifact but the function doesn't return a tuple", async () => {
6
+ const weatherSchema = z.object({
7
+ location: z.string(),
8
+ });
9
+ const weatherTool = tool((_) => {
10
+ return "str";
11
+ }, {
12
+ name: "weather",
13
+ schema: weatherSchema,
14
+ responseFormat: "content_and_artifact",
15
+ });
16
+ await expect(async () => {
17
+ await weatherTool.invoke({ location: "San Francisco" });
18
+ }).rejects.toThrow();
19
+ });
20
+ test("Tool works if responseFormat is content_and_artifact and returns a tuple", async () => {
21
+ const weatherSchema = z.object({
22
+ location: z.string(),
23
+ });
24
+ const weatherTool = tool((input) => {
25
+ return ["msg_content", input];
26
+ }, {
27
+ name: "weather",
28
+ schema: weatherSchema,
29
+ responseFormat: "content_and_artifact",
30
+ });
31
+ const toolResult = await weatherTool.invoke({ location: "San Francisco" });
32
+ expect(toolResult).not.toBeInstanceOf(ToolMessage);
33
+ expect(toolResult).toBe("msg_content");
34
+ });
35
+ test("Does not return tool message if responseFormat is content_and_artifact and returns a tuple and a tool call with no id is passed in", async () => {
36
+ const weatherSchema = z.object({
37
+ location: z.string(),
38
+ });
39
+ const weatherTool = tool((input) => {
40
+ return ["msg_content", input];
41
+ }, {
42
+ name: "weather",
43
+ schema: weatherSchema,
44
+ responseFormat: "content_and_artifact",
45
+ });
46
+ const toolResult = await weatherTool.invoke({
47
+ args: { location: "San Francisco" },
48
+ name: "weather",
49
+ type: "tool_call",
50
+ });
51
+ expect(toolResult).toBe("msg_content");
52
+ });
53
+ test("Returns tool message if responseFormat is content_and_artifact and returns a tuple and a tool call with id is passed in", async () => {
54
+ const weatherSchema = z.object({
55
+ location: z.string(),
56
+ });
57
+ const weatherTool = tool((input) => {
58
+ return ["msg_content", input];
59
+ }, {
60
+ name: "weather",
61
+ schema: weatherSchema,
62
+ responseFormat: "content_and_artifact",
63
+ });
64
+ const toolResult = await weatherTool.invoke({
65
+ id: "testid",
66
+ args: { location: "San Francisco" },
67
+ name: "weather",
68
+ type: "tool_call",
69
+ });
70
+ expect(toolResult).toBeInstanceOf(ToolMessage);
71
+ expect(toolResult.content).toBe("msg_content");
72
+ expect(toolResult.artifact).toEqual({ location: "San Francisco" });
73
+ expect(toolResult.name).toBe("weather");
74
+ });
@@ -274,6 +274,7 @@ class BaseTracer extends base_js_1.BaseCallbackHandler {
274
274
  await this.onToolStart?.(run);
275
275
  return run;
276
276
  }
277
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
277
278
  async handleToolEnd(output, runId) {
278
279
  const run = this.runMap.get(runId);
279
280
  if (!run || run?.run_type !== "tool") {
@@ -46,7 +46,7 @@ export declare abstract class BaseTracer extends BaseCallbackHandler {
46
46
  inputs?: Record<string, unknown>;
47
47
  }): Promise<Run>;
48
48
  handleToolStart(tool: Serialized, input: string, runId: string, parentRunId?: string, tags?: string[], metadata?: KVMap, name?: string): Promise<Run>;
49
- handleToolEnd(output: string, runId: string): Promise<Run>;
49
+ handleToolEnd(output: any, runId: string): Promise<Run>;
50
50
  handleToolError(error: unknown, runId: string): Promise<Run>;
51
51
  handleAgentAction(action: AgentAction, runId: string): Promise<void>;
52
52
  handleAgentEnd(action: AgentFinish, runId: string): Promise<void>;
@@ -271,6 +271,7 @@ export class BaseTracer extends BaseCallbackHandler {
271
271
  await this.onToolStart?.(run);
272
272
  return run;
273
273
  }
274
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
274
275
  async handleToolEnd(output, runId) {
275
276
  const run = this.runMap.get(runId);
276
277
  if (!run || run?.run_type !== "tool") {
@@ -489,6 +489,21 @@ class EventStreamCallbackHandler extends base_js_1.BaseTracer {
489
489
  metadata: runInfo.metadata,
490
490
  }, runInfo);
491
491
  }
492
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
493
+ async handleCustomEvent(eventName, data, runId) {
494
+ const runInfo = this.runInfoMap.get(runId);
495
+ if (runInfo === undefined) {
496
+ throw new Error(`handleCustomEvent: Run ID ${runId} not found in run map.`);
497
+ }
498
+ await this.send({
499
+ event: "on_custom_event",
500
+ run_id: runId,
501
+ name: eventName,
502
+ tags: runInfo.tags,
503
+ metadata: runInfo.metadata,
504
+ data,
505
+ }, runInfo);
506
+ }
492
507
  async finish() {
493
508
  const pendingPromises = [...this.tappedPromises.values()];
494
509
  void Promise.all(pendingPromises).finally(() => {
@@ -133,6 +133,7 @@ export declare class EventStreamCallbackHandler extends BaseTracer {
133
133
  onToolEnd(run: Run): Promise<void>;
134
134
  onRetrieverStart(run: Run): Promise<void>;
135
135
  onRetrieverEnd(run: Run): Promise<void>;
136
+ handleCustomEvent(eventName: string, data: any, runId: string): Promise<void>;
136
137
  finish(): Promise<void>;
137
138
  }
138
139
  export {};
@@ -485,6 +485,21 @@ export class EventStreamCallbackHandler extends BaseTracer {
485
485
  metadata: runInfo.metadata,
486
486
  }, runInfo);
487
487
  }
488
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
489
+ async handleCustomEvent(eventName, data, runId) {
490
+ const runInfo = this.runInfoMap.get(runId);
491
+ if (runInfo === undefined) {
492
+ throw new Error(`handleCustomEvent: Run ID ${runId} not found in run map.`);
493
+ }
494
+ await this.send({
495
+ event: "on_custom_event",
496
+ run_id: runId,
497
+ name: eventName,
498
+ tags: runInfo.tags,
499
+ metadata: runInfo.metadata,
500
+ data,
501
+ }, runInfo);
502
+ }
488
503
  async finish() {
489
504
  const pendingPromises = [...this.tappedPromises.values()];
490
505
  void Promise.all(pendingPromises).finally(() => {
@@ -24,6 +24,8 @@ async function getTracingCallbackHandler(session) {
24
24
  }
25
25
  exports.getTracingCallbackHandler = getTracingCallbackHandler;
26
26
  /**
27
+ * @deprecated Instantiate directly using the LangChainTracer constructor.
28
+ *
27
29
  * Function that returns an instance of `LangChainTracer`. It does not
28
30
  * load any session data.
29
31
  * @returns An instance of `LangChainTracer`.
@@ -11,6 +11,8 @@ import { LangChainTracerV1 } from "./tracer_langchain_v1.js";
11
11
  */
12
12
  export declare function getTracingCallbackHandler(session?: string): Promise<LangChainTracerV1>;
13
13
  /**
14
+ * @deprecated Instantiate directly using the LangChainTracer constructor.
15
+ *
14
16
  * Function that returns an instance of `LangChainTracer`. It does not
15
17
  * load any session data.
16
18
  * @returns An instance of `LangChainTracer`.
@@ -20,6 +20,8 @@ export async function getTracingCallbackHandler(session) {
20
20
  return tracer;
21
21
  }
22
22
  /**
23
+ * @deprecated Instantiate directly using the LangChainTracer constructor.
24
+ *
23
25
  * Function that returns an instance of `LangChainTracer`. It does not
24
26
  * load any session data.
25
27
  * @returns An instance of `LangChainTracer`.
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ import type { z } from "zod";
2
+ export type ZodAny = z.ZodObject<any, any, any, any>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isTracingEnabled = void 0;
4
+ const env_js_1 = require("./env.cjs");
5
+ const isTracingEnabled = (tracingEnabled) => {
6
+ if (tracingEnabled !== undefined) {
7
+ return tracingEnabled;
8
+ }
9
+ const envVars = [
10
+ "LANGSMITH_TRACING_V2",
11
+ "LANGCHAIN_TRACING_V2",
12
+ "LANGSMITH_TRACING",
13
+ "LANGCHAIN_TRACING",
14
+ ];
15
+ return !!envVars.find((envVar) => (0, env_js_1.getEnvironmentVariable)(envVar) === "true");
16
+ };
17
+ exports.isTracingEnabled = isTracingEnabled;
@@ -0,0 +1 @@
1
+ export declare const isTracingEnabled: (tracingEnabled?: boolean) => boolean;
@@ -0,0 +1,13 @@
1
+ import { getEnvironmentVariable } from "./env.js";
2
+ export const isTracingEnabled = (tracingEnabled) => {
3
+ if (tracingEnabled !== undefined) {
4
+ return tracingEnabled;
5
+ }
6
+ const envVars = [
7
+ "LANGSMITH_TRACING_V2",
8
+ "LANGCHAIN_TRACING_V2",
9
+ "LANGSMITH_TRACING",
10
+ "LANGCHAIN_TRACING",
11
+ ];
12
+ return !!envVars.find((envVar) => getEnvironmentVariable(envVar) === "true");
13
+ };