@langchain/core 0.2.15 → 0.2.17

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 (103) hide show
  1. package/caches.cjs +1 -1
  2. package/caches.d.cts +1 -1
  3. package/caches.d.ts +1 -1
  4. package/caches.js +1 -1
  5. package/callbacks/dispatch/web.cjs +1 -0
  6. package/callbacks/dispatch/web.d.cts +1 -0
  7. package/callbacks/dispatch/web.d.ts +1 -0
  8. package/callbacks/dispatch/web.js +1 -0
  9. package/callbacks/dispatch.cjs +1 -0
  10. package/callbacks/dispatch.d.cts +1 -0
  11. package/callbacks/dispatch.d.ts +1 -0
  12. package/callbacks/dispatch.js +1 -0
  13. package/dist/{caches.cjs → caches/base.cjs} +6 -6
  14. package/dist/{caches.d.ts → caches/base.d.ts} +7 -7
  15. package/dist/{caches.js → caches/base.js} +6 -6
  16. package/dist/caches/tests/in_memory_cache.test.d.ts +1 -0
  17. package/dist/caches/tests/in_memory_cache.test.js +33 -0
  18. package/dist/callbacks/base.cjs +8 -0
  19. package/dist/callbacks/base.d.ts +16 -10
  20. package/dist/callbacks/base.js +8 -0
  21. package/dist/callbacks/dispatch/index.cjs +49 -0
  22. package/dist/callbacks/dispatch/index.d.ts +35 -0
  23. package/dist/callbacks/dispatch/index.js +45 -0
  24. package/dist/callbacks/dispatch/web.cjs +61 -0
  25. package/dist/callbacks/dispatch/web.d.ts +32 -0
  26. package/dist/callbacks/dispatch/web.js +57 -0
  27. package/dist/callbacks/manager.cjs +20 -0
  28. package/dist/callbacks/manager.d.ts +2 -1
  29. package/dist/callbacks/manager.js +20 -0
  30. package/dist/language_models/base.cjs +4 -4
  31. package/dist/language_models/base.d.ts +2 -2
  32. package/dist/language_models/base.js +1 -1
  33. package/dist/language_models/chat_models.d.ts +22 -5
  34. package/dist/language_models/llms.d.ts +1 -1
  35. package/dist/language_models/tests/chat_models.test.js +33 -0
  36. package/dist/load/import_map.cjs +2 -2
  37. package/dist/load/import_map.d.ts +2 -2
  38. package/dist/load/import_map.js +2 -2
  39. package/dist/messages/ai.cjs +19 -0
  40. package/dist/messages/ai.d.ts +2 -0
  41. package/dist/messages/ai.js +19 -0
  42. package/dist/messages/base.cjs +95 -5
  43. package/dist/messages/base.d.ts +5 -1
  44. package/dist/messages/base.js +93 -4
  45. package/dist/messages/chat.cjs +12 -0
  46. package/dist/messages/chat.d.ts +2 -0
  47. package/dist/messages/chat.js +12 -0
  48. package/dist/messages/index.cjs +1 -0
  49. package/dist/messages/index.d.ts +2 -1
  50. package/dist/messages/index.js +1 -0
  51. package/dist/messages/modifier.cjs +35 -0
  52. package/dist/messages/modifier.d.ts +19 -0
  53. package/dist/messages/modifier.js +31 -0
  54. package/dist/messages/tests/base_message.test.js +134 -2
  55. package/dist/messages/tests/message_utils.test.js +54 -2
  56. package/dist/messages/tool.cjs +45 -0
  57. package/dist/messages/tool.d.ts +29 -0
  58. package/dist/messages/tool.js +46 -1
  59. package/dist/messages/transformers.cjs +6 -0
  60. package/dist/messages/transformers.d.ts +3 -2
  61. package/dist/messages/transformers.js +6 -0
  62. package/dist/messages/utils.cjs +5 -1
  63. package/dist/messages/utils.js +5 -1
  64. package/dist/output_parsers/openai_tools/json_output_tools_parsers.cjs +2 -0
  65. package/dist/output_parsers/openai_tools/json_output_tools_parsers.js +2 -0
  66. package/dist/runnables/base.cjs +104 -1
  67. package/dist/runnables/base.d.ts +50 -0
  68. package/dist/runnables/base.js +101 -0
  69. package/dist/runnables/index.cjs +2 -1
  70. package/dist/runnables/index.d.ts +1 -1
  71. package/dist/runnables/index.js +1 -1
  72. package/dist/runnables/tests/runnable_stream_events.test.js +1 -1
  73. package/dist/runnables/tests/runnable_stream_events_v2.test.js +106 -1
  74. package/dist/runnables/tests/runnable_tools.test.d.ts +1 -0
  75. package/dist/runnables/tests/runnable_tools.test.js +149 -0
  76. package/dist/{tools.cjs → tools/index.cjs} +135 -47
  77. package/dist/{tools.d.ts → tools/index.d.ts} +76 -47
  78. package/dist/{tools.js → tools/index.js} +134 -45
  79. package/dist/tools/tests/tools.test.d.ts +1 -0
  80. package/dist/tools/tests/tools.test.js +85 -0
  81. package/dist/tools/utils.cjs +28 -0
  82. package/dist/tools/utils.d.ts +11 -0
  83. package/dist/tools/utils.js +23 -0
  84. package/dist/tracers/base.cjs +1 -0
  85. package/dist/tracers/base.d.ts +1 -1
  86. package/dist/tracers/base.js +1 -0
  87. package/dist/tracers/event_stream.cjs +15 -0
  88. package/dist/tracers/event_stream.d.ts +1 -0
  89. package/dist/tracers/event_stream.js +15 -0
  90. package/dist/types/zod.cjs +2 -0
  91. package/dist/types/zod.d.ts +2 -0
  92. package/dist/types/zod.js +1 -0
  93. package/dist/utils/function_calling.cjs +38 -10
  94. package/dist/utils/function_calling.d.ts +32 -11
  95. package/dist/utils/function_calling.js +36 -9
  96. package/dist/utils/testing/index.cjs +10 -3
  97. package/dist/utils/testing/index.d.ts +1 -1
  98. package/dist/utils/testing/index.js +9 -2
  99. package/package.json +28 -1
  100. package/tools.cjs +1 -1
  101. package/tools.d.cts +1 -1
  102. package/tools.d.ts +1 -1
  103. package/tools.js +1 -1
@@ -1,5 +1,13 @@
1
1
  import { BaseMessage, BaseMessageChunk, type BaseMessageFields, type MessageType } from "./base.js";
2
2
  export interface ToolMessageFieldsWithToolCallId extends BaseMessageFields {
3
+ /**
4
+ * Artifact of the Tool execution which is not meant to be sent to the model.
5
+ *
6
+ * Should only be specified if it is different from the message content, e.g. if only
7
+ * a subset of the full tool output is being passed as message content but the full
8
+ * output is needed in other parts of the code.
9
+ */
10
+ artifact?: any;
3
11
  tool_call_id: string;
4
12
  }
5
13
  /**
@@ -9,10 +17,19 @@ export declare class ToolMessage extends BaseMessage {
9
17
  static lc_name(): string;
10
18
  get lc_aliases(): Record<string, string>;
11
19
  tool_call_id: string;
20
+ /**
21
+ * Artifact of the Tool execution which is not meant to be sent to the model.
22
+ *
23
+ * Should only be specified if it is different from the message content, e.g. if only
24
+ * a subset of the full tool output is being passed as message content but the full
25
+ * output is needed in other parts of the code.
26
+ */
27
+ artifact?: any;
12
28
  constructor(fields: ToolMessageFieldsWithToolCallId);
13
29
  constructor(fields: string | BaseMessageFields, tool_call_id: string, name?: string);
14
30
  _getType(): MessageType;
15
31
  static isInstance(message: BaseMessage): message is ToolMessage;
32
+ get _printableFields(): Record<string, unknown>;
16
33
  }
17
34
  /**
18
35
  * Represents a chunk of a tool message, which can be concatenated
@@ -20,10 +37,19 @@ export declare class ToolMessage extends BaseMessage {
20
37
  */
21
38
  export declare class ToolMessageChunk extends BaseMessageChunk {
22
39
  tool_call_id: string;
40
+ /**
41
+ * Artifact of the Tool execution which is not meant to be sent to the model.
42
+ *
43
+ * Should only be specified if it is different from the message content, e.g. if only
44
+ * a subset of the full tool output is being passed as message content but the full
45
+ * output is needed in other parts of the code.
46
+ */
47
+ artifact?: any;
23
48
  constructor(fields: ToolMessageFieldsWithToolCallId);
24
49
  static lc_name(): string;
25
50
  _getType(): MessageType;
26
51
  concat(chunk: ToolMessageChunk): ToolMessageChunk;
52
+ get _printableFields(): Record<string, unknown>;
27
53
  }
28
54
  /**
29
55
  * A call to a tool.
@@ -35,6 +61,7 @@ export type ToolCall = {
35
61
  name: string;
36
62
  args: Record<string, any>;
37
63
  id?: string;
64
+ type?: "tool_call";
38
65
  };
39
66
  /**
40
67
  * A chunk of a tool call (e.g., as part of a stream).
@@ -91,11 +118,13 @@ export type ToolCallChunk = {
91
118
  args?: string;
92
119
  id?: string;
93
120
  index?: number;
121
+ type?: "tool_call_chunk";
94
122
  };
95
123
  export type InvalidToolCall = {
96
124
  name?: string;
97
125
  args?: string;
98
126
  id?: string;
99
127
  error?: string;
128
+ type?: "invalid_tool_call";
100
129
  };
101
130
  export declare function defaultToolCallParser(rawToolCalls: Record<string, any>[]): [ToolCall[], InvalidToolCall[]];
@@ -1,4 +1,4 @@
1
- import { BaseMessage, BaseMessageChunk, mergeContent, _mergeDicts, } from "./base.js";
1
+ import { BaseMessage, BaseMessageChunk, mergeContent, _mergeDicts, _mergeObj, } from "./base.js";
2
2
  /**
3
3
  * Represents a tool message in a conversation.
4
4
  */
@@ -22,7 +22,22 @@ export class ToolMessage extends BaseMessage {
22
22
  writable: true,
23
23
  value: void 0
24
24
  });
25
+ /**
26
+ * Artifact of the Tool execution which is not meant to be sent to the model.
27
+ *
28
+ * Should only be specified if it is different from the message content, e.g. if only
29
+ * a subset of the full tool output is being passed as message content but the full
30
+ * output is needed in other parts of the code.
31
+ */
32
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
33
+ Object.defineProperty(this, "artifact", {
34
+ enumerable: true,
35
+ configurable: true,
36
+ writable: true,
37
+ value: void 0
38
+ });
25
39
  this.tool_call_id = fields.tool_call_id;
40
+ this.artifact = fields.artifact;
26
41
  }
27
42
  _getType() {
28
43
  return "tool";
@@ -30,6 +45,13 @@ export class ToolMessage extends BaseMessage {
30
45
  static isInstance(message) {
31
46
  return message._getType() === "tool";
32
47
  }
48
+ get _printableFields() {
49
+ return {
50
+ ...super._printableFields,
51
+ tool_call_id: this.tool_call_id,
52
+ artifact: this.artifact,
53
+ };
54
+ }
33
55
  }
34
56
  /**
35
57
  * Represents a chunk of a tool message, which can be concatenated
@@ -44,7 +66,22 @@ export class ToolMessageChunk extends BaseMessageChunk {
44
66
  writable: true,
45
67
  value: void 0
46
68
  });
69
+ /**
70
+ * Artifact of the Tool execution which is not meant to be sent to the model.
71
+ *
72
+ * Should only be specified if it is different from the message content, e.g. if only
73
+ * a subset of the full tool output is being passed as message content but the full
74
+ * output is needed in other parts of the code.
75
+ */
76
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
77
+ Object.defineProperty(this, "artifact", {
78
+ enumerable: true,
79
+ configurable: true,
80
+ writable: true,
81
+ value: void 0
82
+ });
47
83
  this.tool_call_id = fields.tool_call_id;
84
+ this.artifact = fields.artifact;
48
85
  }
49
86
  static lc_name() {
50
87
  return "ToolMessageChunk";
@@ -57,10 +94,18 @@ export class ToolMessageChunk extends BaseMessageChunk {
57
94
  content: mergeContent(this.content, chunk.content),
58
95
  additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),
59
96
  response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata),
97
+ artifact: _mergeObj(this.artifact, chunk.artifact),
60
98
  tool_call_id: this.tool_call_id,
61
99
  id: this.id ?? chunk.id,
62
100
  });
63
101
  }
102
+ get _printableFields() {
103
+ return {
104
+ ...super._printableFields,
105
+ tool_call_id: this.tool_call_id,
106
+ artifact: this.artifact,
107
+ };
108
+ }
64
109
  }
65
110
  export function defaultToolCallParser(
66
111
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -6,6 +6,7 @@ const ai_js_1 = require("./ai.cjs");
6
6
  const chat_js_1 = require("./chat.cjs");
7
7
  const function_js_1 = require("./function.cjs");
8
8
  const human_js_1 = require("./human.cjs");
9
+ const modifier_js_1 = require("./modifier.cjs");
9
10
  const system_js_1 = require("./system.cjs");
10
11
  const tool_js_1 = require("./tool.cjs");
11
12
  const utils_js_1 = require("./utils.cjs");
@@ -303,6 +304,10 @@ const _MSG_CHUNK_MAP = {
303
304
  message: chat_js_1.ChatMessage,
304
305
  messageChunk: chat_js_1.ChatMessageChunk,
305
306
  },
307
+ remove: {
308
+ message: modifier_js_1.RemoveMessage,
309
+ messageChunk: modifier_js_1.RemoveMessage, // RemoveMessage does not have a chunk class.
310
+ },
306
311
  };
307
312
  function _switchTypeToMessage(messageType, fields, returnChunk) {
308
313
  let chunk;
@@ -326,6 +331,7 @@ function _switchTypeToMessage(messageType, fields, returnChunk) {
326
331
  ...aiChunkFields,
327
332
  tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({
328
333
  ...tc,
334
+ type: "tool_call_chunk",
329
335
  index: undefined,
330
336
  args: JSON.stringify(tc.args),
331
337
  })),
@@ -6,10 +6,11 @@ import { BaseMessage, MessageType } from "./base.js";
6
6
  import { ChatMessage, ChatMessageChunk } from "./chat.js";
7
7
  import { FunctionMessage, FunctionMessageChunk } from "./function.js";
8
8
  import { HumanMessage, HumanMessageChunk } from "./human.js";
9
+ import { RemoveMessage } from "./modifier.js";
9
10
  import { SystemMessage, SystemMessageChunk } from "./system.js";
10
11
  import { ToolMessage, ToolMessageChunk } from "./tool.js";
11
- export type MessageUnion = typeof HumanMessage | typeof AIMessage | typeof SystemMessage | typeof ChatMessage | typeof FunctionMessage | typeof ToolMessage;
12
- export type MessageChunkUnion = typeof HumanMessageChunk | typeof AIMessageChunk | typeof SystemMessageChunk | typeof FunctionMessageChunk | typeof ToolMessageChunk | typeof ChatMessageChunk;
12
+ export type MessageUnion = typeof HumanMessage | typeof AIMessage | typeof SystemMessage | typeof ChatMessage | typeof FunctionMessage | typeof ToolMessage | typeof RemoveMessage;
13
+ export type MessageChunkUnion = typeof HumanMessageChunk | typeof AIMessageChunk | typeof SystemMessageChunk | typeof FunctionMessageChunk | typeof ToolMessageChunk | typeof ChatMessageChunk | typeof RemoveMessage;
13
14
  export type MessageTypeOrClass = MessageType | MessageUnion | MessageChunkUnion;
14
15
  export interface FilterMessagesFields {
15
16
  /**
@@ -3,6 +3,7 @@ import { AIMessage, AIMessageChunk } from "./ai.js";
3
3
  import { ChatMessage, ChatMessageChunk, } from "./chat.js";
4
4
  import { FunctionMessage, FunctionMessageChunk, } from "./function.js";
5
5
  import { HumanMessage, HumanMessageChunk } from "./human.js";
6
+ import { RemoveMessage } from "./modifier.js";
6
7
  import { SystemMessage, SystemMessageChunk } from "./system.js";
7
8
  import { ToolMessage, ToolMessageChunk, } from "./tool.js";
8
9
  import { convertToChunk } from "./utils.js";
@@ -297,6 +298,10 @@ const _MSG_CHUNK_MAP = {
297
298
  message: ChatMessage,
298
299
  messageChunk: ChatMessageChunk,
299
300
  },
301
+ remove: {
302
+ message: RemoveMessage,
303
+ messageChunk: RemoveMessage, // RemoveMessage does not have a chunk class.
304
+ },
300
305
  };
301
306
  function _switchTypeToMessage(messageType, fields, returnChunk) {
302
307
  let chunk;
@@ -320,6 +325,7 @@ function _switchTypeToMessage(messageType, fields, returnChunk) {
320
325
  ...aiChunkFields,
321
326
  tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({
322
327
  ...tc,
328
+ type: "tool_call_chunk",
323
329
  index: undefined,
324
330
  args: JSON.stringify(tc.args),
325
331
  })),
@@ -69,7 +69,10 @@ function getBufferString(messages, humanPrefix = "Human", aiPrefix = "AI") {
69
69
  throw new Error(`Got unsupported message type: ${m._getType()}`);
70
70
  }
71
71
  const nameStr = m.name ? `${m.name}, ` : "";
72
- string_messages.push(`${role}: ${nameStr}${m.content}`);
72
+ const readableContent = typeof m.content === "string"
73
+ ? m.content
74
+ : JSON.stringify(m.content, null, 2);
75
+ string_messages.push(`${role}: ${nameStr}${readableContent}`);
73
76
  }
74
77
  return string_messages.join("\n");
75
78
  }
@@ -166,6 +169,7 @@ function convertToChunk(message) {
166
169
  ...aiChunkFields,
167
170
  tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({
168
171
  ...tc,
172
+ type: "tool_call_chunk",
169
173
  index: undefined,
170
174
  args: JSON.stringify(tc.args),
171
175
  })),
@@ -65,7 +65,10 @@ export function getBufferString(messages, humanPrefix = "Human", aiPrefix = "AI"
65
65
  throw new Error(`Got unsupported message type: ${m._getType()}`);
66
66
  }
67
67
  const nameStr = m.name ? `${m.name}, ` : "";
68
- string_messages.push(`${role}: ${nameStr}${m.content}`);
68
+ const readableContent = typeof m.content === "string"
69
+ ? m.content
70
+ : JSON.stringify(m.content, null, 2);
71
+ string_messages.push(`${role}: ${nameStr}${readableContent}`);
69
72
  }
70
73
  return string_messages.join("\n");
71
74
  }
@@ -158,6 +161,7 @@ export function convertToChunk(message) {
158
161
  ...aiChunkFields,
159
162
  tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({
160
163
  ...tc,
164
+ type: "tool_call_chunk",
161
165
  index: undefined,
162
166
  args: JSON.stringify(tc.args),
163
167
  })),
@@ -37,6 +37,7 @@ rawToolCall, options) {
37
37
  const parsedToolCall = {
38
38
  name: rawToolCall.function.name,
39
39
  args: functionArgs,
40
+ type: "tool_call",
40
41
  };
41
42
  if (options?.returnId) {
42
43
  parsedToolCall.id = rawToolCall.id;
@@ -66,6 +67,7 @@ rawToolCall, errorMsg) {
66
67
  args: rawToolCall.function?.arguments,
67
68
  id: rawToolCall.id,
68
69
  error: errorMsg,
70
+ type: "invalid_tool_call",
69
71
  };
70
72
  }
71
73
  exports.makeInvalidToolCall = makeInvalidToolCall;
@@ -34,6 +34,7 @@ rawToolCall, options) {
34
34
  const parsedToolCall = {
35
35
  name: rawToolCall.function.name,
36
36
  args: functionArgs,
37
+ type: "tool_call",
37
38
  };
38
39
  if (options?.returnId) {
39
40
  parsedToolCall.id = rawToolCall.id;
@@ -61,6 +62,7 @@ rawToolCall, errorMsg) {
61
62
  args: rawToolCall.function?.arguments,
62
63
  id: rawToolCall.id,
63
64
  error: errorMsg,
65
+ type: "invalid_tool_call",
64
66
  };
65
67
  }
66
68
  /**
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.RunnablePick = exports.RunnableAssign = exports._coerceToRunnable = exports.RunnableWithFallbacks = exports.RunnableParallel = exports.RunnableLambda = exports.RunnableTraceable = exports.RunnableMap = exports.RunnableSequence = exports.RunnableRetry = exports.RunnableEach = exports.RunnableBinding = exports.Runnable = exports._coerceToDict = void 0;
6
+ exports.convertRunnableToTool = exports.RunnableToolLike = exports.RunnablePick = exports.RunnableAssign = exports._coerceToRunnable = exports.RunnableWithFallbacks = exports.RunnableParallel = exports.RunnableLambda = exports.RunnableTraceable = exports.RunnableMap = exports.RunnableSequence = exports.RunnableRetry = exports.RunnableEach = exports.RunnableBinding = exports.Runnable = exports._coerceToDict = void 0;
7
7
  const zod_1 = require("zod");
8
8
  const p_retry_1 = __importDefault(require("p-retry"));
9
9
  const uuid_1 = require("uuid");
@@ -20,6 +20,7 @@ const index_js_1 = require("../singletons/index.cjs");
20
20
  const graph_js_1 = require("./graph.cjs");
21
21
  const wrappers_js_1 = require("./wrappers.cjs");
22
22
  const iter_js_1 = require("./iter.cjs");
23
+ const utils_js_2 = require("../tools/utils.cjs");
23
24
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
24
25
  function _coerceToDict(value, defaultKey) {
25
26
  return value &&
@@ -718,6 +719,21 @@ class Runnable extends serializable_js_1.Serializable {
718
719
  ],
719
720
  });
720
721
  }
722
+ /**
723
+ * Convert a runnable to a tool. Return a new instance of `RunnableToolLike`
724
+ * which contains the runnable, name, description and schema.
725
+ *
726
+ * @template {T extends RunInput = RunInput} RunInput - The input type of the runnable. Should be the same as the `RunInput` type of the runnable.
727
+ *
728
+ * @param fields
729
+ * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable.
730
+ * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided.
731
+ * @param {z.ZodType<T>} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable.
732
+ * @returns {RunnableToolLike<z.ZodType<T>, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool.
733
+ */
734
+ asTool(fields) {
735
+ return convertRunnableToTool(this, fields);
736
+ }
721
737
  }
722
738
  exports.Runnable = Runnable;
723
739
  /**
@@ -1912,3 +1928,90 @@ class RunnablePick extends Runnable {
1912
1928
  }
1913
1929
  }
1914
1930
  exports.RunnablePick = RunnablePick;
1931
+ class RunnableToolLike extends RunnableBinding {
1932
+ constructor(fields) {
1933
+ const sequence = RunnableSequence.from([
1934
+ RunnableLambda.from(async (input) => {
1935
+ let toolInput;
1936
+ if ((0, utils_js_2._isToolCall)(input)) {
1937
+ try {
1938
+ toolInput = await this.schema.parseAsync(input.args);
1939
+ }
1940
+ catch (e) {
1941
+ throw new utils_js_2.ToolInputParsingException(`Received tool input did not match expected schema`, JSON.stringify(input.args));
1942
+ }
1943
+ }
1944
+ else {
1945
+ toolInput = input;
1946
+ }
1947
+ return toolInput;
1948
+ }).withConfig({ runName: `${fields.name}:parse_input` }),
1949
+ fields.bound,
1950
+ ]).withConfig({ runName: fields.name });
1951
+ super({
1952
+ bound: sequence,
1953
+ config: fields.config ?? {},
1954
+ });
1955
+ Object.defineProperty(this, "name", {
1956
+ enumerable: true,
1957
+ configurable: true,
1958
+ writable: true,
1959
+ value: void 0
1960
+ });
1961
+ Object.defineProperty(this, "description", {
1962
+ enumerable: true,
1963
+ configurable: true,
1964
+ writable: true,
1965
+ value: void 0
1966
+ });
1967
+ Object.defineProperty(this, "schema", {
1968
+ enumerable: true,
1969
+ configurable: true,
1970
+ writable: true,
1971
+ value: void 0
1972
+ });
1973
+ this.name = fields.name;
1974
+ this.description = fields.description;
1975
+ this.schema = fields.schema;
1976
+ }
1977
+ static lc_name() {
1978
+ return "RunnableToolLike";
1979
+ }
1980
+ }
1981
+ exports.RunnableToolLike = RunnableToolLike;
1982
+ /**
1983
+ * Given a runnable and a Zod schema, convert the runnable to a tool.
1984
+ *
1985
+ * @template RunInput The input type for the runnable.
1986
+ * @template RunOutput The output type for the runnable.
1987
+ *
1988
+ * @param {Runnable<RunInput, RunOutput>} runnable The runnable to convert to a tool.
1989
+ * @param fields
1990
+ * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable.
1991
+ * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided.
1992
+ * @param {z.ZodType<RunInput>} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable.
1993
+ * @returns {RunnableToolLike<z.ZodType<RunInput>, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool.
1994
+ */
1995
+ function convertRunnableToTool(runnable, fields) {
1996
+ const name = fields.name ?? runnable.getName();
1997
+ const description = fields.description ?? fields.schema?.description;
1998
+ if (fields.schema.constructor === zod_1.z.ZodString) {
1999
+ return new RunnableToolLike({
2000
+ name,
2001
+ description,
2002
+ schema: zod_1.z
2003
+ .object({
2004
+ input: zod_1.z.string(),
2005
+ })
2006
+ .transform((input) => input.input),
2007
+ bound: runnable,
2008
+ });
2009
+ }
2010
+ return new RunnableToolLike({
2011
+ name,
2012
+ description,
2013
+ schema: fields.schema,
2014
+ bound: runnable,
2015
+ });
2016
+ }
2017
+ exports.convertRunnableToTool = convertRunnableToTool;
@@ -1,3 +1,4 @@
1
+ import { z } from "zod";
1
2
  import { type TraceableFunction } from "langsmith/singletons/traceable";
2
3
  import type { RunnableInterface, RunnableBatchOptions } from "./types.js";
3
4
  import { CallbackManagerForChainRun } from "../callbacks/manager.js";
@@ -8,6 +9,7 @@ import { IterableReadableStream } from "../utils/stream.js";
8
9
  import { RunnableConfig } from "./config.js";
9
10
  import { Run } from "../tracers/base.js";
10
11
  import { Graph } from "./graph.js";
12
+ import { ToolCall } from "../messages/tool.js";
11
13
  export { type RunnableInterface, RunnableBatchOptions };
12
14
  export type RunnableFunc<RunInput, RunOutput> = (input: RunInput, options?: ({
13
15
  /** @deprecated Use top-level config fields instead. */
@@ -245,6 +247,23 @@ export declare abstract class Runnable<RunInput = any, RunOutput = any, CallOpti
245
247
  onEnd?: (run: Run, config?: RunnableConfig) => void | Promise<void>;
246
248
  onError?: (run: Run, config?: RunnableConfig) => void | Promise<void>;
247
249
  }): Runnable<RunInput, RunOutput, CallOptions>;
250
+ /**
251
+ * Convert a runnable to a tool. Return a new instance of `RunnableToolLike`
252
+ * which contains the runnable, name, description and schema.
253
+ *
254
+ * @template {T extends RunInput = RunInput} RunInput - The input type of the runnable. Should be the same as the `RunInput` type of the runnable.
255
+ *
256
+ * @param fields
257
+ * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable.
258
+ * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided.
259
+ * @param {z.ZodType<T>} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable.
260
+ * @returns {RunnableToolLike<z.ZodType<T>, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool.
261
+ */
262
+ asTool<T extends RunInput = RunInput>(fields: {
263
+ name?: string;
264
+ description?: string;
265
+ schema: z.ZodType<T>;
266
+ }): RunnableToolLike<z.ZodType<T | ToolCall>, RunOutput>;
248
267
  }
249
268
  export type RunnableBindingArgs<RunInput, RunOutput, CallOptions extends RunnableConfig = RunnableConfig> = {
250
269
  bound: Runnable<RunInput, RunOutput, CallOptions>;
@@ -560,3 +579,34 @@ export declare class RunnablePick<RunInput extends Record<string, any> = Record<
560
579
  transform(generator: AsyncGenerator<RunInput>, options?: Partial<RunnableConfig>): AsyncGenerator<RunOutput>;
561
580
  stream(input: RunInput, options?: Partial<RunnableConfig>): Promise<IterableReadableStream<RunOutput>>;
562
581
  }
582
+ export interface RunnableToolLikeArgs<RunInput extends z.ZodType = z.ZodType, RunOutput = unknown> extends Omit<RunnableBindingArgs<z.infer<RunInput>, RunOutput>, "config"> {
583
+ name: string;
584
+ description?: string;
585
+ schema: RunInput;
586
+ config?: RunnableConfig;
587
+ }
588
+ export declare class RunnableToolLike<RunInput extends z.ZodType = z.ZodType, RunOutput = unknown> extends RunnableBinding<z.infer<RunInput>, RunOutput> {
589
+ name: string;
590
+ description?: string;
591
+ schema: RunInput;
592
+ constructor(fields: RunnableToolLikeArgs<RunInput, RunOutput>);
593
+ static lc_name(): string;
594
+ }
595
+ /**
596
+ * Given a runnable and a Zod schema, convert the runnable to a tool.
597
+ *
598
+ * @template RunInput The input type for the runnable.
599
+ * @template RunOutput The output type for the runnable.
600
+ *
601
+ * @param {Runnable<RunInput, RunOutput>} runnable The runnable to convert to a tool.
602
+ * @param fields
603
+ * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable.
604
+ * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided.
605
+ * @param {z.ZodType<RunInput>} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable.
606
+ * @returns {RunnableToolLike<z.ZodType<RunInput>, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool.
607
+ */
608
+ export declare function convertRunnableToTool<RunInput, RunOutput>(runnable: Runnable<RunInput, RunOutput>, fields: {
609
+ name?: string;
610
+ description?: string;
611
+ schema: z.ZodType<RunInput>;
612
+ }): RunnableToolLike<z.ZodType<RunInput | ToolCall>, RunOutput>;
@@ -14,6 +14,7 @@ import { AsyncLocalStorageProviderSingleton } from "../singletons/index.js";
14
14
  import { Graph } from "./graph.js";
15
15
  import { convertToHttpEventStream } from "./wrappers.js";
16
16
  import { consumeAsyncIterableInContext, consumeIteratorInContext, isAsyncIterable, isIterableIterator, isIterator, } from "./iter.js";
17
+ import { _isToolCall, ToolInputParsingException } from "../tools/utils.js";
17
18
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
18
19
  export function _coerceToDict(value, defaultKey) {
19
20
  return value &&
@@ -711,6 +712,21 @@ export class Runnable extends Serializable {
711
712
  ],
712
713
  });
713
714
  }
715
+ /**
716
+ * Convert a runnable to a tool. Return a new instance of `RunnableToolLike`
717
+ * which contains the runnable, name, description and schema.
718
+ *
719
+ * @template {T extends RunInput = RunInput} RunInput - The input type of the runnable. Should be the same as the `RunInput` type of the runnable.
720
+ *
721
+ * @param fields
722
+ * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable.
723
+ * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided.
724
+ * @param {z.ZodType<T>} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable.
725
+ * @returns {RunnableToolLike<z.ZodType<T>, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool.
726
+ */
727
+ asTool(fields) {
728
+ return convertRunnableToTool(this, fields);
729
+ }
714
730
  }
715
731
  /**
716
732
  * A runnable that delegates calls to another runnable with a set of kwargs.
@@ -1892,3 +1908,88 @@ export class RunnablePick extends Runnable {
1892
1908
  return IterableReadableStream.fromAsyncGenerator(wrappedGenerator);
1893
1909
  }
1894
1910
  }
1911
+ export class RunnableToolLike extends RunnableBinding {
1912
+ constructor(fields) {
1913
+ const sequence = RunnableSequence.from([
1914
+ RunnableLambda.from(async (input) => {
1915
+ let toolInput;
1916
+ if (_isToolCall(input)) {
1917
+ try {
1918
+ toolInput = await this.schema.parseAsync(input.args);
1919
+ }
1920
+ catch (e) {
1921
+ throw new ToolInputParsingException(`Received tool input did not match expected schema`, JSON.stringify(input.args));
1922
+ }
1923
+ }
1924
+ else {
1925
+ toolInput = input;
1926
+ }
1927
+ return toolInput;
1928
+ }).withConfig({ runName: `${fields.name}:parse_input` }),
1929
+ fields.bound,
1930
+ ]).withConfig({ runName: fields.name });
1931
+ super({
1932
+ bound: sequence,
1933
+ config: fields.config ?? {},
1934
+ });
1935
+ Object.defineProperty(this, "name", {
1936
+ enumerable: true,
1937
+ configurable: true,
1938
+ writable: true,
1939
+ value: void 0
1940
+ });
1941
+ Object.defineProperty(this, "description", {
1942
+ enumerable: true,
1943
+ configurable: true,
1944
+ writable: true,
1945
+ value: void 0
1946
+ });
1947
+ Object.defineProperty(this, "schema", {
1948
+ enumerable: true,
1949
+ configurable: true,
1950
+ writable: true,
1951
+ value: void 0
1952
+ });
1953
+ this.name = fields.name;
1954
+ this.description = fields.description;
1955
+ this.schema = fields.schema;
1956
+ }
1957
+ static lc_name() {
1958
+ return "RunnableToolLike";
1959
+ }
1960
+ }
1961
+ /**
1962
+ * Given a runnable and a Zod schema, convert the runnable to a tool.
1963
+ *
1964
+ * @template RunInput The input type for the runnable.
1965
+ * @template RunOutput The output type for the runnable.
1966
+ *
1967
+ * @param {Runnable<RunInput, RunOutput>} runnable The runnable to convert to a tool.
1968
+ * @param fields
1969
+ * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable.
1970
+ * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided.
1971
+ * @param {z.ZodType<RunInput>} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable.
1972
+ * @returns {RunnableToolLike<z.ZodType<RunInput>, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool.
1973
+ */
1974
+ export function convertRunnableToTool(runnable, fields) {
1975
+ const name = fields.name ?? runnable.getName();
1976
+ const description = fields.description ?? fields.schema?.description;
1977
+ if (fields.schema.constructor === z.ZodString) {
1978
+ return new RunnableToolLike({
1979
+ name,
1980
+ description,
1981
+ schema: z
1982
+ .object({
1983
+ input: z.string(),
1984
+ })
1985
+ .transform((input) => input.input),
1986
+ bound: runnable,
1987
+ });
1988
+ }
1989
+ return new RunnableToolLike({
1990
+ name,
1991
+ description,
1992
+ schema: fields.schema,
1993
+ bound: runnable,
1994
+ });
1995
+ }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RunnableWithMessageHistory = exports.RunnableBranch = exports.RouterRunnable = exports.RunnablePassthrough = exports.mergeConfigs = exports.ensureConfig = exports.patchConfig = exports.getCallbackManagerForConfig = exports._coerceToRunnable = exports.RunnablePick = exports.RunnableAssign = exports.RunnableWithFallbacks = exports.RunnableLambda = exports.RunnableParallel = exports.RunnableMap = exports.RunnableSequence = exports.RunnableRetry = exports.RunnableEach = exports.RunnableBinding = exports.Runnable = void 0;
3
+ exports.RunnableWithMessageHistory = exports.RunnableBranch = exports.RouterRunnable = exports.RunnablePassthrough = exports.mergeConfigs = exports.ensureConfig = exports.patchConfig = exports.getCallbackManagerForConfig = exports.RunnableToolLike = exports._coerceToRunnable = exports.RunnablePick = exports.RunnableAssign = exports.RunnableWithFallbacks = exports.RunnableLambda = exports.RunnableParallel = exports.RunnableMap = exports.RunnableSequence = exports.RunnableRetry = exports.RunnableEach = exports.RunnableBinding = exports.Runnable = void 0;
4
4
  var base_js_1 = require("./base.cjs");
5
5
  Object.defineProperty(exports, "Runnable", { enumerable: true, get: function () { return base_js_1.Runnable; } });
6
6
  Object.defineProperty(exports, "RunnableBinding", { enumerable: true, get: function () { return base_js_1.RunnableBinding; } });
@@ -14,6 +14,7 @@ Object.defineProperty(exports, "RunnableWithFallbacks", { enumerable: true, get:
14
14
  Object.defineProperty(exports, "RunnableAssign", { enumerable: true, get: function () { return base_js_1.RunnableAssign; } });
15
15
  Object.defineProperty(exports, "RunnablePick", { enumerable: true, get: function () { return base_js_1.RunnablePick; } });
16
16
  Object.defineProperty(exports, "_coerceToRunnable", { enumerable: true, get: function () { return base_js_1._coerceToRunnable; } });
17
+ Object.defineProperty(exports, "RunnableToolLike", { enumerable: true, get: function () { return base_js_1.RunnableToolLike; } });
17
18
  var config_js_1 = require("./config.cjs");
18
19
  Object.defineProperty(exports, "getCallbackManagerForConfig", { enumerable: true, get: function () { return config_js_1.getCallbackManagerForConfig; } });
19
20
  Object.defineProperty(exports, "patchConfig", { enumerable: true, get: function () { return config_js_1.patchConfig; } });
@@ -1,4 +1,4 @@
1
- export { type RunnableFunc, type RunnableLike, type RunnableRetryFailedAttemptHandler, Runnable, type RunnableBindingArgs, RunnableBinding, RunnableEach, RunnableRetry, RunnableSequence, RunnableMap, RunnableParallel, RunnableLambda, RunnableWithFallbacks, RunnableAssign, RunnablePick, _coerceToRunnable, } from "./base.js";
1
+ export { type RunnableFunc, type RunnableLike, type RunnableRetryFailedAttemptHandler, Runnable, type RunnableBindingArgs, RunnableBinding, RunnableEach, RunnableRetry, RunnableSequence, RunnableMap, RunnableParallel, RunnableLambda, RunnableWithFallbacks, RunnableAssign, RunnablePick, _coerceToRunnable, RunnableToolLike, type RunnableToolLikeArgs, } from "./base.js";
2
2
  export { type RunnableBatchOptions, type RunnableInterface, type RunnableIOSchema, } from "./types.js";
3
3
  export { type RunnableConfig, getCallbackManagerForConfig, patchConfig, ensureConfig, mergeConfigs, } from "./config.js";
4
4
  export { RunnablePassthrough } from "./passthrough.js";
@@ -1,4 +1,4 @@
1
- export { Runnable, RunnableBinding, RunnableEach, RunnableRetry, RunnableSequence, RunnableMap, RunnableParallel, RunnableLambda, RunnableWithFallbacks, RunnableAssign, RunnablePick, _coerceToRunnable, } from "./base.js";
1
+ export { Runnable, RunnableBinding, RunnableEach, RunnableRetry, RunnableSequence, RunnableMap, RunnableParallel, RunnableLambda, RunnableWithFallbacks, RunnableAssign, RunnablePick, _coerceToRunnable, RunnableToolLike, } from "./base.js";
2
2
  export { getCallbackManagerForConfig, patchConfig, ensureConfig, mergeConfigs, } from "./config.js";
3
3
  export { RunnablePassthrough } from "./passthrough.js";
4
4
  export { RouterRunnable } from "./router.js";
@@ -8,7 +8,7 @@ import { ChatPromptTemplate } from "../../prompts/chat.js";
8
8
  import { FakeListChatModel, FakeRetriever, FakeStreamingLLM, } from "../../utils/testing/index.js";
9
9
  import { AIMessageChunk, HumanMessage, SystemMessage, } from "../../messages/index.js";
10
10
  import { ChatGenerationChunk, GenerationChunk } from "../../outputs.js";
11
- import { DynamicStructuredTool, DynamicTool } from "../../tools.js";
11
+ import { DynamicStructuredTool, DynamicTool } from "../../tools/index.js";
12
12
  import { Document } from "../../documents/document.js";
13
13
  function reverse(s) {
14
14
  // Reverse a string.