@langchain/core 0.2.5 → 0.2.7

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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # 🦜🍎️ @langchain/core
2
2
 
3
- [![CI](https://github.com/langchain-ai/langchainjs/actions/workflows/ci.yml/badge.svg)](https://github.com/langchain-ai/langchainjs/actions/workflows/ci.yml) ![npm](https://img.shields.io/npm/dw/@langchain/core) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Twitter](https://img.shields.io/twitter/url/https/twitter.com/langchainai.svg?style=social&label=Follow%20%40LangChainAI)](https://twitter.com/langchainai) [![](https://dcbadge.vercel.app/api/server/6adMQxSpJS?compact=true&style=flat)](https://discord.gg/6adMQxSpJS)
3
+ [![CI](https://github.com/langchain-ai/langchainjs/actions/workflows/ci.yml/badge.svg)](https://github.com/langchain-ai/langchainjs/actions/workflows/ci.yml) ![npm](https://img.shields.io/npm/dm/@langchain/core) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Twitter](https://img.shields.io/twitter/url/https/twitter.com/langchainai.svg?style=social&label=Follow%20%40LangChainAI)](https://twitter.com/langchainai) [![](https://dcbadge.vercel.app/api/server/6adMQxSpJS?compact=true&style=flat)](https://discord.gg/6adMQxSpJS)
4
4
 
5
5
  `@langchain/core` contains the core abstractions and schemas of LangChain.js, including base classes for language models,
6
6
  chat models, vectorstores, retrievers, and runnables.
@@ -20,7 +20,7 @@ function createQueue() {
20
20
  }
21
21
  /**
22
22
  * Consume a promise, either adding it to the queue or waiting for it to resolve
23
- * @param promise Promise to consume
23
+ * @param promiseFn Promise to consume
24
24
  * @param wait Whether to wait for the promise to resolve or resolve immediately
25
25
  */
26
26
  async function consumeCallback(promiseFn, wait) {
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Consume a promise, either adding it to the queue or waiting for it to resolve
3
- * @param promise Promise to consume
3
+ * @param promiseFn Promise to consume
4
4
  * @param wait Whether to wait for the promise to resolve or resolve immediately
5
5
  */
6
6
  export declare function consumeCallback<T>(promiseFn: () => Promise<T> | T | void, wait: boolean): Promise<void>;
@@ -14,7 +14,7 @@ function createQueue() {
14
14
  }
15
15
  /**
16
16
  * Consume a promise, either adding it to the queue or waiting for it to resolve
17
- * @param promise Promise to consume
17
+ * @param promiseFn Promise to consume
18
18
  * @param wait Whether to wait for the promise to resolve or resolve immediately
19
19
  */
20
20
  export async function consumeCallback(promiseFn, wait) {
@@ -78,7 +78,7 @@ export declare abstract class BaseChatModel<CallOptions extends BaseChatModelCal
78
78
  invoke(input: BaseLanguageModelInput, options?: CallOptions): Promise<OutputMessageType>;
79
79
  _streamResponseChunks(_messages: BaseMessage[], _options: this["ParsedCallOptions"], _runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;
80
80
  _streamIterator(input: BaseLanguageModelInput, options?: CallOptions): AsyncGenerator<OutputMessageType>;
81
- protected getLsParams(options: this["ParsedCallOptions"]): LangSmithParams;
81
+ getLsParams(options: this["ParsedCallOptions"]): LangSmithParams;
82
82
  /** @ignore */
83
83
  _generateUncached(messages: BaseMessageLike[][], parsedOptions: this["ParsedCallOptions"], handledOptions: RunnableConfig): Promise<LLMResult>;
84
84
  _generateCached({ messages, cache, llmStringKey, parsedOptions, handledOptions, }: ChatModelGenerateCachedParameters<typeof this>): Promise<LLMResult & {
@@ -301,14 +301,20 @@ class _StringImageMessagePromptTemplate extends BaseMessagePromptTemplate {
301
301
  else if (typeof item.text === "string") {
302
302
  text = item.text ?? "";
303
303
  }
304
- prompt.push(prompt_js_1.PromptTemplate.fromTemplate(text));
304
+ prompt.push(prompt_js_1.PromptTemplate.fromTemplate(text, additionalOptions));
305
305
  }
306
306
  else if (typeof item === "object" && "image_url" in item) {
307
307
  let imgTemplate = item.image_url ?? "";
308
308
  let imgTemplateObject;
309
309
  let inputVariables = [];
310
310
  if (typeof imgTemplate === "string") {
311
- const parsedTemplate = (0, template_js_1.parseFString)(imgTemplate);
311
+ let parsedTemplate;
312
+ if (additionalOptions?.templateFormat === "mustache") {
313
+ parsedTemplate = (0, template_js_1.parseMustache)(imgTemplate);
314
+ }
315
+ else {
316
+ parsedTemplate = (0, template_js_1.parseFString)(imgTemplate);
317
+ }
312
318
  const variables = parsedTemplate.flatMap((item) => item.type === "variable" ? [item.name] : []);
313
319
  if ((variables?.length ?? 0) > 0) {
314
320
  if (variables.length > 1) {
@@ -327,7 +333,13 @@ class _StringImageMessagePromptTemplate extends BaseMessagePromptTemplate {
327
333
  }
328
334
  else if (typeof imgTemplate === "object") {
329
335
  if ("url" in imgTemplate) {
330
- const parsedTemplate = (0, template_js_1.parseFString)(imgTemplate.url);
336
+ let parsedTemplate;
337
+ if (additionalOptions?.templateFormat === "mustache") {
338
+ parsedTemplate = (0, template_js_1.parseMustache)(imgTemplate.url);
339
+ }
340
+ else {
341
+ parsedTemplate = (0, template_js_1.parseFString)(imgTemplate.url);
342
+ }
331
343
  inputVariables = parsedTemplate.flatMap((item) => item.type === "variable" ? [item.name] : []);
332
344
  }
333
345
  else {
@@ -600,7 +612,9 @@ class ChatPromptTemplate extends BaseChatPromptTemplate {
600
612
  else {
601
613
  imageUrl = item.image_url.url;
602
614
  }
603
- const promptTemplatePlaceholder = prompt_js_1.PromptTemplate.fromTemplate(imageUrl);
615
+ const promptTemplatePlaceholder = prompt_js_1.PromptTemplate.fromTemplate(imageUrl, {
616
+ templateFormat: this.templateFormat,
617
+ });
604
618
  const formattedUrl = await promptTemplatePlaceholder.format(inputValues);
605
619
  if (typeof item.image_url !== "string" && "url" in item.image_url) {
606
620
  // eslint-disable-next-line no-param-reassign
@@ -7,7 +7,7 @@ import { BaseStringPromptTemplate } from "./string.js";
7
7
  import { BasePromptTemplate, } from "./base.js";
8
8
  import { PromptTemplate, } from "./prompt.js";
9
9
  import { ImagePromptTemplate } from "./image.js";
10
- import { parseFString } from "./template.js";
10
+ import { parseFString, parseMustache, } from "./template.js";
11
11
  /**
12
12
  * Abstract class that serves as a base for creating message prompt
13
13
  * templates. It defines how to format messages for different roles in a
@@ -293,14 +293,20 @@ class _StringImageMessagePromptTemplate extends BaseMessagePromptTemplate {
293
293
  else if (typeof item.text === "string") {
294
294
  text = item.text ?? "";
295
295
  }
296
- prompt.push(PromptTemplate.fromTemplate(text));
296
+ prompt.push(PromptTemplate.fromTemplate(text, additionalOptions));
297
297
  }
298
298
  else if (typeof item === "object" && "image_url" in item) {
299
299
  let imgTemplate = item.image_url ?? "";
300
300
  let imgTemplateObject;
301
301
  let inputVariables = [];
302
302
  if (typeof imgTemplate === "string") {
303
- const parsedTemplate = parseFString(imgTemplate);
303
+ let parsedTemplate;
304
+ if (additionalOptions?.templateFormat === "mustache") {
305
+ parsedTemplate = parseMustache(imgTemplate);
306
+ }
307
+ else {
308
+ parsedTemplate = parseFString(imgTemplate);
309
+ }
304
310
  const variables = parsedTemplate.flatMap((item) => item.type === "variable" ? [item.name] : []);
305
311
  if ((variables?.length ?? 0) > 0) {
306
312
  if (variables.length > 1) {
@@ -319,7 +325,13 @@ class _StringImageMessagePromptTemplate extends BaseMessagePromptTemplate {
319
325
  }
320
326
  else if (typeof imgTemplate === "object") {
321
327
  if ("url" in imgTemplate) {
322
- const parsedTemplate = parseFString(imgTemplate.url);
328
+ let parsedTemplate;
329
+ if (additionalOptions?.templateFormat === "mustache") {
330
+ parsedTemplate = parseMustache(imgTemplate.url);
331
+ }
332
+ else {
333
+ parsedTemplate = parseFString(imgTemplate.url);
334
+ }
323
335
  inputVariables = parsedTemplate.flatMap((item) => item.type === "variable" ? [item.name] : []);
324
336
  }
325
337
  else {
@@ -589,7 +601,9 @@ export class ChatPromptTemplate extends BaseChatPromptTemplate {
589
601
  else {
590
602
  imageUrl = item.image_url.url;
591
603
  }
592
- const promptTemplatePlaceholder = PromptTemplate.fromTemplate(imageUrl);
604
+ const promptTemplatePlaceholder = PromptTemplate.fromTemplate(imageUrl, {
605
+ templateFormat: this.templateFormat,
606
+ });
593
607
  const formattedUrl = await promptTemplatePlaceholder.format(inputValues);
594
608
  if (typeof item.image_url !== "string" && "url" in item.image_url) {
595
609
  // eslint-disable-next-line no-param-reassign
@@ -66,7 +66,9 @@ const mustacheTemplateToNodes = (template) => template.map((temp) => {
66
66
  const name = temp[1].includes(".") ? temp[1].split(".")[0] : temp[1];
67
67
  return { type: "variable", name };
68
68
  }
69
- else if (temp[0] === "#") {
69
+ else if (["#", "&"].includes(temp[0])) {
70
+ // # represents a section, "&" represents an unescaped variable.
71
+ // These should both be considered variables.
70
72
  return { type: "variable", name: temp[1] };
71
73
  }
72
74
  else {
@@ -59,7 +59,9 @@ const mustacheTemplateToNodes = (template) => template.map((temp) => {
59
59
  const name = temp[1].includes(".") ? temp[1].split(".")[0] : temp[1];
60
60
  return { type: "variable", name };
61
61
  }
62
- else if (temp[0] === "#") {
62
+ else if (["#", "&"].includes(temp[0])) {
63
+ // # represents a section, "&" represents an unescaped variable.
64
+ // These should both be considered variables.
63
65
  return { type: "variable", name: temp[1] };
64
66
  }
65
67
  else {
@@ -2,7 +2,7 @@ import { test, expect } from "@jest/globals";
2
2
  import { AIMessage } from "../../messages/ai.js";
3
3
  import { HumanMessage } from "../../messages/human.js";
4
4
  import { SystemMessage } from "../../messages/system.js";
5
- import { ChatPromptTemplate } from "../chat.js";
5
+ import { ChatPromptTemplate, HumanMessagePromptTemplate } from "../chat.js";
6
6
  test("Test creating a chat prompt template from role string messages", async () => {
7
7
  const template = ChatPromptTemplate.fromMessages([
8
8
  ["system", "You are a helpful AI bot. Your name is {{name}}."],
@@ -59,3 +59,43 @@ test("Ignores f-string inputs input variables with repeats.", async () => {
59
59
  new HumanMessage("This {bar} is a {foo} test {foo}."),
60
60
  ]);
61
61
  });
62
+ test("Mustache template with image and chat prompts inside one template (fromMessages)", async () => {
63
+ const template = ChatPromptTemplate.fromMessages([
64
+ [
65
+ "human",
66
+ [
67
+ {
68
+ type: "image_url",
69
+ image_url: "{{image_url}}",
70
+ },
71
+ {
72
+ type: "text",
73
+ text: "{{other_var}}",
74
+ },
75
+ ],
76
+ ],
77
+ ["human", "hello {{name}}"],
78
+ ], {
79
+ templateFormat: "mustache",
80
+ });
81
+ expect(template.inputVariables.sort()).toEqual([
82
+ "image_url",
83
+ "name",
84
+ "other_var",
85
+ ]);
86
+ });
87
+ test("Mustache image template with nested URL and chat prompts HumanMessagePromptTemplate.fromTemplate", async () => {
88
+ const template = HumanMessagePromptTemplate.fromTemplate([
89
+ {
90
+ text: "{{name}}",
91
+ },
92
+ {
93
+ image_url: {
94
+ url: "{{image_url}}",
95
+ },
96
+ },
97
+ ], {
98
+ templateFormat: "mustache",
99
+ });
100
+ expect(template.inputVariables.sort()).toEqual(["image_url", "name"]);
101
+ });
@@ -1,5 +1,6 @@
1
1
  import { test, expect } from "@jest/globals";
2
2
  import { PromptTemplate } from "../prompt.js";
3
+ import { parseTemplate } from "../template.js";
3
4
  test("Single input variable.", async () => {
4
5
  const template = "This is a {{foo}} test.";
5
6
  const prompt = PromptTemplate.fromTemplate(template, {
@@ -83,3 +84,22 @@ hello
83
84
  is a test.`);
84
85
  expect(promptWithRepeats.inputVariables).toEqual(["foo"]);
85
86
  });
87
+ test("Escaped variables", async () => {
88
+ const template = `test: {{{text}}}`;
89
+ const parsed = parseTemplate(template, "mustache");
90
+ expect(parsed[0]).toStrictEqual({
91
+ type: "literal",
92
+ text: "test: ",
93
+ });
94
+ expect(parsed[1]).toStrictEqual({
95
+ type: "variable",
96
+ name: "text",
97
+ });
98
+ const promptTemplate = PromptTemplate.fromTemplate(template, {
99
+ templateFormat: "mustache",
100
+ });
101
+ const result = await promptTemplate.invoke({
102
+ text: `hello i have a "quote`,
103
+ });
104
+ expect(result.value).toBe(`test: hello i have a "quote`);
105
+ });
@@ -7,7 +7,7 @@ import { RunnableLambda, RunnableMap, RunnablePassthrough, RunnablePick, } from
7
7
  import { ChatPromptTemplate } from "../../prompts/chat.js";
8
8
  import { FakeChatModel, FakeLLM, FakeListChatModel, FakeRetriever, FakeStreamingLLM, } from "../../utils/testing/index.js";
9
9
  import { AIMessage, AIMessageChunk, HumanMessage, SystemMessage, } from "../../messages/index.js";
10
- import { DynamicStructuredTool, DynamicTool } from "../../tools.js";
10
+ import { DynamicStructuredTool, DynamicTool, tool } from "../../tools.js";
11
11
  import { Document } from "../../documents/document.js";
12
12
  import { PromptTemplate } from "../../prompts/prompt.js";
13
13
  import { GenerationChunk } from "../../outputs.js";
@@ -1748,6 +1748,70 @@ test("Runnable streamEvents method with simple tools", async () => {
1748
1748
  },
1749
1749
  ]);
1750
1750
  });
1751
+ test("Runnable streamEvents method with tools that return objects", async () => {
1752
+ const adderFunc = (_params) => {
1753
+ return JSON.stringify({ sum: 3 });
1754
+ };
1755
+ const parameterlessTool = tool(adderFunc, {
1756
+ name: "parameterless",
1757
+ });
1758
+ const events = [];
1759
+ const eventStream = parameterlessTool.streamEvents({}, { version: "v2" });
1760
+ for await (const event of eventStream) {
1761
+ events.push(event);
1762
+ }
1763
+ expect(events).toEqual([
1764
+ {
1765
+ data: { input: {} },
1766
+ event: "on_tool_start",
1767
+ metadata: {},
1768
+ name: "parameterless",
1769
+ run_id: expect.any(String),
1770
+ tags: [],
1771
+ },
1772
+ {
1773
+ data: {
1774
+ output: JSON.stringify({ sum: 3 }),
1775
+ },
1776
+ event: "on_tool_end",
1777
+ metadata: {},
1778
+ name: "parameterless",
1779
+ run_id: expect.any(String),
1780
+ tags: [],
1781
+ },
1782
+ ]);
1783
+ const adderTool = tool(adderFunc, {
1784
+ name: "with_parameters",
1785
+ description: "A tool that does nothing",
1786
+ schema: z.object({
1787
+ x: z.number(),
1788
+ y: z.number(),
1789
+ }),
1790
+ });
1791
+ const events2 = [];
1792
+ const eventStream2 = adderTool.streamEvents({ x: 1, y: 2 }, { version: "v2" });
1793
+ for await (const event of eventStream2) {
1794
+ events2.push(event);
1795
+ }
1796
+ expect(events2).toEqual([
1797
+ {
1798
+ data: { input: { x: 1, y: 2 } },
1799
+ event: "on_tool_start",
1800
+ metadata: {},
1801
+ name: "with_parameters",
1802
+ run_id: expect.any(String),
1803
+ tags: [],
1804
+ },
1805
+ {
1806
+ data: { output: JSON.stringify({ sum: 3 }) },
1807
+ event: "on_tool_end",
1808
+ metadata: {},
1809
+ name: "with_parameters",
1810
+ run_id: expect.any(String),
1811
+ tags: [],
1812
+ },
1813
+ ]);
1814
+ });
1751
1815
  test("Runnable streamEvents method with a retriever", async () => {
1752
1816
  const retriever = new FakeRetriever({
1753
1817
  output: [
package/dist/tools.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BaseToolkit = exports.DynamicStructuredTool = exports.DynamicTool = exports.Tool = exports.StructuredTool = exports.ToolInputParsingException = void 0;
3
+ exports.tool = exports.BaseToolkit = exports.DynamicStructuredTool = exports.DynamicTool = exports.Tool = exports.StructuredTool = exports.ToolInputParsingException = void 0;
4
4
  const zod_1 = require("zod");
5
5
  const manager_js_1 = require("./callbacks/manager.cjs");
6
6
  const base_js_1 = require("./language_models/base.cjs");
@@ -233,3 +233,28 @@ class BaseToolkit {
233
233
  }
234
234
  }
235
235
  exports.BaseToolkit = BaseToolkit;
236
+ /**
237
+ * Creates a new StructuredTool instance with the provided function, name, description, and schema.
238
+ * @function
239
+ * @template {ZodAny} RunInput The input schema for the tool.
240
+ *
241
+ * @param {RunnableFunc<RunInput, string>} func - The function to invoke when the tool is called.
242
+ * @param fields - An object containing the following properties:
243
+ * @param {string} fields.name The name of the tool.
244
+ * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.
245
+ * @param {z.ZodObject<any, any, any, any>} fields.schema The Zod schema defining the input for the tool.
246
+ *
247
+ * @returns {StructuredTool<RunInput, string>} A new StructuredTool instance.
248
+ */
249
+ function tool(func, fields) {
250
+ const schema = fields.schema ??
251
+ zod_1.z.object({ input: zod_1.z.string().optional() }).transform((obj) => obj.input);
252
+ const description = fields.description ?? schema.description ?? `${fields.name} tool`;
253
+ return new DynamicStructuredTool({
254
+ name: fields.name,
255
+ description,
256
+ schema: schema,
257
+ func: async (input, _runManager, config) => func(input, config),
258
+ });
259
+ }
260
+ exports.tool = tool;
package/dist/tools.d.ts CHANGED
@@ -2,7 +2,8 @@ import { z } from "zod";
2
2
  import { CallbackManagerForToolRun, Callbacks } from "./callbacks/manager.js";
3
3
  import { BaseLangChain, type BaseLangChainParams } from "./language_models/base.js";
4
4
  import { type RunnableConfig } from "./runnables/config.js";
5
- import type { RunnableInterface } from "./runnables/base.js";
5
+ import type { RunnableFunc, RunnableInterface } from "./runnables/base.js";
6
+ type ZodAny = z.ZodObject<any, any, any, any>;
6
7
  /**
7
8
  * Parameters for the Tool classes.
8
9
  */
@@ -17,7 +18,7 @@ export declare class ToolInputParsingException extends Error {
17
18
  output?: string;
18
19
  constructor(message: string, output?: string);
19
20
  }
20
- export interface StructuredToolInterface<T extends z.ZodObject<any, any, any, any> = z.ZodObject<any, any, any, any>> extends RunnableInterface<(z.output<T> extends string ? string : never) | z.input<T>, string> {
21
+ export interface StructuredToolInterface<T extends ZodAny = ZodAny> extends RunnableInterface<(z.output<T> extends string ? string : never) | z.input<T>, string> {
21
22
  lc_namespace: string[];
22
23
  schema: T | z.ZodEffects<T>;
23
24
  /**
@@ -41,7 +42,7 @@ export interface StructuredToolInterface<T extends z.ZodObject<any, any, any, an
41
42
  /**
42
43
  * Base class for Tools that accept input of any shape defined by a Zod schema.
43
44
  */
44
- export declare abstract class StructuredTool<T extends z.ZodObject<any, any, any, any> = z.ZodObject<any, any, any, any>> extends BaseLangChain<(z.output<T> extends string ? string : never) | z.input<T>, string> {
45
+ export declare abstract class StructuredTool<T extends ZodAny = ZodAny> extends BaseLangChain<(z.output<T> extends string ? string : never) | z.input<T>, string> {
45
46
  abstract schema: T | z.ZodEffects<T>;
46
47
  get lc_namespace(): string[];
47
48
  constructor(fields?: ToolParams);
@@ -122,7 +123,7 @@ export interface DynamicToolInput extends BaseDynamicToolInput {
122
123
  /**
123
124
  * Interface for the input parameters of the DynamicStructuredTool class.
124
125
  */
125
- export interface DynamicStructuredToolInput<T extends z.ZodObject<any, any, any, any> = z.ZodObject<any, any, any, any>> extends BaseDynamicToolInput {
126
+ export interface DynamicStructuredToolInput<T extends ZodAny = ZodAny> extends BaseDynamicToolInput {
126
127
  func: (input: z.infer<T>, runManager?: CallbackManagerForToolRun, config?: RunnableConfig) => Promise<string>;
127
128
  schema: T;
128
129
  }
@@ -148,11 +149,11 @@ export declare class DynamicTool extends Tool {
148
149
  * StructuredTool class and overrides the _call method to execute the
149
150
  * provided function when the tool is called.
150
151
  */
151
- export declare class DynamicStructuredTool<T extends z.ZodObject<any, any, any, any> = z.ZodObject<any, any, any, any>> extends StructuredTool {
152
+ export declare class DynamicStructuredTool<T extends ZodAny = ZodAny> extends StructuredTool<T> {
152
153
  static lc_name(): string;
153
154
  name: string;
154
155
  description: string;
155
- func: DynamicStructuredToolInput["func"];
156
+ func: DynamicStructuredToolInput<T>["func"];
156
157
  schema: T;
157
158
  constructor(fields: DynamicStructuredToolInput<T>);
158
159
  /**
@@ -172,3 +173,40 @@ export declare abstract class BaseToolkit {
172
173
  abstract tools: StructuredToolInterface[];
173
174
  getTools(): StructuredToolInterface[];
174
175
  }
176
+ /**
177
+ * Parameters for the tool function.
178
+ * @template {ZodAny} RunInput The input schema for the tool.
179
+ */
180
+ interface ToolWrapperParams<RunInput extends ZodAny = ZodAny> extends ToolParams {
181
+ /**
182
+ * The name of the tool. If using with an LLM, this
183
+ * will be passed as the tool name.
184
+ */
185
+ name: string;
186
+ /**
187
+ * The description of the tool.
188
+ * @default `${fields.name} tool`
189
+ */
190
+ description?: string;
191
+ /**
192
+ * The input schema for the tool. If using an LLM, this
193
+ * will be passed as the tool schema to generate arguments
194
+ * for.
195
+ */
196
+ schema?: RunInput;
197
+ }
198
+ /**
199
+ * Creates a new StructuredTool instance with the provided function, name, description, and schema.
200
+ * @function
201
+ * @template {ZodAny} RunInput The input schema for the tool.
202
+ *
203
+ * @param {RunnableFunc<RunInput, string>} func - The function to invoke when the tool is called.
204
+ * @param fields - An object containing the following properties:
205
+ * @param {string} fields.name The name of the tool.
206
+ * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.
207
+ * @param {z.ZodObject<any, any, any, any>} fields.schema The Zod schema defining the input for the tool.
208
+ *
209
+ * @returns {StructuredTool<RunInput, string>} A new StructuredTool instance.
210
+ */
211
+ export declare function tool<RunInput extends ZodAny = ZodAny>(func: RunnableFunc<z.infer<RunInput>, string>, fields: ToolWrapperParams<RunInput>): DynamicStructuredTool<RunInput>;
212
+ export {};
package/dist/tools.js CHANGED
@@ -224,3 +224,27 @@ export class BaseToolkit {
224
224
  return this.tools;
225
225
  }
226
226
  }
227
+ /**
228
+ * Creates a new StructuredTool instance with the provided function, name, description, and schema.
229
+ * @function
230
+ * @template {ZodAny} RunInput The input schema for the tool.
231
+ *
232
+ * @param {RunnableFunc<RunInput, string>} func - The function to invoke when the tool is called.
233
+ * @param fields - An object containing the following properties:
234
+ * @param {string} fields.name The name of the tool.
235
+ * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.
236
+ * @param {z.ZodObject<any, any, any, any>} fields.schema The Zod schema defining the input for the tool.
237
+ *
238
+ * @returns {StructuredTool<RunInput, string>} A new StructuredTool instance.
239
+ */
240
+ export function tool(func, fields) {
241
+ const schema = fields.schema ??
242
+ z.object({ input: z.string().optional() }).transform((obj) => obj.input);
243
+ const description = fields.description ?? schema.description ?? `${fields.name} tool`;
244
+ return new DynamicStructuredTool({
245
+ name: fields.name,
246
+ description,
247
+ schema: schema,
248
+ func: async (input, _runManager, config) => func(input, config),
249
+ });
250
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@langchain/core",
3
- "version": "0.2.5",
3
+ "version": "0.2.7",
4
4
  "description": "Core LangChain.js abstractions and schemas",
5
5
  "type": "module",
6
6
  "engines": {