@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,6 +1,6 @@
1
- import { test } from "@jest/globals";
1
+ import { test, describe, it, expect } from "@jest/globals";
2
2
  import { ChatPromptTemplate } from "../../prompts/chat.js";
3
- import { HumanMessage, AIMessage, ToolMessage } from "../index.js";
3
+ import { HumanMessage, AIMessage, ToolMessage, ToolMessageChunk, AIMessageChunk, } from "../index.js";
4
4
  import { load } from "../../load/index.js";
5
5
  test("Test ChatPromptTemplate can format OpenAI content image messages", async () => {
6
6
  const message = new HumanMessage({
@@ -111,3 +111,135 @@ test("Deserialisation and serialisation of messages with ID", async () => {
111
111
  expect(deserialized).toEqual(message);
112
112
  expect(deserialized.id).toBe(messageId);
113
113
  });
114
+ test("Can concat artifact (string) of ToolMessageChunk", () => {
115
+ const rawOutputOne = "Hello";
116
+ const rawOutputTwo = " world";
117
+ const chunk1 = new ToolMessageChunk({
118
+ content: "Hello",
119
+ tool_call_id: "1",
120
+ artifact: rawOutputOne,
121
+ });
122
+ const chunk2 = new ToolMessageChunk({
123
+ content: " world",
124
+ tool_call_id: "1",
125
+ artifact: rawOutputTwo,
126
+ });
127
+ const concated = chunk1.concat(chunk2);
128
+ expect(concated.artifact).toBe(`${rawOutputOne}${rawOutputTwo}`);
129
+ });
130
+ test("Can concat artifact (array) of ToolMessageChunk", () => {
131
+ const rawOutputOne = ["Hello", " world"];
132
+ const rawOutputTwo = ["!!"];
133
+ const chunk1 = new ToolMessageChunk({
134
+ content: "Hello",
135
+ tool_call_id: "1",
136
+ artifact: rawOutputOne,
137
+ });
138
+ const chunk2 = new ToolMessageChunk({
139
+ content: " world",
140
+ tool_call_id: "1",
141
+ artifact: rawOutputTwo,
142
+ });
143
+ const concated = chunk1.concat(chunk2);
144
+ expect(concated.artifact).toEqual(["Hello", " world", "!!"]);
145
+ });
146
+ test("Can concat artifact (object) of ToolMessageChunk", () => {
147
+ const rawOutputOne = {
148
+ foo: "bar",
149
+ };
150
+ const rawOutputTwo = {
151
+ bar: "baz",
152
+ };
153
+ const chunk1 = new ToolMessageChunk({
154
+ content: "Hello",
155
+ tool_call_id: "1",
156
+ artifact: rawOutputOne,
157
+ });
158
+ const chunk2 = new ToolMessageChunk({
159
+ content: " world",
160
+ tool_call_id: "1",
161
+ artifact: rawOutputTwo,
162
+ });
163
+ const concated = chunk1.concat(chunk2);
164
+ expect(concated.artifact).toEqual({
165
+ foo: "bar",
166
+ bar: "baz",
167
+ });
168
+ });
169
+ describe("Complex AIMessageChunk concat", () => {
170
+ it("concatenates content arrays of strings", () => {
171
+ expect(new AIMessageChunk({
172
+ content: [{ type: "text", text: "I am" }],
173
+ id: "ai4",
174
+ }).concat(new AIMessageChunk({ content: [{ type: "text", text: " indeed." }] }))).toEqual(new AIMessageChunk({
175
+ id: "ai4",
176
+ content: [
177
+ { type: "text", text: "I am" },
178
+ { type: "text", text: " indeed." },
179
+ ],
180
+ }));
181
+ });
182
+ it("concatenates mixed content arrays", () => {
183
+ expect(new AIMessageChunk({
184
+ content: [{ index: 0, type: "text", text: "I am" }],
185
+ }).concat(new AIMessageChunk({ content: [{ type: "text", text: " indeed." }] }))).toEqual(new AIMessageChunk({
186
+ content: [
187
+ { index: 0, type: "text", text: "I am" },
188
+ { type: "text", text: " indeed." },
189
+ ],
190
+ }));
191
+ });
192
+ it("merges content arrays with same index", () => {
193
+ expect(new AIMessageChunk({ content: [{ index: 0, text: "I am" }] }).concat(new AIMessageChunk({ content: [{ index: 0, text: " indeed." }] }))).toEqual(new AIMessageChunk({ content: [{ index: 0, text: "I am indeed." }] }));
194
+ });
195
+ it("does not merge when one chunk is missing an index", () => {
196
+ expect(new AIMessageChunk({ content: [{ index: 0, text: "I am" }] }).concat(new AIMessageChunk({ content: [{ text: " indeed." }] }))).toEqual(new AIMessageChunk({
197
+ content: [{ index: 0, text: "I am" }, { text: " indeed." }],
198
+ }));
199
+ });
200
+ it("does not create a holey array when there's a gap between indexes", () => {
201
+ expect(new AIMessageChunk({ content: [{ index: 0, text: "I am" }] }).concat(new AIMessageChunk({ content: [{ index: 2, text: " indeed." }] }))).toEqual(new AIMessageChunk({
202
+ content: [
203
+ { index: 0, text: "I am" },
204
+ { index: 2, text: " indeed." },
205
+ ],
206
+ }));
207
+ });
208
+ it("does not merge content arrays with separate indexes", () => {
209
+ expect(new AIMessageChunk({ content: [{ index: 0, text: "I am" }] }).concat(new AIMessageChunk({ content: [{ index: 1, text: " indeed." }] }))).toEqual(new AIMessageChunk({
210
+ content: [
211
+ { index: 0, text: "I am" },
212
+ { index: 1, text: " indeed." },
213
+ ],
214
+ }));
215
+ });
216
+ it("merges content arrays with same index and type", () => {
217
+ expect(new AIMessageChunk({
218
+ content: [{ index: 0, text: "I am", type: "text_block" }],
219
+ }).concat(new AIMessageChunk({
220
+ content: [{ index: 0, text: " indeed.", type: "text_block" }],
221
+ }))).toEqual(new AIMessageChunk({
222
+ content: [{ index: 0, text: "I am indeed.", type: "text_block" }],
223
+ }));
224
+ });
225
+ it("merges content arrays with same index and different types without updating type", () => {
226
+ expect(new AIMessageChunk({
227
+ content: [{ index: 0, text: "I am", type: "text_block" }],
228
+ }).concat(new AIMessageChunk({
229
+ content: [{ index: 0, text: " indeed.", type: "text_block_delta" }],
230
+ }))).toEqual(new AIMessageChunk({
231
+ content: [{ index: 0, text: "I am indeed.", type: "text_block" }],
232
+ }));
233
+ });
234
+ it("concatenates empty string content and merges other fields", () => {
235
+ expect(new AIMessageChunk({
236
+ content: [{ index: 0, type: "text", text: "I am" }],
237
+ }).concat(new AIMessageChunk({
238
+ content: [{ type: "text", text: "" }],
239
+ response_metadata: { extra: "value" },
240
+ }))).toEqual(new AIMessageChunk({
241
+ content: [{ index: 0, type: "text", text: "I am" }],
242
+ response_metadata: { extra: "value" },
243
+ }));
244
+ });
245
+ });
@@ -3,6 +3,7 @@ import { filterMessages, mergeMessageRuns, trimMessages, } from "../transformers
3
3
  import { AIMessage } from "../ai.js";
4
4
  import { HumanMessage } from "../human.js";
5
5
  import { SystemMessage } from "../system.js";
6
+ import { getBufferString } from "../utils.js";
6
7
  describe("filterMessage", () => {
7
8
  const getMessages = () => [
8
9
  new SystemMessage("you're a good assistant."),
@@ -97,8 +98,8 @@ describe("mergeMessageRuns", () => {
97
98
  { type: "text", text: "my favorite dish is lasagna" },
98
99
  ],
99
100
  tool_calls: [
100
- { name: "blah_tool", args: { x: 2 }, id: "123" },
101
- { name: "blah_tool", args: { x: -10 }, id: "456" },
101
+ { name: "blah_tool", args: { x: 2 }, id: "123", type: "tool_call" },
102
+ { name: "blah_tool", args: { x: -10 }, id: "456", type: "tool_call" },
102
103
  ],
103
104
  id: "baz",
104
105
  }),
@@ -380,3 +381,54 @@ describe("trimMessages can trim", () => {
380
381
  expect(typeof trimmedMessages.func).toBe("function");
381
382
  });
382
383
  });
384
+ test("getBufferString can handle complex messages", () => {
385
+ const messageArr1 = [new HumanMessage("Hello there!")];
386
+ const messageArr2 = [
387
+ new AIMessage({
388
+ content: [
389
+ {
390
+ type: "text",
391
+ text: "Hello there!",
392
+ },
393
+ ],
394
+ }),
395
+ ];
396
+ const messageArr3 = [
397
+ new HumanMessage({
398
+ content: [
399
+ {
400
+ type: "image_url",
401
+ image_url: {
402
+ url: "https://example.com/image.jpg",
403
+ },
404
+ },
405
+ {
406
+ type: "image_url",
407
+ image_url: "https://example.com/image.jpg",
408
+ },
409
+ ],
410
+ }),
411
+ ];
412
+ const bufferString1 = getBufferString(messageArr1);
413
+ expect(bufferString1).toBe("Human: Hello there!");
414
+ const bufferString2 = getBufferString(messageArr2);
415
+ expect(bufferString2).toBe(`AI: ${JSON.stringify([
416
+ {
417
+ type: "text",
418
+ text: "Hello there!",
419
+ },
420
+ ], null, 2)}`);
421
+ const bufferString3 = getBufferString(messageArr3);
422
+ expect(bufferString3).toBe(`Human: ${JSON.stringify([
423
+ {
424
+ type: "image_url",
425
+ image_url: {
426
+ url: "https://example.com/image.jpg",
427
+ },
428
+ },
429
+ {
430
+ type: "image_url",
431
+ image_url: "https://example.com/image.jpg",
432
+ },
433
+ ], null, 2)}`);
434
+ });
@@ -25,7 +25,22 @@ class ToolMessage extends base_js_1.BaseMessage {
25
25
  writable: true,
26
26
  value: void 0
27
27
  });
28
+ /**
29
+ * Artifact of the Tool execution which is not meant to be sent to the model.
30
+ *
31
+ * Should only be specified if it is different from the message content, e.g. if only
32
+ * a subset of the full tool output is being passed as message content but the full
33
+ * output is needed in other parts of the code.
34
+ */
35
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
36
+ Object.defineProperty(this, "artifact", {
37
+ enumerable: true,
38
+ configurable: true,
39
+ writable: true,
40
+ value: void 0
41
+ });
28
42
  this.tool_call_id = fields.tool_call_id;
43
+ this.artifact = fields.artifact;
29
44
  }
30
45
  _getType() {
31
46
  return "tool";
@@ -48,7 +63,22 @@ class ToolMessageChunk extends base_js_1.BaseMessageChunk {
48
63
  writable: true,
49
64
  value: void 0
50
65
  });
66
+ /**
67
+ * Artifact of the Tool execution which is not meant to be sent to the model.
68
+ *
69
+ * Should only be specified if it is different from the message content, e.g. if only
70
+ * a subset of the full tool output is being passed as message content but the full
71
+ * output is needed in other parts of the code.
72
+ */
73
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
74
+ Object.defineProperty(this, "artifact", {
75
+ enumerable: true,
76
+ configurable: true,
77
+ writable: true,
78
+ value: void 0
79
+ });
51
80
  this.tool_call_id = fields.tool_call_id;
81
+ this.artifact = fields.artifact;
52
82
  }
53
83
  static lc_name() {
54
84
  return "ToolMessageChunk";
@@ -61,6 +91,7 @@ class ToolMessageChunk extends base_js_1.BaseMessageChunk {
61
91
  content: (0, base_js_1.mergeContent)(this.content, chunk.content),
62
92
  additional_kwargs: (0, base_js_1._mergeDicts)(this.additional_kwargs, chunk.additional_kwargs),
63
93
  response_metadata: (0, base_js_1._mergeDicts)(this.response_metadata, chunk.response_metadata),
94
+ artifact: (0, base_js_1._mergeObj)(this.artifact, chunk.artifact),
64
95
  tool_call_id: this.tool_call_id,
65
96
  id: this.id ?? chunk.id,
66
97
  });
@@ -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,6 +17,14 @@ 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;
@@ -20,6 +36,14 @@ export declare class ToolMessage extends BaseMessage {
20
36
  */
21
37
  export declare class ToolMessageChunk extends BaseMessageChunk {
22
38
  tool_call_id: string;
39
+ /**
40
+ * Artifact of the Tool execution which is not meant to be sent to the model.
41
+ *
42
+ * Should only be specified if it is different from the message content, e.g. if only
43
+ * a subset of the full tool output is being passed as message content but the full
44
+ * output is needed in other parts of the code.
45
+ */
46
+ artifact?: any;
23
47
  constructor(fields: ToolMessageFieldsWithToolCallId);
24
48
  static lc_name(): string;
25
49
  _getType(): MessageType;
@@ -35,6 +59,7 @@ export type ToolCall = {
35
59
  name: string;
36
60
  args: Record<string, any>;
37
61
  id?: string;
62
+ type?: "tool_call";
38
63
  };
39
64
  /**
40
65
  * A chunk of a tool call (e.g., as part of a stream).
@@ -91,11 +116,13 @@ export type ToolCallChunk = {
91
116
  args?: string;
92
117
  id?: string;
93
118
  index?: number;
119
+ type?: "tool_call_chunk";
94
120
  };
95
121
  export type InvalidToolCall = {
96
122
  name?: string;
97
123
  args?: string;
98
124
  id?: string;
99
125
  error?: string;
126
+ type?: "invalid_tool_call";
100
127
  };
101
128
  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";
@@ -44,7 +59,22 @@ export class ToolMessageChunk extends BaseMessageChunk {
44
59
  writable: true,
45
60
  value: void 0
46
61
  });
62
+ /**
63
+ * Artifact of the Tool execution which is not meant to be sent to the model.
64
+ *
65
+ * Should only be specified if it is different from the message content, e.g. if only
66
+ * a subset of the full tool output is being passed as message content but the full
67
+ * output is needed in other parts of the code.
68
+ */
69
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
70
+ Object.defineProperty(this, "artifact", {
71
+ enumerable: true,
72
+ configurable: true,
73
+ writable: true,
74
+ value: void 0
75
+ });
47
76
  this.tool_call_id = fields.tool_call_id;
77
+ this.artifact = fields.artifact;
48
78
  }
49
79
  static lc_name() {
50
80
  return "ToolMessageChunk";
@@ -57,6 +87,7 @@ export class ToolMessageChunk extends BaseMessageChunk {
57
87
  content: mergeContent(this.content, chunk.content),
58
88
  additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs),
59
89
  response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata),
90
+ artifact: _mergeObj(this.artifact, chunk.artifact),
60
91
  tool_call_id: this.tool_call_id,
61
92
  id: this.id ?? chunk.id,
62
93
  });
@@ -326,6 +326,7 @@ function _switchTypeToMessage(messageType, fields, returnChunk) {
326
326
  ...aiChunkFields,
327
327
  tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({
328
328
  ...tc,
329
+ type: "tool_call_chunk",
329
330
  index: undefined,
330
331
  args: JSON.stringify(tc.args),
331
332
  })),
@@ -320,6 +320,7 @@ function _switchTypeToMessage(messageType, fields, returnChunk) {
320
320
  ...aiChunkFields,
321
321
  tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({
322
322
  ...tc,
323
+ type: "tool_call_chunk",
323
324
  index: undefined,
324
325
  args: JSON.stringify(tc.args),
325
326
  })),
@@ -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,12 +3,11 @@ 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");
10
10
  const traceable_1 = require("langsmith/singletons/traceable");
11
- const manager_js_1 = require("../callbacks/manager.cjs");
12
11
  const log_stream_js_1 = require("../tracers/log_stream.cjs");
13
12
  const event_stream_js_1 = require("../tracers/event_stream.cjs");
14
13
  const serializable_js_1 = require("../load/serializable.cjs");
@@ -719,6 +718,21 @@ class Runnable extends serializable_js_1.Serializable {
719
718
  ],
720
719
  });
721
720
  }
721
+ /**
722
+ * Convert a runnable to a tool. Return a new instance of `RunnableToolLike`
723
+ * which contains the runnable, name, description and schema.
724
+ *
725
+ * @template {T extends RunInput = RunInput} RunInput - The input type of the runnable. Should be the same as the `RunInput` type of the runnable.
726
+ *
727
+ * @param fields
728
+ * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable.
729
+ * @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.
730
+ * @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.
731
+ * @returns {RunnableToolLike<z.ZodType<T>, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool.
732
+ */
733
+ asTool(fields) {
734
+ return convertRunnableToTool(this, fields);
735
+ }
722
736
  }
723
737
  exports.Runnable = Runnable;
724
738
  /**
@@ -1574,12 +1588,16 @@ class RunnableLambda extends Runnable {
1574
1588
  }
1575
1589
  }
1576
1590
  }
1591
+ const childConfig = (0, config_js_1.patchConfig)(config, {
1592
+ callbacks: runManager?.getChild(),
1593
+ recursionLimit: (config?.recursionLimit ?? config_js_1.DEFAULT_RECURSION_LIMIT) - 1,
1594
+ });
1577
1595
  const output = await new Promise((resolve, reject) => {
1578
- void index_js_1.AsyncLocalStorageProviderSingleton.getInstance().run(config, async () => {
1596
+ void index_js_1.AsyncLocalStorageProviderSingleton.getInstance().run(childConfig, async () => {
1579
1597
  try {
1580
1598
  const res = await this.func(finalChunk, {
1581
- ...config,
1582
- config,
1599
+ ...childConfig,
1600
+ config: childConfig,
1583
1601
  });
1584
1602
  resolve(res);
1585
1603
  }
@@ -1592,21 +1610,18 @@ class RunnableLambda extends Runnable {
1592
1610
  if (config?.recursionLimit === 0) {
1593
1611
  throw new Error("Recursion limit reached.");
1594
1612
  }
1595
- const stream = await output.stream(finalChunk, (0, config_js_1.patchConfig)(config, {
1596
- callbacks: runManager?.getChild(),
1597
- recursionLimit: (config?.recursionLimit ?? config_js_1.DEFAULT_RECURSION_LIMIT) - 1,
1598
- }));
1613
+ const stream = await output.stream(finalChunk, childConfig);
1599
1614
  for await (const chunk of stream) {
1600
1615
  yield chunk;
1601
1616
  }
1602
1617
  }
1603
1618
  else if ((0, iter_js_1.isAsyncIterable)(output)) {
1604
- for await (const chunk of (0, iter_js_1.consumeAsyncIterableInContext)(config, output)) {
1619
+ for await (const chunk of (0, iter_js_1.consumeAsyncIterableInContext)(childConfig, output)) {
1605
1620
  yield chunk;
1606
1621
  }
1607
1622
  }
1608
1623
  else if ((0, iter_js_1.isIterableIterator)(output)) {
1609
- for (const chunk of (0, iter_js_1.consumeIteratorInContext)(config, output)) {
1624
+ for (const chunk of (0, iter_js_1.consumeIteratorInContext)(childConfig, output)) {
1610
1625
  yield chunk;
1611
1626
  }
1612
1627
  }
@@ -1677,13 +1692,14 @@ class RunnableWithFallbacks extends Runnable {
1677
1692
  }
1678
1693
  }
1679
1694
  async invoke(input, options) {
1680
- const callbackManager_ = await manager_js_1.CallbackManager.configure(options?.callbacks, undefined, options?.tags, undefined, options?.metadata);
1681
- const { runId, ...otherOptions } = options ?? {};
1682
- const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherOptions?.runName);
1695
+ const config = (0, config_js_1.ensureConfig)(options);
1696
+ const callbackManager_ = await (0, config_js_1.getCallbackManagerForConfig)(options);
1697
+ const { runId, ...otherConfigFields } = config;
1698
+ const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherConfigFields?.runName);
1683
1699
  let firstError;
1684
1700
  for (const runnable of this.runnables()) {
1685
1701
  try {
1686
- const output = await runnable.invoke(input, (0, config_js_1.patchConfig)(otherOptions, { callbacks: runManager?.getChild() }));
1702
+ const output = await runnable.invoke(input, (0, config_js_1.patchConfig)(otherConfigFields, { callbacks: runManager?.getChild() }));
1687
1703
  await runManager?.handleChainEnd(_coerceToDict(output, "output"));
1688
1704
  return output;
1689
1705
  }
@@ -1704,7 +1720,7 @@ class RunnableWithFallbacks extends Runnable {
1704
1720
  throw new Error("Not implemented.");
1705
1721
  }
1706
1722
  const configList = this._getOptionsList(options ?? {}, inputs.length);
1707
- const callbackManagers = await Promise.all(configList.map((config) => manager_js_1.CallbackManager.configure(config?.callbacks, undefined, config?.tags, undefined, config?.metadata)));
1723
+ const callbackManagers = await Promise.all(configList.map((config) => (0, config_js_1.getCallbackManagerForConfig)(config)));
1708
1724
  const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => {
1709
1725
  const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"), configList[i].runId, undefined, undefined, undefined, configList[i].runName);
1710
1726
  delete configList[i].runId;
@@ -1911,3 +1927,60 @@ class RunnablePick extends Runnable {
1911
1927
  }
1912
1928
  }
1913
1929
  exports.RunnablePick = RunnablePick;
1930
+ class RunnableToolLike extends RunnableBinding {
1931
+ constructor(fields) {
1932
+ super({
1933
+ bound: fields.bound,
1934
+ config: fields.config ?? {},
1935
+ });
1936
+ Object.defineProperty(this, "name", {
1937
+ enumerable: true,
1938
+ configurable: true,
1939
+ writable: true,
1940
+ value: void 0
1941
+ });
1942
+ Object.defineProperty(this, "description", {
1943
+ enumerable: true,
1944
+ configurable: true,
1945
+ writable: true,
1946
+ value: void 0
1947
+ });
1948
+ Object.defineProperty(this, "schema", {
1949
+ enumerable: true,
1950
+ configurable: true,
1951
+ writable: true,
1952
+ value: void 0
1953
+ });
1954
+ this.name = fields.name;
1955
+ this.description = fields.description;
1956
+ this.schema = fields.schema;
1957
+ }
1958
+ static lc_name() {
1959
+ return "RunnableToolLike";
1960
+ }
1961
+ }
1962
+ exports.RunnableToolLike = RunnableToolLike;
1963
+ /**
1964
+ * Given a runnable and a Zod schema, convert the runnable to a tool.
1965
+ *
1966
+ * @template RunInput The input type for the runnable.
1967
+ * @template RunOutput The output type for the runnable.
1968
+ *
1969
+ * @param {Runnable<RunInput, RunOutput>} runnable The runnable to convert to a tool.
1970
+ * @param fields
1971
+ * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable.
1972
+ * @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.
1973
+ * @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.
1974
+ * @returns {RunnableToolLike<z.ZodType<RunInput>, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool.
1975
+ */
1976
+ function convertRunnableToTool(runnable, fields) {
1977
+ const name = fields.name ?? runnable.getName();
1978
+ const description = fields.description ?? fields.schema.description;
1979
+ return new RunnableToolLike({
1980
+ name,
1981
+ description,
1982
+ schema: fields.schema,
1983
+ bound: runnable,
1984
+ });
1985
+ }
1986
+ exports.convertRunnableToTool = convertRunnableToTool;