@langchain/core 0.2.15 → 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 (90) 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 +4 -4
  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 +2 -0
  40. package/dist/messages/ai.js +2 -0
  41. package/dist/messages/base.cjs +45 -5
  42. package/dist/messages/base.d.ts +1 -0
  43. package/dist/messages/base.js +43 -4
  44. package/dist/messages/index.d.ts +1 -1
  45. package/dist/messages/tests/base_message.test.js +134 -2
  46. package/dist/messages/tests/message_utils.test.js +54 -2
  47. package/dist/messages/tool.cjs +31 -0
  48. package/dist/messages/tool.d.ts +27 -0
  49. package/dist/messages/tool.js +32 -1
  50. package/dist/messages/transformers.cjs +1 -0
  51. package/dist/messages/transformers.js +1 -0
  52. package/dist/messages/utils.cjs +5 -1
  53. package/dist/messages/utils.js +5 -1
  54. package/dist/output_parsers/openai_tools/json_output_tools_parsers.cjs +2 -0
  55. package/dist/output_parsers/openai_tools/json_output_tools_parsers.js +2 -0
  56. package/dist/runnables/base.cjs +73 -1
  57. package/dist/runnables/base.d.ts +49 -0
  58. package/dist/runnables/base.js +70 -0
  59. package/dist/runnables/index.cjs +2 -1
  60. package/dist/runnables/index.d.ts +1 -1
  61. package/dist/runnables/index.js +1 -1
  62. package/dist/runnables/tests/runnable_stream_events.test.js +1 -1
  63. package/dist/runnables/tests/runnable_stream_events_v2.test.js +106 -1
  64. package/dist/runnables/tests/runnable_tools.test.d.ts +1 -0
  65. package/dist/runnables/tests/runnable_tools.test.js +111 -0
  66. package/dist/{tools.cjs → tools/index.cjs} +130 -14
  67. package/dist/{tools.d.ts → tools/index.d.ts} +69 -31
  68. package/dist/{tools.js → tools/index.js} +130 -14
  69. package/dist/tools/tests/tools.test.d.ts +1 -0
  70. package/dist/tools/tests/tools.test.js +74 -0
  71. package/dist/tracers/base.cjs +1 -0
  72. package/dist/tracers/base.d.ts +1 -1
  73. package/dist/tracers/base.js +1 -0
  74. package/dist/tracers/event_stream.cjs +15 -0
  75. package/dist/tracers/event_stream.d.ts +1 -0
  76. package/dist/tracers/event_stream.js +15 -0
  77. package/dist/types/zod.cjs +2 -0
  78. package/dist/types/zod.d.ts +2 -0
  79. package/dist/types/zod.js +1 -0
  80. package/dist/utils/function_calling.cjs +38 -10
  81. package/dist/utils/function_calling.d.ts +32 -11
  82. package/dist/utils/function_calling.js +36 -9
  83. package/dist/utils/testing/index.cjs +10 -3
  84. package/dist/utils/testing/index.d.ts +1 -1
  85. package/dist/utils/testing/index.js +9 -2
  86. package/package.json +28 -1
  87. package/tools.cjs +1 -1
  88. package/tools.d.cts +1 -1
  89. package/tools.d.ts +1 -1
  90. package/tools.js +1 -1
@@ -1,7 +1,9 @@
1
1
  import { z } from "zod";
2
- import { CallbackManager, parseCallbackConfigArg, } from "./callbacks/manager.js";
3
- import { BaseLangChain, } from "./language_models/base.js";
4
- import { ensureConfig } from "./runnables/config.js";
2
+ import { CallbackManager, parseCallbackConfigArg, } from "../callbacks/manager.js";
3
+ import { BaseLangChain, } from "../language_models/base.js";
4
+ import { ensureConfig, patchConfig, } from "../runnables/config.js";
5
+ import { ToolMessage } from "../messages/tool.js";
6
+ import { AsyncLocalStorageProviderSingleton } from "../singletons/index.js";
5
7
  /**
6
8
  * Custom error class used to handle exceptions related to tool input parsing.
7
9
  * It extends the built-in `Error` class and adds an optional `output`
@@ -34,6 +36,22 @@ export class StructuredTool extends BaseLangChain {
34
36
  writable: true,
35
37
  value: false
36
38
  });
39
+ /**
40
+ * The tool response format.
41
+ *
42
+ * If "content" then the output of the tool is interpreted as the contents of a
43
+ * ToolMessage. If "content_and_artifact" then the output is expected to be a
44
+ * two-tuple corresponding to the (content, artifact) of a ToolMessage.
45
+ *
46
+ * @default "content"
47
+ */
48
+ Object.defineProperty(this, "responseFormat", {
49
+ enumerable: true,
50
+ configurable: true,
51
+ writable: true,
52
+ value: "content"
53
+ });
54
+ this.responseFormat = fields?.responseFormat ?? this.responseFormat;
37
55
  }
38
56
  /**
39
57
  * Invokes the tool with the provided input and configuration.
@@ -42,7 +60,23 @@ export class StructuredTool extends BaseLangChain {
42
60
  * @returns A Promise that resolves with a string.
43
61
  */
44
62
  async invoke(input, config) {
45
- return this.call(input, ensureConfig(config));
63
+ let tool_call_id;
64
+ let toolInput;
65
+ if (_isToolCall(input)) {
66
+ tool_call_id = input.id;
67
+ toolInput = input.args;
68
+ }
69
+ else {
70
+ toolInput = input;
71
+ }
72
+ const ensuredConfig = ensureConfig(config);
73
+ return this.call(toolInput, {
74
+ ...ensuredConfig,
75
+ configurable: {
76
+ ...ensuredConfig.configurable,
77
+ tool_call_id,
78
+ },
79
+ });
46
80
  }
47
81
  /**
48
82
  * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
@@ -77,8 +111,32 @@ export class StructuredTool extends BaseLangChain {
77
111
  await runManager?.handleToolError(e);
78
112
  throw e;
79
113
  }
80
- await runManager?.handleToolEnd(result);
81
- return result;
114
+ let content;
115
+ let artifact;
116
+ if (this.responseFormat === "content_and_artifact") {
117
+ if (Array.isArray(result) && result.length === 2) {
118
+ [content, artifact] = result;
119
+ }
120
+ else {
121
+ throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(result)}`);
122
+ }
123
+ }
124
+ else {
125
+ content = result;
126
+ }
127
+ let toolCallId;
128
+ if (config && "configurable" in config) {
129
+ toolCallId = config.configurable
130
+ .tool_call_id;
131
+ }
132
+ const formattedOutput = _formatToolOutput({
133
+ content,
134
+ artifact,
135
+ toolCallId,
136
+ name: this.name,
137
+ });
138
+ await runManager?.handleToolEnd(formattedOutput);
139
+ return formattedOutput;
82
140
  }
83
141
  }
84
142
  /**
@@ -152,8 +210,8 @@ export class DynamicTool extends Tool {
152
210
  return super.call(arg, config);
153
211
  }
154
212
  /** @ignore */
155
- async _call(input, runManager, config) {
156
- return this.func(input, runManager, config);
213
+ async _call(input, runManager, parentConfig) {
214
+ return this.func(input, runManager, parentConfig);
157
215
  }
158
216
  }
159
217
  /**
@@ -210,8 +268,8 @@ export class DynamicStructuredTool extends StructuredTool {
210
268
  }
211
269
  return super.call(arg, config, tags);
212
270
  }
213
- _call(arg, runManager, config) {
214
- return this.func(arg, runManager, config);
271
+ _call(arg, runManager, parentConfig) {
272
+ return this.func(arg, runManager, parentConfig);
215
273
  }
216
274
  }
217
275
  /**
@@ -227,15 +285,17 @@ export class BaseToolkit {
227
285
  /**
228
286
  * Creates a new StructuredTool instance with the provided function, name, description, and schema.
229
287
  * @function
230
- * @template {ZodAny} RunInput The input schema for the tool.
288
+ * @template {RunInput extends ZodAny = ZodAny} RunInput The input schema for the tool. This corresponds to the input type when the tool is invoked.
289
+ * @template {RunOutput = any} RunOutput The output type for the tool. This corresponds to the output type when the tool is invoked.
290
+ * @template {FuncInput extends z.infer<RunInput> | ToolCall = z.infer<RunInput>} FuncInput The input type for the function.
231
291
  *
232
- * @param {RunnableFunc<RunInput, string>} func - The function to invoke when the tool is called.
292
+ * @param {RunnableFunc<z.infer<RunInput> | ToolCall, RunOutput>} func - The function to invoke when the tool is called.
233
293
  * @param fields - An object containing the following properties:
234
294
  * @param {string} fields.name The name of the tool.
235
295
  * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.
236
296
  * @param {z.ZodObject<any, any, any, any>} fields.schema The Zod schema defining the input for the tool.
237
297
  *
238
- * @returns {StructuredTool<RunInput, string>} A new StructuredTool instance.
298
+ * @returns {DynamicStructuredTool<RunInput, RunOutput>} A new StructuredTool instance.
239
299
  */
240
300
  export function tool(func, fields) {
241
301
  const schema = fields.schema ??
@@ -245,6 +305,62 @@ export function tool(func, fields) {
245
305
  name: fields.name,
246
306
  description,
247
307
  schema: schema,
248
- func: async (input, _runManager, config) => func(input, config),
308
+ // TODO: Consider moving into DynamicStructuredTool constructor
309
+ func: async (input, runManager, config) => {
310
+ return new Promise((resolve, reject) => {
311
+ const childConfig = patchConfig(config, {
312
+ callbacks: runManager?.getChild(),
313
+ });
314
+ void AsyncLocalStorageProviderSingleton.getInstance().run(childConfig, async () => {
315
+ try {
316
+ resolve(func(input, childConfig));
317
+ }
318
+ catch (e) {
319
+ reject(e);
320
+ }
321
+ });
322
+ });
323
+ },
324
+ responseFormat: fields.responseFormat,
249
325
  });
250
326
  }
327
+ function _isToolCall(toolCall) {
328
+ return !!(toolCall &&
329
+ typeof toolCall === "object" &&
330
+ "type" in toolCall &&
331
+ toolCall.type === "tool_call");
332
+ }
333
+ function _formatToolOutput(params) {
334
+ const { content, artifact, toolCallId } = params;
335
+ if (toolCallId) {
336
+ if (typeof content === "string" ||
337
+ (Array.isArray(content) &&
338
+ content.every((item) => typeof item === "object"))) {
339
+ return new ToolMessage({
340
+ content,
341
+ artifact,
342
+ tool_call_id: toolCallId,
343
+ name: params.name,
344
+ });
345
+ }
346
+ else {
347
+ return new ToolMessage({
348
+ content: _stringify(content),
349
+ artifact,
350
+ tool_call_id: toolCallId,
351
+ name: params.name,
352
+ });
353
+ }
354
+ }
355
+ else {
356
+ return content;
357
+ }
358
+ }
359
+ function _stringify(content) {
360
+ try {
361
+ return JSON.stringify(content, null, 2);
362
+ }
363
+ catch (_noOp) {
364
+ return `${content}`;
365
+ }
366
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,74 @@
1
+ import { test, expect } from "@jest/globals";
2
+ import { z } from "zod";
3
+ import { tool } from "../index.js";
4
+ import { ToolMessage } from "../../messages/tool.js";
5
+ test("Tool should error if responseFormat is content_and_artifact but the function doesn't return a tuple", async () => {
6
+ const weatherSchema = z.object({
7
+ location: z.string(),
8
+ });
9
+ const weatherTool = tool((_) => {
10
+ return "str";
11
+ }, {
12
+ name: "weather",
13
+ schema: weatherSchema,
14
+ responseFormat: "content_and_artifact",
15
+ });
16
+ await expect(async () => {
17
+ await weatherTool.invoke({ location: "San Francisco" });
18
+ }).rejects.toThrow();
19
+ });
20
+ test("Tool works if responseFormat is content_and_artifact and returns a tuple", async () => {
21
+ const weatherSchema = z.object({
22
+ location: z.string(),
23
+ });
24
+ const weatherTool = tool((input) => {
25
+ return ["msg_content", input];
26
+ }, {
27
+ name: "weather",
28
+ schema: weatherSchema,
29
+ responseFormat: "content_and_artifact",
30
+ });
31
+ const toolResult = await weatherTool.invoke({ location: "San Francisco" });
32
+ expect(toolResult).not.toBeInstanceOf(ToolMessage);
33
+ expect(toolResult).toBe("msg_content");
34
+ });
35
+ test("Does not return tool message if responseFormat is content_and_artifact and returns a tuple and a tool call with no id is passed in", async () => {
36
+ const weatherSchema = z.object({
37
+ location: z.string(),
38
+ });
39
+ const weatherTool = tool((input) => {
40
+ return ["msg_content", input];
41
+ }, {
42
+ name: "weather",
43
+ schema: weatherSchema,
44
+ responseFormat: "content_and_artifact",
45
+ });
46
+ const toolResult = await weatherTool.invoke({
47
+ args: { location: "San Francisco" },
48
+ name: "weather",
49
+ type: "tool_call",
50
+ });
51
+ expect(toolResult).toBe("msg_content");
52
+ });
53
+ test("Returns tool message if responseFormat is content_and_artifact and returns a tuple and a tool call with id is passed in", async () => {
54
+ const weatherSchema = z.object({
55
+ location: z.string(),
56
+ });
57
+ const weatherTool = tool((input) => {
58
+ return ["msg_content", input];
59
+ }, {
60
+ name: "weather",
61
+ schema: weatherSchema,
62
+ responseFormat: "content_and_artifact",
63
+ });
64
+ const toolResult = await weatherTool.invoke({
65
+ id: "testid",
66
+ args: { location: "San Francisco" },
67
+ name: "weather",
68
+ type: "tool_call",
69
+ });
70
+ expect(toolResult).toBeInstanceOf(ToolMessage);
71
+ expect(toolResult.content).toBe("msg_content");
72
+ expect(toolResult.artifact).toEqual({ location: "San Francisco" });
73
+ expect(toolResult.name).toBe("weather");
74
+ });
@@ -274,6 +274,7 @@ class BaseTracer extends base_js_1.BaseCallbackHandler {
274
274
  await this.onToolStart?.(run);
275
275
  return run;
276
276
  }
277
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
277
278
  async handleToolEnd(output, runId) {
278
279
  const run = this.runMap.get(runId);
279
280
  if (!run || run?.run_type !== "tool") {
@@ -46,7 +46,7 @@ export declare abstract class BaseTracer extends BaseCallbackHandler {
46
46
  inputs?: Record<string, unknown>;
47
47
  }): Promise<Run>;
48
48
  handleToolStart(tool: Serialized, input: string, runId: string, parentRunId?: string, tags?: string[], metadata?: KVMap, name?: string): Promise<Run>;
49
- handleToolEnd(output: string, runId: string): Promise<Run>;
49
+ handleToolEnd(output: any, runId: string): Promise<Run>;
50
50
  handleToolError(error: unknown, runId: string): Promise<Run>;
51
51
  handleAgentAction(action: AgentAction, runId: string): Promise<void>;
52
52
  handleAgentEnd(action: AgentFinish, runId: string): Promise<void>;
@@ -271,6 +271,7 @@ export class BaseTracer extends BaseCallbackHandler {
271
271
  await this.onToolStart?.(run);
272
272
  return run;
273
273
  }
274
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
274
275
  async handleToolEnd(output, runId) {
275
276
  const run = this.runMap.get(runId);
276
277
  if (!run || run?.run_type !== "tool") {
@@ -489,6 +489,21 @@ class EventStreamCallbackHandler extends base_js_1.BaseTracer {
489
489
  metadata: runInfo.metadata,
490
490
  }, runInfo);
491
491
  }
492
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
493
+ async handleCustomEvent(eventName, data, runId) {
494
+ const runInfo = this.runInfoMap.get(runId);
495
+ if (runInfo === undefined) {
496
+ throw new Error(`handleCustomEvent: Run ID ${runId} not found in run map.`);
497
+ }
498
+ await this.send({
499
+ event: "on_custom_event",
500
+ run_id: runId,
501
+ name: eventName,
502
+ tags: runInfo.tags,
503
+ metadata: runInfo.metadata,
504
+ data,
505
+ }, runInfo);
506
+ }
492
507
  async finish() {
493
508
  const pendingPromises = [...this.tappedPromises.values()];
494
509
  void Promise.all(pendingPromises).finally(() => {
@@ -133,6 +133,7 @@ export declare class EventStreamCallbackHandler extends BaseTracer {
133
133
  onToolEnd(run: Run): Promise<void>;
134
134
  onRetrieverStart(run: Run): Promise<void>;
135
135
  onRetrieverEnd(run: Run): Promise<void>;
136
+ handleCustomEvent(eventName: string, data: any, runId: string): Promise<void>;
136
137
  finish(): Promise<void>;
137
138
  }
138
139
  export {};
@@ -485,6 +485,21 @@ export class EventStreamCallbackHandler extends BaseTracer {
485
485
  metadata: runInfo.metadata,
486
486
  }, runInfo);
487
487
  }
488
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
489
+ async handleCustomEvent(eventName, data, runId) {
490
+ const runInfo = this.runInfoMap.get(runId);
491
+ if (runInfo === undefined) {
492
+ throw new Error(`handleCustomEvent: Run ID ${runId} not found in run map.`);
493
+ }
494
+ await this.send({
495
+ event: "on_custom_event",
496
+ run_id: runId,
497
+ name: eventName,
498
+ tags: runInfo.tags,
499
+ metadata: runInfo.metadata,
500
+ data,
501
+ }, runInfo);
502
+ }
488
503
  async finish() {
489
504
  const pendingPromises = [...this.tappedPromises.values()];
490
505
  void Promise.all(pendingPromises).finally(() => {
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ import type { z } from "zod";
2
+ export type ZodAny = z.ZodObject<any, any, any, any>;
@@ -0,0 +1 @@
1
+ export {};
@@ -1,12 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isStructuredTool = exports.convertToOpenAITool = exports.convertToOpenAIFunction = void 0;
3
+ exports.isRunnableToolLike = exports.isStructuredTool = exports.convertToOpenAITool = exports.convertToOpenAIFunction = void 0;
4
4
  const zod_to_json_schema_1 = require("zod-to-json-schema");
5
+ const base_js_1 = require("../runnables/base.cjs");
5
6
  /**
6
- * Formats a `StructuredTool` instance into a format that is compatible
7
- * with OpenAI function calling. It uses the `zodToJsonSchema`
8
- * function to convert the schema of the `StructuredTool` into a JSON
9
- * schema, which is then used as the parameters for the OpenAI function.
7
+ * Formats a `StructuredTool` or `RunnableToolLike` instance into a format
8
+ * that is compatible with OpenAI function calling. It uses the `zodToJsonSchema`
9
+ * function to convert the schema of the `StructuredTool` or `RunnableToolLike`
10
+ * into a JSON schema, which is then used as the parameters for the OpenAI function.
11
+ *
12
+ * @param {StructuredToolInterface | RunnableToolLike} tool The tool to convert to an OpenAI function.
13
+ * @returns {FunctionDefinition} The inputted tool in OpenAI function format.
10
14
  */
11
15
  function convertToOpenAIFunction(tool) {
12
16
  return {
@@ -17,15 +21,19 @@ function convertToOpenAIFunction(tool) {
17
21
  }
18
22
  exports.convertToOpenAIFunction = convertToOpenAIFunction;
19
23
  /**
20
- * Formats a `StructuredTool` instance into a format that is compatible
21
- * with OpenAI tool calling. It uses the `zodToJsonSchema`
22
- * function to convert the schema of the `StructuredTool` into a JSON
23
- * schema, which is then used as the parameters for the OpenAI tool.
24
+ * Formats a `StructuredTool` or `RunnableToolLike` instance into a
25
+ * format that is compatible with OpenAI tool calling. It uses the
26
+ * `zodToJsonSchema` function to convert the schema of the `StructuredTool`
27
+ * or `RunnableToolLike` into a JSON schema, which is then used as the
28
+ * parameters for the OpenAI tool.
29
+ *
30
+ * @param {StructuredToolInterface | Record<string, any> | RunnableToolLike} tool The tool to convert to an OpenAI tool.
31
+ * @returns {ToolDefinition} The inputted tool in OpenAI tool format.
24
32
  */
25
33
  function convertToOpenAITool(
26
34
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
27
35
  tool) {
28
- if (isStructuredTool(tool)) {
36
+ if (isStructuredTool(tool) || isRunnableToolLike(tool)) {
29
37
  return {
30
38
  type: "function",
31
39
  function: convertToOpenAIFunction(tool),
@@ -34,6 +42,12 @@ tool) {
34
42
  return tool;
35
43
  }
36
44
  exports.convertToOpenAITool = convertToOpenAITool;
45
+ /**
46
+ * Confirm whether the inputted tool is an instance of `StructuredToolInterface`.
47
+ *
48
+ * @param {StructuredToolInterface | Record<string, any> | undefined} tool The tool to check if it is an instance of `StructuredToolInterface`.
49
+ * @returns {tool is StructuredToolInterface} Whether the inputted tool is an instance of `StructuredToolInterface`.
50
+ */
37
51
  function isStructuredTool(
38
52
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
39
53
  tool) {
@@ -41,3 +55,17 @@ tool) {
41
55
  Array.isArray(tool.lc_namespace));
42
56
  }
43
57
  exports.isStructuredTool = isStructuredTool;
58
+ /**
59
+ * Confirm whether the inputted tool is an instance of `RunnableToolLike`.
60
+ *
61
+ * @param {unknown | undefined} tool The tool to check if it is an instance of `RunnableToolLike`.
62
+ * @returns {tool is RunnableToolLike} Whether the inputted tool is an instance of `RunnableToolLike`.
63
+ */
64
+ function isRunnableToolLike(tool) {
65
+ return (tool !== undefined &&
66
+ base_js_1.Runnable.isRunnable(tool) &&
67
+ "lc_name" in tool.constructor &&
68
+ typeof tool.constructor.lc_name === "function" &&
69
+ tool.constructor.lc_name() === "RunnableToolLike");
70
+ }
71
+ exports.isRunnableToolLike = isRunnableToolLike;
@@ -1,17 +1,38 @@
1
- import { StructuredToolInterface } from "../tools.js";
1
+ import { StructuredToolInterface } from "../tools/index.js";
2
2
  import { FunctionDefinition, ToolDefinition } from "../language_models/base.js";
3
+ import { RunnableToolLike } from "../runnables/base.js";
3
4
  /**
4
- * Formats a `StructuredTool` instance into a format that is compatible
5
- * with OpenAI function calling. It uses the `zodToJsonSchema`
6
- * function to convert the schema of the `StructuredTool` into a JSON
7
- * schema, which is then used as the parameters for the OpenAI function.
5
+ * Formats a `StructuredTool` or `RunnableToolLike` instance into a format
6
+ * that is compatible with OpenAI function calling. It uses the `zodToJsonSchema`
7
+ * function to convert the schema of the `StructuredTool` or `RunnableToolLike`
8
+ * into a JSON schema, which is then used as the parameters for the OpenAI function.
9
+ *
10
+ * @param {StructuredToolInterface | RunnableToolLike} tool The tool to convert to an OpenAI function.
11
+ * @returns {FunctionDefinition} The inputted tool in OpenAI function format.
8
12
  */
9
- export declare function convertToOpenAIFunction(tool: StructuredToolInterface): FunctionDefinition;
13
+ export declare function convertToOpenAIFunction(tool: StructuredToolInterface | RunnableToolLike): FunctionDefinition;
10
14
  /**
11
- * Formats a `StructuredTool` instance into a format that is compatible
12
- * with OpenAI tool calling. It uses the `zodToJsonSchema`
13
- * function to convert the schema of the `StructuredTool` into a JSON
14
- * schema, which is then used as the parameters for the OpenAI tool.
15
+ * Formats a `StructuredTool` or `RunnableToolLike` instance into a
16
+ * format that is compatible with OpenAI tool calling. It uses the
17
+ * `zodToJsonSchema` function to convert the schema of the `StructuredTool`
18
+ * or `RunnableToolLike` into a JSON schema, which is then used as the
19
+ * parameters for the OpenAI tool.
20
+ *
21
+ * @param {StructuredToolInterface | Record<string, any> | RunnableToolLike} tool The tool to convert to an OpenAI tool.
22
+ * @returns {ToolDefinition} The inputted tool in OpenAI tool format.
23
+ */
24
+ export declare function convertToOpenAITool(tool: StructuredToolInterface | Record<string, any> | RunnableToolLike): ToolDefinition;
25
+ /**
26
+ * Confirm whether the inputted tool is an instance of `StructuredToolInterface`.
27
+ *
28
+ * @param {StructuredToolInterface | Record<string, any> | undefined} tool The tool to check if it is an instance of `StructuredToolInterface`.
29
+ * @returns {tool is StructuredToolInterface} Whether the inputted tool is an instance of `StructuredToolInterface`.
15
30
  */
16
- export declare function convertToOpenAITool(tool: StructuredToolInterface | Record<string, any>): ToolDefinition;
17
31
  export declare function isStructuredTool(tool?: StructuredToolInterface | Record<string, any>): tool is StructuredToolInterface;
32
+ /**
33
+ * Confirm whether the inputted tool is an instance of `RunnableToolLike`.
34
+ *
35
+ * @param {unknown | undefined} tool The tool to check if it is an instance of `RunnableToolLike`.
36
+ * @returns {tool is RunnableToolLike} Whether the inputted tool is an instance of `RunnableToolLike`.
37
+ */
38
+ export declare function isRunnableToolLike(tool?: unknown): tool is RunnableToolLike;
@@ -1,9 +1,13 @@
1
1
  import { zodToJsonSchema } from "zod-to-json-schema";
2
+ import { Runnable } from "../runnables/base.js";
2
3
  /**
3
- * Formats a `StructuredTool` instance into a format that is compatible
4
- * with OpenAI function calling. It uses the `zodToJsonSchema`
5
- * function to convert the schema of the `StructuredTool` into a JSON
6
- * schema, which is then used as the parameters for the OpenAI function.
4
+ * Formats a `StructuredTool` or `RunnableToolLike` instance into a format
5
+ * that is compatible with OpenAI function calling. It uses the `zodToJsonSchema`
6
+ * function to convert the schema of the `StructuredTool` or `RunnableToolLike`
7
+ * into a JSON schema, which is then used as the parameters for the OpenAI function.
8
+ *
9
+ * @param {StructuredToolInterface | RunnableToolLike} tool The tool to convert to an OpenAI function.
10
+ * @returns {FunctionDefinition} The inputted tool in OpenAI function format.
7
11
  */
8
12
  export function convertToOpenAIFunction(tool) {
9
13
  return {
@@ -13,15 +17,19 @@ export function convertToOpenAIFunction(tool) {
13
17
  };
14
18
  }
15
19
  /**
16
- * Formats a `StructuredTool` instance into a format that is compatible
17
- * with OpenAI tool calling. It uses the `zodToJsonSchema`
18
- * function to convert the schema of the `StructuredTool` into a JSON
19
- * schema, which is then used as the parameters for the OpenAI tool.
20
+ * Formats a `StructuredTool` or `RunnableToolLike` instance into a
21
+ * format that is compatible with OpenAI tool calling. It uses the
22
+ * `zodToJsonSchema` function to convert the schema of the `StructuredTool`
23
+ * or `RunnableToolLike` into a JSON schema, which is then used as the
24
+ * parameters for the OpenAI tool.
25
+ *
26
+ * @param {StructuredToolInterface | Record<string, any> | RunnableToolLike} tool The tool to convert to an OpenAI tool.
27
+ * @returns {ToolDefinition} The inputted tool in OpenAI tool format.
20
28
  */
21
29
  export function convertToOpenAITool(
22
30
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
23
31
  tool) {
24
- if (isStructuredTool(tool)) {
32
+ if (isStructuredTool(tool) || isRunnableToolLike(tool)) {
25
33
  return {
26
34
  type: "function",
27
35
  function: convertToOpenAIFunction(tool),
@@ -29,9 +37,28 @@ tool) {
29
37
  }
30
38
  return tool;
31
39
  }
40
+ /**
41
+ * Confirm whether the inputted tool is an instance of `StructuredToolInterface`.
42
+ *
43
+ * @param {StructuredToolInterface | Record<string, any> | undefined} tool The tool to check if it is an instance of `StructuredToolInterface`.
44
+ * @returns {tool is StructuredToolInterface} Whether the inputted tool is an instance of `StructuredToolInterface`.
45
+ */
32
46
  export function isStructuredTool(
33
47
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
34
48
  tool) {
35
49
  return (tool !== undefined &&
36
50
  Array.isArray(tool.lc_namespace));
37
51
  }
52
+ /**
53
+ * Confirm whether the inputted tool is an instance of `RunnableToolLike`.
54
+ *
55
+ * @param {unknown | undefined} tool The tool to check if it is an instance of `RunnableToolLike`.
56
+ * @returns {tool is RunnableToolLike} Whether the inputted tool is an instance of `RunnableToolLike`.
57
+ */
58
+ export function isRunnableToolLike(tool) {
59
+ return (tool !== undefined &&
60
+ Runnable.isRunnable(tool) &&
61
+ "lc_name" in tool.constructor &&
62
+ typeof tool.constructor.lc_name === "function" &&
63
+ tool.constructor.lc_name() === "RunnableToolLike");
64
+ }
@@ -13,7 +13,7 @@ const base_js_1 = require("../../output_parsers/base.cjs");
13
13
  const outputs_js_1 = require("../../outputs.cjs");
14
14
  const index_js_2 = require("../../retrievers/index.cjs");
15
15
  const base_js_2 = require("../../runnables/base.cjs");
16
- const tools_js_1 = require("../../tools.cjs");
16
+ const index_js_3 = require("../../tools/index.cjs");
17
17
  const base_js_3 = require("../../tracers/base.cjs");
18
18
  const embeddings_js_1 = require("../../embeddings.cjs");
19
19
  /**
@@ -162,7 +162,14 @@ class FakeChatModel extends chat_models_js_1.BaseChatModel {
162
162
  ],
163
163
  };
164
164
  }
165
- const text = messages.map((m) => m.content).join("\n");
165
+ const text = messages
166
+ .map((m) => {
167
+ if (typeof m.content === "string") {
168
+ return m.content;
169
+ }
170
+ return JSON.stringify(m.content, null, 2);
171
+ })
172
+ .join("\n");
166
173
  await runManager?.handleLLMNewToken(text);
167
174
  return {
168
175
  generations: [
@@ -475,7 +482,7 @@ class FakeTracer extends base_js_3.BaseTracer {
475
482
  }
476
483
  }
477
484
  exports.FakeTracer = FakeTracer;
478
- class FakeTool extends tools_js_1.StructuredTool {
485
+ class FakeTool extends index_js_3.StructuredTool {
479
486
  constructor(fields) {
480
487
  super(fields);
481
488
  Object.defineProperty(this, "name", {
@@ -9,7 +9,7 @@ import { BaseOutputParser } from "../../output_parsers/base.js";
9
9
  import { GenerationChunk, type ChatResult, ChatGenerationChunk } from "../../outputs.js";
10
10
  import { BaseRetriever } from "../../retrievers/index.js";
11
11
  import { Runnable } from "../../runnables/base.js";
12
- import { StructuredTool, ToolParams } from "../../tools.js";
12
+ import { StructuredTool, ToolParams } from "../../tools/index.js";
13
13
  import { BaseTracer, Run } from "../../tracers/base.js";
14
14
  import { Embeddings, EmbeddingsParams } from "../../embeddings.js";
15
15
  import { StructuredOutputMethodParams, BaseLanguageModelInput, StructuredOutputMethodOptions } from "../../language_models/base.js";
@@ -10,7 +10,7 @@ import { BaseOutputParser } from "../../output_parsers/base.js";
10
10
  import { ChatGenerationChunk, } from "../../outputs.js";
11
11
  import { BaseRetriever } from "../../retrievers/index.js";
12
12
  import { Runnable, RunnableLambda } from "../../runnables/base.js";
13
- import { StructuredTool } from "../../tools.js";
13
+ import { StructuredTool } from "../../tools/index.js";
14
14
  import { BaseTracer } from "../../tracers/base.js";
15
15
  import { Embeddings } from "../../embeddings.js";
16
16
  /**
@@ -155,7 +155,14 @@ export class FakeChatModel extends BaseChatModel {
155
155
  ],
156
156
  };
157
157
  }
158
- const text = messages.map((m) => m.content).join("\n");
158
+ const text = messages
159
+ .map((m) => {
160
+ if (typeof m.content === "string") {
161
+ return m.content;
162
+ }
163
+ return JSON.stringify(m.content, null, 2);
164
+ })
165
+ .join("\n");
159
166
  await runManager?.handleLLMNewToken(text);
160
167
  return {
161
168
  generations: [