@langchain/core 1.1.18 → 1.1.20
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/CHANGELOG.md +12 -0
- package/dist/caches/index.d.cts.map +1 -1
- package/dist/callbacks/base.cjs.map +1 -1
- package/dist/callbacks/base.d.cts.map +1 -1
- package/dist/callbacks/base.js.map +1 -1
- package/dist/documents/document.cjs.map +1 -1
- package/dist/documents/document.js.map +1 -1
- package/dist/embeddings.cjs.map +1 -1
- package/dist/embeddings.js.map +1 -1
- package/dist/language_models/base.cjs.map +1 -1
- package/dist/language_models/base.js.map +1 -1
- package/dist/language_models/chat_models.d.cts.map +1 -1
- package/dist/load/serializable.cjs.map +1 -1
- package/dist/load/serializable.js.map +1 -1
- package/dist/memory.d.cts.map +1 -1
- package/dist/messages/ai.cjs.map +1 -1
- package/dist/messages/ai.js.map +1 -1
- package/dist/messages/base.cjs.map +1 -1
- package/dist/messages/base.js.map +1 -1
- package/dist/messages/content/tools.cjs.map +1 -1
- package/dist/messages/content/tools.js.map +1 -1
- package/dist/messages/function.cjs.map +1 -1
- package/dist/messages/function.js.map +1 -1
- package/dist/messages/message.cjs.map +1 -1
- package/dist/messages/message.js.map +1 -1
- package/dist/output_parsers/structured.cjs.map +1 -1
- package/dist/output_parsers/structured.js.map +1 -1
- package/dist/output_parsers/xml.cjs.map +1 -1
- package/dist/output_parsers/xml.js.map +1 -1
- package/dist/prompts/base.cjs.map +1 -1
- package/dist/prompts/base.js.map +1 -1
- package/dist/prompts/chat.cjs.map +1 -1
- package/dist/prompts/chat.js.map +1 -1
- package/dist/prompts/few_shot.cjs.map +1 -1
- package/dist/prompts/few_shot.js.map +1 -1
- package/dist/prompts/prompt.cjs.map +1 -1
- package/dist/prompts/prompt.js.map +1 -1
- package/dist/prompts/structured.cjs.map +1 -1
- package/dist/prompts/structured.js.map +1 -1
- package/dist/retrievers/index.cjs.map +1 -1
- package/dist/retrievers/index.js.map +1 -1
- package/dist/runnables/base.cjs.map +1 -1
- package/dist/runnables/base.js.map +1 -1
- package/dist/runnables/history.cjs.map +1 -1
- package/dist/runnables/history.js.map +1 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/tools/index.cjs +1 -1
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.js +1 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/types.cjs.map +1 -1
- package/dist/tools/types.js.map +1 -1
- package/dist/tracers/event_stream.cjs.map +1 -1
- package/dist/tracers/event_stream.js.map +1 -1
- package/dist/tracers/log_stream.cjs.map +1 -1
- package/dist/tracers/log_stream.js.map +1 -1
- package/dist/utils/async_caller.cjs +1 -1
- package/dist/utils/async_caller.cjs.map +1 -1
- package/dist/utils/async_caller.js +1 -1
- package/dist/utils/async_caller.js.map +1 -1
- package/dist/utils/fast-json-patch/src/core.cjs +3 -10
- package/dist/utils/fast-json-patch/src/core.cjs.map +1 -1
- package/dist/utils/fast-json-patch/src/core.js +3 -10
- package/dist/utils/fast-json-patch/src/core.js.map +1 -1
- package/dist/utils/signal.cjs +1 -1
- package/dist/utils/signal.cjs.map +1 -1
- package/dist/utils/signal.js +1 -1
- package/dist/utils/signal.js.map +1 -1
- package/dist/utils/stream.cjs.map +1 -1
- package/dist/utils/stream.js.map +1 -1
- package/dist/utils/testing/chat_models.cjs.map +1 -1
- package/dist/utils/testing/chat_models.js.map +1 -1
- package/dist/utils/testing/tools.cjs.map +1 -1
- package/dist/utils/testing/tools.js.map +1 -1
- package/dist/vectorstores.cjs.map +1 -1
- package/dist/vectorstores.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"history.cjs","names":["RunnableBinding","fields: RunnableWithMessageHistoryInputs<RunInput, RunOutput>","historyChain: Runnable","RunnableLambda","RunnablePassthrough","config","inputValue: string | BaseMessage | Array<BaseMessage> | Record<string, any>","isBaseMessage","HumanMessage","outputValue: string | BaseMessage | Array<BaseMessage> | Record<string, any>","AIMessage","input: any","kwargs?: RunnableConfig","run: Run","config: RunnableConfig"],"sources":["../../src/runnables/history.ts"],"sourcesContent":["import {\n BaseChatMessageHistory,\n BaseListChatMessageHistory,\n} from \"../chat_history.js\";\nimport {\n AIMessage,\n BaseMessage,\n HumanMessage,\n isBaseMessage,\n} from \"../messages/index.js\";\nimport { Run } from \"../tracers/base.js\";\nimport {\n Runnable,\n RunnableBinding,\n type RunnableBindingArgs,\n RunnableLambda,\n} from \"./base.js\";\nimport { RunnableConfig } from \"./config.js\";\nimport { RunnablePassthrough } from \"./passthrough.js\";\n\ntype GetSessionHistoryCallable = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...args: Array<any>\n) =>\n | Promise<BaseChatMessageHistory | BaseListChatMessageHistory>\n | BaseChatMessageHistory\n | BaseListChatMessageHistory;\n\nexport interface RunnableWithMessageHistoryInputs<RunInput, RunOutput>\n extends Omit<RunnableBindingArgs<RunInput, RunOutput>, \"bound\" | \"config\"> {\n runnable: Runnable<RunInput, RunOutput>;\n getMessageHistory: GetSessionHistoryCallable;\n inputMessagesKey?: string;\n outputMessagesKey?: string;\n historyMessagesKey?: string;\n config?: RunnableConfig;\n}\n\n/**\n * Wraps a LCEL chain and manages history. It appends input messages\n * and chain outputs as history, and adds the current history messages to\n * the chain input.\n * @example\n * ```typescript\n * // pnpm install @langchain/anthropic @langchain/community @upstash/redis\n *\n * import {\n * ChatPromptTemplate,\n * MessagesPlaceholder,\n * } from \"@langchain/core/prompts\";\n * import { ChatAnthropic } from \"@langchain/anthropic\";\n * import { UpstashRedisChatMessageHistory } from \"@langchain/community/stores/message/upstash_redis\";\n * // For demos, you can also use an in-memory store:\n * // import { ChatMessageHistory } from \"@langchain/classic/stores/message/in_memory\";\n *\n * const prompt = ChatPromptTemplate.fromMessages([\n * [\"system\", \"You're an assistant who's good at {ability}\"],\n * new MessagesPlaceholder(\"history\"),\n * [\"human\", \"{question}\"],\n * ]);\n *\n * const chain = prompt.pipe(new ChatAnthropic({}));\n *\n * const chainWithHistory = new RunnableWithMessageHistory({\n * runnable: chain,\n * getMessageHistory: (sessionId) =>\n * new UpstashRedisChatMessageHistory({\n * sessionId,\n * config: {\n * url: process.env.UPSTASH_REDIS_REST_URL!,\n * token: process.env.UPSTASH_REDIS_REST_TOKEN!,\n * },\n * }),\n * inputMessagesKey: \"question\",\n * historyMessagesKey: \"history\",\n * });\n *\n * const result = await chainWithHistory.invoke(\n * {\n * ability: \"math\",\n * question: \"What does cosine mean?\",\n * },\n * {\n * configurable: {\n * sessionId: \"some_string_identifying_a_user\",\n * },\n * }\n * );\n *\n * const result2 = await chainWithHistory.invoke(\n * {\n * ability: \"math\",\n * question: \"What's its inverse?\",\n * },\n * {\n * configurable: {\n * sessionId: \"some_string_identifying_a_user\",\n * },\n * }\n * );\n * ```\n */\nexport class RunnableWithMessageHistory<\n RunInput,\n RunOutput,\n> extends RunnableBinding<RunInput, RunOutput> {\n runnable: Runnable<RunInput, RunOutput>;\n\n inputMessagesKey?: string;\n\n outputMessagesKey?: string;\n\n historyMessagesKey?: string;\n\n getMessageHistory: GetSessionHistoryCallable;\n\n constructor(fields: RunnableWithMessageHistoryInputs<RunInput, RunOutput>) {\n let historyChain: Runnable = RunnableLambda.from((input, options) =>\n this._enterHistory(input, options ?? {})\n ).withConfig({ runName: \"loadHistory\" });\n\n const messagesKey = fields.historyMessagesKey ?? fields.inputMessagesKey;\n if (messagesKey) {\n historyChain = RunnablePassthrough.assign({\n [messagesKey]: historyChain,\n }).withConfig({ runName: \"insertHistory\" });\n }\n\n const bound = historyChain\n .pipe(\n fields.runnable.withListeners({\n onEnd: (run, config) => this._exitHistory(run, config ?? {}),\n })\n )\n .withConfig({ runName: \"RunnableWithMessageHistory\" });\n\n const config = fields.config ?? {};\n\n super({\n ...fields,\n config,\n bound,\n });\n this.runnable = fields.runnable;\n this.getMessageHistory = fields.getMessageHistory;\n this.inputMessagesKey = fields.inputMessagesKey;\n this.outputMessagesKey = fields.outputMessagesKey;\n this.historyMessagesKey = fields.historyMessagesKey;\n }\n\n _getInputMessages(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputValue: string | BaseMessage | Array<BaseMessage> | Record<string, any>\n ): Array<BaseMessage> {\n let parsedInputValue;\n if (\n typeof inputValue === \"object\" &&\n !Array.isArray(inputValue) &&\n !isBaseMessage(inputValue)\n ) {\n let key;\n if (this.inputMessagesKey) {\n key = this.inputMessagesKey;\n } else if (Object.keys(inputValue).length === 1) {\n key = Object.keys(inputValue)[0];\n } else {\n key = \"input\";\n }\n if (Array.isArray(inputValue[key]) && Array.isArray(inputValue[key][0])) {\n parsedInputValue = inputValue[key][0];\n } else {\n parsedInputValue = inputValue[key];\n }\n } else {\n parsedInputValue = inputValue;\n }\n if (typeof parsedInputValue === \"string\") {\n return [new HumanMessage(parsedInputValue)];\n } else if (Array.isArray(parsedInputValue)) {\n return parsedInputValue;\n } else if (isBaseMessage(parsedInputValue)) {\n return [parsedInputValue];\n } else {\n throw new Error(\n `Expected a string, BaseMessage, or array of BaseMessages.\\nGot ${JSON.stringify(\n parsedInputValue,\n null,\n 2\n )}`\n );\n }\n }\n\n _getOutputMessages(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n outputValue: string | BaseMessage | Array<BaseMessage> | Record<string, any>\n ): Array<BaseMessage> {\n let parsedOutputValue;\n if (\n !Array.isArray(outputValue) &&\n !isBaseMessage(outputValue) &&\n typeof outputValue !== \"string\"\n ) {\n let key;\n if (this.outputMessagesKey !== undefined) {\n key = this.outputMessagesKey;\n } else if (Object.keys(outputValue).length === 1) {\n key = Object.keys(outputValue)[0];\n } else {\n key = \"output\";\n }\n // If you are wrapping a chat model directly\n // The output is actually this weird generations object\n if (outputValue.generations !== undefined) {\n parsedOutputValue = outputValue.generations[0][0].message;\n } else {\n parsedOutputValue = outputValue[key];\n }\n } else {\n parsedOutputValue = outputValue;\n }\n\n if (typeof parsedOutputValue === \"string\") {\n return [new AIMessage(parsedOutputValue)];\n } else if (Array.isArray(parsedOutputValue)) {\n return parsedOutputValue;\n } else if (isBaseMessage(parsedOutputValue)) {\n return [parsedOutputValue];\n } else {\n throw new Error(\n `Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(\n parsedOutputValue,\n null,\n 2\n )}`\n );\n }\n }\n\n async _enterHistory(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any,\n kwargs?: RunnableConfig\n ): Promise<BaseMessage[]> {\n const history = kwargs?.configurable?.messageHistory;\n const messages = await history.getMessages();\n if (this.historyMessagesKey === undefined) {\n return messages.concat(this._getInputMessages(input));\n }\n return messages;\n }\n\n async _exitHistory(run: Run, config: RunnableConfig): Promise<void> {\n const history = config.configurable?.messageHistory;\n\n // Get input messages\n let inputs;\n // Chat model inputs are nested arrays\n if (Array.isArray(run.inputs) && Array.isArray(run.inputs[0])) {\n inputs = run.inputs[0];\n } else {\n inputs = run.inputs;\n }\n let inputMessages = this._getInputMessages(inputs);\n // If historic messages were prepended to the input messages, remove them to\n // avoid adding duplicate messages to history.\n if (this.historyMessagesKey === undefined) {\n const existingMessages = await history.getMessages();\n inputMessages = inputMessages.slice(existingMessages.length);\n }\n // Get output messages\n const outputValue = run.outputs;\n if (!outputValue) {\n throw new Error(\n `Output values from 'Run' undefined. Run: ${JSON.stringify(\n run,\n null,\n 2\n )}`\n );\n }\n const outputMessages = this._getOutputMessages(outputValue);\n await history.addMessages([...inputMessages, ...outputMessages]);\n }\n\n async _mergeConfig(...configs: Array<RunnableConfig | undefined>) {\n const config = await super._mergeConfig(...configs);\n // Extract sessionId\n if (!config.configurable || !config.configurable.sessionId) {\n const exampleInput = {\n [this.inputMessagesKey ?? \"input\"]: \"foo\",\n };\n const exampleConfig = { configurable: { sessionId: \"123\" } };\n throw new Error(\n `sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\\n` +\n `eg. chain.invoke(${JSON.stringify(exampleInput)}, ${JSON.stringify(\n exampleConfig\n )})`\n );\n }\n // attach messageHistory\n const { sessionId } = config.configurable;\n config.configurable.messageHistory =\n await this.getMessageHistory(sessionId);\n return config;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsGA,IAAa,6BAAb,cAGUA,+BAAqC;CAC7C;CAEA;CAEA;CAEA;CAEA;CAEA,YAAYC,QAA+D;EACzE,IAAIC,eAAyBC,8BAAe,KAAK,CAAC,OAAO,YACvD,KAAK,cAAc,OAAO,WAAW,CAAE,EAAC,CACzC,CAAC,WAAW,EAAE,SAAS,cAAe,EAAC;EAExC,MAAM,cAAc,OAAO,sBAAsB,OAAO;AACxD,MAAI,aACF,eAAeC,wCAAoB,OAAO,GACvC,cAAc,aAChB,EAAC,CAAC,WAAW,EAAE,SAAS,gBAAiB,EAAC;EAG7C,MAAM,QAAQ,aACX,KACC,OAAO,SAAS,cAAc,EAC5B,OAAO,CAAC,KAAKC,aAAW,KAAK,aAAa,KAAKA,YAAU,CAAE,EAAC,CAC7D,EAAC,CACH,CACA,WAAW,EAAE,SAAS,6BAA8B,EAAC;EAExD,MAAM,SAAS,OAAO,UAAU,CAAE;EAElC,MAAM;GACJ,GAAG;GACH;GACA;EACD,EAAC;EACF,KAAK,WAAW,OAAO;EACvB,KAAK,oBAAoB,OAAO;EAChC,KAAK,mBAAmB,OAAO;EAC/B,KAAK,oBAAoB,OAAO;EAChC,KAAK,qBAAqB,OAAO;CAClC;CAED,kBAEEC,YACoB;EACpB,IAAI;AACJ,MACE,OAAO,eAAe,YACtB,CAAC,MAAM,QAAQ,WAAW,IAC1B,CAACC,2BAAc,WAAW,EAC1B;GACA,IAAI;AACJ,OAAI,KAAK,kBACP,MAAM,KAAK;YACF,OAAO,KAAK,WAAW,CAAC,WAAW,GAC5C,MAAM,OAAO,KAAK,WAAW,CAAC;QAE9B,MAAM;AAER,OAAI,MAAM,QAAQ,WAAW,KAAK,IAAI,MAAM,QAAQ,WAAW,KAAK,GAAG,EACr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I,MAAM,QAAQ,IAAI,OAAO,GAAG,EAC3D,SAAS,IAAI,OAAO;OAEpB,SAAS,IAAI;EAEf,IAAI,gBAAgB,KAAK,kBAAkB,OAAO;AAGlD,MAAI,KAAK,uBAAuB,QAAW;GACzC,MAAM,mBAAmB,MAAM,QAAQ,aAAa;GACpD,gBAAgB,cAAc,MAAM,iBAAiB,OAAO;EAC7D;EAED,MAAM,cAAc,IAAI;AACxB,MAAI,CAAC,YACH,OAAM,IAAI,MACR,CAAC,yCAAyC,EAAE,KAAK,UAC/C,KACA,MACA,EACD,EAAE;EAGP,MAAM,iBAAiB,KAAK,mBAAmB,YAAY;EAC3D,MAAM,QAAQ,YAAY,CAAC,GAAG,eAAe,GAAG,cAAe,EAAC;CACjE;CAED,MAAM,aAAa,GAAG,SAA4C;EAChE,MAAM,SAAS,MAAM,MAAM,aAAa,GAAG,QAAQ;AAEnD,MAAI,CAAC,OAAO,gBAAgB,CAAC,OAAO,aAAa,WAAW;GAC1D,MAAM,eAAe,GAClB,KAAK,oBAAoB,UAAU,MACrC;GACD,MAAM,gBAAgB,EAAE,cAAc,EAAE,WAAW,MAAO,EAAE;AAC5D,SAAM,IAAI,MACR,CAAC,6GAA4F,EACvE,KAAK,UAAU,aAAa,CAAC,EAAE,EAAE,KAAK,UACxD,cACD,CAAC,CAAC,CAAC;EAET;EAED,MAAM,EAAE,WAAW,GAAG,OAAO;EAC7B,OAAO,aAAa,iBAClB,MAAM,KAAK,kBAAkB,UAAU;AACzC,SAAO;CACR;AACF"}
|
|
1
|
+
{"version":3,"file":"history.cjs","names":["RunnableBinding","fields: RunnableWithMessageHistoryInputs<RunInput, RunOutput>","historyChain: Runnable","RunnableLambda","RunnablePassthrough","config","inputValue: string | BaseMessage | Array<BaseMessage> | Record<string, any>","isBaseMessage","HumanMessage","outputValue: string | BaseMessage | Array<BaseMessage> | Record<string, any>","AIMessage","input: any","kwargs?: RunnableConfig","run: Run","config: RunnableConfig"],"sources":["../../src/runnables/history.ts"],"sourcesContent":["import {\n BaseChatMessageHistory,\n BaseListChatMessageHistory,\n} from \"../chat_history.js\";\nimport {\n AIMessage,\n BaseMessage,\n HumanMessage,\n isBaseMessage,\n} from \"../messages/index.js\";\nimport { Run } from \"../tracers/base.js\";\nimport {\n Runnable,\n RunnableBinding,\n type RunnableBindingArgs,\n RunnableLambda,\n} from \"./base.js\";\nimport { RunnableConfig } from \"./config.js\";\nimport { RunnablePassthrough } from \"./passthrough.js\";\n\ntype GetSessionHistoryCallable = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...args: Array<any>\n) =>\n | Promise<BaseChatMessageHistory | BaseListChatMessageHistory>\n | BaseChatMessageHistory\n | BaseListChatMessageHistory;\n\nexport interface RunnableWithMessageHistoryInputs<\n RunInput,\n RunOutput,\n> extends Omit<RunnableBindingArgs<RunInput, RunOutput>, \"bound\" | \"config\"> {\n runnable: Runnable<RunInput, RunOutput>;\n getMessageHistory: GetSessionHistoryCallable;\n inputMessagesKey?: string;\n outputMessagesKey?: string;\n historyMessagesKey?: string;\n config?: RunnableConfig;\n}\n\n/**\n * Wraps a LCEL chain and manages history. It appends input messages\n * and chain outputs as history, and adds the current history messages to\n * the chain input.\n * @example\n * ```typescript\n * // pnpm install @langchain/anthropic @langchain/community @upstash/redis\n *\n * import {\n * ChatPromptTemplate,\n * MessagesPlaceholder,\n * } from \"@langchain/core/prompts\";\n * import { ChatAnthropic } from \"@langchain/anthropic\";\n * import { UpstashRedisChatMessageHistory } from \"@langchain/community/stores/message/upstash_redis\";\n * // For demos, you can also use an in-memory store:\n * // import { ChatMessageHistory } from \"@langchain/classic/stores/message/in_memory\";\n *\n * const prompt = ChatPromptTemplate.fromMessages([\n * [\"system\", \"You're an assistant who's good at {ability}\"],\n * new MessagesPlaceholder(\"history\"),\n * [\"human\", \"{question}\"],\n * ]);\n *\n * const chain = prompt.pipe(new ChatAnthropic({}));\n *\n * const chainWithHistory = new RunnableWithMessageHistory({\n * runnable: chain,\n * getMessageHistory: (sessionId) =>\n * new UpstashRedisChatMessageHistory({\n * sessionId,\n * config: {\n * url: process.env.UPSTASH_REDIS_REST_URL!,\n * token: process.env.UPSTASH_REDIS_REST_TOKEN!,\n * },\n * }),\n * inputMessagesKey: \"question\",\n * historyMessagesKey: \"history\",\n * });\n *\n * const result = await chainWithHistory.invoke(\n * {\n * ability: \"math\",\n * question: \"What does cosine mean?\",\n * },\n * {\n * configurable: {\n * sessionId: \"some_string_identifying_a_user\",\n * },\n * }\n * );\n *\n * const result2 = await chainWithHistory.invoke(\n * {\n * ability: \"math\",\n * question: \"What's its inverse?\",\n * },\n * {\n * configurable: {\n * sessionId: \"some_string_identifying_a_user\",\n * },\n * }\n * );\n * ```\n */\nexport class RunnableWithMessageHistory<\n RunInput,\n RunOutput,\n> extends RunnableBinding<RunInput, RunOutput> {\n runnable: Runnable<RunInput, RunOutput>;\n\n inputMessagesKey?: string;\n\n outputMessagesKey?: string;\n\n historyMessagesKey?: string;\n\n getMessageHistory: GetSessionHistoryCallable;\n\n constructor(fields: RunnableWithMessageHistoryInputs<RunInput, RunOutput>) {\n let historyChain: Runnable = RunnableLambda.from((input, options) =>\n this._enterHistory(input, options ?? {})\n ).withConfig({ runName: \"loadHistory\" });\n\n const messagesKey = fields.historyMessagesKey ?? fields.inputMessagesKey;\n if (messagesKey) {\n historyChain = RunnablePassthrough.assign({\n [messagesKey]: historyChain,\n }).withConfig({ runName: \"insertHistory\" });\n }\n\n const bound = historyChain\n .pipe(\n fields.runnable.withListeners({\n onEnd: (run, config) => this._exitHistory(run, config ?? {}),\n })\n )\n .withConfig({ runName: \"RunnableWithMessageHistory\" });\n\n const config = fields.config ?? {};\n\n super({\n ...fields,\n config,\n bound,\n });\n this.runnable = fields.runnable;\n this.getMessageHistory = fields.getMessageHistory;\n this.inputMessagesKey = fields.inputMessagesKey;\n this.outputMessagesKey = fields.outputMessagesKey;\n this.historyMessagesKey = fields.historyMessagesKey;\n }\n\n _getInputMessages(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputValue: string | BaseMessage | Array<BaseMessage> | Record<string, any>\n ): Array<BaseMessage> {\n let parsedInputValue;\n if (\n typeof inputValue === \"object\" &&\n !Array.isArray(inputValue) &&\n !isBaseMessage(inputValue)\n ) {\n let key;\n if (this.inputMessagesKey) {\n key = this.inputMessagesKey;\n } else if (Object.keys(inputValue).length === 1) {\n key = Object.keys(inputValue)[0];\n } else {\n key = \"input\";\n }\n if (Array.isArray(inputValue[key]) && Array.isArray(inputValue[key][0])) {\n parsedInputValue = inputValue[key][0];\n } else {\n parsedInputValue = inputValue[key];\n }\n } else {\n parsedInputValue = inputValue;\n }\n if (typeof parsedInputValue === \"string\") {\n return [new HumanMessage(parsedInputValue)];\n } else if (Array.isArray(parsedInputValue)) {\n return parsedInputValue;\n } else if (isBaseMessage(parsedInputValue)) {\n return [parsedInputValue];\n } else {\n throw new Error(\n `Expected a string, BaseMessage, or array of BaseMessages.\\nGot ${JSON.stringify(\n parsedInputValue,\n null,\n 2\n )}`\n );\n }\n }\n\n _getOutputMessages(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n outputValue: string | BaseMessage | Array<BaseMessage> | Record<string, any>\n ): Array<BaseMessage> {\n let parsedOutputValue;\n if (\n !Array.isArray(outputValue) &&\n !isBaseMessage(outputValue) &&\n typeof outputValue !== \"string\"\n ) {\n let key;\n if (this.outputMessagesKey !== undefined) {\n key = this.outputMessagesKey;\n } else if (Object.keys(outputValue).length === 1) {\n key = Object.keys(outputValue)[0];\n } else {\n key = \"output\";\n }\n // If you are wrapping a chat model directly\n // The output is actually this weird generations object\n if (outputValue.generations !== undefined) {\n parsedOutputValue = outputValue.generations[0][0].message;\n } else {\n parsedOutputValue = outputValue[key];\n }\n } else {\n parsedOutputValue = outputValue;\n }\n\n if (typeof parsedOutputValue === \"string\") {\n return [new AIMessage(parsedOutputValue)];\n } else if (Array.isArray(parsedOutputValue)) {\n return parsedOutputValue;\n } else if (isBaseMessage(parsedOutputValue)) {\n return [parsedOutputValue];\n } else {\n throw new Error(\n `Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(\n parsedOutputValue,\n null,\n 2\n )}`\n );\n }\n }\n\n async _enterHistory(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any,\n kwargs?: RunnableConfig\n ): Promise<BaseMessage[]> {\n const history = kwargs?.configurable?.messageHistory;\n const messages = await history.getMessages();\n if (this.historyMessagesKey === undefined) {\n return messages.concat(this._getInputMessages(input));\n }\n return messages;\n }\n\n async _exitHistory(run: Run, config: RunnableConfig): Promise<void> {\n const history = config.configurable?.messageHistory;\n\n // Get input messages\n let inputs;\n // Chat model inputs are nested arrays\n if (Array.isArray(run.inputs) && Array.isArray(run.inputs[0])) {\n inputs = run.inputs[0];\n } else {\n inputs = run.inputs;\n }\n let inputMessages = this._getInputMessages(inputs);\n // If historic messages were prepended to the input messages, remove them to\n // avoid adding duplicate messages to history.\n if (this.historyMessagesKey === undefined) {\n const existingMessages = await history.getMessages();\n inputMessages = inputMessages.slice(existingMessages.length);\n }\n // Get output messages\n const outputValue = run.outputs;\n if (!outputValue) {\n throw new Error(\n `Output values from 'Run' undefined. Run: ${JSON.stringify(\n run,\n null,\n 2\n )}`\n );\n }\n const outputMessages = this._getOutputMessages(outputValue);\n await history.addMessages([...inputMessages, ...outputMessages]);\n }\n\n async _mergeConfig(...configs: Array<RunnableConfig | undefined>) {\n const config = await super._mergeConfig(...configs);\n // Extract sessionId\n if (!config.configurable || !config.configurable.sessionId) {\n const exampleInput = {\n [this.inputMessagesKey ?? \"input\"]: \"foo\",\n };\n const exampleConfig = { configurable: { sessionId: \"123\" } };\n throw new Error(\n `sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\\n` +\n `eg. chain.invoke(${JSON.stringify(exampleInput)}, ${JSON.stringify(\n exampleConfig\n )})`\n );\n }\n // attach messageHistory\n const { sessionId } = config.configurable;\n config.configurable.messageHistory =\n await this.getMessageHistory(sessionId);\n return config;\n }\n}\n"],"m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,SAAS,IAAI;EAEf,IAAI,gBAAgB,KAAK,kBAAkB,OAAO;AAGlD,MAAI,KAAK,uBAAuB,QAAW;GACzC,MAAM,mBAAmB,MAAM,QAAQ,aAAa;GACpD,gBAAgB,cAAc,MAAM,iBAAiB,OAAO;EAC7D;EAED,MAAM,cAAc,IAAI;AACxB,MAAI,CAAC,YACH,OAAM,IAAI,MACR,CAAC,yCAAyC,EAAE,KAAK,UAC/C,KACA,MACA,EACD,EAAE;EAGP,MAAM,iBAAiB,KAAK,mBAAmB,YAAY;EAC3D,MAAM,QAAQ,YAAY,CAAC,GAAG,eAAe,GAAG,cAAe,EAAC;CACjE;CAED,MAAM,aAAa,GAAG,SAA4C;EAChE,MAAM,SAAS,MAAM,MAAM,aAAa,GAAG,QAAQ;AAEnD,MAAI,CAAC,OAAO,gBAAgB,CAAC,OAAO,aAAa,WAAW;GAC1D,MAAM,eAAe,GAClB,KAAK,oBAAoB,UAAU,MACrC;GACD,MAAM,gBAAgB,EAAE,cAAc,EAAE,WAAW,MAAO,EAAE;AAC5D,SAAM,IAAI,MACR,CAAC,6GAA4F,EACvE,KAAK,UAAU,aAAa,CAAC,EAAE,EAAE,KAAK,UACxD,cACD,CAAC,CAAC,CAAC;EAET;EAED,MAAM,EAAE,WAAW,GAAG,OAAO;EAC7B,OAAO,aAAa,iBAClB,MAAM,KAAK,kBAAkB,UAAU;AACzC,SAAO;CACR;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"history.js","names":["fields: RunnableWithMessageHistoryInputs<RunInput, RunOutput>","historyChain: Runnable","config","inputValue: string | BaseMessage | Array<BaseMessage> | Record<string, any>","outputValue: string | BaseMessage | Array<BaseMessage> | Record<string, any>","input: any","kwargs?: RunnableConfig","run: Run","config: RunnableConfig"],"sources":["../../src/runnables/history.ts"],"sourcesContent":["import {\n BaseChatMessageHistory,\n BaseListChatMessageHistory,\n} from \"../chat_history.js\";\nimport {\n AIMessage,\n BaseMessage,\n HumanMessage,\n isBaseMessage,\n} from \"../messages/index.js\";\nimport { Run } from \"../tracers/base.js\";\nimport {\n Runnable,\n RunnableBinding,\n type RunnableBindingArgs,\n RunnableLambda,\n} from \"./base.js\";\nimport { RunnableConfig } from \"./config.js\";\nimport { RunnablePassthrough } from \"./passthrough.js\";\n\ntype GetSessionHistoryCallable = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...args: Array<any>\n) =>\n | Promise<BaseChatMessageHistory | BaseListChatMessageHistory>\n | BaseChatMessageHistory\n | BaseListChatMessageHistory;\n\nexport interface RunnableWithMessageHistoryInputs<RunInput, RunOutput>\n extends Omit<RunnableBindingArgs<RunInput, RunOutput>, \"bound\" | \"config\"> {\n runnable: Runnable<RunInput, RunOutput>;\n getMessageHistory: GetSessionHistoryCallable;\n inputMessagesKey?: string;\n outputMessagesKey?: string;\n historyMessagesKey?: string;\n config?: RunnableConfig;\n}\n\n/**\n * Wraps a LCEL chain and manages history. It appends input messages\n * and chain outputs as history, and adds the current history messages to\n * the chain input.\n * @example\n * ```typescript\n * // pnpm install @langchain/anthropic @langchain/community @upstash/redis\n *\n * import {\n * ChatPromptTemplate,\n * MessagesPlaceholder,\n * } from \"@langchain/core/prompts\";\n * import { ChatAnthropic } from \"@langchain/anthropic\";\n * import { UpstashRedisChatMessageHistory } from \"@langchain/community/stores/message/upstash_redis\";\n * // For demos, you can also use an in-memory store:\n * // import { ChatMessageHistory } from \"@langchain/classic/stores/message/in_memory\";\n *\n * const prompt = ChatPromptTemplate.fromMessages([\n * [\"system\", \"You're an assistant who's good at {ability}\"],\n * new MessagesPlaceholder(\"history\"),\n * [\"human\", \"{question}\"],\n * ]);\n *\n * const chain = prompt.pipe(new ChatAnthropic({}));\n *\n * const chainWithHistory = new RunnableWithMessageHistory({\n * runnable: chain,\n * getMessageHistory: (sessionId) =>\n * new UpstashRedisChatMessageHistory({\n * sessionId,\n * config: {\n * url: process.env.UPSTASH_REDIS_REST_URL!,\n * token: process.env.UPSTASH_REDIS_REST_TOKEN!,\n * },\n * }),\n * inputMessagesKey: \"question\",\n * historyMessagesKey: \"history\",\n * });\n *\n * const result = await chainWithHistory.invoke(\n * {\n * ability: \"math\",\n * question: \"What does cosine mean?\",\n * },\n * {\n * configurable: {\n * sessionId: \"some_string_identifying_a_user\",\n * },\n * }\n * );\n *\n * const result2 = await chainWithHistory.invoke(\n * {\n * ability: \"math\",\n * question: \"What's its inverse?\",\n * },\n * {\n * configurable: {\n * sessionId: \"some_string_identifying_a_user\",\n * },\n * }\n * );\n * ```\n */\nexport class RunnableWithMessageHistory<\n RunInput,\n RunOutput,\n> extends RunnableBinding<RunInput, RunOutput> {\n runnable: Runnable<RunInput, RunOutput>;\n\n inputMessagesKey?: string;\n\n outputMessagesKey?: string;\n\n historyMessagesKey?: string;\n\n getMessageHistory: GetSessionHistoryCallable;\n\n constructor(fields: RunnableWithMessageHistoryInputs<RunInput, RunOutput>) {\n let historyChain: Runnable = RunnableLambda.from((input, options) =>\n this._enterHistory(input, options ?? {})\n ).withConfig({ runName: \"loadHistory\" });\n\n const messagesKey = fields.historyMessagesKey ?? fields.inputMessagesKey;\n if (messagesKey) {\n historyChain = RunnablePassthrough.assign({\n [messagesKey]: historyChain,\n }).withConfig({ runName: \"insertHistory\" });\n }\n\n const bound = historyChain\n .pipe(\n fields.runnable.withListeners({\n onEnd: (run, config) => this._exitHistory(run, config ?? {}),\n })\n )\n .withConfig({ runName: \"RunnableWithMessageHistory\" });\n\n const config = fields.config ?? {};\n\n super({\n ...fields,\n config,\n bound,\n });\n this.runnable = fields.runnable;\n this.getMessageHistory = fields.getMessageHistory;\n this.inputMessagesKey = fields.inputMessagesKey;\n this.outputMessagesKey = fields.outputMessagesKey;\n this.historyMessagesKey = fields.historyMessagesKey;\n }\n\n _getInputMessages(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputValue: string | BaseMessage | Array<BaseMessage> | Record<string, any>\n ): Array<BaseMessage> {\n let parsedInputValue;\n if (\n typeof inputValue === \"object\" &&\n !Array.isArray(inputValue) &&\n !isBaseMessage(inputValue)\n ) {\n let key;\n if (this.inputMessagesKey) {\n key = this.inputMessagesKey;\n } else if (Object.keys(inputValue).length === 1) {\n key = Object.keys(inputValue)[0];\n } else {\n key = \"input\";\n }\n if (Array.isArray(inputValue[key]) && Array.isArray(inputValue[key][0])) {\n parsedInputValue = inputValue[key][0];\n } else {\n parsedInputValue = inputValue[key];\n }\n } else {\n parsedInputValue = inputValue;\n }\n if (typeof parsedInputValue === \"string\") {\n return [new HumanMessage(parsedInputValue)];\n } else if (Array.isArray(parsedInputValue)) {\n return parsedInputValue;\n } else if (isBaseMessage(parsedInputValue)) {\n return [parsedInputValue];\n } else {\n throw new Error(\n `Expected a string, BaseMessage, or array of BaseMessages.\\nGot ${JSON.stringify(\n parsedInputValue,\n null,\n 2\n )}`\n );\n }\n }\n\n _getOutputMessages(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n outputValue: string | BaseMessage | Array<BaseMessage> | Record<string, any>\n ): Array<BaseMessage> {\n let parsedOutputValue;\n if (\n !Array.isArray(outputValue) &&\n !isBaseMessage(outputValue) &&\n typeof outputValue !== \"string\"\n ) {\n let key;\n if (this.outputMessagesKey !== undefined) {\n key = this.outputMessagesKey;\n } else if (Object.keys(outputValue).length === 1) {\n key = Object.keys(outputValue)[0];\n } else {\n key = \"output\";\n }\n // If you are wrapping a chat model directly\n // The output is actually this weird generations object\n if (outputValue.generations !== undefined) {\n parsedOutputValue = outputValue.generations[0][0].message;\n } else {\n parsedOutputValue = outputValue[key];\n }\n } else {\n parsedOutputValue = outputValue;\n }\n\n if (typeof parsedOutputValue === \"string\") {\n return [new AIMessage(parsedOutputValue)];\n } else if (Array.isArray(parsedOutputValue)) {\n return parsedOutputValue;\n } else if (isBaseMessage(parsedOutputValue)) {\n return [parsedOutputValue];\n } else {\n throw new Error(\n `Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(\n parsedOutputValue,\n null,\n 2\n )}`\n );\n }\n }\n\n async _enterHistory(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any,\n kwargs?: RunnableConfig\n ): Promise<BaseMessage[]> {\n const history = kwargs?.configurable?.messageHistory;\n const messages = await history.getMessages();\n if (this.historyMessagesKey === undefined) {\n return messages.concat(this._getInputMessages(input));\n }\n return messages;\n }\n\n async _exitHistory(run: Run, config: RunnableConfig): Promise<void> {\n const history = config.configurable?.messageHistory;\n\n // Get input messages\n let inputs;\n // Chat model inputs are nested arrays\n if (Array.isArray(run.inputs) && Array.isArray(run.inputs[0])) {\n inputs = run.inputs[0];\n } else {\n inputs = run.inputs;\n }\n let inputMessages = this._getInputMessages(inputs);\n // If historic messages were prepended to the input messages, remove them to\n // avoid adding duplicate messages to history.\n if (this.historyMessagesKey === undefined) {\n const existingMessages = await history.getMessages();\n inputMessages = inputMessages.slice(existingMessages.length);\n }\n // Get output messages\n const outputValue = run.outputs;\n if (!outputValue) {\n throw new Error(\n `Output values from 'Run' undefined. Run: ${JSON.stringify(\n run,\n null,\n 2\n )}`\n );\n }\n const outputMessages = this._getOutputMessages(outputValue);\n await history.addMessages([...inputMessages, ...outputMessages]);\n }\n\n async _mergeConfig(...configs: Array<RunnableConfig | undefined>) {\n const config = await super._mergeConfig(...configs);\n // Extract sessionId\n if (!config.configurable || !config.configurable.sessionId) {\n const exampleInput = {\n [this.inputMessagesKey ?? \"input\"]: \"foo\",\n };\n const exampleConfig = { configurable: { sessionId: \"123\" } };\n throw new Error(\n `sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\\n` +\n `eg. chain.invoke(${JSON.stringify(exampleInput)}, ${JSON.stringify(\n exampleConfig\n )})`\n );\n }\n // attach messageHistory\n const { sessionId } = config.configurable;\n config.configurable.messageHistory =\n await this.getMessageHistory(sessionId);\n return config;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsGA,IAAa,6BAA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Aa;GACpD,gBAAgB,cAAc,MAAM,iBAAiB,OAAO;EAC7D;EAED,MAAM,cAAc,IAAI;AACxB,MAAI,CAAC,YACH,OAAM,IAAI,MACR,CAAC,yCAAyC,EAAE,KAAK,UAC/C,KACA,MACA,EACD,EAAE;EAGP,MAAM,iBAAiB,KAAK,mBAAmB,YAAY;EAC3D,MAAM,QAAQ,YAAY,CAAC,GAAG,eAAe,GAAG,cAAe,EAAC;CACjE;CAED,MAAM,aAAa,GAAG,SAA4C;EAChE,MAAM,SAAS,MAAM,MAAM,aAAa,GAAG,QAAQ;AAEnD,MAAI,CAAC,OAAO,gBAAgB,CAAC,OAAO,aAAa,WAAW;GAC1D,MAAM,eAAe,GAClB,KAAK,oBAAoB,UAAU,MACrC;GACD,MAAM,gBAAgB,EAAE,cAAc,EAAE,WAAW,MAAO,EAAE;AAC5D,SAAM,IAAI,MACR,CAAC,6GAA4F,EACvE,KAAK,UAAU,aAAa,CAAC,EAAE,EAAE,KAAK,UACxD,cACD,CAAC,CAAC,CAAC;EAET;EAED,MAAM,EAAE,WAAW,GAAG,OAAO;EAC7B,OAAO,aAAa,iBAClB,MAAM,KAAK,kBAAkB,UAAU;AACzC,SAAO;CACR;AACF"}
|
|
1
|
+
{"version":3,"file":"history.js","names":["fields: RunnableWithMessageHistoryInputs<RunInput, RunOutput>","historyChain: Runnable","config","inputValue: string | BaseMessage | Array<BaseMessage> | Record<string, any>","outputValue: string | BaseMessage | Array<BaseMessage> | Record<string, any>","input: any","kwargs?: RunnableConfig","run: Run","config: RunnableConfig"],"sources":["../../src/runnables/history.ts"],"sourcesContent":["import {\n BaseChatMessageHistory,\n BaseListChatMessageHistory,\n} from \"../chat_history.js\";\nimport {\n AIMessage,\n BaseMessage,\n HumanMessage,\n isBaseMessage,\n} from \"../messages/index.js\";\nimport { Run } from \"../tracers/base.js\";\nimport {\n Runnable,\n RunnableBinding,\n type RunnableBindingArgs,\n RunnableLambda,\n} from \"./base.js\";\nimport { RunnableConfig } from \"./config.js\";\nimport { RunnablePassthrough } from \"./passthrough.js\";\n\ntype GetSessionHistoryCallable = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...args: Array<any>\n) =>\n | Promise<BaseChatMessageHistory | BaseListChatMessageHistory>\n | BaseChatMessageHistory\n | BaseListChatMessageHistory;\n\nexport interface RunnableWithMessageHistoryInputs<\n RunInput,\n RunOutput,\n> extends Omit<RunnableBindingArgs<RunInput, RunOutput>, \"bound\" | \"config\"> {\n runnable: Runnable<RunInput, RunOutput>;\n getMessageHistory: GetSessionHistoryCallable;\n inputMessagesKey?: string;\n outputMessagesKey?: string;\n historyMessagesKey?: string;\n config?: RunnableConfig;\n}\n\n/**\n * Wraps a LCEL chain and manages history. It appends input messages\n * and chain outputs as history, and adds the current history messages to\n * the chain input.\n * @example\n * ```typescript\n * // pnpm install @langchain/anthropic @langchain/community @upstash/redis\n *\n * import {\n * ChatPromptTemplate,\n * MessagesPlaceholder,\n * } from \"@langchain/core/prompts\";\n * import { ChatAnthropic } from \"@langchain/anthropic\";\n * import { UpstashRedisChatMessageHistory } from \"@langchain/community/stores/message/upstash_redis\";\n * // For demos, you can also use an in-memory store:\n * // import { ChatMessageHistory } from \"@langchain/classic/stores/message/in_memory\";\n *\n * const prompt = ChatPromptTemplate.fromMessages([\n * [\"system\", \"You're an assistant who's good at {ability}\"],\n * new MessagesPlaceholder(\"history\"),\n * [\"human\", \"{question}\"],\n * ]);\n *\n * const chain = prompt.pipe(new ChatAnthropic({}));\n *\n * const chainWithHistory = new RunnableWithMessageHistory({\n * runnable: chain,\n * getMessageHistory: (sessionId) =>\n * new UpstashRedisChatMessageHistory({\n * sessionId,\n * config: {\n * url: process.env.UPSTASH_REDIS_REST_URL!,\n * token: process.env.UPSTASH_REDIS_REST_TOKEN!,\n * },\n * }),\n * inputMessagesKey: \"question\",\n * historyMessagesKey: \"history\",\n * });\n *\n * const result = await chainWithHistory.invoke(\n * {\n * ability: \"math\",\n * question: \"What does cosine mean?\",\n * },\n * {\n * configurable: {\n * sessionId: \"some_string_identifying_a_user\",\n * },\n * }\n * );\n *\n * const result2 = await chainWithHistory.invoke(\n * {\n * ability: \"math\",\n * question: \"What's its inverse?\",\n * },\n * {\n * configurable: {\n * sessionId: \"some_string_identifying_a_user\",\n * },\n * }\n * );\n * ```\n */\nexport class RunnableWithMessageHistory<\n RunInput,\n RunOutput,\n> extends RunnableBinding<RunInput, RunOutput> {\n runnable: Runnable<RunInput, RunOutput>;\n\n inputMessagesKey?: string;\n\n outputMessagesKey?: string;\n\n historyMessagesKey?: string;\n\n getMessageHistory: GetSessionHistoryCallable;\n\n constructor(fields: RunnableWithMessageHistoryInputs<RunInput, RunOutput>) {\n let historyChain: Runnable = RunnableLambda.from((input, options) =>\n this._enterHistory(input, options ?? {})\n ).withConfig({ runName: \"loadHistory\" });\n\n const messagesKey = fields.historyMessagesKey ?? fields.inputMessagesKey;\n if (messagesKey) {\n historyChain = RunnablePassthrough.assign({\n [messagesKey]: historyChain,\n }).withConfig({ runName: \"insertHistory\" });\n }\n\n const bound = historyChain\n .pipe(\n fields.runnable.withListeners({\n onEnd: (run, config) => this._exitHistory(run, config ?? {}),\n })\n )\n .withConfig({ runName: \"RunnableWithMessageHistory\" });\n\n const config = fields.config ?? {};\n\n super({\n ...fields,\n config,\n bound,\n });\n this.runnable = fields.runnable;\n this.getMessageHistory = fields.getMessageHistory;\n this.inputMessagesKey = fields.inputMessagesKey;\n this.outputMessagesKey = fields.outputMessagesKey;\n this.historyMessagesKey = fields.historyMessagesKey;\n }\n\n _getInputMessages(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputValue: string | BaseMessage | Array<BaseMessage> | Record<string, any>\n ): Array<BaseMessage> {\n let parsedInputValue;\n if (\n typeof inputValue === \"object\" &&\n !Array.isArray(inputValue) &&\n !isBaseMessage(inputValue)\n ) {\n let key;\n if (this.inputMessagesKey) {\n key = this.inputMessagesKey;\n } else if (Object.keys(inputValue).length === 1) {\n key = Object.keys(inputValue)[0];\n } else {\n key = \"input\";\n }\n if (Array.isArray(inputValue[key]) && Array.isArray(inputValue[key][0])) {\n parsedInputValue = inputValue[key][0];\n } else {\n parsedInputValue = inputValue[key];\n }\n } else {\n parsedInputValue = inputValue;\n }\n if (typeof parsedInputValue === \"string\") {\n return [new HumanMessage(parsedInputValue)];\n } else if (Array.isArray(parsedInputValue)) {\n return parsedInputValue;\n } else if (isBaseMessage(parsedInputValue)) {\n return [parsedInputValue];\n } else {\n throw new Error(\n `Expected a string, BaseMessage, or array of BaseMessages.\\nGot ${JSON.stringify(\n parsedInputValue,\n null,\n 2\n )}`\n );\n }\n }\n\n _getOutputMessages(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n outputValue: string | BaseMessage | Array<BaseMessage> | Record<string, any>\n ): Array<BaseMessage> {\n let parsedOutputValue;\n if (\n !Array.isArray(outputValue) &&\n !isBaseMessage(outputValue) &&\n typeof outputValue !== \"string\"\n ) {\n let key;\n if (this.outputMessagesKey !== undefined) {\n key = this.outputMessagesKey;\n } else if (Object.keys(outputValue).length === 1) {\n key = Object.keys(outputValue)[0];\n } else {\n key = \"output\";\n }\n // If you are wrapping a chat model directly\n // The output is actually this weird generations object\n if (outputValue.generations !== undefined) {\n parsedOutputValue = outputValue.generations[0][0].message;\n } else {\n parsedOutputValue = outputValue[key];\n }\n } else {\n parsedOutputValue = outputValue;\n }\n\n if (typeof parsedOutputValue === \"string\") {\n return [new AIMessage(parsedOutputValue)];\n } else if (Array.isArray(parsedOutputValue)) {\n return parsedOutputValue;\n } else if (isBaseMessage(parsedOutputValue)) {\n return [parsedOutputValue];\n } else {\n throw new Error(\n `Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(\n parsedOutputValue,\n null,\n 2\n )}`\n );\n }\n }\n\n async _enterHistory(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any,\n kwargs?: RunnableConfig\n ): Promise<BaseMessage[]> {\n const history = kwargs?.configurable?.messageHistory;\n const messages = await history.getMessages();\n if (this.historyMessagesKey === undefined) {\n return messages.concat(this._getInputMessages(input));\n }\n return messages;\n }\n\n async _exitHistory(run: Run, config: RunnableConfig): Promise<void> {\n const history = config.configurable?.messageHistory;\n\n // Get input messages\n let inputs;\n // Chat model inputs are nested arrays\n if (Array.isArray(run.inputs) && Array.isArray(run.inputs[0])) {\n inputs = run.inputs[0];\n } else {\n inputs = run.inputs;\n }\n let inputMessages = this._getInputMessages(inputs);\n // If historic messages were prepended to the input messages, remove them to\n // avoid adding duplicate messages to history.\n if (this.historyMessagesKey === undefined) {\n const existingMessages = await history.getMessages();\n inputMessages = inputMessages.slice(existingMessages.length);\n }\n // Get output messages\n const outputValue = run.outputs;\n if (!outputValue) {\n throw new Error(\n `Output values from 'Run' undefined. Run: ${JSON.stringify(\n run,\n null,\n 2\n )}`\n );\n }\n const outputMessages = this._getOutputMessages(outputValue);\n await history.addMessages([...inputMessages, ...outputMessages]);\n }\n\n async _mergeConfig(...configs: Array<RunnableConfig | undefined>) {\n const config = await super._mergeConfig(...configs);\n // Extract sessionId\n if (!config.configurable || !config.configurable.sessionId) {\n const exampleInput = {\n [this.inputMessagesKey ?? \"input\"]: \"foo\",\n };\n const exampleConfig = { configurable: { sessionId: \"123\" } };\n throw new Error(\n `sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\\n` +\n `eg. chain.invoke(${JSON.stringify(exampleInput)}, ${JSON.stringify(\n exampleConfig\n )})`\n );\n }\n // attach messageHistory\n const { sessionId } = config.configurable;\n config.configurable.messageHistory =\n await this.getMessageHistory(sessionId);\n return config;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwGA,IAAa,6BAAb,cAGU,gBAAqC;CAC7C;CAEA;CAEA;CAEA;CAEA;CAEA,YAAYA,QAA+D;EACzE,IAAIC,eAAyB,eAAe,KAAK,CAAC,OAAO,YACvD,KAAK,cAAc,OAAO,WA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,UAC/C,KACA,MACA,EACD,EAAE;EAGP,MAAM,iBAAiB,KAAK,mBAAmB,YAAY;EAC3D,MAAM,QAAQ,YAAY,CAAC,GAAG,eAAe,GAAG,cAAe,EAAC;CACjE;CAED,MAAM,aAAa,GAAG,SAA4C;EAChE,MAAM,SAAS,MAAM,MAAM,aAAa,GAAG,QAAQ;AAEnD,MAAI,CAAC,OAAO,gBAAgB,CAAC,OAAO,aAAa,WAAW;GAC1D,MAAM,eAAe,GAClB,KAAK,oBAAoB,UAAU,MACrC;GACD,MAAM,gBAAgB,EAAE,cAAc,EAAE,WAAW,MAAO,EAAE;AAC5D,SAAM,IAAI,MACR,CAAC,6GAA4F,EACvE,KAAK,UAAU,aAAa,CAAC,EAAE,EAAE,KAAK,UACxD,cACD,CAAC,CAAC,CAAC;EAET;EAED,MAAM,EAAE,WAAW,GAAG,OAAO;EAC7B,OAAO,aAAa,iBAClB,MAAM,KAAK,kBAAkB,UAAU;AACzC,SAAO;CACR;AACF"}
|
package/dist/stores.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stores.d.ts","names":["Serializable","BaseStore","K","V","Promise","AsyncGenerator","InMemoryStore","T","Record"],"sources":["../src/stores.d.ts"],"sourcesContent":["import { Serializable } from \"./load/serializable.js\";\n/**\n * Abstract interface for a key-value store.\n */\nexport declare abstract class BaseStore<K, V> extends Serializable {\n /**\n * Abstract method to get multiple values for a set of keys.\n * @param {K[]} keys - An array of keys.\n * @returns {Promise<(V | undefined)[]>} - A Promise that resolves with array of values or undefined if key not found.\n */\n abstract mget(keys: K[]): Promise<(V | undefined)[]>;\n /**\n * Abstract method to set a value for multiple keys.\n * @param {[K, V][]} keyValuePairs - An array of key-value pairs.\n * @returns {Promise<void>} - A Promise that resolves when the operation is complete.\n */\n abstract mset(keyValuePairs: [K, V][]): Promise<void>;\n /**\n * Abstract method to delete multiple keys.\n * @param {K[]} keys - An array of keys to delete.\n * @returns {Promise<void>} - A Promise that resolves when the operation is complete.\n */\n abstract mdelete(keys: K[]): Promise<void>;\n /**\n * Abstract method to yield keys optionally based on a prefix.\n * @param {string} prefix - Optional prefix to filter keys.\n * @returns {AsyncGenerator<K | string>} - An asynchronous generator that yields keys on iteration.\n */\n abstract yieldKeys(prefix?: string): AsyncGenerator<K | string>;\n}\n/**\n * In-memory implementation of the BaseStore using a dictionary. Used for\n * storing key-value pairs in memory.\n * @example\n * ```typescript\n * const store = new InMemoryStore<BaseMessage>();\n * await store.mset(\n * Array.from({ length: 5 }).map((_, index) => [\n * `message:id:${index}`,\n * index % 2 === 0\n * ? new AIMessage(\"ai stuff...\")\n * : new HumanMessage(\"human stuff...\"),\n * ]),\n * );\n *\n * const retrievedMessages = await store.mget([\"message:id:0\", \"message:id:1\"]);\n * await store.mdelete(await store.yieldKeys(\"message:id:\").toArray());\n * ```\n */\nexport declare class InMemoryStore<T = any> extends BaseStore<string, T> {\n lc_namespace: string[];\n protected store: Record<string, T>;\n /**\n * Retrieves the values associated with the given keys from the store.\n * @param keys Keys to retrieve values for.\n * @returns Array of values associated with the given keys.\n */\n mget(keys: string[]): Promise<T[]>;\n /**\n * Sets the values for the given keys in the store.\n * @param keyValuePairs Array of key-value pairs to set in the store.\n * @returns Promise that resolves when all key-value pairs have been set.\n */\n mset(keyValuePairs: [string, T][]): Promise<void>;\n /**\n * Deletes the given keys and their associated values from the store.\n * @param keys Keys to delete from the store.\n * @returns Promise that resolves when all keys have been deleted.\n */\n mdelete(keys: string[]): Promise<void>;\n /**\n * Asynchronous generator that yields keys from the store. If a prefix is\n * provided, it only yields keys that start with the prefix.\n * @param prefix Optional prefix to filter keys.\n * @returns AsyncGenerator that yields keys from the store.\n */\n yieldKeys(prefix?: string | undefined): AsyncGenerator<string>;\n}\n//# sourceMappingURL=stores.d.ts.map"],"mappings":";;;;;;AAIA;AAMwBE,uBANMD,SAMNC,CAAAA,CAAAA,EAAAA,CAAAA,CAAAA,SAN8BF,YAAAA,CAM9BE;EAAeC;;;;;EAYZD,SAAAA,IAAAA,CAAAA,IAAAA,EAZHA,CAYGA,EAAAA,CAAAA,EAZGE,OAYHF,CAAAA,CAZYC,CAYZD,GAAAA,SAAAA,CAAAA,EAAAA,CAAAA;EAAME;;;;AAlBiC;EA6C7CE,SAAAA,IAAAA,CAAAA,
|
|
1
|
+
{"version":3,"file":"stores.d.ts","names":["Serializable","BaseStore","K","V","Promise","AsyncGenerator","InMemoryStore","T","Record"],"sources":["../src/stores.d.ts"],"sourcesContent":["import { Serializable } from \"./load/serializable.js\";\n/**\n * Abstract interface for a key-value store.\n */\nexport declare abstract class BaseStore<K, V> extends Serializable {\n /**\n * Abstract method to get multiple values for a set of keys.\n * @param {K[]} keys - An array of keys.\n * @returns {Promise<(V | undefined)[]>} - A Promise that resolves with array of values or undefined if key not found.\n */\n abstract mget(keys: K[]): Promise<(V | undefined)[]>;\n /**\n * Abstract method to set a value for multiple keys.\n * @param {[K, V][]} keyValuePairs - An array of key-value pairs.\n * @returns {Promise<void>} - A Promise that resolves when the operation is complete.\n */\n abstract mset(keyValuePairs: [K, V][]): Promise<void>;\n /**\n * Abstract method to delete multiple keys.\n * @param {K[]} keys - An array of keys to delete.\n * @returns {Promise<void>} - A Promise that resolves when the operation is complete.\n */\n abstract mdelete(keys: K[]): Promise<void>;\n /**\n * Abstract method to yield keys optionally based on a prefix.\n * @param {string} prefix - Optional prefix to filter keys.\n * @returns {AsyncGenerator<K | string>} - An asynchronous generator that yields keys on iteration.\n */\n abstract yieldKeys(prefix?: string): AsyncGenerator<K | string>;\n}\n/**\n * In-memory implementation of the BaseStore using a dictionary. Used for\n * storing key-value pairs in memory.\n * @example\n * ```typescript\n * const store = new InMemoryStore<BaseMessage>();\n * await store.mset(\n * Array.from({ length: 5 }).map((_, index) => [\n * `message:id:${index}`,\n * index % 2 === 0\n * ? new AIMessage(\"ai stuff...\")\n * : new HumanMessage(\"human stuff...\"),\n * ]),\n * );\n *\n * const retrievedMessages = await store.mget([\"message:id:0\", \"message:id:1\"]);\n * await store.mdelete(await store.yieldKeys(\"message:id:\").toArray());\n * ```\n */\nexport declare class InMemoryStore<T = any> extends BaseStore<string, T> {\n lc_namespace: string[];\n protected store: Record<string, T>;\n /**\n * Retrieves the values associated with the given keys from the store.\n * @param keys Keys to retrieve values for.\n * @returns Array of values associated with the given keys.\n */\n mget(keys: string[]): Promise<T[]>;\n /**\n * Sets the values for the given keys in the store.\n * @param keyValuePairs Array of key-value pairs to set in the store.\n * @returns Promise that resolves when all key-value pairs have been set.\n */\n mset(keyValuePairs: [string, T][]): Promise<void>;\n /**\n * Deletes the given keys and their associated values from the store.\n * @param keys Keys to delete from the store.\n * @returns Promise that resolves when all keys have been deleted.\n */\n mdelete(keys: string[]): Promise<void>;\n /**\n * Asynchronous generator that yields keys from the store. If a prefix is\n * provided, it only yields keys that start with the prefix.\n * @param prefix Optional prefix to filter keys.\n * @returns AsyncGenerator that yields keys from the store.\n */\n yieldKeys(prefix?: string | undefined): AsyncGenerator<string>;\n}\n//# sourceMappingURL=stores.d.ts.map"],"mappings":";;;;;;AAIA;AAMwBE,uBANMD,SAMNC,CAAAA,CAAAA,EAAAA,CAAAA,CAAAA,SAN8BF,YAAAA,CAM9BE;EAAeC;;;;;EAYZD,SAAAA,IAAAA,CAAAA,IAAAA,EAZHA,CAYGA,EAAAA,CAAAA,EAZGE,OAYHF,CAAAA,CAZYC,CAYZD,GAAAA,SAAAA,CAAAA,EAAAA,CAAAA;EAAME;;;;AAlBiC;EA6C7CE,SAAAA,IAAAA,CAAAA,aAAa,EAAA,CAjCAJ,CAiCA,EAjCGC,CAiCH,CAAA,EAAA,CAAA,EAjCUC,OAiCV,CAAA,IAAA,CAAA;EAAoCG;;;;;EAcrCA,SAAAA,OAAAA,CAAAA,IAAAA,EAzCNL,CAyCMK,EAAAA,CAAAA,EAzCAH,OAyCAG,CAAAA,IAAAA,CAAAA;EAAOH;;;;AAdqB;uCArBpBC,eAAeH;;;;;;;;;;;;;;;;;;;;;cAqBnCI,+BAA+BL,kBAAkBM;;mBAEjDC,eAAeD;;;;;;wBAMVH,QAAQG;;;;;;+BAMDA,OAAOH;;;;;;2BAMXA;;;;;;;0CAOeC"}
|
package/dist/tools/index.cjs
CHANGED
|
@@ -292,7 +292,7 @@ function tool(func, fields) {
|
|
|
292
292
|
cleanup();
|
|
293
293
|
reject(require_signal.getAbortSignalError(config.signal));
|
|
294
294
|
};
|
|
295
|
-
config.signal.addEventListener("abort", listener);
|
|
295
|
+
config.signal.addEventListener("abort", listener, { once: true });
|
|
296
296
|
}
|
|
297
297
|
const childConfig = require_config.patchConfig(config, { callbacks: runManager?.getChild() });
|
|
298
298
|
require_index.AsyncLocalStorageProviderSingleton.runWithConfig(require_config.pickRunnableConfigKeys(childConfig), async () => {
|
package/dist/tools/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["BaseLangChain","fields?: ToolParams","input: TInput","config?: TConfig","toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >","enrichedConfig: ToolRunnableConfig","ensureConfig","mergeConfigs","_isToolCall","arg: TArg","configArg?: TConfig","tags?: string[]","parsed: SchemaOutputT","isInteropZodSchema","interopParseAsync","isInteropZodError","z4","ToolInputParsingException","result","parseCallbackConfigArg","CallbackManager","toolCallId: string | undefined","_configHasToolCallId","z","callbacks?: TConfig","fields: DynamicToolInput<ToolOutputT>","input: string","runManager?: CallbackManagerForToolRun","parentConfig?: ToolRunnableConfig","fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT> & {\n name: NameT;\n }","arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0]","parentConfig?: RunnableConfig","func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>","fields: ToolWrapperParams<SchemaT, NameT>","isSimpleStringZodSchema","validatesOnlyStrings","patchConfig","AsyncLocalStorageProviderSingleton","pickRunnableConfigKeys","listener: (() => void) | undefined","getAbortSignalError","params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}","isDirectToolOutput","ToolMessage","content: unknown"],"sources":["../../src/tools/index.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { z as z4, ZodError } from \"zod/v4\";\nimport {\n validate,\n type Schema as ValidationSchema,\n} from \"@cfworker/json-schema\";\nimport {\n CallbackManager,\n CallbackManagerForToolRun,\n parseCallbackConfigArg,\n} from \"../callbacks/manager.js\";\nimport { BaseLangChain } from \"../language_models/base.js\";\nimport {\n mergeConfigs,\n ensureConfig,\n patchConfig,\n pickRunnableConfigKeys,\n type RunnableConfig,\n} from \"../runnables/config.js\";\nimport type { RunnableFunc } from \"../runnables/base.js\";\nimport { isDirectToolOutput, ToolCall, ToolMessage } from \"../messages/tool.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../singletons/index.js\";\nimport type { RunnableToolLike } from \"../runnables/base.js\";\nimport {\n _configHasToolCallId,\n _isToolCall,\n ToolInputParsingException,\n} from \"./utils.js\";\nimport {\n type InferInteropZodInput,\n type InferInteropZodOutput,\n type InteropZodObject,\n type InteropZodType,\n interopParseAsync,\n isSimpleStringZodSchema,\n isInteropZodError,\n isInteropZodSchema,\n type ZodStringV3,\n type ZodStringV4,\n type ZodObjectV3,\n type ZodObjectV4,\n} from \"../utils/types/zod.js\";\nimport { getAbortSignalError } from \"../utils/signal.js\";\nimport type {\n StructuredToolCallInput,\n ToolInputSchemaBase,\n ToolReturnType,\n ResponseFormat,\n ToolInputSchemaInputType,\n ToolInputSchemaOutputType,\n ToolParams,\n ToolRunnableConfig,\n StructuredToolInterface,\n DynamicToolInput,\n DynamicStructuredToolInput,\n StringInputToolSchema,\n ToolInterface,\n ToolOutputType,\n ToolRuntime,\n} from \"./types.js\";\nimport { type JSONSchema, validatesOnlyStrings } from \"../utils/json_schema.js\";\n\nexport type {\n BaseDynamicToolInput,\n ContentAndArtifact,\n DynamicToolInput,\n DynamicStructuredToolInput,\n ResponseFormat,\n StructuredToolCallInput,\n StructuredToolInterface,\n StructuredToolParams,\n ToolInterface,\n ToolParams,\n ToolReturnType,\n ToolRunnableConfig,\n ToolInputSchemaBase as ToolSchemaBase,\n} from \"./types.js\";\n\nexport {\n isLangChainTool,\n isRunnableToolLike,\n isStructuredTool,\n isStructuredToolParams,\n type ToolRuntime,\n} from \"./types.js\";\n\nexport { ToolInputParsingException };\n/**\n * Base class for Tools that accept input of any shape defined by a Zod schema.\n */\nexport abstract class StructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n >\n extends BaseLangChain<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolOutputT | ToolMessage\n >\n implements StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT>\n{\n abstract name: string;\n\n abstract description: string;\n\n abstract schema: SchemaT;\n\n /**\n * Optional provider-specific extra fields for the tool.\n *\n * This is used to pass provider-specific configuration that doesn't fit into\n * standard tool fields.\n */\n extras?: Record<string, unknown>;\n\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect = false;\n\n verboseParsingErrors = false;\n\n get lc_namespace() {\n return [\"langchain\", \"tools\"];\n }\n\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat = \"content\";\n\n /**\n * Default config object for the tool runnable.\n */\n defaultConfig?: ToolRunnableConfig;\n\n constructor(fields?: ToolParams) {\n super(fields ?? {});\n\n this.verboseParsingErrors =\n fields?.verboseParsingErrors ?? this.verboseParsingErrors;\n this.responseFormat = fields?.responseFormat ?? this.responseFormat;\n this.defaultConfig = fields?.defaultConfig ?? this.defaultConfig;\n this.metadata = fields?.metadata ?? this.metadata;\n this.extras = fields?.extras ?? this.extras;\n }\n\n protected abstract _call(\n arg: SchemaOutputT,\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT>;\n\n /**\n * Invokes the tool with the provided input and configuration.\n * @param input The input for the tool.\n * @param config Optional configuration for the tool.\n * @returns A Promise that resolves with the tool's output.\n */\n async invoke<\n TInput extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n input: TInput,\n config?: TConfig\n ): Promise<ToolReturnType<TInput, TConfig, ToolOutputT>> {\n let toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n\n let enrichedConfig: ToolRunnableConfig = ensureConfig(\n mergeConfigs(this.defaultConfig, config)\n );\n if (_isToolCall(input)) {\n toolInput = input.args as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n enrichedConfig = {\n ...enrichedConfig,\n toolCall: input,\n };\n } else {\n toolInput = input as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n }\n\n return this.call(toolInput, enrichedConfig) as Promise<\n ToolReturnType<TInput, TConfig, ToolOutputT>\n >;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument, configuration, and tags. It\n * parses the input according to the schema, handles any errors, and\n * manages callbacks.\n * @param arg The input argument for the tool.\n * @param configArg Optional configuration or callbacks for the tool.\n * @param tags Optional tags for the tool.\n * @returns A Promise that resolves with a string.\n */\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>> {\n // Determine the actual input that needs parsing/validation.\n // If arg is a ToolCall, use its args; otherwise, use arg directly.\n const inputForValidation = _isToolCall(arg) ? arg.args : arg;\n\n let parsed: SchemaOutputT; // This will hold the successfully parsed input of the expected output type.\n if (isInteropZodSchema(this.schema)) {\n try {\n // Validate the inputForValidation - TS needs help here as it can't exclude ToolCall based on the check\n parsed = await interopParseAsync(\n this.schema as InteropZodType,\n inputForValidation as Exclude<TArg, ToolCall>\n );\n } catch (e) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${(e as Error).message}`;\n }\n if (isInteropZodError(e)) {\n message = `${message}\\n\\n${z4.prettifyError(e as ZodError)}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n } else {\n const result = validate(\n inputForValidation,\n this.schema as ValidationSchema\n );\n if (!result.valid) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${result.errors\n .map((e) => `${e.keywordLocation}: ${e.error}`)\n .join(\"\\n\")}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n // Assign the validated input to parsed\n // We cast here because validate() doesn't narrow the type sufficiently for TS, but we know it's valid.\n parsed = inputForValidation as SchemaOutputT;\n }\n\n const config = parseCallbackConfigArg(configArg);\n const callbackManager_ = CallbackManager.configure(\n config.callbacks,\n this.callbacks,\n config.tags || tags,\n this.tags,\n config.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n const runManager = await callbackManager_?.handleToolStart(\n this.toJSON(),\n // Log the original raw input arg\n typeof arg === \"string\" ? arg : JSON.stringify(arg),\n config.runId,\n undefined,\n undefined,\n undefined,\n config.runName\n );\n delete config.runId;\n let result;\n try {\n // Pass the correctly typed parsed input to _call\n result = await this._call(parsed, runManager, config);\n } catch (e) {\n await runManager?.handleToolError(e);\n throw e;\n }\n let content;\n let artifact;\n if (this.responseFormat === \"content_and_artifact\") {\n if (Array.isArray(result) && result.length === 2) {\n [content, artifact] = result;\n } else {\n throw new Error(\n `Tool response format is \"content_and_artifact\" but the output was not a two-tuple.\\nResult: ${JSON.stringify(\n result\n )}`\n );\n }\n } else {\n content = result;\n }\n\n let toolCallId: string | undefined;\n // Extract toolCallId ONLY if the original arg was a ToolCall\n if (_isToolCall(arg)) {\n toolCallId = arg.id;\n }\n // Or if it was provided in the config's toolCall property\n if (!toolCallId && _configHasToolCallId(config)) {\n toolCallId = config.toolCall.id;\n }\n\n const formattedOutput = _formatToolOutput<ToolOutputT>({\n content,\n artifact,\n toolCallId,\n name: this.name,\n metadata: this.metadata,\n });\n await runManager?.handleToolEnd(formattedOutput);\n return formattedOutput as ToolReturnType<TArg, TConfig, ToolOutputT>;\n }\n}\n\n/**\n * Base class for Tools that accept input as a string.\n */\nexport abstract class Tool<ToolOutputT = ToolOutputType>\n extends StructuredTool<\n StringInputToolSchema,\n ToolInputSchemaOutputType<StringInputToolSchema>,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n implements\n ToolInterface<\n StringInputToolSchema,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n{\n schema = z\n .object({ input: z.string().optional() })\n .transform((obj) => obj.input);\n\n constructor(fields?: ToolParams) {\n super(fields);\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument and callbacks. It handles\n * string inputs specifically.\n * @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema.\n * @param callbacks Optional callbacks for the tool.\n * @returns A Promise that resolves with a string.\n */\n // Match the base class signature including the generics and conditional return type\n call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n callbacks?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n // Prepare the input for the base class call method.\n // If arg is string or undefined, wrap it; otherwise, pass ToolCall or { input: ... } directly.\n const structuredArg =\n typeof arg === \"string\" || arg == null ? { input: arg } : arg;\n\n // Ensure TConfig is passed to super.call\n return super.call(structuredArg, callbacks);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and description.\n */\nexport class DynamicTool<\n ToolOutputT = ToolOutputType,\n> extends Tool<ToolOutputT> {\n static lc_name() {\n return \"DynamicTool\";\n }\n\n name: string;\n\n description: string;\n\n func: DynamicToolInput<ToolOutputT>[\"func\"];\n\n constructor(fields: DynamicToolInput<ToolOutputT>) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n async call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n // Call the Tool class's call method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig);\n }\n\n /** @ignore */\n async _call(\n input: string, // DynamicTool's _call specifically expects a string after schema transformation\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT> {\n return this.func(input, runManager, parentConfig);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and\n * description, designed to work with structured data. It extends the\n * StructuredTool class and overrides the _call method to execute the\n * provided function when the tool is called.\n *\n * Schema can be passed as Zod or JSON schema. The tool will not validate\n * input if JSON schema is passed.\n *\n * @template SchemaT The input schema type for the tool (Zod schema or JSON schema). Defaults to `ToolInputSchemaBase`.\n * @template SchemaOutputT The output type derived from the schema after parsing/validation. Defaults to `ToolInputSchemaOutputType<SchemaT>`.\n * @template SchemaInputT The input type derived from the schema before parsing. Defaults to `ToolInputSchemaInputType<SchemaT>`.\n * @template ToolOutputT The return type of the tool's function. Defaults to `ToolOutputType`.\n * @template NameT The literal type of the tool name (for discriminated union support). Defaults to `string`.\n */\nexport class DynamicStructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n NameT extends string = string,\n> extends StructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT> {\n static lc_name() {\n return \"DynamicStructuredTool\";\n }\n\n declare name: NameT;\n\n description: string;\n\n func: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>[\"func\"];\n\n schema: SchemaT;\n\n constructor(\n fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT> & {\n name: NameT;\n }\n ) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n this.schema = fields.schema;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n // Match the base class signature\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n\n // Call the base class method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig, tags);\n }\n\n protected _call(\n arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0],\n runManager?: CallbackManagerForToolRun,\n parentConfig?: RunnableConfig\n ): Promise<ToolOutputT> {\n return this.func(arg, runManager, parentConfig);\n }\n}\n\n/**\n * Abstract base class for toolkits in LangChain. Toolkits are collections\n * of tools that agents can use. Subclasses must implement the `tools`\n * property to provide the specific tools for the toolkit.\n */\nexport abstract class BaseToolkit {\n abstract tools: StructuredToolInterface[];\n\n getTools(): StructuredToolInterface[] {\n return this.tools;\n }\n}\n\n/**\n * Parameters for the tool function.\n * Schema can be provided as Zod or JSON schema.\n * Both schema types will be validated.\n * @template {ToolInputSchemaBase} RunInput The input schema for the tool.\n * @template {string} NameT The literal name type for discriminated union support.\n */\ninterface ToolWrapperParams<\n RunInput = ToolInputSchemaBase | undefined,\n NameT extends string = string,\n> extends ToolParams {\n /**\n * The name of the tool. If using with an LLM, this\n * will be passed as the tool name.\n */\n name: NameT;\n /**\n * The description of the tool.\n * @default `${fields.name} tool`\n */\n description?: string;\n /**\n * The input schema for the tool. If using an LLM, this\n * will be passed as the tool schema to generate arguments\n * for.\n */\n schema?: RunInput;\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat;\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect?: boolean;\n}\n\n/**\n * Creates a new StructuredTool instance with the provided function, name, description, and schema.\n *\n * Schema can be provided as Zod or JSON schema, and both will be validated.\n *\n * @function\n * @template {ToolInputSchemaBase} SchemaT The input schema for the tool.\n * @template {ToolReturnType} ToolOutputT The output type of the tool.\n *\n * @param {RunnableFunc<z.output<SchemaT>, ToolOutputT>} func - The function to invoke when the tool is called.\n * @param {ToolWrapperParams<SchemaT>} fields - An object containing the following properties:\n * @param {string} fields.name The name of the tool.\n * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.\n * @param {z.AnyZodObject | z.ZodString | undefined} fields.schema The Zod schema defining the input for the tool. If undefined, it will default to a Zod string schema.\n *\n * @returns {DynamicStructuredTool<SchemaT>} A new StructuredTool instance.\n */\nexport function tool<SchemaT extends ZodStringV3, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<SchemaT extends ZodStringV4, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n NameT extends string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n>(\n func: RunnableFunc<\n Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends\n | InteropZodObject\n | InteropZodType<string>\n | JSONSchema = InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >\n | DynamicTool<ToolOutputT>;\n\n// Overloads with ToolRuntime as CallOptions\nexport function tool<\n SchemaT extends ZodStringV3,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodStringV4,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n NameT extends string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends\n | InteropZodObject\n | InteropZodType<string>\n | JSONSchema = InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >\n | DynamicTool<ToolOutputT> {\n const isSimpleStringSchema = isSimpleStringZodSchema(fields.schema);\n const isStringJSONSchema = validatesOnlyStrings(fields.schema);\n\n // If the schema is not provided, or it's a simple string schema, create a DynamicTool\n if (!fields.schema || isSimpleStringSchema || isStringJSONSchema) {\n return new DynamicTool<ToolOutputT>({\n ...fields,\n description:\n fields.description ??\n (fields.schema as { description?: string } | undefined)?.description ??\n `${fields.name} tool`,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n resolve(func(input as any, childConfig as any));\n } catch (e) {\n reject(e);\n }\n }\n );\n });\n },\n });\n }\n\n const schema = fields.schema as InteropZodObject | JSONSchema;\n\n const description =\n fields.description ??\n (fields.schema as { description?: string }).description ??\n `${fields.name} tool`;\n\n return new DynamicStructuredTool<\n typeof schema,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >({\n ...fields,\n description,\n schema,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n let listener: (() => void) | undefined;\n const cleanup = () => {\n if (config?.signal && listener) {\n config.signal.removeEventListener(\"abort\", listener);\n }\n };\n\n if (config?.signal) {\n listener = () => {\n cleanup();\n reject(getAbortSignalError(config.signal));\n };\n config.signal.addEventListener(\"abort\", listener);\n }\n\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await func(input as any, childConfig as any);\n\n /**\n * If the signal is aborted, we don't want to resolve the promise\n * as the promise is already rejected.\n */\n if (config?.signal?.aborted) {\n cleanup();\n return;\n }\n\n cleanup();\n resolve(result);\n } catch (e) {\n cleanup();\n reject(e);\n }\n }\n );\n });\n },\n }) as DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >;\n}\n\nfunction _formatToolOutput<TOutput extends ToolOutputType>(params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}): ToolMessage | TOutput {\n const { content, artifact, toolCallId, metadata } = params;\n if (toolCallId && !isDirectToolOutput(content)) {\n if (\n typeof content === \"string\" ||\n (Array.isArray(content) &&\n content.every((item) => typeof item === \"object\"))\n ) {\n return new ToolMessage({\n status: \"success\",\n content,\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n } else {\n return new ToolMessage({\n status: \"success\",\n content: _stringify(content),\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n }\n } else {\n return content;\n }\n}\n\nfunction _stringify(content: unknown): string {\n try {\n return JSON.stringify(content) ?? \"\";\n } catch (_noOp) {\n return `${content}`;\n }\n}\n\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool =\n | StructuredToolInterface\n | DynamicTool\n | RunnableToolLike;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,IAAsB,iBAAtB,cAMUA,2CAKV;;;;;;;CAaE;;;;;;;CAQA,eAAe;CAEf,uBAAuB;CAEvB,IAAI,eAAe;AACjB,SAAO,CAAC,aAAa,OAAQ;CAC9B;;;;;;;;;;CAWD,iBAAkC;;;;CAKlC;CAEA,YAAYC,QAAqB;EAC/B,MAAM,UAAU,CAAE,EAAC;EAEnB,KAAK,uBACH,QAAQ,wBAAwB,KAAK;EACvC,KAAK,iBAAiB,QAAQ,kBAAkB,KAAK;EACrD,KAAK,gBAAgB,QAAQ,iBAAiB,KAAK;EACnD,KAAK,WAAW,QAAQ,YAAY,KAAK;EACzC,KAAK,SAAS,QAAQ,UAAU,KAAK;CACtC;;;;;;;CAcD,MAAM,OAIJC,OACAC,QACuD;EACvD,IAAIC;EAKJ,IAAIC,iBAAqCC,4BACvC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I,cAAc,CAACC,yCAAmB,QAAQ,CAC5C,KACE,OAAO,YAAY,YAClB,MAAM,QAAQ,QAAQ,IACrB,QAAQ,MAAM,CAAC,SAAS,OAAO,SAAS,SAAS,CAEnD,QAAO,IAAIC,kCAAY;EACrB,QAAQ;EACR;EACA;EACA,cAAc;EACd,MAAM,OAAO;EACb;CACD;KAED,QAAO,IAAIA,kCAAY;EACrB,QAAQ;EACR,SAAS,WAAW,QAAQ;EAC5B;EACA,cAAc;EACd,MAAM,OAAO;EACb;CACD;KAGH,QAAO;AAEV;AAED,SAAS,WAAWC,SAA0B;AAC5C,KAAI;AACF,SAAO,KAAK,UAAU,QAAQ,IAAI;CACnC,SAAQ,OAAO;AACd,SAAO,GAAG,SAAS;CACpB;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["BaseLangChain","fields?: ToolParams","input: TInput","config?: TConfig","toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >","enrichedConfig: ToolRunnableConfig","ensureConfig","mergeConfigs","_isToolCall","arg: TArg","configArg?: TConfig","tags?: string[]","parsed: SchemaOutputT","isInteropZodSchema","interopParseAsync","isInteropZodError","z4","ToolInputParsingException","result","parseCallbackConfigArg","CallbackManager","toolCallId: string | undefined","_configHasToolCallId","z","callbacks?: TConfig","fields: DynamicToolInput<ToolOutputT>","input: string","runManager?: CallbackManagerForToolRun","parentConfig?: ToolRunnableConfig","fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT> & {\n name: NameT;\n }","arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0]","parentConfig?: RunnableConfig","func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>","fields: ToolWrapperParams<SchemaT, NameT>","isSimpleStringZodSchema","validatesOnlyStrings","patchConfig","AsyncLocalStorageProviderSingleton","pickRunnableConfigKeys","listener: (() => void) | undefined","getAbortSignalError","params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}","isDirectToolOutput","ToolMessage","content: unknown"],"sources":["../../src/tools/index.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { z as z4, ZodError } from \"zod/v4\";\nimport {\n validate,\n type Schema as ValidationSchema,\n} from \"@cfworker/json-schema\";\nimport {\n CallbackManager,\n CallbackManagerForToolRun,\n parseCallbackConfigArg,\n} from \"../callbacks/manager.js\";\nimport { BaseLangChain } from \"../language_models/base.js\";\nimport {\n mergeConfigs,\n ensureConfig,\n patchConfig,\n pickRunnableConfigKeys,\n type RunnableConfig,\n} from \"../runnables/config.js\";\nimport type { RunnableFunc } from \"../runnables/base.js\";\nimport { isDirectToolOutput, ToolCall, ToolMessage } from \"../messages/tool.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../singletons/index.js\";\nimport type { RunnableToolLike } from \"../runnables/base.js\";\nimport {\n _configHasToolCallId,\n _isToolCall,\n ToolInputParsingException,\n} from \"./utils.js\";\nimport {\n type InferInteropZodInput,\n type InferInteropZodOutput,\n type InteropZodObject,\n type InteropZodType,\n interopParseAsync,\n isSimpleStringZodSchema,\n isInteropZodError,\n isInteropZodSchema,\n type ZodStringV3,\n type ZodStringV4,\n type ZodObjectV3,\n type ZodObjectV4,\n} from \"../utils/types/zod.js\";\nimport { getAbortSignalError } from \"../utils/signal.js\";\nimport type {\n StructuredToolCallInput,\n ToolInputSchemaBase,\n ToolReturnType,\n ResponseFormat,\n ToolInputSchemaInputType,\n ToolInputSchemaOutputType,\n ToolParams,\n ToolRunnableConfig,\n StructuredToolInterface,\n DynamicToolInput,\n DynamicStructuredToolInput,\n StringInputToolSchema,\n ToolInterface,\n ToolOutputType,\n ToolRuntime,\n} from \"./types.js\";\nimport { type JSONSchema, validatesOnlyStrings } from \"../utils/json_schema.js\";\n\nexport type {\n BaseDynamicToolInput,\n ContentAndArtifact,\n DynamicToolInput,\n DynamicStructuredToolInput,\n ResponseFormat,\n StructuredToolCallInput,\n StructuredToolInterface,\n StructuredToolParams,\n ToolInterface,\n ToolParams,\n ToolReturnType,\n ToolRunnableConfig,\n ToolInputSchemaBase as ToolSchemaBase,\n} from \"./types.js\";\n\nexport {\n isLangChainTool,\n isRunnableToolLike,\n isStructuredTool,\n isStructuredToolParams,\n type ToolRuntime,\n} from \"./types.js\";\n\nexport { ToolInputParsingException };\n/**\n * Base class for Tools that accept input of any shape defined by a Zod schema.\n */\nexport abstract class StructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n>\n extends BaseLangChain<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolOutputT | ToolMessage\n >\n implements StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT>\n{\n abstract name: string;\n\n abstract description: string;\n\n abstract schema: SchemaT;\n\n /**\n * Optional provider-specific extra fields for the tool.\n *\n * This is used to pass provider-specific configuration that doesn't fit into\n * standard tool fields.\n */\n extras?: Record<string, unknown>;\n\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect = false;\n\n verboseParsingErrors = false;\n\n get lc_namespace() {\n return [\"langchain\", \"tools\"];\n }\n\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat = \"content\";\n\n /**\n * Default config object for the tool runnable.\n */\n defaultConfig?: ToolRunnableConfig;\n\n constructor(fields?: ToolParams) {\n super(fields ?? {});\n\n this.verboseParsingErrors =\n fields?.verboseParsingErrors ?? this.verboseParsingErrors;\n this.responseFormat = fields?.responseFormat ?? this.responseFormat;\n this.defaultConfig = fields?.defaultConfig ?? this.defaultConfig;\n this.metadata = fields?.metadata ?? this.metadata;\n this.extras = fields?.extras ?? this.extras;\n }\n\n protected abstract _call(\n arg: SchemaOutputT,\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT>;\n\n /**\n * Invokes the tool with the provided input and configuration.\n * @param input The input for the tool.\n * @param config Optional configuration for the tool.\n * @returns A Promise that resolves with the tool's output.\n */\n async invoke<\n TInput extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n input: TInput,\n config?: TConfig\n ): Promise<ToolReturnType<TInput, TConfig, ToolOutputT>> {\n let toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n\n let enrichedConfig: ToolRunnableConfig = ensureConfig(\n mergeConfigs(this.defaultConfig, config)\n );\n if (_isToolCall(input)) {\n toolInput = input.args as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n enrichedConfig = {\n ...enrichedConfig,\n toolCall: input,\n };\n } else {\n toolInput = input as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n }\n\n return this.call(toolInput, enrichedConfig) as Promise<\n ToolReturnType<TInput, TConfig, ToolOutputT>\n >;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument, configuration, and tags. It\n * parses the input according to the schema, handles any errors, and\n * manages callbacks.\n * @param arg The input argument for the tool.\n * @param configArg Optional configuration or callbacks for the tool.\n * @param tags Optional tags for the tool.\n * @returns A Promise that resolves with a string.\n */\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>> {\n // Determine the actual input that needs parsing/validation.\n // If arg is a ToolCall, use its args; otherwise, use arg directly.\n const inputForValidation = _isToolCall(arg) ? arg.args : arg;\n\n let parsed: SchemaOutputT; // This will hold the successfully parsed input of the expected output type.\n if (isInteropZodSchema(this.schema)) {\n try {\n // Validate the inputForValidation - TS needs help here as it can't exclude ToolCall based on the check\n parsed = await interopParseAsync(\n this.schema as InteropZodType,\n inputForValidation as Exclude<TArg, ToolCall>\n );\n } catch (e) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${(e as Error).message}`;\n }\n if (isInteropZodError(e)) {\n message = `${message}\\n\\n${z4.prettifyError(e as ZodError)}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n } else {\n const result = validate(\n inputForValidation,\n this.schema as ValidationSchema\n );\n if (!result.valid) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${result.errors\n .map((e) => `${e.keywordLocation}: ${e.error}`)\n .join(\"\\n\")}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n // Assign the validated input to parsed\n // We cast here because validate() doesn't narrow the type sufficiently for TS, but we know it's valid.\n parsed = inputForValidation as SchemaOutputT;\n }\n\n const config = parseCallbackConfigArg(configArg);\n const callbackManager_ = CallbackManager.configure(\n config.callbacks,\n this.callbacks,\n config.tags || tags,\n this.tags,\n config.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n const runManager = await callbackManager_?.handleToolStart(\n this.toJSON(),\n // Log the original raw input arg\n typeof arg === \"string\" ? arg : JSON.stringify(arg),\n config.runId,\n undefined,\n undefined,\n undefined,\n config.runName\n );\n delete config.runId;\n let result;\n try {\n // Pass the correctly typed parsed input to _call\n result = await this._call(parsed, runManager, config);\n } catch (e) {\n await runManager?.handleToolError(e);\n throw e;\n }\n let content;\n let artifact;\n if (this.responseFormat === \"content_and_artifact\") {\n if (Array.isArray(result) && result.length === 2) {\n [content, artifact] = result;\n } else {\n throw new Error(\n `Tool response format is \"content_and_artifact\" but the output was not a two-tuple.\\nResult: ${JSON.stringify(\n result\n )}`\n );\n }\n } else {\n content = result;\n }\n\n let toolCallId: string | undefined;\n // Extract toolCallId ONLY if the original arg was a ToolCall\n if (_isToolCall(arg)) {\n toolCallId = arg.id;\n }\n // Or if it was provided in the config's toolCall property\n if (!toolCallId && _configHasToolCallId(config)) {\n toolCallId = config.toolCall.id;\n }\n\n const formattedOutput = _formatToolOutput<ToolOutputT>({\n content,\n artifact,\n toolCallId,\n name: this.name,\n metadata: this.metadata,\n });\n await runManager?.handleToolEnd(formattedOutput);\n return formattedOutput as ToolReturnType<TArg, TConfig, ToolOutputT>;\n }\n}\n\n/**\n * Base class for Tools that accept input as a string.\n */\nexport abstract class Tool<ToolOutputT = ToolOutputType>\n extends StructuredTool<\n StringInputToolSchema,\n ToolInputSchemaOutputType<StringInputToolSchema>,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n implements\n ToolInterface<\n StringInputToolSchema,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n{\n schema = z\n .object({ input: z.string().optional() })\n .transform((obj) => obj.input);\n\n constructor(fields?: ToolParams) {\n super(fields);\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument and callbacks. It handles\n * string inputs specifically.\n * @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema.\n * @param callbacks Optional callbacks for the tool.\n * @returns A Promise that resolves with a string.\n */\n // Match the base class signature including the generics and conditional return type\n call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n callbacks?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n // Prepare the input for the base class call method.\n // If arg is string or undefined, wrap it; otherwise, pass ToolCall or { input: ... } directly.\n const structuredArg =\n typeof arg === \"string\" || arg == null ? { input: arg } : arg;\n\n // Ensure TConfig is passed to super.call\n return super.call(structuredArg, callbacks);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and description.\n */\nexport class DynamicTool<\n ToolOutputT = ToolOutputType,\n> extends Tool<ToolOutputT> {\n static lc_name() {\n return \"DynamicTool\";\n }\n\n name: string;\n\n description: string;\n\n func: DynamicToolInput<ToolOutputT>[\"func\"];\n\n constructor(fields: DynamicToolInput<ToolOutputT>) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n async call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n // Call the Tool class's call method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig);\n }\n\n /** @ignore */\n async _call(\n input: string, // DynamicTool's _call specifically expects a string after schema transformation\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT> {\n return this.func(input, runManager, parentConfig);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and\n * description, designed to work with structured data. It extends the\n * StructuredTool class and overrides the _call method to execute the\n * provided function when the tool is called.\n *\n * Schema can be passed as Zod or JSON schema. The tool will not validate\n * input if JSON schema is passed.\n *\n * @template SchemaT The input schema type for the tool (Zod schema or JSON schema). Defaults to `ToolInputSchemaBase`.\n * @template SchemaOutputT The output type derived from the schema after parsing/validation. Defaults to `ToolInputSchemaOutputType<SchemaT>`.\n * @template SchemaInputT The input type derived from the schema before parsing. Defaults to `ToolInputSchemaInputType<SchemaT>`.\n * @template ToolOutputT The return type of the tool's function. Defaults to `ToolOutputType`.\n * @template NameT The literal type of the tool name (for discriminated union support). Defaults to `string`.\n */\nexport class DynamicStructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n NameT extends string = string,\n> extends StructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT> {\n static lc_name() {\n return \"DynamicStructuredTool\";\n }\n\n declare name: NameT;\n\n description: string;\n\n func: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>[\"func\"];\n\n schema: SchemaT;\n\n constructor(\n fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT> & {\n name: NameT;\n }\n ) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n this.schema = fields.schema;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n // Match the base class signature\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n\n // Call the base class method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig, tags);\n }\n\n protected _call(\n arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0],\n runManager?: CallbackManagerForToolRun,\n parentConfig?: RunnableConfig\n ): Promise<ToolOutputT> {\n return this.func(arg, runManager, parentConfig);\n }\n}\n\n/**\n * Abstract base class for toolkits in LangChain. Toolkits are collections\n * of tools that agents can use. Subclasses must implement the `tools`\n * property to provide the specific tools for the toolkit.\n */\nexport abstract class BaseToolkit {\n abstract tools: StructuredToolInterface[];\n\n getTools(): StructuredToolInterface[] {\n return this.tools;\n }\n}\n\n/**\n * Parameters for the tool function.\n * Schema can be provided as Zod or JSON schema.\n * Both schema types will be validated.\n * @template {ToolInputSchemaBase} RunInput The input schema for the tool.\n * @template {string} NameT The literal name type for discriminated union support.\n */\ninterface ToolWrapperParams<\n RunInput = ToolInputSchemaBase | undefined,\n NameT extends string = string,\n> extends ToolParams {\n /**\n * The name of the tool. If using with an LLM, this\n * will be passed as the tool name.\n */\n name: NameT;\n /**\n * The description of the tool.\n * @default `${fields.name} tool`\n */\n description?: string;\n /**\n * The input schema for the tool. If using an LLM, this\n * will be passed as the tool schema to generate arguments\n * for.\n */\n schema?: RunInput;\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat;\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect?: boolean;\n}\n\n/**\n * Creates a new StructuredTool instance with the provided function, name, description, and schema.\n *\n * Schema can be provided as Zod or JSON schema, and both will be validated.\n *\n * @function\n * @template {ToolInputSchemaBase} SchemaT The input schema for the tool.\n * @template {ToolReturnType} ToolOutputT The output type of the tool.\n *\n * @param {RunnableFunc<z.output<SchemaT>, ToolOutputT>} func - The function to invoke when the tool is called.\n * @param {ToolWrapperParams<SchemaT>} fields - An object containing the following properties:\n * @param {string} fields.name The name of the tool.\n * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.\n * @param {z.AnyZodObject | z.ZodString | undefined} fields.schema The Zod schema defining the input for the tool. If undefined, it will default to a Zod string schema.\n *\n * @returns {DynamicStructuredTool<SchemaT>} A new StructuredTool instance.\n */\nexport function tool<SchemaT extends ZodStringV3, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<SchemaT extends ZodStringV4, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n NameT extends string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n>(\n func: RunnableFunc<\n Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends InteropZodObject | InteropZodType<string> | JSONSchema =\n InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >\n | DynamicTool<ToolOutputT>;\n\n// Overloads with ToolRuntime as CallOptions\nexport function tool<\n SchemaT extends ZodStringV3,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodStringV4,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n NameT extends string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends InteropZodObject | InteropZodType<string> | JSONSchema =\n InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >\n | DynamicTool<ToolOutputT> {\n const isSimpleStringSchema = isSimpleStringZodSchema(fields.schema);\n const isStringJSONSchema = validatesOnlyStrings(fields.schema);\n\n // If the schema is not provided, or it's a simple string schema, create a DynamicTool\n if (!fields.schema || isSimpleStringSchema || isStringJSONSchema) {\n return new DynamicTool<ToolOutputT>({\n ...fields,\n description:\n fields.description ??\n (fields.schema as { description?: string } | undefined)?.description ??\n `${fields.name} tool`,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n resolve(func(input as any, childConfig as any));\n } catch (e) {\n reject(e);\n }\n }\n );\n });\n },\n });\n }\n\n const schema = fields.schema as InteropZodObject | JSONSchema;\n\n const description =\n fields.description ??\n (fields.schema as { description?: string }).description ??\n `${fields.name} tool`;\n\n return new DynamicStructuredTool<\n typeof schema,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >({\n ...fields,\n description,\n schema,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n let listener: (() => void) | undefined;\n const cleanup = () => {\n if (config?.signal && listener) {\n config.signal.removeEventListener(\"abort\", listener);\n }\n };\n\n if (config?.signal) {\n listener = () => {\n cleanup();\n reject(getAbortSignalError(config.signal));\n };\n config.signal.addEventListener(\"abort\", listener, { once: true });\n }\n\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await func(input as any, childConfig as any);\n\n /**\n * If the signal is aborted, we don't want to resolve the promise\n * as the promise is already rejected.\n */\n if (config?.signal?.aborted) {\n cleanup();\n return;\n }\n\n cleanup();\n resolve(result);\n } catch (e) {\n cleanup();\n reject(e);\n }\n }\n );\n });\n },\n }) as DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >;\n}\n\nfunction _formatToolOutput<TOutput extends ToolOutputType>(params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}): ToolMessage | TOutput {\n const { content, artifact, toolCallId, metadata } = params;\n if (toolCallId && !isDirectToolOutput(content)) {\n if (\n typeof content === \"string\" ||\n (Array.isArray(content) &&\n content.every((item) => typeof item === \"object\"))\n ) {\n return new ToolMessage({\n status: \"success\",\n content,\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n } else {\n return new ToolMessage({\n status: \"success\",\n content: _stringify(content),\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n }\n } else {\n return content;\n }\n}\n\nfunction _stringify(content: unknown): string {\n try {\n return JSON.stringify(content) ?? \"\";\n } catch (_noOp) {\n return `${content}`;\n }\n}\n\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool =\n | StructuredToolInterface\n | DynamicTool\n | RunnableToolLike;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,IAAsB,iBAAtB,cAMUA,2CAKV;;;;;;;CAaE;;;;;;;CAQA,eAAe;CAEf,uBAAuB;CAEvB,IAAI,eAAe;AACjB,SAAO,CAAC,aAAa,OAAQ;CAC9B;;;;;;;;;;CAWD,iBAAkC;;;;CAKlC;CAEA,YAAYC,QAAqB;EAC/B,MAAM,UAAU,CAAE,EAAC;EAEnB,KAAK,uBACH,QAAQ,wBAAwB,KAAK;EACvC,KAAK,iBAAiB,QAAQ,kBAAkB,KAAK;EACrD,KAAK,gBAAgB,QAAQ,iBAAiB,KAAK;EACnD,KAAK,WAAW,QAAQ,YAAY,KAAK;EACzC,KAAK,SAAS,QAAQ,UAAU,KAAK;CACtC;;;;;;;CAcD,MAAM,OAIJC,OACAC,QACuD;EACvD,IAAIC;EAKJ,IAAIC,iBAAqCC,4BACvCC,4BAAa,KAAK,eAAe,OAAO,CACzC;AACD,MAAIC,0BAA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Q,CAC5C,KACE,OAAO,YAAY,YAClB,MAAM,QAAQ,QAAQ,IACrB,QAAQ,MAAM,CAAC,SAAS,OAAO,SAAS,SAAS,CAEnD,QAAO,IAAIC,kCAAY;EACrB,QAAQ;EACR;EACA;EACA,cAAc;EACd,MAAM,OAAO;EACb;CACD;KAED,QAAO,IAAIA,kCAAY;EACrB,QAAQ;EACR,SAAS,WAAW,QAAQ;EAC5B;EACA,cAAc;EACd,MAAM,OAAO;EACb;CACD;KAGH,QAAO;AAEV;AAED,SAAS,WAAWC,SAA0B;AAC5C,KAAI;AACF,SAAO,KAAK,UAAU,QAAQ,IAAI;CACnC,SAAQ,OAAO;AACd,SAAO,GAAG,SAAS;CACpB;AACF"}
|
package/dist/tools/index.js
CHANGED
|
@@ -292,7 +292,7 @@ function tool(func, fields) {
|
|
|
292
292
|
cleanup();
|
|
293
293
|
reject(getAbortSignalError(config.signal));
|
|
294
294
|
};
|
|
295
|
-
config.signal.addEventListener("abort", listener);
|
|
295
|
+
config.signal.addEventListener("abort", listener, { once: true });
|
|
296
296
|
}
|
|
297
297
|
const childConfig = patchConfig(config, { callbacks: runManager?.getChild() });
|
|
298
298
|
AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => {
|
package/dist/tools/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["fields?: ToolParams","input: TInput","config?: TConfig","toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >","enrichedConfig: ToolRunnableConfig","arg: TArg","configArg?: TConfig","tags?: string[]","parsed: SchemaOutputT","z4","result","toolCallId: string | undefined","callbacks?: TConfig","fields: DynamicToolInput<ToolOutputT>","input: string","runManager?: CallbackManagerForToolRun","parentConfig?: ToolRunnableConfig","fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT> & {\n name: NameT;\n }","arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0]","parentConfig?: RunnableConfig","func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>","fields: ToolWrapperParams<SchemaT, NameT>","listener: (() => void) | undefined","params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}","content: unknown"],"sources":["../../src/tools/index.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { z as z4, ZodError } from \"zod/v4\";\nimport {\n validate,\n type Schema as ValidationSchema,\n} from \"@cfworker/json-schema\";\nimport {\n CallbackManager,\n CallbackManagerForToolRun,\n parseCallbackConfigArg,\n} from \"../callbacks/manager.js\";\nimport { BaseLangChain } from \"../language_models/base.js\";\nimport {\n mergeConfigs,\n ensureConfig,\n patchConfig,\n pickRunnableConfigKeys,\n type RunnableConfig,\n} from \"../runnables/config.js\";\nimport type { RunnableFunc } from \"../runnables/base.js\";\nimport { isDirectToolOutput, ToolCall, ToolMessage } from \"../messages/tool.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../singletons/index.js\";\nimport type { RunnableToolLike } from \"../runnables/base.js\";\nimport {\n _configHasToolCallId,\n _isToolCall,\n ToolInputParsingException,\n} from \"./utils.js\";\nimport {\n type InferInteropZodInput,\n type InferInteropZodOutput,\n type InteropZodObject,\n type InteropZodType,\n interopParseAsync,\n isSimpleStringZodSchema,\n isInteropZodError,\n isInteropZodSchema,\n type ZodStringV3,\n type ZodStringV4,\n type ZodObjectV3,\n type ZodObjectV4,\n} from \"../utils/types/zod.js\";\nimport { getAbortSignalError } from \"../utils/signal.js\";\nimport type {\n StructuredToolCallInput,\n ToolInputSchemaBase,\n ToolReturnType,\n ResponseFormat,\n ToolInputSchemaInputType,\n ToolInputSchemaOutputType,\n ToolParams,\n ToolRunnableConfig,\n StructuredToolInterface,\n DynamicToolInput,\n DynamicStructuredToolInput,\n StringInputToolSchema,\n ToolInterface,\n ToolOutputType,\n ToolRuntime,\n} from \"./types.js\";\nimport { type JSONSchema, validatesOnlyStrings } from \"../utils/json_schema.js\";\n\nexport type {\n BaseDynamicToolInput,\n ContentAndArtifact,\n DynamicToolInput,\n DynamicStructuredToolInput,\n ResponseFormat,\n StructuredToolCallInput,\n StructuredToolInterface,\n StructuredToolParams,\n ToolInterface,\n ToolParams,\n ToolReturnType,\n ToolRunnableConfig,\n ToolInputSchemaBase as ToolSchemaBase,\n} from \"./types.js\";\n\nexport {\n isLangChainTool,\n isRunnableToolLike,\n isStructuredTool,\n isStructuredToolParams,\n type ToolRuntime,\n} from \"./types.js\";\n\nexport { ToolInputParsingException };\n/**\n * Base class for Tools that accept input of any shape defined by a Zod schema.\n */\nexport abstract class StructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n >\n extends BaseLangChain<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolOutputT | ToolMessage\n >\n implements StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT>\n{\n abstract name: string;\n\n abstract description: string;\n\n abstract schema: SchemaT;\n\n /**\n * Optional provider-specific extra fields for the tool.\n *\n * This is used to pass provider-specific configuration that doesn't fit into\n * standard tool fields.\n */\n extras?: Record<string, unknown>;\n\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect = false;\n\n verboseParsingErrors = false;\n\n get lc_namespace() {\n return [\"langchain\", \"tools\"];\n }\n\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat = \"content\";\n\n /**\n * Default config object for the tool runnable.\n */\n defaultConfig?: ToolRunnableConfig;\n\n constructor(fields?: ToolParams) {\n super(fields ?? {});\n\n this.verboseParsingErrors =\n fields?.verboseParsingErrors ?? this.verboseParsingErrors;\n this.responseFormat = fields?.responseFormat ?? this.responseFormat;\n this.defaultConfig = fields?.defaultConfig ?? this.defaultConfig;\n this.metadata = fields?.metadata ?? this.metadata;\n this.extras = fields?.extras ?? this.extras;\n }\n\n protected abstract _call(\n arg: SchemaOutputT,\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT>;\n\n /**\n * Invokes the tool with the provided input and configuration.\n * @param input The input for the tool.\n * @param config Optional configuration for the tool.\n * @returns A Promise that resolves with the tool's output.\n */\n async invoke<\n TInput extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n input: TInput,\n config?: TConfig\n ): Promise<ToolReturnType<TInput, TConfig, ToolOutputT>> {\n let toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n\n let enrichedConfig: ToolRunnableConfig = ensureConfig(\n mergeConfigs(this.defaultConfig, config)\n );\n if (_isToolCall(input)) {\n toolInput = input.args as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n enrichedConfig = {\n ...enrichedConfig,\n toolCall: input,\n };\n } else {\n toolInput = input as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n }\n\n return this.call(toolInput, enrichedConfig) as Promise<\n ToolReturnType<TInput, TConfig, ToolOutputT>\n >;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument, configuration, and tags. It\n * parses the input according to the schema, handles any errors, and\n * manages callbacks.\n * @param arg The input argument for the tool.\n * @param configArg Optional configuration or callbacks for the tool.\n * @param tags Optional tags for the tool.\n * @returns A Promise that resolves with a string.\n */\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>> {\n // Determine the actual input that needs parsing/validation.\n // If arg is a ToolCall, use its args; otherwise, use arg directly.\n const inputForValidation = _isToolCall(arg) ? arg.args : arg;\n\n let parsed: SchemaOutputT; // This will hold the successfully parsed input of the expected output type.\n if (isInteropZodSchema(this.schema)) {\n try {\n // Validate the inputForValidation - TS needs help here as it can't exclude ToolCall based on the check\n parsed = await interopParseAsync(\n this.schema as InteropZodType,\n inputForValidation as Exclude<TArg, ToolCall>\n );\n } catch (e) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${(e as Error).message}`;\n }\n if (isInteropZodError(e)) {\n message = `${message}\\n\\n${z4.prettifyError(e as ZodError)}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n } else {\n const result = validate(\n inputForValidation,\n this.schema as ValidationSchema\n );\n if (!result.valid) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${result.errors\n .map((e) => `${e.keywordLocation}: ${e.error}`)\n .join(\"\\n\")}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n // Assign the validated input to parsed\n // We cast here because validate() doesn't narrow the type sufficiently for TS, but we know it's valid.\n parsed = inputForValidation as SchemaOutputT;\n }\n\n const config = parseCallbackConfigArg(configArg);\n const callbackManager_ = CallbackManager.configure(\n config.callbacks,\n this.callbacks,\n config.tags || tags,\n this.tags,\n config.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n const runManager = await callbackManager_?.handleToolStart(\n this.toJSON(),\n // Log the original raw input arg\n typeof arg === \"string\" ? arg : JSON.stringify(arg),\n config.runId,\n undefined,\n undefined,\n undefined,\n config.runName\n );\n delete config.runId;\n let result;\n try {\n // Pass the correctly typed parsed input to _call\n result = await this._call(parsed, runManager, config);\n } catch (e) {\n await runManager?.handleToolError(e);\n throw e;\n }\n let content;\n let artifact;\n if (this.responseFormat === \"content_and_artifact\") {\n if (Array.isArray(result) && result.length === 2) {\n [content, artifact] = result;\n } else {\n throw new Error(\n `Tool response format is \"content_and_artifact\" but the output was not a two-tuple.\\nResult: ${JSON.stringify(\n result\n )}`\n );\n }\n } else {\n content = result;\n }\n\n let toolCallId: string | undefined;\n // Extract toolCallId ONLY if the original arg was a ToolCall\n if (_isToolCall(arg)) {\n toolCallId = arg.id;\n }\n // Or if it was provided in the config's toolCall property\n if (!toolCallId && _configHasToolCallId(config)) {\n toolCallId = config.toolCall.id;\n }\n\n const formattedOutput = _formatToolOutput<ToolOutputT>({\n content,\n artifact,\n toolCallId,\n name: this.name,\n metadata: this.metadata,\n });\n await runManager?.handleToolEnd(formattedOutput);\n return formattedOutput as ToolReturnType<TArg, TConfig, ToolOutputT>;\n }\n}\n\n/**\n * Base class for Tools that accept input as a string.\n */\nexport abstract class Tool<ToolOutputT = ToolOutputType>\n extends StructuredTool<\n StringInputToolSchema,\n ToolInputSchemaOutputType<StringInputToolSchema>,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n implements\n ToolInterface<\n StringInputToolSchema,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n{\n schema = z\n .object({ input: z.string().optional() })\n .transform((obj) => obj.input);\n\n constructor(fields?: ToolParams) {\n super(fields);\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument and callbacks. It handles\n * string inputs specifically.\n * @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema.\n * @param callbacks Optional callbacks for the tool.\n * @returns A Promise that resolves with a string.\n */\n // Match the base class signature including the generics and conditional return type\n call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n callbacks?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n // Prepare the input for the base class call method.\n // If arg is string or undefined, wrap it; otherwise, pass ToolCall or { input: ... } directly.\n const structuredArg =\n typeof arg === \"string\" || arg == null ? { input: arg } : arg;\n\n // Ensure TConfig is passed to super.call\n return super.call(structuredArg, callbacks);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and description.\n */\nexport class DynamicTool<\n ToolOutputT = ToolOutputType,\n> extends Tool<ToolOutputT> {\n static lc_name() {\n return \"DynamicTool\";\n }\n\n name: string;\n\n description: string;\n\n func: DynamicToolInput<ToolOutputT>[\"func\"];\n\n constructor(fields: DynamicToolInput<ToolOutputT>) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n async call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n // Call the Tool class's call method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig);\n }\n\n /** @ignore */\n async _call(\n input: string, // DynamicTool's _call specifically expects a string after schema transformation\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT> {\n return this.func(input, runManager, parentConfig);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and\n * description, designed to work with structured data. It extends the\n * StructuredTool class and overrides the _call method to execute the\n * provided function when the tool is called.\n *\n * Schema can be passed as Zod or JSON schema. The tool will not validate\n * input if JSON schema is passed.\n *\n * @template SchemaT The input schema type for the tool (Zod schema or JSON schema). Defaults to `ToolInputSchemaBase`.\n * @template SchemaOutputT The output type derived from the schema after parsing/validation. Defaults to `ToolInputSchemaOutputType<SchemaT>`.\n * @template SchemaInputT The input type derived from the schema before parsing. Defaults to `ToolInputSchemaInputType<SchemaT>`.\n * @template ToolOutputT The return type of the tool's function. Defaults to `ToolOutputType`.\n * @template NameT The literal type of the tool name (for discriminated union support). Defaults to `string`.\n */\nexport class DynamicStructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n NameT extends string = string,\n> extends StructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT> {\n static lc_name() {\n return \"DynamicStructuredTool\";\n }\n\n declare name: NameT;\n\n description: string;\n\n func: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>[\"func\"];\n\n schema: SchemaT;\n\n constructor(\n fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT> & {\n name: NameT;\n }\n ) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n this.schema = fields.schema;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n // Match the base class signature\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n\n // Call the base class method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig, tags);\n }\n\n protected _call(\n arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0],\n runManager?: CallbackManagerForToolRun,\n parentConfig?: RunnableConfig\n ): Promise<ToolOutputT> {\n return this.func(arg, runManager, parentConfig);\n }\n}\n\n/**\n * Abstract base class for toolkits in LangChain. Toolkits are collections\n * of tools that agents can use. Subclasses must implement the `tools`\n * property to provide the specific tools for the toolkit.\n */\nexport abstract class BaseToolkit {\n abstract tools: StructuredToolInterface[];\n\n getTools(): StructuredToolInterface[] {\n return this.tools;\n }\n}\n\n/**\n * Parameters for the tool function.\n * Schema can be provided as Zod or JSON schema.\n * Both schema types will be validated.\n * @template {ToolInputSchemaBase} RunInput The input schema for the tool.\n * @template {string} NameT The literal name type for discriminated union support.\n */\ninterface ToolWrapperParams<\n RunInput = ToolInputSchemaBase | undefined,\n NameT extends string = string,\n> extends ToolParams {\n /**\n * The name of the tool. If using with an LLM, this\n * will be passed as the tool name.\n */\n name: NameT;\n /**\n * The description of the tool.\n * @default `${fields.name} tool`\n */\n description?: string;\n /**\n * The input schema for the tool. If using an LLM, this\n * will be passed as the tool schema to generate arguments\n * for.\n */\n schema?: RunInput;\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat;\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect?: boolean;\n}\n\n/**\n * Creates a new StructuredTool instance with the provided function, name, description, and schema.\n *\n * Schema can be provided as Zod or JSON schema, and both will be validated.\n *\n * @function\n * @template {ToolInputSchemaBase} SchemaT The input schema for the tool.\n * @template {ToolReturnType} ToolOutputT The output type of the tool.\n *\n * @param {RunnableFunc<z.output<SchemaT>, ToolOutputT>} func - The function to invoke when the tool is called.\n * @param {ToolWrapperParams<SchemaT>} fields - An object containing the following properties:\n * @param {string} fields.name The name of the tool.\n * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.\n * @param {z.AnyZodObject | z.ZodString | undefined} fields.schema The Zod schema defining the input for the tool. If undefined, it will default to a Zod string schema.\n *\n * @returns {DynamicStructuredTool<SchemaT>} A new StructuredTool instance.\n */\nexport function tool<SchemaT extends ZodStringV3, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<SchemaT extends ZodStringV4, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n NameT extends string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n>(\n func: RunnableFunc<\n Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends\n | InteropZodObject\n | InteropZodType<string>\n | JSONSchema = InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >\n | DynamicTool<ToolOutputT>;\n\n// Overloads with ToolRuntime as CallOptions\nexport function tool<\n SchemaT extends ZodStringV3,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodStringV4,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n NameT extends string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends\n | InteropZodObject\n | InteropZodType<string>\n | JSONSchema = InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >\n | DynamicTool<ToolOutputT> {\n const isSimpleStringSchema = isSimpleStringZodSchema(fields.schema);\n const isStringJSONSchema = validatesOnlyStrings(fields.schema);\n\n // If the schema is not provided, or it's a simple string schema, create a DynamicTool\n if (!fields.schema || isSimpleStringSchema || isStringJSONSchema) {\n return new DynamicTool<ToolOutputT>({\n ...fields,\n description:\n fields.description ??\n (fields.schema as { description?: string } | undefined)?.description ??\n `${fields.name} tool`,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n resolve(func(input as any, childConfig as any));\n } catch (e) {\n reject(e);\n }\n }\n );\n });\n },\n });\n }\n\n const schema = fields.schema as InteropZodObject | JSONSchema;\n\n const description =\n fields.description ??\n (fields.schema as { description?: string }).description ??\n `${fields.name} tool`;\n\n return new DynamicStructuredTool<\n typeof schema,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >({\n ...fields,\n description,\n schema,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n let listener: (() => void) | undefined;\n const cleanup = () => {\n if (config?.signal && listener) {\n config.signal.removeEventListener(\"abort\", listener);\n }\n };\n\n if (config?.signal) {\n listener = () => {\n cleanup();\n reject(getAbortSignalError(config.signal));\n };\n config.signal.addEventListener(\"abort\", listener);\n }\n\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await func(input as any, childConfig as any);\n\n /**\n * If the signal is aborted, we don't want to resolve the promise\n * as the promise is already rejected.\n */\n if (config?.signal?.aborted) {\n cleanup();\n return;\n }\n\n cleanup();\n resolve(result);\n } catch (e) {\n cleanup();\n reject(e);\n }\n }\n );\n });\n },\n }) as DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >;\n}\n\nfunction _formatToolOutput<TOutput extends ToolOutputType>(params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}): ToolMessage | TOutput {\n const { content, artifact, toolCallId, metadata } = params;\n if (toolCallId && !isDirectToolOutput(content)) {\n if (\n typeof content === \"string\" ||\n (Array.isArray(content) &&\n content.every((item) => typeof item === \"object\"))\n ) {\n return new ToolMessage({\n status: \"success\",\n content,\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n } else {\n return new ToolMessage({\n status: \"success\",\n content: _stringify(content),\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n }\n } else {\n return content;\n }\n}\n\nfunction _stringify(content: unknown): string {\n try {\n return JSON.stringify(content) ?? \"\";\n } catch (_noOp) {\n return `${content}`;\n }\n}\n\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool =\n | StructuredToolInterface\n | DynamicTool\n | RunnableToolLike;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,IAAsB,iBAAtB,cAMU,cAKV;;;;;;;CAaE;;;;;;;CAQA,eAAe;CAEf,uBAAuB;CAEvB,IAAI,eAAe;AACjB,SAAO,CAAC,aAAa,OAAQ;CAC9B;;;;;;;;;;CAWD,iBAAkC;;;;CAKlC;CAEA,YAAYA,QAAqB;EAC/B,MAAM,UAAU,CAAE,EAAC;EAEnB,KAAK,uBACH,QAAQ,wBAAwB,KAAK;EACvC,KAAK,iBAAiB,QAAQ,kBAAkB,KAAK;EACrD,KAAK,gBAAgB,QAAQ,iBAAiB,KAAK;EACnD,KAAK,WAAW,QAAQ,YAAY,KAAK;EACzC,KAAK,SAAS,QAAQ,UAAU,KAAK;CACt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AAM,EAAE,SAAS,UAAU,YAAY,UAAU,GAAG;AACpD,KAAI,cAAc,CAAC,mBAAmB,QAAQ,CAC5C,KACE,OAAO,YAAY,YAClB,MAAM,QAAQ,QAAQ,IACrB,QAAQ,MAAM,CAAC,SAAS,OAAO,SAAS,SAAS,CAEnD,QAAO,IAAI,YAAY;EACrB,QAAQ;EACR;EACA;EACA,cAAc;EACd,MAAM,OAAO;EACb;CACD;KAED,QAAO,IAAI,YAAY;EACrB,QAAQ;EACR,SAAS,WAAW,QAAQ;EAC5B;EACA,cAAc;EACd,MAAM,OAAO;EACb;CACD;KAGH,QAAO;AAEV;AAED,SAAS,WAAWC,SAA0B;AAC5C,KAAI;AACF,SAAO,KAAK,UAAU,QAAQ,IAAI;CACnC,SAAQ,OAAO;AACd,SAAO,GAAG,SAAS;CACpB;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["fields?: ToolParams","input: TInput","config?: TConfig","toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >","enrichedConfig: ToolRunnableConfig","arg: TArg","configArg?: TConfig","tags?: string[]","parsed: SchemaOutputT","z4","result","toolCallId: string | undefined","callbacks?: TConfig","fields: DynamicToolInput<ToolOutputT>","input: string","runManager?: CallbackManagerForToolRun","parentConfig?: ToolRunnableConfig","fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT> & {\n name: NameT;\n }","arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0]","parentConfig?: RunnableConfig","func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>","fields: ToolWrapperParams<SchemaT, NameT>","listener: (() => void) | undefined","params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}","content: unknown"],"sources":["../../src/tools/index.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { z as z4, ZodError } from \"zod/v4\";\nimport {\n validate,\n type Schema as ValidationSchema,\n} from \"@cfworker/json-schema\";\nimport {\n CallbackManager,\n CallbackManagerForToolRun,\n parseCallbackConfigArg,\n} from \"../callbacks/manager.js\";\nimport { BaseLangChain } from \"../language_models/base.js\";\nimport {\n mergeConfigs,\n ensureConfig,\n patchConfig,\n pickRunnableConfigKeys,\n type RunnableConfig,\n} from \"../runnables/config.js\";\nimport type { RunnableFunc } from \"../runnables/base.js\";\nimport { isDirectToolOutput, ToolCall, ToolMessage } from \"../messages/tool.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../singletons/index.js\";\nimport type { RunnableToolLike } from \"../runnables/base.js\";\nimport {\n _configHasToolCallId,\n _isToolCall,\n ToolInputParsingException,\n} from \"./utils.js\";\nimport {\n type InferInteropZodInput,\n type InferInteropZodOutput,\n type InteropZodObject,\n type InteropZodType,\n interopParseAsync,\n isSimpleStringZodSchema,\n isInteropZodError,\n isInteropZodSchema,\n type ZodStringV3,\n type ZodStringV4,\n type ZodObjectV3,\n type ZodObjectV4,\n} from \"../utils/types/zod.js\";\nimport { getAbortSignalError } from \"../utils/signal.js\";\nimport type {\n StructuredToolCallInput,\n ToolInputSchemaBase,\n ToolReturnType,\n ResponseFormat,\n ToolInputSchemaInputType,\n ToolInputSchemaOutputType,\n ToolParams,\n ToolRunnableConfig,\n StructuredToolInterface,\n DynamicToolInput,\n DynamicStructuredToolInput,\n StringInputToolSchema,\n ToolInterface,\n ToolOutputType,\n ToolRuntime,\n} from \"./types.js\";\nimport { type JSONSchema, validatesOnlyStrings } from \"../utils/json_schema.js\";\n\nexport type {\n BaseDynamicToolInput,\n ContentAndArtifact,\n DynamicToolInput,\n DynamicStructuredToolInput,\n ResponseFormat,\n StructuredToolCallInput,\n StructuredToolInterface,\n StructuredToolParams,\n ToolInterface,\n ToolParams,\n ToolReturnType,\n ToolRunnableConfig,\n ToolInputSchemaBase as ToolSchemaBase,\n} from \"./types.js\";\n\nexport {\n isLangChainTool,\n isRunnableToolLike,\n isStructuredTool,\n isStructuredToolParams,\n type ToolRuntime,\n} from \"./types.js\";\n\nexport { ToolInputParsingException };\n/**\n * Base class for Tools that accept input of any shape defined by a Zod schema.\n */\nexport abstract class StructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n>\n extends BaseLangChain<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolOutputT | ToolMessage\n >\n implements StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT>\n{\n abstract name: string;\n\n abstract description: string;\n\n abstract schema: SchemaT;\n\n /**\n * Optional provider-specific extra fields for the tool.\n *\n * This is used to pass provider-specific configuration that doesn't fit into\n * standard tool fields.\n */\n extras?: Record<string, unknown>;\n\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect = false;\n\n verboseParsingErrors = false;\n\n get lc_namespace() {\n return [\"langchain\", \"tools\"];\n }\n\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat = \"content\";\n\n /**\n * Default config object for the tool runnable.\n */\n defaultConfig?: ToolRunnableConfig;\n\n constructor(fields?: ToolParams) {\n super(fields ?? {});\n\n this.verboseParsingErrors =\n fields?.verboseParsingErrors ?? this.verboseParsingErrors;\n this.responseFormat = fields?.responseFormat ?? this.responseFormat;\n this.defaultConfig = fields?.defaultConfig ?? this.defaultConfig;\n this.metadata = fields?.metadata ?? this.metadata;\n this.extras = fields?.extras ?? this.extras;\n }\n\n protected abstract _call(\n arg: SchemaOutputT,\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT>;\n\n /**\n * Invokes the tool with the provided input and configuration.\n * @param input The input for the tool.\n * @param config Optional configuration for the tool.\n * @returns A Promise that resolves with the tool's output.\n */\n async invoke<\n TInput extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n input: TInput,\n config?: TConfig\n ): Promise<ToolReturnType<TInput, TConfig, ToolOutputT>> {\n let toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n\n let enrichedConfig: ToolRunnableConfig = ensureConfig(\n mergeConfigs(this.defaultConfig, config)\n );\n if (_isToolCall(input)) {\n toolInput = input.args as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n enrichedConfig = {\n ...enrichedConfig,\n toolCall: input,\n };\n } else {\n toolInput = input as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n }\n\n return this.call(toolInput, enrichedConfig) as Promise<\n ToolReturnType<TInput, TConfig, ToolOutputT>\n >;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument, configuration, and tags. It\n * parses the input according to the schema, handles any errors, and\n * manages callbacks.\n * @param arg The input argument for the tool.\n * @param configArg Optional configuration or callbacks for the tool.\n * @param tags Optional tags for the tool.\n * @returns A Promise that resolves with a string.\n */\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>> {\n // Determine the actual input that needs parsing/validation.\n // If arg is a ToolCall, use its args; otherwise, use arg directly.\n const inputForValidation = _isToolCall(arg) ? arg.args : arg;\n\n let parsed: SchemaOutputT; // This will hold the successfully parsed input of the expected output type.\n if (isInteropZodSchema(this.schema)) {\n try {\n // Validate the inputForValidation - TS needs help here as it can't exclude ToolCall based on the check\n parsed = await interopParseAsync(\n this.schema as InteropZodType,\n inputForValidation as Exclude<TArg, ToolCall>\n );\n } catch (e) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${(e as Error).message}`;\n }\n if (isInteropZodError(e)) {\n message = `${message}\\n\\n${z4.prettifyError(e as ZodError)}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n } else {\n const result = validate(\n inputForValidation,\n this.schema as ValidationSchema\n );\n if (!result.valid) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${result.errors\n .map((e) => `${e.keywordLocation}: ${e.error}`)\n .join(\"\\n\")}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n // Assign the validated input to parsed\n // We cast here because validate() doesn't narrow the type sufficiently for TS, but we know it's valid.\n parsed = inputForValidation as SchemaOutputT;\n }\n\n const config = parseCallbackConfigArg(configArg);\n const callbackManager_ = CallbackManager.configure(\n config.callbacks,\n this.callbacks,\n config.tags || tags,\n this.tags,\n config.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n const runManager = await callbackManager_?.handleToolStart(\n this.toJSON(),\n // Log the original raw input arg\n typeof arg === \"string\" ? arg : JSON.stringify(arg),\n config.runId,\n undefined,\n undefined,\n undefined,\n config.runName\n );\n delete config.runId;\n let result;\n try {\n // Pass the correctly typed parsed input to _call\n result = await this._call(parsed, runManager, config);\n } catch (e) {\n await runManager?.handleToolError(e);\n throw e;\n }\n let content;\n let artifact;\n if (this.responseFormat === \"content_and_artifact\") {\n if (Array.isArray(result) && result.length === 2) {\n [content, artifact] = result;\n } else {\n throw new Error(\n `Tool response format is \"content_and_artifact\" but the output was not a two-tuple.\\nResult: ${JSON.stringify(\n result\n )}`\n );\n }\n } else {\n content = result;\n }\n\n let toolCallId: string | undefined;\n // Extract toolCallId ONLY if the original arg was a ToolCall\n if (_isToolCall(arg)) {\n toolCallId = arg.id;\n }\n // Or if it was provided in the config's toolCall property\n if (!toolCallId && _configHasToolCallId(config)) {\n toolCallId = config.toolCall.id;\n }\n\n const formattedOutput = _formatToolOutput<ToolOutputT>({\n content,\n artifact,\n toolCallId,\n name: this.name,\n metadata: this.metadata,\n });\n await runManager?.handleToolEnd(formattedOutput);\n return formattedOutput as ToolReturnType<TArg, TConfig, ToolOutputT>;\n }\n}\n\n/**\n * Base class for Tools that accept input as a string.\n */\nexport abstract class Tool<ToolOutputT = ToolOutputType>\n extends StructuredTool<\n StringInputToolSchema,\n ToolInputSchemaOutputType<StringInputToolSchema>,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n implements\n ToolInterface<\n StringInputToolSchema,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n{\n schema = z\n .object({ input: z.string().optional() })\n .transform((obj) => obj.input);\n\n constructor(fields?: ToolParams) {\n super(fields);\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument and callbacks. It handles\n * string inputs specifically.\n * @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema.\n * @param callbacks Optional callbacks for the tool.\n * @returns A Promise that resolves with a string.\n */\n // Match the base class signature including the generics and conditional return type\n call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n callbacks?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n // Prepare the input for the base class call method.\n // If arg is string or undefined, wrap it; otherwise, pass ToolCall or { input: ... } directly.\n const structuredArg =\n typeof arg === \"string\" || arg == null ? { input: arg } : arg;\n\n // Ensure TConfig is passed to super.call\n return super.call(structuredArg, callbacks);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and description.\n */\nexport class DynamicTool<\n ToolOutputT = ToolOutputType,\n> extends Tool<ToolOutputT> {\n static lc_name() {\n return \"DynamicTool\";\n }\n\n name: string;\n\n description: string;\n\n func: DynamicToolInput<ToolOutputT>[\"func\"];\n\n constructor(fields: DynamicToolInput<ToolOutputT>) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n async call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n // Call the Tool class's call method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig);\n }\n\n /** @ignore */\n async _call(\n input: string, // DynamicTool's _call specifically expects a string after schema transformation\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT> {\n return this.func(input, runManager, parentConfig);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and\n * description, designed to work with structured data. It extends the\n * StructuredTool class and overrides the _call method to execute the\n * provided function when the tool is called.\n *\n * Schema can be passed as Zod or JSON schema. The tool will not validate\n * input if JSON schema is passed.\n *\n * @template SchemaT The input schema type for the tool (Zod schema or JSON schema). Defaults to `ToolInputSchemaBase`.\n * @template SchemaOutputT The output type derived from the schema after parsing/validation. Defaults to `ToolInputSchemaOutputType<SchemaT>`.\n * @template SchemaInputT The input type derived from the schema before parsing. Defaults to `ToolInputSchemaInputType<SchemaT>`.\n * @template ToolOutputT The return type of the tool's function. Defaults to `ToolOutputType`.\n * @template NameT The literal type of the tool name (for discriminated union support). Defaults to `string`.\n */\nexport class DynamicStructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n NameT extends string = string,\n> extends StructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT> {\n static lc_name() {\n return \"DynamicStructuredTool\";\n }\n\n declare name: NameT;\n\n description: string;\n\n func: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>[\"func\"];\n\n schema: SchemaT;\n\n constructor(\n fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT> & {\n name: NameT;\n }\n ) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n this.schema = fields.schema;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n // Match the base class signature\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n\n // Call the base class method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig, tags);\n }\n\n protected _call(\n arg: Parameters<\n DynamicStructuredToolInput<SchemaT, SchemaOutputT>[\"func\"]\n >[0],\n runManager?: CallbackManagerForToolRun,\n parentConfig?: RunnableConfig\n ): Promise<ToolOutputT> {\n return this.func(arg, runManager, parentConfig);\n }\n}\n\n/**\n * Abstract base class for toolkits in LangChain. Toolkits are collections\n * of tools that agents can use. Subclasses must implement the `tools`\n * property to provide the specific tools for the toolkit.\n */\nexport abstract class BaseToolkit {\n abstract tools: StructuredToolInterface[];\n\n getTools(): StructuredToolInterface[] {\n return this.tools;\n }\n}\n\n/**\n * Parameters for the tool function.\n * Schema can be provided as Zod or JSON schema.\n * Both schema types will be validated.\n * @template {ToolInputSchemaBase} RunInput The input schema for the tool.\n * @template {string} NameT The literal name type for discriminated union support.\n */\ninterface ToolWrapperParams<\n RunInput = ToolInputSchemaBase | undefined,\n NameT extends string = string,\n> extends ToolParams {\n /**\n * The name of the tool. If using with an LLM, this\n * will be passed as the tool name.\n */\n name: NameT;\n /**\n * The description of the tool.\n * @default `${fields.name} tool`\n */\n description?: string;\n /**\n * The input schema for the tool. If using an LLM, this\n * will be passed as the tool schema to generate arguments\n * for.\n */\n schema?: RunInput;\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat;\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect?: boolean;\n}\n\n/**\n * Creates a new StructuredTool instance with the provided function, name, description, and schema.\n *\n * Schema can be provided as Zod or JSON schema, and both will be validated.\n *\n * @function\n * @template {ToolInputSchemaBase} SchemaT The input schema for the tool.\n * @template {ToolReturnType} ToolOutputT The output type of the tool.\n *\n * @param {RunnableFunc<z.output<SchemaT>, ToolOutputT>} func - The function to invoke when the tool is called.\n * @param {ToolWrapperParams<SchemaT>} fields - An object containing the following properties:\n * @param {string} fields.name The name of the tool.\n * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.\n * @param {z.AnyZodObject | z.ZodString | undefined} fields.schema The Zod schema defining the input for the tool. If undefined, it will default to a Zod string schema.\n *\n * @returns {DynamicStructuredTool<SchemaT>} A new StructuredTool instance.\n */\nexport function tool<SchemaT extends ZodStringV3, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<SchemaT extends ZodStringV4, ToolOutputT = ToolOutputType>(\n func: RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n NameT extends string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n>(\n func: RunnableFunc<\n Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n ToolOutputT,\n ToolRunnableConfig\n >,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends InteropZodObject | InteropZodType<string> | JSONSchema =\n InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n>(\n func: RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >\n | DynamicTool<ToolOutputT>;\n\n// Overloads with ToolRuntime as CallOptions\nexport function tool<\n SchemaT extends ZodStringV3,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodStringV4,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n NameT extends string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n>;\n\nexport function tool<\n SchemaT extends InteropZodObject | InteropZodType<string> | JSONSchema =\n InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >\n | DynamicTool<ToolOutputT> {\n const isSimpleStringSchema = isSimpleStringZodSchema(fields.schema);\n const isStringJSONSchema = validatesOnlyStrings(fields.schema);\n\n // If the schema is not provided, or it's a simple string schema, create a DynamicTool\n if (!fields.schema || isSimpleStringSchema || isStringJSONSchema) {\n return new DynamicTool<ToolOutputT>({\n ...fields,\n description:\n fields.description ??\n (fields.schema as { description?: string } | undefined)?.description ??\n `${fields.name} tool`,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n resolve(func(input as any, childConfig as any));\n } catch (e) {\n reject(e);\n }\n }\n );\n });\n },\n });\n }\n\n const schema = fields.schema as InteropZodObject | JSONSchema;\n\n const description =\n fields.description ??\n (fields.schema as { description?: string }).description ??\n `${fields.name} tool`;\n\n return new DynamicStructuredTool<\n typeof schema,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >({\n ...fields,\n description,\n schema,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n let listener: (() => void) | undefined;\n const cleanup = () => {\n if (config?.signal && listener) {\n config.signal.removeEventListener(\"abort\", listener);\n }\n };\n\n if (config?.signal) {\n listener = () => {\n cleanup();\n reject(getAbortSignalError(config.signal));\n };\n config.signal.addEventListener(\"abort\", listener, { once: true });\n }\n\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // eslint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await func(input as any, childConfig as any);\n\n /**\n * If the signal is aborted, we don't want to resolve the promise\n * as the promise is already rejected.\n */\n if (config?.signal?.aborted) {\n cleanup();\n return;\n }\n\n cleanup();\n resolve(result);\n } catch (e) {\n cleanup();\n reject(e);\n }\n }\n );\n });\n },\n }) as DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n NameT\n >;\n}\n\nfunction _formatToolOutput<TOutput extends ToolOutputType>(params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}): ToolMessage | TOutput {\n const { content, artifact, toolCallId, metadata } = params;\n if (toolCallId && !isDirectToolOutput(content)) {\n if (\n typeof content === \"string\" ||\n (Array.isArray(content) &&\n content.every((item) => typeof item === \"object\"))\n ) {\n return new ToolMessage({\n status: \"success\",\n content,\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n } else {\n return new ToolMessage({\n status: \"success\",\n content: _stringify(content),\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n }\n } else {\n return content;\n }\n}\n\nfunction _stringify(content: unknown): string {\n try {\n return JSON.stringify(content) ?? \"\";\n } catch (_noOp) {\n return `${content}`;\n }\n}\n\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool =\n | StructuredToolInterface\n | DynamicTool\n | RunnableToolLike;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0FA,IAAsB,iBAAtB,cAMU,cAKV;;;;;;;CAaE;;;;;;;CAQA,eAAe;CAEf,uBAAuB;CAEvB,IAAI,eAAe;AACjB,SAAO,CAAC,aAAa,OAAQ;CAC9B;;;;;;;;;;CAWD,iBAAkC;;;;CAKlC;CAEA,YAAYA,QAAqB;EAC/B,MAAM,UAAU,CAAE,EAAC;EAEnB,KAAK,uBACH,QAAQ,wBAAwB,KAAK;EACvC,KAAK,iBAAiB,QAAQ,kBAAkB,KAAK;EACrD,KAAK,gBAAgB,QAAQ,iBAAiB,KAAK;EACnD,KAAK,WAAW,QAAQ,YAAY,KAAK;EACzC,KAAK,SAAS,QAAQ,UAAU,KAAK;CACtC;;;;;;;CAcD,MAAM,OAIJC,OACAC,QACuD;EACvD,IAAIC;EAKJ,IAAIC,iBAAqC,aACvC,aAAa,KAAK,eAAe,OAAO,CACzC;AACD,MAAI,YAAY,MAAM,EAAE;GACtB,YAAY,MAAM;GAIlB,iBAAiB;IACf,GAAG;IACH,UAAU;GACX;EACF,OACC,YAAY;AAMd,SAAO,KAAK,KAAK,WAAW,eAAe;CAG5C;;;;;;;;;;;;CAaD,MAAM,KAIJC,KACAC,WAEAC,MACqD;EA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