@langchain/core 0.3.53 → 0.3.55

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.
@@ -5,16 +5,36 @@ export type AIMessageFields = BaseMessageFields & {
5
5
  invalid_tool_calls?: InvalidToolCall[];
6
6
  usage_metadata?: UsageMetadata;
7
7
  };
8
+ export type ModalitiesTokenDetails = {
9
+ /**
10
+ * Text tokens.
11
+ * Does not need to be reported, but some models will do so.
12
+ */
13
+ text?: number;
14
+ /**
15
+ * Image (non-video) tokens.
16
+ */
17
+ image?: number;
18
+ /**
19
+ * Audio tokens.
20
+ */
21
+ audio?: number;
22
+ /**
23
+ * Video tokens.
24
+ */
25
+ video?: number;
26
+ /**
27
+ * Document tokens.
28
+ * e.g. PDF
29
+ */
30
+ document?: number;
31
+ };
8
32
  /**
9
33
  * Breakdown of input token counts.
10
34
  *
11
35
  * Does not *need* to sum to full input token count. Does *not* need to have all keys.
12
36
  */
13
- export type InputTokenDetails = {
14
- /**
15
- * Audio input tokens.
16
- */
17
- audio?: number;
37
+ export type InputTokenDetails = ModalitiesTokenDetails & {
18
38
  /**
19
39
  * Input tokens that were cached and there was a cache hit.
20
40
  *
@@ -34,11 +54,7 @@ export type InputTokenDetails = {
34
54
  *
35
55
  * Does *not* need to sum to full output token count. Does *not* need to have all keys.
36
56
  */
37
- export type OutputTokenDetails = {
38
- /**
39
- * Audio output tokens
40
- */
41
- audio?: number;
57
+ export type OutputTokenDetails = ModalitiesTokenDetails & {
42
58
  /**
43
59
  * Reasoning output tokens.
44
60
  *
@@ -27,7 +27,7 @@ export interface ToolMessageFieldsWithToolCallId extends ToolMessageFields {
27
27
  * a string and wrapped in a ToolMessage.
28
28
  */
29
29
  export interface DirectToolOutput {
30
- readonly lc_direct_tool_output: boolean;
30
+ readonly lc_direct_tool_output: true;
31
31
  }
32
32
  export declare function isDirectToolOutput(x: unknown): x is DirectToolOutput;
33
33
  /**
@@ -37,7 +37,7 @@ export declare class ToolMessage extends BaseMessage implements DirectToolOutput
37
37
  content: string | (MessageContentComplex | DataContentBlock)[];
38
38
  static lc_name(): string;
39
39
  get lc_aliases(): Record<string, string>;
40
- lc_direct_tool_output: boolean;
40
+ lc_direct_tool_output: true;
41
41
  /**
42
42
  * Status of the tool invocation.
43
43
  * @version 0.2.19
@@ -51,7 +51,7 @@ export declare abstract class Runnable<RunInput = any, RunOutput = any, CallOpti
51
51
  * @param config New configuration parameters to attach to the new runnable.
52
52
  * @returns A new RunnableBinding with a config matching what's passed.
53
53
  */
54
- withConfig(config: RunnableConfig): Runnable<RunInput, RunOutput, CallOptions>;
54
+ withConfig(config: Partial<CallOptions>): Runnable<RunInput, RunOutput, CallOptions>;
55
55
  /**
56
56
  * Create a new runnable from the current one that will try invoking
57
57
  * other passed fallback runnables if the initial invocation fails.
@@ -67,22 +67,16 @@ class StructuredTool extends base_js_1.BaseLangChain {
67
67
  * Invokes the tool with the provided input and configuration.
68
68
  * @param input The input for the tool.
69
69
  * @param config Optional configuration for the tool.
70
- * @returns A Promise that resolves with a string.
70
+ * @returns A Promise that resolves with the tool's output.
71
71
  */
72
72
  async invoke(input, config) {
73
- let tool_call_id;
74
73
  let toolInput;
75
74
  let enrichedConfig = (0, config_js_1.ensureConfig)(config);
76
75
  if ((0, utils_js_1._isToolCall)(input)) {
77
- tool_call_id = input.id;
78
76
  toolInput = input.args;
79
77
  enrichedConfig = {
80
78
  ...enrichedConfig,
81
79
  toolCall: input,
82
- configurable: {
83
- ...enrichedConfig.configurable,
84
- tool_call_id,
85
- },
86
80
  };
87
81
  }
88
82
  else {
@@ -104,21 +98,26 @@ class StructuredTool extends base_js_1.BaseLangChain {
104
98
  async call(arg, configArg,
105
99
  /** @deprecated */
106
100
  tags) {
107
- let parsed = arg;
101
+ // Determine the actual input that needs parsing/validation.
102
+ // If arg is a ToolCall, use its args; otherwise, use arg directly.
103
+ const inputForValidation = (0, utils_js_1._isToolCall)(arg) ? arg.args : arg;
104
+ let parsed; // This will hold the successfully parsed input of the expected output type.
108
105
  if ((0, is_zod_schema_js_1.isZodSchema)(this.schema)) {
109
106
  try {
110
- parsed = await this.schema.parseAsync(arg);
107
+ // Validate the inputForValidation - TS needs help here as it can't exclude ToolCall based on the check
108
+ parsed = await this.schema.parseAsync(inputForValidation);
111
109
  }
112
110
  catch (e) {
113
111
  let message = `Received tool input did not match expected schema`;
114
112
  if (this.verboseParsingErrors) {
115
113
  message = `${message}\nDetails: ${e.message}`;
116
114
  }
115
+ // Pass the original raw input arg to the exception
117
116
  throw new utils_js_1.ToolInputParsingException(message, JSON.stringify(arg));
118
117
  }
119
118
  }
120
119
  else {
121
- const result = (0, json_schema_1.validate)(arg, this.schema);
120
+ const result = (0, json_schema_1.validate)(inputForValidation, this.schema);
122
121
  if (!result.valid) {
123
122
  let message = `Received tool input did not match expected schema`;
124
123
  if (this.verboseParsingErrors) {
@@ -126,15 +125,22 @@ class StructuredTool extends base_js_1.BaseLangChain {
126
125
  .map((e) => `${e.keywordLocation}: ${e.error}`)
127
126
  .join("\n")}`;
128
127
  }
128
+ // Pass the original raw input arg to the exception
129
129
  throw new utils_js_1.ToolInputParsingException(message, JSON.stringify(arg));
130
130
  }
131
+ // Assign the validated input to parsed
132
+ // We cast here because validate() doesn't narrow the type sufficiently for TS, but we know it's valid.
133
+ parsed = inputForValidation;
131
134
  }
132
135
  const config = (0, manager_js_1.parseCallbackConfigArg)(configArg);
133
136
  const callbackManager_ = manager_js_1.CallbackManager.configure(config.callbacks, this.callbacks, config.tags || tags, this.tags, config.metadata, this.metadata, { verbose: this.verbose });
134
- const runManager = await callbackManager_?.handleToolStart(this.toJSON(), typeof parsed === "string" ? parsed : JSON.stringify(parsed), config.runId, undefined, undefined, undefined, config.runName);
137
+ const runManager = await callbackManager_?.handleToolStart(this.toJSON(),
138
+ // Log the original raw input arg
139
+ typeof arg === "string" ? arg : JSON.stringify(arg), config.runId, undefined, undefined, undefined, config.runName);
135
140
  delete config.runId;
136
141
  let result;
137
142
  try {
143
+ // Pass the correctly typed parsed input to _call
138
144
  result = await this._call(parsed, runManager, config);
139
145
  }
140
146
  catch (e) {
@@ -155,9 +161,13 @@ class StructuredTool extends base_js_1.BaseLangChain {
155
161
  content = result;
156
162
  }
157
163
  let toolCallId;
158
- if (config && "configurable" in config) {
159
- toolCallId = config.configurable
160
- .tool_call_id;
164
+ // Extract toolCallId ONLY if the original arg was a ToolCall
165
+ if ((0, utils_js_1._isToolCall)(arg)) {
166
+ toolCallId = arg.id;
167
+ }
168
+ // Or if it was provided in the config's toolCall property
169
+ if (!toolCallId && (0, utils_js_1._configHasToolCallId)(config)) {
170
+ toolCallId = config.toolCall.id;
161
171
  }
162
172
  const formattedOutput = _formatToolOutput({
163
173
  content,
@@ -194,8 +204,13 @@ class Tool extends StructuredTool {
194
204
  * @param callbacks Optional callbacks for the tool.
195
205
  * @returns A Promise that resolves with a string.
196
206
  */
207
+ // Match the base class signature including the generics and conditional return type
197
208
  call(arg, callbacks) {
198
- return super.call(typeof arg === "string" || !arg ? { input: arg } : arg, callbacks);
209
+ // Prepare the input for the base class call method.
210
+ // If arg is string or undefined, wrap it; otherwise, pass ToolCall or { input: ... } directly.
211
+ const structuredArg = typeof arg === "string" || arg == null ? { input: arg } : arg;
212
+ // Ensure TConfig is passed to super.call
213
+ return super.call(structuredArg, callbacks);
199
214
  }
200
215
  }
201
216
  exports.Tool = Tool;
@@ -239,10 +254,13 @@ class DynamicTool extends Tool {
239
254
  if (config.runName === undefined) {
240
255
  config.runName = this.name;
241
256
  }
257
+ // Call the Tool class's call method, passing generics through
258
+ // Cast config to TConfig to satisfy the super.call signature
242
259
  return super.call(arg, config);
243
260
  }
244
261
  /** @ignore */
245
- async _call(input, runManager, parentConfig) {
262
+ async _call(input, // DynamicTool's _call specifically expects a string after schema transformation
263
+ runManager, parentConfig) {
246
264
  return this.func(input, runManager, parentConfig);
247
265
  }
248
266
  }
@@ -295,6 +313,7 @@ class DynamicStructuredTool extends StructuredTool {
295
313
  /**
296
314
  * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
297
315
  */
316
+ // Match the base class signature
298
317
  async call(arg, configArg,
299
318
  /** @deprecated */
300
319
  tags) {
@@ -302,6 +321,8 @@ class DynamicStructuredTool extends StructuredTool {
302
321
  if (config.runName === undefined) {
303
322
  config.runName = this.name;
304
323
  }
324
+ // Call the base class method, passing generics through
325
+ // Cast config to TConfig to satisfy the super.call signature
305
326
  return super.call(arg, config, tags);
306
327
  }
307
328
  _call(arg, runManager, parentConfig) {
@@ -1,11 +1,11 @@
1
1
  import { z } from "zod";
2
- import { CallbackManagerForToolRun, Callbacks } from "../callbacks/manager.js";
2
+ import { CallbackManagerForToolRun } from "../callbacks/manager.js";
3
3
  import { BaseLangChain } from "../language_models/base.js";
4
4
  import { type RunnableConfig } from "../runnables/config.js";
5
5
  import type { RunnableFunc } from "../runnables/base.js";
6
- import { ToolCall } from "../messages/tool.js";
6
+ import { ToolCall, ToolMessage } from "../messages/tool.js";
7
7
  import { ToolInputParsingException } from "./utils.js";
8
- import type { StructuredToolCallInput, ToolInputSchemaBase, ToolReturnType, ResponseFormat, ToolInputSchemaInputType, ToolInputSchemaOutputType, ToolParams, ToolRunnableConfig, StructuredToolInterface, DynamicToolInput, DynamicStructuredToolInput, ZodObjectAny } from "./types.js";
8
+ import type { StructuredToolCallInput, ToolInputSchemaBase, ToolReturnType, ResponseFormat, ToolInputSchemaInputType, ToolInputSchemaOutputType, ToolParams, ToolRunnableConfig, StructuredToolInterface, DynamicToolInput, DynamicStructuredToolInput, ZodObjectAny, StringInputToolSchema, ToolInterface, ToolOutputType } from "./types.js";
9
9
  import { type JSONSchema } from "../utils/json_schema.js";
10
10
  export type { BaseDynamicToolInput, ContentAndArtifact, DynamicToolInput, DynamicStructuredToolInput, ResponseFormat, StructuredToolCallInput, StructuredToolInterface, StructuredToolParams, ToolInterface, ToolParams, ToolReturnType, ToolRunnableConfig, ToolInputSchemaBase as ToolSchemaBase, } from "./types.js";
11
11
  export { isLangChainTool, isRunnableToolLike, isStructuredTool, isStructuredToolParams, } from "./types.js";
@@ -13,7 +13,7 @@ export { ToolInputParsingException };
13
13
  /**
14
14
  * Base class for Tools that accept input of any shape defined by a Zod schema.
15
15
  */
16
- export declare abstract class StructuredTool<SchemaT extends ToolInputSchemaBase = ZodObjectAny, SchemaOutputT = ToolInputSchemaOutputType<SchemaT>, SchemaInputT = ToolInputSchemaInputType<SchemaT>> extends BaseLangChain<StructuredToolCallInput<SchemaT, SchemaInputT>, ToolReturnType> {
16
+ export declare abstract class StructuredTool<SchemaT extends ToolInputSchemaBase = ToolInputSchemaBase, SchemaOutputT = ToolInputSchemaOutputType<SchemaT>, SchemaInputT = ToolInputSchemaInputType<SchemaT>, ToolOutputT = ToolOutputType> extends BaseLangChain<StructuredToolCallInput<SchemaT, SchemaInputT>, ToolOutputT | ToolMessage> implements StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT> {
17
17
  abstract name: string;
18
18
  abstract description: string;
19
19
  abstract schema: SchemaT;
@@ -37,14 +37,14 @@ export declare abstract class StructuredTool<SchemaT extends ToolInputSchemaBase
37
37
  */
38
38
  responseFormat?: ResponseFormat;
39
39
  constructor(fields?: ToolParams);
40
- protected abstract _call(arg: SchemaOutputT, runManager?: CallbackManagerForToolRun, parentConfig?: ToolRunnableConfig): Promise<ToolReturnType>;
40
+ protected abstract _call(arg: SchemaOutputT, runManager?: CallbackManagerForToolRun, parentConfig?: ToolRunnableConfig): Promise<ToolOutputT>;
41
41
  /**
42
42
  * Invokes the tool with the provided input and configuration.
43
43
  * @param input The input for the tool.
44
44
  * @param config Optional configuration for the tool.
45
- * @returns A Promise that resolves with a string.
45
+ * @returns A Promise that resolves with the tool's output.
46
46
  */
47
- invoke(input: StructuredToolCallInput<SchemaT, SchemaInputT>, config?: RunnableConfig): Promise<ToolReturnType>;
47
+ invoke<TInput extends StructuredToolCallInput<SchemaT, SchemaInputT>, TConfig extends ToolRunnableConfig | undefined>(input: TInput, config?: TConfig): Promise<ToolReturnType<TInput, TConfig, ToolOutputT>>;
48
48
  /**
49
49
  * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
50
50
  *
@@ -56,16 +56,14 @@ export declare abstract class StructuredTool<SchemaT extends ToolInputSchemaBase
56
56
  * @param tags Optional tags for the tool.
57
57
  * @returns A Promise that resolves with a string.
58
58
  */
59
- call(arg: StructuredToolCallInput<SchemaT, SchemaInputT>, configArg?: Callbacks | ToolRunnableConfig,
59
+ call<TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>, TConfig extends ToolRunnableConfig | undefined>(arg: TArg, configArg?: TConfig,
60
60
  /** @deprecated */
61
- tags?: string[]): Promise<ToolReturnType>;
61
+ tags?: string[]): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>>;
62
62
  }
63
63
  /**
64
64
  * Base class for Tools that accept input as a string.
65
65
  */
66
- export declare abstract class Tool extends StructuredTool<z.ZodEffects<z.ZodObject<{
67
- input: z.ZodOptional<z.ZodString>;
68
- }, "strip", z.ZodTypeAny, any, any>, any, any>> {
66
+ export declare abstract class Tool<ToolOutputT = ToolOutputType> extends StructuredTool<StringInputToolSchema, ToolInputSchemaOutputType<StringInputToolSchema>, ToolInputSchemaInputType<StringInputToolSchema>, ToolOutputT> implements ToolInterface<StringInputToolSchema, ToolInputSchemaInputType<StringInputToolSchema>, ToolOutputT> {
69
67
  schema: z.ZodEffects<z.ZodObject<{
70
68
  input: z.ZodOptional<z.ZodString>;
71
69
  }, "strip", z.ZodTypeAny, {
@@ -85,23 +83,24 @@ export declare abstract class Tool extends StructuredTool<z.ZodEffects<z.ZodObje
85
83
  * @param callbacks Optional callbacks for the tool.
86
84
  * @returns A Promise that resolves with a string.
87
85
  */
88
- call(arg: string | undefined | z.input<this["schema"]> | ToolCall, callbacks?: Callbacks | RunnableConfig): Promise<ToolReturnType>;
86
+ call<TArg extends string | undefined | z.input<this["schema"]> | ToolCall, TConfig extends ToolRunnableConfig | undefined>(arg: TArg, callbacks?: TConfig): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>>;
89
87
  }
90
88
  /**
91
89
  * A tool that can be created dynamically from a function, name, and description.
92
90
  */
93
- export declare class DynamicTool extends Tool {
91
+ export declare class DynamicTool<ToolOutputT = ToolOutputType> extends Tool<ToolOutputT> {
94
92
  static lc_name(): string;
95
93
  name: string;
96
94
  description: string;
97
- func: DynamicToolInput["func"];
98
- constructor(fields: DynamicToolInput);
95
+ func: DynamicToolInput<ToolOutputT>["func"];
96
+ constructor(fields: DynamicToolInput<ToolOutputT>);
99
97
  /**
100
98
  * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
101
99
  */
102
- call(arg: string | undefined | z.input<this["schema"]> | ToolCall, configArg?: ToolRunnableConfig | Callbacks): Promise<ToolReturnType>;
100
+ call<TArg extends string | undefined | z.input<this["schema"]> | ToolCall, TConfig extends ToolRunnableConfig | undefined>(arg: TArg, configArg?: TConfig): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>>;
103
101
  /** @ignore */
104
- _call(input: string, runManager?: CallbackManagerForToolRun, parentConfig?: ToolRunnableConfig): Promise<ToolReturnType>;
102
+ _call(input: string, // DynamicTool's _call specifically expects a string after schema transformation
103
+ runManager?: CallbackManagerForToolRun, parentConfig?: ToolRunnableConfig): Promise<ToolOutputT>;
105
104
  }
106
105
  /**
107
106
  * A tool that can be created dynamically from a function, name, and
@@ -112,20 +111,20 @@ export declare class DynamicTool extends Tool {
112
111
  * Schema can be passed as Zod or JSON schema. The tool will not validate
113
112
  * input if JSON schema is passed.
114
113
  */
115
- export declare class DynamicStructuredTool<SchemaT extends ToolInputSchemaBase = ZodObjectAny, SchemaOutputT = ToolInputSchemaOutputType<SchemaT>, SchemaInputT = ToolInputSchemaInputType<SchemaT>> extends StructuredTool<SchemaT, SchemaOutputT, SchemaInputT> {
114
+ export declare class DynamicStructuredTool<SchemaT extends ToolInputSchemaBase = ToolInputSchemaBase, SchemaOutputT = ToolInputSchemaOutputType<SchemaT>, SchemaInputT = ToolInputSchemaInputType<SchemaT>, ToolOutputT = ToolOutputType> extends StructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT> {
116
115
  static lc_name(): string;
117
116
  name: string;
118
117
  description: string;
119
- func: DynamicStructuredToolInput<SchemaT, SchemaOutputT>["func"];
118
+ func: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>["func"];
120
119
  schema: SchemaT;
121
- constructor(fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT>);
120
+ constructor(fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>);
122
121
  /**
123
122
  * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
124
123
  */
125
- call(arg: StructuredToolCallInput<SchemaT, SchemaInputT>, configArg?: RunnableConfig | Callbacks,
124
+ call<TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>, TConfig extends ToolRunnableConfig | undefined>(arg: TArg, configArg?: TConfig,
126
125
  /** @deprecated */
127
- tags?: string[]): Promise<ToolReturnType>;
128
- protected _call(arg: Parameters<DynamicStructuredToolInput<SchemaT, SchemaOutputT>["func"]>[0], runManager?: CallbackManagerForToolRun, parentConfig?: RunnableConfig): Promise<ToolReturnType>;
126
+ tags?: string[]): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>>;
127
+ protected _call(arg: Parameters<DynamicStructuredToolInput<SchemaT, SchemaOutputT>["func"]>[0], runManager?: CallbackManagerForToolRun, parentConfig?: RunnableConfig): Promise<ToolOutputT>;
129
128
  }
130
129
  /**
131
130
  * Abstract base class for toolkits in LangChain. Toolkits are collections
@@ -140,9 +139,9 @@ export declare abstract class BaseToolkit {
140
139
  * Parameters for the tool function.
141
140
  * Schema can be provided as Zod or JSON schema.
142
141
  * Both schema types will be validated.
143
- * @template {ZodObjectAny | z.ZodString | JSONSchema = ZodObjectAny} RunInput The input schema for the tool. Either any Zod object, a Zod string, or JSON schema.
142
+ * @template {ToolInputSchemaBase} RunInput The input schema for the tool.
144
143
  */
145
- interface ToolWrapperParams<RunInput extends ZodObjectAny | z.ZodString | JSONSchema = ZodObjectAny> extends ToolParams {
144
+ interface ToolWrapperParams<RunInput extends ToolInputSchemaBase | undefined = ToolInputSchemaBase | undefined> extends ToolParams {
146
145
  /**
147
146
  * The name of the tool. If using with an LLM, this
148
147
  * will be passed as the tool name.
@@ -183,9 +182,10 @@ interface ToolWrapperParams<RunInput extends ZodObjectAny | z.ZodString | JSONSc
183
182
  * Schema can be provided as Zod or JSON schema, and both will be validated.
184
183
  *
185
184
  * @function
186
- * @template {ZodObjectAny | z.ZodString | JSONSchema = ZodObjectAny} SchemaT The input schema for the tool. Either any Zod object, a Zod string, or JSON schema instance.
185
+ * @template {ToolInputSchemaBase} SchemaT The input schema for the tool.
186
+ * @template {ToolReturnType} ToolOutputT The output type of the tool.
187
187
  *
188
- * @param {RunnableFunc<z.output<SchemaT>, ToolReturnType>} func - The function to invoke when the tool is called.
188
+ * @param {RunnableFunc<z.output<SchemaT>, ToolOutputT>} func - The function to invoke when the tool is called.
189
189
  * @param {ToolWrapperParams<SchemaT>} fields - An object containing the following properties:
190
190
  * @param {string} fields.name The name of the tool.
191
191
  * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.
@@ -193,6 +193,6 @@ interface ToolWrapperParams<RunInput extends ZodObjectAny | z.ZodString | JSONSc
193
193
  *
194
194
  * @returns {DynamicStructuredTool<SchemaT>} A new StructuredTool instance.
195
195
  */
196
- export declare function tool<SchemaT extends z.ZodString>(func: RunnableFunc<SchemaT extends z.ZodString ? z.output<SchemaT> : string, ToolReturnType, ToolRunnableConfig>, fields: ToolWrapperParams<SchemaT>): DynamicTool;
197
- export declare function tool<SchemaT extends ZodObjectAny, SchemaOutputT = z.output<SchemaT>, SchemaInputT = z.input<SchemaT>>(func: RunnableFunc<SchemaOutputT, ToolReturnType, ToolRunnableConfig>, fields: ToolWrapperParams<SchemaT>): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT>;
198
- export declare function tool<SchemaT extends JSONSchema, SchemaOutputT = ToolInputSchemaOutputType<SchemaT>, SchemaInputT = ToolInputSchemaInputType<SchemaT>>(func: RunnableFunc<Parameters<DynamicStructuredToolInput<SchemaT>["func"]>[0], ToolReturnType, ToolRunnableConfig>, fields: ToolWrapperParams<SchemaT>): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT>;
196
+ export declare function tool<SchemaT extends z.ZodString, ToolOutputT = ToolOutputType>(func: RunnableFunc<SchemaT extends z.ZodString ? z.output<SchemaT> : string, ToolOutputT, ToolRunnableConfig>, fields: ToolWrapperParams<SchemaT>): DynamicTool<ToolOutputT>;
197
+ export declare function tool<SchemaT extends ZodObjectAny, SchemaOutputT = z.output<SchemaT>, SchemaInputT = z.input<SchemaT>, ToolOutputT = ToolOutputType>(func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>, fields: ToolWrapperParams<SchemaT>): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;
198
+ export declare function tool<SchemaT extends JSONSchema, SchemaOutputT = ToolInputSchemaOutputType<SchemaT>, SchemaInputT = ToolInputSchemaInputType<SchemaT>, ToolOutputT = ToolOutputType>(func: RunnableFunc<Parameters<DynamicStructuredToolInput<SchemaT>["func"]>[0], ToolOutputT, ToolRunnableConfig>, fields: ToolWrapperParams<SchemaT>): DynamicStructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT>;
@@ -5,7 +5,7 @@ import { BaseLangChain } from "../language_models/base.js";
5
5
  import { ensureConfig, patchConfig, pickRunnableConfigKeys, } from "../runnables/config.js";
6
6
  import { isDirectToolOutput, ToolMessage } from "../messages/tool.js";
7
7
  import { AsyncLocalStorageProviderSingleton } from "../singletons/index.js";
8
- import { _isToolCall, ToolInputParsingException } from "./utils.js";
8
+ import { _configHasToolCallId, _isToolCall, ToolInputParsingException, } from "./utils.js";
9
9
  import { isZodSchema } from "../utils/types/is_zod_schema.js";
10
10
  import { validatesOnlyStrings } from "../utils/json_schema.js";
11
11
  export { isLangChainTool, isRunnableToolLike, isStructuredTool, isStructuredToolParams, } from "./types.js";
@@ -60,22 +60,16 @@ export class StructuredTool extends BaseLangChain {
60
60
  * Invokes the tool with the provided input and configuration.
61
61
  * @param input The input for the tool.
62
62
  * @param config Optional configuration for the tool.
63
- * @returns A Promise that resolves with a string.
63
+ * @returns A Promise that resolves with the tool's output.
64
64
  */
65
65
  async invoke(input, config) {
66
- let tool_call_id;
67
66
  let toolInput;
68
67
  let enrichedConfig = ensureConfig(config);
69
68
  if (_isToolCall(input)) {
70
- tool_call_id = input.id;
71
69
  toolInput = input.args;
72
70
  enrichedConfig = {
73
71
  ...enrichedConfig,
74
72
  toolCall: input,
75
- configurable: {
76
- ...enrichedConfig.configurable,
77
- tool_call_id,
78
- },
79
73
  };
80
74
  }
81
75
  else {
@@ -97,21 +91,26 @@ export class StructuredTool extends BaseLangChain {
97
91
  async call(arg, configArg,
98
92
  /** @deprecated */
99
93
  tags) {
100
- let parsed = arg;
94
+ // Determine the actual input that needs parsing/validation.
95
+ // If arg is a ToolCall, use its args; otherwise, use arg directly.
96
+ const inputForValidation = _isToolCall(arg) ? arg.args : arg;
97
+ let parsed; // This will hold the successfully parsed input of the expected output type.
101
98
  if (isZodSchema(this.schema)) {
102
99
  try {
103
- parsed = await this.schema.parseAsync(arg);
100
+ // Validate the inputForValidation - TS needs help here as it can't exclude ToolCall based on the check
101
+ parsed = await this.schema.parseAsync(inputForValidation);
104
102
  }
105
103
  catch (e) {
106
104
  let message = `Received tool input did not match expected schema`;
107
105
  if (this.verboseParsingErrors) {
108
106
  message = `${message}\nDetails: ${e.message}`;
109
107
  }
108
+ // Pass the original raw input arg to the exception
110
109
  throw new ToolInputParsingException(message, JSON.stringify(arg));
111
110
  }
112
111
  }
113
112
  else {
114
- const result = validate(arg, this.schema);
113
+ const result = validate(inputForValidation, this.schema);
115
114
  if (!result.valid) {
116
115
  let message = `Received tool input did not match expected schema`;
117
116
  if (this.verboseParsingErrors) {
@@ -119,15 +118,22 @@ export class StructuredTool extends BaseLangChain {
119
118
  .map((e) => `${e.keywordLocation}: ${e.error}`)
120
119
  .join("\n")}`;
121
120
  }
121
+ // Pass the original raw input arg to the exception
122
122
  throw new ToolInputParsingException(message, JSON.stringify(arg));
123
123
  }
124
+ // Assign the validated input to parsed
125
+ // We cast here because validate() doesn't narrow the type sufficiently for TS, but we know it's valid.
126
+ parsed = inputForValidation;
124
127
  }
125
128
  const config = parseCallbackConfigArg(configArg);
126
129
  const callbackManager_ = CallbackManager.configure(config.callbacks, this.callbacks, config.tags || tags, this.tags, config.metadata, this.metadata, { verbose: this.verbose });
127
- const runManager = await callbackManager_?.handleToolStart(this.toJSON(), typeof parsed === "string" ? parsed : JSON.stringify(parsed), config.runId, undefined, undefined, undefined, config.runName);
130
+ const runManager = await callbackManager_?.handleToolStart(this.toJSON(),
131
+ // Log the original raw input arg
132
+ typeof arg === "string" ? arg : JSON.stringify(arg), config.runId, undefined, undefined, undefined, config.runName);
128
133
  delete config.runId;
129
134
  let result;
130
135
  try {
136
+ // Pass the correctly typed parsed input to _call
131
137
  result = await this._call(parsed, runManager, config);
132
138
  }
133
139
  catch (e) {
@@ -148,9 +154,13 @@ export class StructuredTool extends BaseLangChain {
148
154
  content = result;
149
155
  }
150
156
  let toolCallId;
151
- if (config && "configurable" in config) {
152
- toolCallId = config.configurable
153
- .tool_call_id;
157
+ // Extract toolCallId ONLY if the original arg was a ToolCall
158
+ if (_isToolCall(arg)) {
159
+ toolCallId = arg.id;
160
+ }
161
+ // Or if it was provided in the config's toolCall property
162
+ if (!toolCallId && _configHasToolCallId(config)) {
163
+ toolCallId = config.toolCall.id;
154
164
  }
155
165
  const formattedOutput = _formatToolOutput({
156
166
  content,
@@ -186,8 +196,13 @@ export class Tool extends StructuredTool {
186
196
  * @param callbacks Optional callbacks for the tool.
187
197
  * @returns A Promise that resolves with a string.
188
198
  */
199
+ // Match the base class signature including the generics and conditional return type
189
200
  call(arg, callbacks) {
190
- return super.call(typeof arg === "string" || !arg ? { input: arg } : arg, callbacks);
201
+ // Prepare the input for the base class call method.
202
+ // If arg is string or undefined, wrap it; otherwise, pass ToolCall or { input: ... } directly.
203
+ const structuredArg = typeof arg === "string" || arg == null ? { input: arg } : arg;
204
+ // Ensure TConfig is passed to super.call
205
+ return super.call(structuredArg, callbacks);
191
206
  }
192
207
  }
193
208
  /**
@@ -230,10 +245,13 @@ export class DynamicTool extends Tool {
230
245
  if (config.runName === undefined) {
231
246
  config.runName = this.name;
232
247
  }
248
+ // Call the Tool class's call method, passing generics through
249
+ // Cast config to TConfig to satisfy the super.call signature
233
250
  return super.call(arg, config);
234
251
  }
235
252
  /** @ignore */
236
- async _call(input, runManager, parentConfig) {
253
+ async _call(input, // DynamicTool's _call specifically expects a string after schema transformation
254
+ runManager, parentConfig) {
237
255
  return this.func(input, runManager, parentConfig);
238
256
  }
239
257
  }
@@ -285,6 +303,7 @@ export class DynamicStructuredTool extends StructuredTool {
285
303
  /**
286
304
  * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
287
305
  */
306
+ // Match the base class signature
288
307
  async call(arg, configArg,
289
308
  /** @deprecated */
290
309
  tags) {
@@ -292,6 +311,8 @@ export class DynamicStructuredTool extends StructuredTool {
292
311
  if (config.runName === undefined) {
293
312
  config.runName = this.name;
294
313
  }
314
+ // Call the base class method, passing generics through
315
+ // Cast config to TConfig to satisfy the super.call signature
295
316
  return super.call(arg, config, tags);
296
317
  }
297
318
  _call(arg, runManager, parentConfig) {
@@ -1,20 +1,39 @@
1
1
  import { z } from "zod";
2
- import { CallbackManagerForToolRun, type Callbacks } from "../callbacks/manager.js";
2
+ import { CallbackManagerForToolRun } from "../callbacks/manager.js";
3
3
  import type { BaseLangChainParams, ToolDefinition } from "../language_models/base.js";
4
4
  import type { RunnableConfig } from "../runnables/config.js";
5
5
  import { RunnableToolLike, type RunnableInterface } from "../runnables/base.js";
6
- import type { ToolCall } from "../messages/tool.js";
6
+ import { type DirectToolOutput, type ToolCall, type ToolMessage } from "../messages/tool.js";
7
7
  import type { MessageContent } from "../messages/base.js";
8
8
  import { JSONSchema } from "../utils/json_schema.js";
9
9
  export type ResponseFormat = "content" | "content_and_artifact" | string;
10
- export type ToolReturnType = any;
10
+ export type ToolOutputType = any;
11
11
  export type ContentAndArtifact = [MessageContent, any];
12
12
  export type ZodObjectAny = z.ZodObject<any, any, any, any>;
13
+ /**
14
+ * Conditional type that determines the return type of the {@link StructuredTool.invoke} method.
15
+ * - If the input is a ToolCall, it returns a ToolMessage
16
+ * - If the config is a runnable config and contains a toolCall property, it returns a ToolMessage
17
+ * - Otherwise, it returns the original output type
18
+ */
19
+ export type ToolReturnType<TInput, TConfig, TOutput> = TOutput extends DirectToolOutput ? TOutput : TConfig extends {
20
+ toolCall: {
21
+ id: string;
22
+ };
23
+ } ? ToolMessage : TConfig extends {
24
+ toolCall: {
25
+ id: undefined;
26
+ };
27
+ } ? TOutput : TConfig extends {
28
+ toolCall: {
29
+ id?: string;
30
+ };
31
+ } ? TOutput | ToolMessage : TInput extends ToolCall ? ToolMessage : TOutput;
13
32
  /**
14
33
  * Base type that establishes the types of input schemas that can be used for LangChain tool
15
34
  * definitions.
16
35
  */
17
- export type ToolInputSchemaBase = ZodObjectAny | z.ZodEffects<ZodObjectAny> | JSONSchema;
36
+ export type ToolInputSchemaBase = z.ZodAny | JSONSchema;
18
37
  /**
19
38
  * Parameters for the Tool classes.
20
39
  */
@@ -80,7 +99,32 @@ export type ToolInputSchemaInputType<T extends ToolInputSchemaBase> = T extends
80
99
  * @param SchemaT - The type of the tool input schema. Usually you don't need to specify this.
81
100
  * @param SchemaInputT - The TypeScript type representing the structure of the tool arguments generated by the LLM. Useful for type checking tool handler functions when using JSONSchema.
82
101
  */
83
- export type StructuredToolCallInput<SchemaT extends ToolInputSchemaBase = ZodObjectAny, SchemaInputT = ToolInputSchemaInputType<SchemaT>> = (ToolInputSchemaOutputType<SchemaT> extends string ? string : never) | SchemaInputT | ToolCall;
102
+ export type StructuredToolCallInput<SchemaT extends ToolInputSchemaBase = ToolInputSchemaBase, SchemaInputT = ToolInputSchemaInputType<SchemaT>> = (ToolInputSchemaOutputType<SchemaT> extends string ? string : never) | SchemaInputT | ToolCall;
103
+ /**
104
+ * An input schema type for tools that accept a single string input.
105
+ *
106
+ * This schema defines a tool that takes an optional string parameter named "input".
107
+ * It uses Zod's effects to transform the input and strip any extra properties.
108
+ *
109
+ * This is primarily used for creating simple string-based tools where the LLM
110
+ * only needs to provide a single text value as input to the tool.
111
+ */
112
+ export type StringInputToolSchema = z.ZodEffects<z.ZodObject<{
113
+ input: z.ZodOptional<z.ZodString>;
114
+ }, "strip", z.ZodTypeAny, any, any>, any, any>;
115
+ /**
116
+ * Defines the type for input to a tool's call method.
117
+ *
118
+ * This type is a convenience alias for StructuredToolCallInput with the input type
119
+ * derived from the schema. It represents the possible inputs that can be passed to a tool,
120
+ * which can be either:
121
+ * - A string (if the tool accepts string input)
122
+ * - A structured input matching the tool's schema
123
+ * - A ToolCall object (typically from an LLM)
124
+ *
125
+ * @param SchemaT - The schema type for the tool input, defaults to StringInputToolSchema
126
+ */
127
+ export type ToolCallInput<SchemaT extends ToolInputSchemaBase = StringInputToolSchema> = StructuredToolCallInput<SchemaT, ToolInputSchemaInputType<SchemaT>>;
84
128
  /**
85
129
  * Interface that defines the shape of a LangChain structured tool.
86
130
  *
@@ -90,12 +134,19 @@ export type StructuredToolCallInput<SchemaT extends ToolInputSchemaBase = ZodObj
90
134
  * @param SchemaT - The type of the tool input schema. Usually you don't need to specify this.
91
135
  * @param SchemaInputT - The TypeScript type representing the structure of the tool arguments generated by the LLM. Useful for type checking tool handler functions when using JSONSchema.
92
136
  */
93
- export interface StructuredToolInterface<SchemaT extends ToolInputSchemaBase = ZodObjectAny | z.ZodEffects<ZodObjectAny> | JSONSchema, SchemaInputT = ToolInputSchemaInputType<SchemaT>> extends RunnableInterface<StructuredToolCallInput<SchemaT, SchemaInputT>, ToolReturnType> {
137
+ export interface StructuredToolInterface<SchemaT extends ToolInputSchemaBase = ToolInputSchemaBase, SchemaInputT = ToolInputSchemaInputType<SchemaT>, ToolOutputT = ToolOutputType> extends RunnableInterface<StructuredToolCallInput<SchemaT, SchemaInputT>, ToolOutputT | ToolMessage> {
94
138
  lc_namespace: string[];
95
139
  /**
96
140
  * A Zod schema representing the parameters of the tool.
97
141
  */
98
142
  schema: SchemaT;
143
+ /**
144
+ * Invokes the tool with the provided argument and configuration.
145
+ * @param arg The input argument for the tool.
146
+ * @param configArg Optional configuration for the tool call.
147
+ * @returns A Promise that resolves with the tool's output.
148
+ */
149
+ invoke<TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>, TConfig extends ToolRunnableConfig | undefined>(arg: TArg, configArg?: TConfig): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>>;
99
150
  /**
100
151
  * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
101
152
  *
@@ -107,9 +158,9 @@ export interface StructuredToolInterface<SchemaT extends ToolInputSchemaBase = Z
107
158
  * @param tags Optional tags for the tool.
108
159
  * @returns A Promise that resolves with a string.
109
160
  */
110
- call(arg: StructuredToolCallInput<SchemaT, SchemaInputT>, configArg?: Callbacks | RunnableConfig,
161
+ call<TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>, TConfig extends ToolRunnableConfig | undefined>(arg: TArg, configArg?: TConfig,
111
162
  /** @deprecated */
112
- tags?: string[]): Promise<ToolReturnType>;
163
+ tags?: string[]): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>>;
113
164
  /**
114
165
  * The name of the tool.
115
166
  */
@@ -132,7 +183,7 @@ export interface StructuredToolInterface<SchemaT extends ToolInputSchemaBase = Z
132
183
  * @param SchemaT - The type of the tool input schema. Usually you don't need to specify this.
133
184
  * @param SchemaInputT - The TypeScript type representing the structure of the tool arguments generated by the LLM. Useful for type checking tool handler functions when using JSONSchema.
134
185
  */
135
- export interface ToolInterface<SchemaT extends ToolInputSchemaBase = ZodObjectAny | z.ZodEffects<ZodObjectAny> | JSONSchema, SchemaInputT = ToolInputSchemaInputType<SchemaT>> extends StructuredToolInterface<SchemaT, SchemaInputT> {
186
+ export interface ToolInterface<SchemaT extends StringInputToolSchema = StringInputToolSchema, SchemaInputT = ToolInputSchemaInputType<SchemaT>, ToolOutputT = ToolOutputType> extends StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT> {
136
187
  /**
137
188
  * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
138
189
  *
@@ -142,7 +193,7 @@ export interface ToolInterface<SchemaT extends ToolInputSchemaBase = ZodObjectAn
142
193
  * @param callbacks Optional callbacks for the tool.
143
194
  * @returns A Promise that resolves with a string.
144
195
  */
145
- call(arg: string | undefined | SchemaInputT | ToolCall, callbacks?: Callbacks | RunnableConfig): Promise<ToolReturnType>;
196
+ call<TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>, TConfig extends ToolRunnableConfig | undefined>(arg: TArg, callbacks?: TConfig): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>>;
146
197
  }
147
198
  /**
148
199
  * Base interface for the input parameters of the {@link DynamicTool} and
@@ -162,8 +213,8 @@ export interface BaseDynamicToolInput extends ToolParams {
162
213
  /**
163
214
  * Interface for the input parameters of the DynamicTool class.
164
215
  */
165
- export interface DynamicToolInput extends BaseDynamicToolInput {
166
- func: (input: string, runManager?: CallbackManagerForToolRun, config?: ToolRunnableConfig) => Promise<ToolReturnType>;
216
+ export interface DynamicToolInput<ToolOutputT = ToolOutputType> extends BaseDynamicToolInput {
217
+ func: (input: string, runManager?: CallbackManagerForToolRun, config?: ToolRunnableConfig) => Promise<ToolOutputT>;
167
218
  }
168
219
  /**
169
220
  * Interface for the input parameters of the DynamicStructuredTool class.
@@ -171,7 +222,7 @@ export interface DynamicToolInput extends BaseDynamicToolInput {
171
222
  * @param SchemaT - The type of the tool input schema. Usually you don't need to specify this.
172
223
  * @param SchemaOutputT - The TypeScript type representing the result of applying the schema to the tool arguments. Useful for type checking tool handler functions when using JSONSchema.
173
224
  */
174
- export interface DynamicStructuredToolInput<SchemaT extends ToolInputSchemaBase = ZodObjectAny, SchemaOutputT = ToolInputSchemaOutputType<SchemaT>> extends BaseDynamicToolInput {
225
+ export interface DynamicStructuredToolInput<SchemaT extends ToolInputSchemaBase = ToolInputSchemaBase, SchemaOutputT = ToolInputSchemaOutputType<SchemaT>, ToolOutputT = ToolOutputType> extends BaseDynamicToolInput {
175
226
  /**
176
227
  * Tool handler function - the function that will be called when the tool is invoked.
177
228
  *
@@ -180,8 +231,8 @@ export interface DynamicStructuredToolInput<SchemaT extends ToolInputSchemaBase
180
231
  * @param config - The configuration for the tool.
181
232
  * @returns The result of the tool.
182
233
  */
183
- func: (input: BaseDynamicToolInput["responseFormat"] extends "content_and_artifact" ? ToolCall : SchemaOutputT, runManager?: CallbackManagerForToolRun, config?: RunnableConfig) => Promise<ToolReturnType>;
184
- schema: SchemaT extends ZodObjectAny ? SchemaT : SchemaT;
234
+ func: (input: SchemaOutputT, runManager?: CallbackManagerForToolRun, config?: RunnableConfig) => Promise<ToolOutputT>;
235
+ schema: SchemaT;
185
236
  }
186
237
  /**
187
238
  * Confirm whether the inputted tool is an instance of `StructuredToolInterface`.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ToolInputParsingException = exports._isToolCall = void 0;
3
+ exports.ToolInputParsingException = exports._configHasToolCallId = exports._isToolCall = void 0;
4
4
  function _isToolCall(toolCall) {
5
5
  return !!(toolCall &&
6
6
  typeof toolCall === "object" &&
@@ -8,6 +8,16 @@ function _isToolCall(toolCall) {
8
8
  toolCall.type === "tool_call");
9
9
  }
10
10
  exports._isToolCall = _isToolCall;
11
+ function _configHasToolCallId(config) {
12
+ return !!(config &&
13
+ typeof config === "object" &&
14
+ "toolCall" in config &&
15
+ config.toolCall != null &&
16
+ typeof config.toolCall === "object" &&
17
+ "id" in config.toolCall &&
18
+ typeof config.toolCall.id === "string");
19
+ }
20
+ exports._configHasToolCallId = _configHasToolCallId;
11
21
  /**
12
22
  * Custom error class used to handle exceptions related to tool input parsing.
13
23
  * It extends the built-in `Error` class and adds an optional `output`
@@ -1,5 +1,10 @@
1
1
  import { ToolCall } from "../messages/tool.js";
2
2
  export declare function _isToolCall(toolCall?: unknown): toolCall is ToolCall;
3
+ export declare function _configHasToolCallId(config?: unknown): config is {
4
+ toolCall: {
5
+ id?: string;
6
+ };
7
+ };
3
8
  /**
4
9
  * Custom error class used to handle exceptions related to tool input parsing.
5
10
  * It extends the built-in `Error` class and adds an optional `output`
@@ -4,6 +4,15 @@ export function _isToolCall(toolCall) {
4
4
  "type" in toolCall &&
5
5
  toolCall.type === "tool_call");
6
6
  }
7
+ export function _configHasToolCallId(config) {
8
+ return !!(config &&
9
+ typeof config === "object" &&
10
+ "toolCall" in config &&
11
+ config.toolCall != null &&
12
+ typeof config.toolCall === "object" &&
13
+ "id" in config.toolCall &&
14
+ typeof config.toolCall.id === "string");
15
+ }
7
16
  /**
8
17
  * Custom error class used to handle exceptions related to tool input parsing.
9
18
  * It extends the built-in `Error` class and adds an optional `output`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@langchain/core",
3
- "version": "0.3.53",
3
+ "version": "0.3.55",
4
4
  "description": "Core LangChain.js abstractions and schemas",
5
5
  "type": "module",
6
6
  "engines": {
@@ -874,4 +874,4 @@
874
874
  "vectorstores.d.ts",
875
875
  "vectorstores.d.cts"
876
876
  ]
877
- }
877
+ }