base.d.ts 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  1. import { z } from "zod";
  2. import { type TraceableFunction } from "langsmith/singletons/traceable";
  3. import type { RunnableInterface, RunnableBatchOptions, RunnableConfig } from "./types.js";
  4. import { CallbackManagerForChainRun } from "../callbacks/manager.js";
  5. import { LogStreamCallbackHandler, LogStreamCallbackHandlerInput, RunLogPatch } from "../tracers/log_stream.js";
  6. import { EventStreamCallbackHandlerInput, StreamEvent } from "../tracers/event_stream.js";
  7. import { Serializable } from "../load/serializable.js";
  8. import { IterableReadableStream } from "../utils/stream.js";
  9. import { Run } from "../tracers/base.js";
  10. import { Graph } from "./graph.js";
  11. import { ToolCall } from "../messages/tool.js";
  12. export { type RunnableInterface, RunnableBatchOptions };
  13. export type RunnableFunc<RunInput, RunOutput, CallOptions extends RunnableConfig = RunnableConfig> = (input: RunInput, options: CallOptions | Record<string, any> | (Record<string, any> & CallOptions)) => RunOutput | Promise<RunOutput>;
  14. export type RunnableMapLike<RunInput, RunOutput> = {
  15. [K in keyof RunOutput]: RunnableLike<RunInput, RunOutput[K]>;
  16. };
  17. export type RunnableLike<RunInput = any, RunOutput = any, CallOptions extends RunnableConfig = RunnableConfig> = RunnableInterface<RunInput, RunOutput, CallOptions> | RunnableFunc<RunInput, RunOutput, CallOptions> | RunnableMapLike<RunInput, RunOutput>;
  18. export type RunnableRetryFailedAttemptHandler = (error: any, input: any) => any;
  19. export declare function _coerceToDict(value: any, defaultKey: string): any;
  20. /**
  21. * A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or
  22. * transformed.
  23. */
  24. export declare abstract class Runnable<RunInput = any, RunOutput = any, CallOptions extends RunnableConfig = RunnableConfig> extends Serializable implements RunnableInterface<RunInput, RunOutput, CallOptions> {
  25. protected lc_runnable: boolean;
  26. name?: string;
  27. getName(suffix?: string): string;
  28. abstract invoke(input: RunInput, options?: Partial<CallOptions>): Promise<RunOutput>;
  29. /**
  30. * Bind arguments to a Runnable, returning a new Runnable.
  31. * @param kwargs
  32. * @returns A new RunnableBinding that, when invoked, will apply the bound args.
  33. *
  34. * @deprecated Use {@link withConfig} instead. This will be removed in the next breaking release.
  35. */
  36. bind(kwargs: Partial<CallOptions>): Runnable<RunInput, RunOutput, CallOptions>;
  37. /**
  38. * Return a new Runnable that maps a list of inputs to a list of outputs,
  39. * by calling invoke() with each input.
  40. *
  41. * @deprecated This will be removed in the next breaking release.
  42. */
  43. map(): Runnable<RunInput[], RunOutput[], CallOptions>;
  44. /**
  45. * Add retry logic to an existing runnable.
  46. * @param fields.stopAfterAttempt The number of attempts to retry.
  47. * @param fields.onFailedAttempt A function that is called when a retry fails.
  48. * @returns A new RunnableRetry that, when invoked, will retry according to the parameters.
  49. */
  50. withRetry(fields?: {
  51. stopAfterAttempt?: number;
  52. onFailedAttempt?: RunnableRetryFailedAttemptHandler;
  53. }): RunnableRetry<RunInput, RunOutput, CallOptions>;
  54. /**
  55. * Bind config to a Runnable, returning a new Runnable.
  56. * @param config New configuration parameters to attach to the new runnable.
  57. * @returns A new RunnableBinding with a config matching what's passed.
  58. */
  59. withConfig(config: Partial<CallOptions>): Runnable<RunInput, RunOutput, CallOptions>;
  60. /**
  61. * Create a new runnable from the current one that will try invoking
  62. * other passed fallback runnables if the initial invocation fails.
  63. * @param fields.fallbacks Other runnables to call if the runnable errors.
  64. * @returns A new RunnableWithFallbacks.
  65. */
  66. withFallbacks(fields: {
  67. fallbacks: Runnable<RunInput, RunOutput>[];
  68. } | Runnable<RunInput, RunOutput>[]): RunnableWithFallbacks<RunInput, RunOutput>;
  69. protected _getOptionsList<O extends CallOptions & {
  70. runType?: string;
  71. }>(options: Partial<O> | Partial<O>[], length?: number): Partial<O>[];
  72. /**
  73. * Default implementation of batch, which calls invoke N times.
  74. * Subclasses should override this method if they can batch more efficiently.
  75. * @param inputs Array of inputs to each batch call.
  76. * @param options Either a single call options object to apply to each batch call or an array for each call.
  77. * @param batchOptions.returnExceptions Whether to return errors rather than throwing on the first one
  78. * @returns An array of RunOutputs, or mixed RunOutputs and errors if batchOptions.returnExceptions is set
  79. */
  80. batch(inputs: RunInput[], options?: Partial<CallOptions> | Partial<CallOptions>[], batchOptions?: RunnableBatchOptions & {
  81. returnExceptions?: false;
  82. }): Promise<RunOutput[]>;
  83. batch(inputs: RunInput[], options?: Partial<CallOptions> | Partial<CallOptions>[], batchOptions?: RunnableBatchOptions & {
  84. returnExceptions: true;
  85. }): Promise<(RunOutput | Error)[]>;
  86. batch(inputs: RunInput[], options?: Partial<CallOptions> | Partial<CallOptions>[], batchOptions?: RunnableBatchOptions): Promise<(RunOutput | Error)[]>;
  87. /**
  88. * Default streaming implementation.
  89. * Subclasses should override this method if they support streaming output.
  90. * @param input
  91. * @param options
  92. */
  93. _streamIterator(input: RunInput, options?: Partial<CallOptions>): AsyncGenerator<RunOutput>;
  94. /**
  95. * Stream output in chunks.
  96. * @param input
  97. * @param options
  98. * @returns A readable stream that is also an iterable.
  99. */
  100. stream(input: RunInput, options?: Partial<CallOptions>): Promise<IterableReadableStream<RunOutput>>;
  101. protected _separateRunnableConfigFromCallOptions(options?: Partial<CallOptions>): [RunnableConfig, Omit<Partial<CallOptions>, keyof RunnableConfig>];
  102. protected _callWithConfig<T extends RunInput>(func: ((input: T) => Promise<RunOutput>) | ((input: T, config?: Partial<CallOptions>, runManager?: CallbackManagerForChainRun) => Promise<RunOutput>), input: T, options?: Partial<CallOptions> & {
  103. runType?: string;
  104. }): Promise<RunOutput>;
  105. /**
  106. * Internal method that handles batching and configuration for a runnable
  107. * It takes a function, input values, and optional configuration, and
  108. * returns a promise that resolves to the output values.
  109. * @param func The function to be executed for each input value.
  110. * @param input The input values to be processed.
  111. * @param config Optional configuration for the function execution.
  112. * @returns A promise that resolves to the output values.
  113. */
  114. _batchWithConfig<T extends RunInput>(func: (inputs: T[], options?: Partial<CallOptions>[], runManagers?: (CallbackManagerForChainRun | undefined)[], batchOptions?: RunnableBatchOptions) => Promise<(RunOutput | Error)[]>, inputs: T[], options?: Partial<CallOptions & {
  115. runType?: string;
  116. }> | Partial<CallOptions & {
  117. runType?: string;
  118. }>[], batchOptions?: RunnableBatchOptions): Promise<(RunOutput | Error)[]>;
  119. /**
  120. * Helper method to transform an Iterator of Input values into an Iterator of
  121. * Output values, with callbacks.
  122. * Use this to implement `stream()` or `transform()` in Runnable subclasses.
  123. */
  124. protected _transformStreamWithConfig<I extends RunInput, O extends RunOutput>(inputGenerator: AsyncGenerator<I>, transformer: (generator: AsyncGenerator<I>, runManager?: CallbackManagerForChainRun, options?: Partial<CallOptions>) => AsyncGenerator<O>, options?: Partial<CallOptions> & {
  125. runType?: string;
  126. }): AsyncGenerator<O>;
  127. getGraph(_?: RunnableConfig): Graph;
  128. /**
  129. * Create a new runnable sequence that runs each individual runnable in series,
  130. * piping the output of one runnable into another runnable or runnable-like.
  131. * @param coerceable A runnable, function, or object whose values are functions or runnables.
  132. * @returns A new runnable sequence.
  133. */
  134. pipe<NewRunOutput>(coerceable: RunnableLike<RunOutput, NewRunOutput>): Runnable<RunInput, Exclude<NewRunOutput, Error>>;
  135. /**
  136. * Pick keys from the dict output of this runnable. Returns a new runnable.
  137. */
  138. pick(keys: string | string[]): Runnable;
  139. /**
  140. * Assigns new fields to the dict output of this runnable. Returns a new runnable.
  141. */
  142. assign(mapping: RunnableMapLike<Record<string, unknown>, Record<string, unknown>>): Runnable;
  143. /**
  144. * Default implementation of transform, which buffers input and then calls stream.
  145. * Subclasses should override this method if they can start producing output while
  146. * input is still being generated.
  147. * @param generator
  148. * @param options
  149. */
  150. transform(generator: AsyncGenerator<RunInput>, options: Partial<CallOptions>): AsyncGenerator<RunOutput>;
  151. /**
  152. * Stream all output from a runnable, as reported to the callback system.
  153. * This includes all inner runs of LLMs, Retrievers, Tools, etc.
  154. * Output is streamed as Log objects, which include a list of
  155. * jsonpatch ops that describe how the state of the run has changed in each
  156. * step, and the final state of the run.
  157. * The jsonpatch ops can be applied in order to construct state.
  158. * @param input
  159. * @param options
  160. * @param streamOptions
  161. */
  162. streamLog(input: RunInput, options?: Partial<CallOptions>, streamOptions?: Omit<LogStreamCallbackHandlerInput, "autoClose">): AsyncGenerator<RunLogPatch>;
  163. protected _streamLog(input: RunInput, logStreamCallbackHandler: LogStreamCallbackHandler, config: Partial<CallOptions>): AsyncGenerator<RunLogPatch>;
  164. /**
  165. * Generate a stream of events emitted by the internal steps of the runnable.
  166. *
  167. * Use to create an iterator over StreamEvents that provide real-time information
  168. * about the progress of the runnable, including StreamEvents from intermediate
  169. * results.
  170. *
  171. * A StreamEvent is a dictionary with the following schema:
  172. *
  173. * - `event`: string - Event names are of the format: on_[runnable_type]_(start|stream|end).
  174. * - `name`: string - The name of the runnable that generated the event.
  175. * - `run_id`: string - Randomly generated ID associated with the given execution of
  176. * the runnable that emitted the event. A child runnable that gets invoked as part of the execution of a
  177. * parent runnable is assigned its own unique ID.
  178. * - `tags`: string[] - The tags of the runnable that generated the event.
  179. * - `metadata`: Record<string, any> - The metadata of the runnable that generated the event.
  180. * - `data`: Record<string, any>
  181. *
  182. * Below is a table that illustrates some events that might be emitted by various
  183. * chains. Metadata fields have been omitted from the table for brevity.
  184. * Chain definitions have been included after the table.
  185. *
  186. * **ATTENTION** This reference table is for the V2 version of the schema.
  187. *
  188. * ```md
  189. * +----------------------+-----------------------------+------------------------------------------+
  190. * | event | input | output/chunk |
  191. * +======================+=============================+==========================================+
  192. * | on_chat_model_start | {"messages": BaseMessage[]} | |
  193. * +----------------------+-----------------------------+------------------------------------------+
  194. * | on_chat_model_stream | | AIMessageChunk("hello") |
  195. * +----------------------+-----------------------------+------------------------------------------+
  196. * | on_chat_model_end | {"messages": BaseMessage[]} | AIMessageChunk("hello world") |
  197. * +----------------------+-----------------------------+------------------------------------------+
  198. * | on_llm_start | {'input': 'hello'} | |
  199. * +----------------------+-----------------------------+------------------------------------------+
  200. * | on_llm_stream | | 'Hello' |
  201. * +----------------------+-----------------------------+------------------------------------------+
  202. * | on_llm_end | 'Hello human!' | |
  203. * +----------------------+-----------------------------+------------------------------------------+
  204. * | on_chain_start | | |
  205. * +----------------------+-----------------------------+------------------------------------------+
  206. * | on_chain_stream | | "hello world!" |
  207. * +----------------------+-----------------------------+------------------------------------------+
  208. * | on_chain_end | [Document(...)] | "hello world!, goodbye world!" |
  209. * +----------------------+-----------------------------+------------------------------------------+
  210. * | on_tool_start | {"x": 1, "y": "2"} | |
  211. * +----------------------+-----------------------------+------------------------------------------+
  212. * | on_tool_end | | {"x": 1, "y": "2"} |
  213. * +----------------------+-----------------------------+------------------------------------------+
  214. * | on_retriever_start | {"query": "hello"} | |
  215. * +----------------------+-----------------------------+------------------------------------------+
  216. * | on_retriever_end | {"query": "hello"} | [Document(...), ..] |
  217. * +----------------------+-----------------------------+------------------------------------------+
  218. * | on_prompt_start | {"question": "hello"} | |
  219. * +----------------------+-----------------------------+------------------------------------------+
  220. * | on_prompt_end | {"question": "hello"} | ChatPromptValue(messages: BaseMessage[]) |
  221. * +----------------------+-----------------------------+------------------------------------------+
  222. * ```
  223. *
  224. * The "on_chain_*" events are the default for Runnables that don't fit one of the above categories.
  225. *
  226. * In addition to the standard events above, users can also dispatch custom events.
  227. *
  228. * Custom events will be only be surfaced with in the `v2` version of the API!
  229. *
  230. * A custom event has following format:
  231. *
  232. * ```md
  233. * +-----------+------+------------------------------------------------------------+
  234. * | Attribute | Type | Description |
  235. * +===========+======+============================================================+
  236. * | name | str | A user defined name for the event. |
  237. * +-----------+------+------------------------------------------------------------+
  238. * | data | Any | The data associated with the event. This can be anything. |
  239. * +-----------+------+------------------------------------------------------------+
  240. * ```
  241. *
  242. * Here's an example:
  243. *
  244. * ```ts
  245. * import { RunnableLambda } from "@langchain/core/runnables";
  246. * import { dispatchCustomEvent } from "@langchain/core/callbacks/dispatch";
  247. * // Use this import for web environments that don't support "async_hooks"
  248. * // and manually pass config to child runs.
  249. * // import { dispatchCustomEvent } from "@langchain/core/callbacks/dispatch/web";
  250. *
  251. * const slowThing = RunnableLambda.from(async (someInput: string) => {
  252. * // Placeholder for some slow operation
  253. * await new Promise((resolve) => setTimeout(resolve, 100));
  254. * await dispatchCustomEvent("progress_event", {
  255. * message: "Finished step 1 of 2",
  256. * });
  257. * await new Promise((resolve) => setTimeout(resolve, 100));
  258. * return "Done";
  259. * });
  260. *
  261. * const eventStream = await slowThing.streamEvents("hello world", {
  262. * version: "v2",
  263. * });
  264. *
  265. * for await (const event of eventStream) {
  266. * if (event.event === "on_custom_event") {
  267. * console.log(event);
  268. * }
  269. * }
  270. * ```
  271. */
  272. streamEvents(input: RunInput, options: Partial<CallOptions> & {
  273. version: "v1" | "v2";
  274. }, streamOptions?: Omit<EventStreamCallbackHandlerInput, "autoClose">): IterableReadableStream<StreamEvent>;
  275. streamEvents(input: RunInput, options: Partial<CallOptions> & {
  276. version: "v1" | "v2";
  277. encoding: "text/event-stream";
  278. }, streamOptions?: Omit<EventStreamCallbackHandlerInput, "autoClose">): IterableReadableStream<Uint8Array>;
  279. private _streamEventsV2;
  280. private _streamEventsV1;
  281. static isRunnable(thing: any): thing is Runnable;
  282. /**
  283. * Bind lifecycle listeners to a Runnable, returning a new Runnable.
  284. * The Run object contains information about the run, including its id,
  285. * type, input, output, error, startTime, endTime, and any tags or metadata
  286. * added to the run.
  287. *
  288. * @param {Object} params - The object containing the callback functions.
  289. * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.
  290. * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.
  291. * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.
  292. */
  293. withListeners({ onStart, onEnd, onError, }: {
  294. onStart?: (run: Run, config?: RunnableConfig) => void | Promise<void>;
  295. onEnd?: (run: Run, config?: RunnableConfig) => void | Promise<void>;
  296. onError?: (run: Run, config?: RunnableConfig) => void | Promise<void>;
  297. }): Runnable<RunInput, RunOutput, CallOptions>;
  298. /**
  299. * Convert a runnable to a tool. Return a new instance of `RunnableToolLike`
  300. * which contains the runnable, name, description and schema.
  301. *
  302. * @template {T extends RunInput = RunInput} RunInput - The input type of the runnable. Should be the same as the `RunInput` type of the runnable.
  303. *
  304. * @param fields
  305. * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable.
  306. * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided.
  307. * @param {z.ZodType<T>} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable.
  308. * @returns {RunnableToolLike<z.ZodType<T>, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool.
  309. */
  310. asTool<T extends RunInput = RunInput>(fields: {
  311. name?: string;
  312. description?: string;
  313. schema: z.ZodType<T>;
  314. }): RunnableToolLike<z.ZodType<T | ToolCall>, RunOutput>;
  315. }
  316. export type RunnableBindingArgs<RunInput, RunOutput, CallOptions extends RunnableConfig = RunnableConfig> = {
  317. bound: Runnable<RunInput, RunOutput, CallOptions>;
  318. /**
  319. * @deprecated use {@link config} instead
  320. */
  321. kwargs?: Partial<CallOptions>;
  322. config: RunnableConfig;
  323. configFactories?: Array<(config: RunnableConfig) => RunnableConfig | Promise<RunnableConfig>>;
  324. };
  325. /**
  326. * Wraps a runnable and applies partial config upon invocation.
  327. *
  328. * @example
  329. * ```typescript
  330. * import {
  331. * type RunnableConfig,
  332. * RunnableLambda,
  333. * } from "@langchain/core/runnables";
  334. *
  335. * const enhanceProfile = (
  336. * profile: Record<string, any>,
  337. * config?: RunnableConfig
  338. * ) => {
  339. * if (config?.configurable?.role) {
  340. * return { ...profile, role: config.configurable.role };
  341. * }
  342. * return profile;
  343. * };
  344. *
  345. * const runnable = RunnableLambda.from(enhanceProfile);
  346. *
  347. * // Bind configuration to the runnable to set the user's role dynamically
  348. * const adminRunnable = runnable.bind({ configurable: { role: "Admin" } });
  349. * const userRunnable = runnable.bind({ configurable: { role: "User" } });
  350. *
  351. * const result1 = await adminRunnable.invoke({
  352. * name: "Alice",
  353. * email: "alice@example.com"
  354. * });
  355. *
  356. * // { name: "Alice", email: "alice@example.com", role: "Admin" }
  357. *
  358. * const result2 = await userRunnable.invoke({
  359. * name: "Bob",
  360. * email: "bob@example.com"
  361. * });
  362. *
  363. * // { name: "Bob", email: "bob@example.com", role: "User" }
  364. * ```
  365. */
  366. export declare class RunnableBinding<RunInput, RunOutput, CallOptions extends RunnableConfig = RunnableConfig> extends Runnable<RunInput, RunOutput, CallOptions> {
  367. static lc_name(): string;
  368. lc_namespace: string[];
  369. lc_serializable: boolean;
  370. bound: Runnable<RunInput, RunOutput, CallOptions>;
  371. config: RunnableConfig;
  372. kwargs?: Partial<CallOptions>;
  373. configFactories?: Array<(config: RunnableConfig) => RunnableConfig | Promise<RunnableConfig>>;
  374. constructor(fields: RunnableBindingArgs<RunInput, RunOutput, CallOptions>);
  375. getName(suffix?: string | undefined): string;
  376. _mergeConfig(...options: (Partial<CallOptions> | RunnableConfig | undefined)[]): Promise<Partial<CallOptions>>;
  377. /**
  378. * Binds the runnable with the specified arguments.
  379. * @param kwargs The arguments to bind the runnable with.
  380. * @returns A new instance of the `RunnableBinding` class that is bound with the specified arguments.
  381. *
  382. * @deprecated Use {@link withConfig} instead. This will be removed in the next breaking release.
  383. */
  384. bind(kwargs: Partial<CallOptions>): RunnableBinding<RunInput, RunOutput, CallOptions>;
  385. withConfig(config: Partial<CallOptions>): Runnable<RunInput, RunOutput, CallOptions>;
  386. withRetry(fields?: {
  387. stopAfterAttempt?: number;
  388. onFailedAttempt?: RunnableRetryFailedAttemptHandler;
  389. }): RunnableRetry<RunInput, RunOutput, CallOptions>;
  390. invoke(input: RunInput, options?: Partial<CallOptions>): Promise<RunOutput>;
  391. batch(inputs: RunInput[], options?: Partial<CallOptions> | Partial<CallOptions>[], batchOptions?: RunnableBatchOptions & {
  392. returnExceptions?: false;
  393. }): Promise<RunOutput[]>;
  394. batch(inputs: RunInput[], options?: Partial<CallOptions> | Partial<CallOptions>[], batchOptions?: RunnableBatchOptions & {
  395. returnExceptions: true;
  396. }): Promise<(RunOutput | Error)[]>;
  397. batch(inputs: RunInput[], options?: Partial<CallOptions> | Partial<CallOptions>[], batchOptions?: RunnableBatchOptions): Promise<(RunOutput | Error)[]>;
  398. _streamIterator(input: RunInput, options?: Partial<CallOptions> | undefined): AsyncGenerator<Awaited<RunOutput>, void, unknown>;
  399. stream(input: RunInput, options?: Partial<CallOptions> | undefined): Promise<IterableReadableStream<RunOutput>>;
  400. transform(generator: AsyncGenerator<RunInput>, options?: Partial<CallOptions>): AsyncGenerator<RunOutput>;
  401. streamEvents(input: RunInput, options: Partial<CallOptions> & {
  402. version: "v1" | "v2";
  403. }, streamOptions?: Omit<LogStreamCallbackHandlerInput, "autoClose">): IterableReadableStream<StreamEvent>;
  404. streamEvents(input: RunInput, options: Partial<CallOptions> & {
  405. version: "v1" | "v2";
  406. encoding: "text/event-stream";
  407. }, streamOptions?: Omit<LogStreamCallbackHandlerInput, "autoClose">): IterableReadableStream<Uint8Array>;
  408. static isRunnableBinding(thing: any): thing is RunnableBinding<any, any, any>;
  409. /**
  410. * Bind lifecycle listeners to a Runnable, returning a new Runnable.
  411. * The Run object contains information about the run, including its id,
  412. * type, input, output, error, startTime, endTime, and any tags or metadata
  413. * added to the run.
  414. *
  415. * @param {Object} params - The object containing the callback functions.
  416. * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.
  417. * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.
  418. * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.
  419. */
  420. withListeners({ onStart, onEnd, onError, }: {
  421. onStart?: (run: Run, config?: RunnableConfig) => void | Promise<void>;
  422. onEnd?: (run: Run, config?: RunnableConfig) => void | Promise<void>;
  423. onError?: (run: Run, config?: RunnableConfig) => void | Promise<void>;
  424. }): Runnable<RunInput, RunOutput, CallOptions>;
  425. }
  426. /**
  427. * A runnable that delegates calls to another runnable
  428. * with each element of the input sequence.
  429. * @example
  430. * ```typescript
  431. * import { RunnableEach, RunnableLambda } from "@langchain/core/runnables";
  432. *
  433. * const toUpperCase = (input: string): string => input.toUpperCase();
  434. * const addGreeting = (input: string): string => `Hello, ${input}!`;
  435. *
  436. * const upperCaseLambda = RunnableLambda.from(toUpperCase);
  437. * const greetingLambda = RunnableLambda.from(addGreeting);
  438. *
  439. * const chain = new RunnableEach({
  440. * bound: upperCaseLambda.pipe(greetingLambda),
  441. * });
  442. *
  443. * const result = await chain.invoke(["alice", "bob", "carol"])
  444. *
  445. * // ["Hello, ALICE!", "Hello, BOB!", "Hello, CAROL!"]
  446. * ```
  447. *
  448. * @deprecated This will be removed in the next breaking release.
  449. */
  450. export declare class RunnableEach<RunInputItem, RunOutputItem, CallOptions extends RunnableConfig> extends Runnable<RunInputItem[], RunOutputItem[], CallOptions> {
  451. static lc_name(): string;
  452. lc_serializable: boolean;
  453. lc_namespace: string[];
  454. bound: Runnable<RunInputItem, RunOutputItem, CallOptions>;
  455. constructor(fields: {
  456. bound: Runnable<RunInputItem, RunOutputItem, CallOptions>;
  457. });
  458. /**
  459. * Binds the runnable with the specified arguments.
  460. * @param kwargs The arguments to bind the runnable with.
  461. * @returns A new instance of the `RunnableEach` class that is bound with the specified arguments.
  462. *
  463. * @deprecated Use {@link withConfig} instead. This will be removed in the next breaking release.
  464. */
  465. bind(kwargs: Partial<CallOptions>): RunnableEach<RunInputItem, RunOutputItem, CallOptions>;
  466. /**
  467. * Invokes the runnable with the specified input and configuration.
  468. * @param input The input to invoke the runnable with.
  469. * @param config The configuration to invoke the runnable with.
  470. * @returns A promise that resolves to the output of the runnable.
  471. */
  472. invoke(inputs: RunInputItem[], config?: Partial<CallOptions>): Promise<RunOutputItem[]>;
  473. /**
  474. * A helper method that is used to invoke the runnable with the specified input and configuration.
  475. * @param input The input to invoke the runnable with.
  476. * @param config The configuration to invoke the runnable with.
  477. * @returns A promise that resolves to the output of the runnable.
  478. */
  479. protected _invoke(inputs: RunInputItem[], config?: Partial<CallOptions>, runManager?: CallbackManagerForChainRun): Promise<RunOutputItem[]>;
  480. /**
  481. * Bind lifecycle listeners to a Runnable, returning a new Runnable.
  482. * The Run object contains information about the run, including its id,
  483. * type, input, output, error, startTime, endTime, and any tags or metadata
  484. * added to the run.
  485. *
  486. * @param {Object} params - The object containing the callback functions.
  487. * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.
  488. * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.
  489. * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.
  490. */
  491. withListeners({ onStart, onEnd, onError, }: {
  492. onStart?: (run: Run, config?: RunnableConfig) => void | Promise<void>;
  493. onEnd?: (run: Run, config?: RunnableConfig) => void | Promise<void>;
  494. onError?: (run: Run, config?: RunnableConfig) => void | Promise<void>;
  495. }): Runnable<any, any, CallOptions>;
  496. }
  497. /**
  498. * Base class for runnables that can be retried a
  499. * specified number of times.
  500. * @example
  501. * ```typescript
  502. * import {
  503. * RunnableLambda,
  504. * RunnableRetry,
  505. * } from "@langchain/core/runnables";
  506. *
  507. * // Simulate an API call that fails
  508. * const simulateApiCall = (input: string): string => {
  509. * console.log(`Attempting API call with input: ${input}`);
  510. * throw new Error("API call failed due to network issue");
  511. * };
  512. *
  513. * const apiCallLambda = RunnableLambda.from(simulateApiCall);
  514. *
  515. * // Apply retry logic using the .withRetry() method
  516. * const apiCallWithRetry = apiCallLambda.withRetry({ stopAfterAttempt: 3 });
  517. *
  518. * // Alternatively, create a RunnableRetry instance manually
  519. * const manualRetry = new RunnableRetry({
  520. * bound: apiCallLambda,
  521. * maxAttemptNumber: 3,
  522. * config: {},
  523. * });
  524. *
  525. * // Example invocation using the .withRetry() method
  526. * const res = await apiCallWithRetry
  527. * .invoke("Request 1")
  528. * .catch((error) => {
  529. * console.error("Failed after multiple retries:", error.message);
  530. * });
  531. *
  532. * // Example invocation using the manual retry instance
  533. * const res2 = await manualRetry
  534. * .invoke("Request 2")
  535. * .catch((error) => {
  536. * console.error("Failed after multiple retries:", error.message);
  537. * });
  538. * ```
  539. */
  540. export declare class RunnableRetry<RunInput = any, RunOutput = any, CallOptions extends RunnableConfig = RunnableConfig> extends RunnableBinding<RunInput, RunOutput, CallOptions> {
  541. static lc_name(): string;
  542. lc_namespace: string[];
  543. protected maxAttemptNumber: number;
  544. onFailedAttempt: RunnableRetryFailedAttemptHandler;
  545. constructor(fields: RunnableBindingArgs<RunInput, RunOutput, CallOptions> & {
  546. maxAttemptNumber?: number;
  547. onFailedAttempt?: RunnableRetryFailedAttemptHandler;
  548. });
  549. _patchConfigForRetry(attempt: number, config?: Partial<CallOptions>, runManager?: CallbackManagerForChainRun): Partial<CallOptions>;
  550. protected _invoke(input: RunInput, config?: CallOptions, runManager?: CallbackManagerForChainRun): Promise<RunOutput>;
  551. /**
  552. * Method that invokes the runnable with the specified input, run manager,
  553. * and config. It handles the retry logic by catching any errors and
  554. * recursively invoking itself with the updated config for the next retry
  555. * attempt.
  556. * @param input The input for the runnable.
  557. * @param runManager The run manager for the runnable.
  558. * @param config The config for the runnable.
  559. * @returns A promise that resolves to the output of the runnable.
  560. */
  561. invoke(input: RunInput, config?: CallOptions): Promise<RunOutput>;
  562. _batch<ReturnExceptions extends boolean = false>(inputs: RunInput[], configs?: RunnableConfig[], runManagers?: (CallbackManagerForChainRun | undefined)[], batchOptions?: RunnableBatchOptions): Promise<ReturnExceptions extends false ? RunOutput[] : (Error | RunOutput)[]>;
  563. batch(inputs: RunInput[], options?: Partial<CallOptions> | Partial<CallOptions>[], batchOptions?: RunnableBatchOptions & {
  564. returnExceptions?: false;
  565. }): Promise<RunOutput[]>;
  566. batch(inputs: RunInput[], options?: Partial<CallOptions> | Partial<CallOptions>[], batchOptions?: RunnableBatchOptions & {
  567. returnExceptions: true;
  568. }): Promise<(RunOutput | Error)[]>;
  569. batch(inputs: RunInput[], options?: Partial<CallOptions> | Partial<CallOptions>[], batchOptions?: RunnableBatchOptions): Promise<(RunOutput | Error)[]>;
  570. }
  571. export type RunnableSequenceFields<RunInput, RunOutput> = {
  572. first: Runnable<RunInput>;
  573. middle?: Runnable[];
  574. last: Runnable<any, RunOutput>;
  575. name?: string;
  576. omitSequenceTags?: boolean;
  577. };
  578. /**
  579. * A sequence of runnables, where the output of each is the input of the next.
  580. * @example
  581. * ```typescript
  582. * const promptTemplate = PromptTemplate.fromTemplate(
  583. * "Tell me a joke about {topic}",
  584. * );
  585. * const chain = RunnableSequence.from([promptTemplate, new ChatOpenAI({})]);
  586. * const result = await chain.invoke({ topic: "bears" });
  587. * ```
  588. */
  589. export declare class RunnableSequence<RunInput = any, RunOutput = any> extends Runnable<RunInput, RunOutput> {
  590. static lc_name(): string;
  591. protected first: Runnable<RunInput>;
  592. protected middle: Runnable[];
  593. protected last: Runnable<any, RunOutput>;
  594. omitSequenceTags: boolean;
  595. lc_serializable: boolean;
  596. lc_namespace: string[];
  597. constructor(fields: RunnableSequenceFields<RunInput, RunOutput>);
  598. get steps(): Runnable<any, any, RunnableConfig<Record<string, any>>>[];
  599. invoke(input: RunInput, options?: RunnableConfig): Promise<RunOutput>;
  600. batch(inputs: RunInput[], options?: Partial<RunnableConfig> | Partial<RunnableConfig>[], batchOptions?: RunnableBatchOptions & {
  601. returnExceptions?: false;
  602. }): Promise<RunOutput[]>;
  603. batch(inputs: RunInput[], options?: Partial<RunnableConfig> | Partial<RunnableConfig>[], batchOptions?: RunnableBatchOptions & {
  604. returnExceptions: true;
  605. }): Promise<(RunOutput | Error)[]>;
  606. batch(inputs: RunInput[], options?: Partial<RunnableConfig> | Partial<RunnableConfig>[], batchOptions?: RunnableBatchOptions): Promise<(RunOutput | Error)[]>;
  607. _streamIterator(input: RunInput, options?: RunnableConfig): AsyncGenerator<RunOutput>;
  608. getGraph(config?: RunnableConfig): Graph;
  609. pipe<NewRunOutput>(coerceable: RunnableLike<RunOutput, NewRunOutput>): RunnableSequence<RunInput, Exclude<NewRunOutput, Error>>;
  610. static isRunnableSequence(thing: any): thing is RunnableSequence;
  611. static from<RunInput = any, RunOutput = any>([first, ...runnables]: [
  612. RunnableLike<RunInput>,
  613. ...RunnableLike[],
  614. RunnableLike<any, RunOutput>
  615. ], nameOrFields?: string | Omit<RunnableSequenceFields<RunInput, RunOutput>, "first" | "middle" | "last">): RunnableSequence<RunInput, Exclude<RunOutput, Error>>;
  616. }
  617. /**
  618. * A runnable that runs a mapping of runnables in parallel,
  619. * and returns a mapping of their outputs.
  620. * @example
  621. * ```typescript
  622. * const mapChain = RunnableMap.from({
  623. * joke: PromptTemplate.fromTemplate("Tell me a joke about {topic}").pipe(
  624. * new ChatAnthropic({}),
  625. * ),
  626. * poem: PromptTemplate.fromTemplate("write a 2-line poem about {topic}").pipe(
  627. * new ChatAnthropic({}),
  628. * ),
  629. * });
  630. * const result = await mapChain.invoke({ topic: "bear" });
  631. * ```
  632. */
  633. export declare class RunnableMap<RunInput = any, RunOutput extends Record<string, any> = Record<string, any>> extends Runnable<RunInput, RunOutput> {
  634. static lc_name(): string;
  635. lc_namespace: string[];
  636. lc_serializable: boolean;
  637. protected steps: Record<string, Runnable<RunInput>>;
  638. getStepsKeys(): string[];
  639. constructor(fields: {
  640. steps: RunnableMapLike<RunInput, RunOutput>;
  641. });
  642. static from<RunInput, RunOutput extends Record<string, any> = Record<string, any>>(steps: RunnableMapLike<RunInput, RunOutput>): RunnableMap<RunInput, RunOutput>;
  643. invoke(input: RunInput, options?: Partial<RunnableConfig>): Promise<RunOutput>;
  644. _transform(generator: AsyncGenerator<RunInput>, runManager?: CallbackManagerForChainRun, options?: Partial<RunnableConfig>): AsyncGenerator<RunOutput>;
  645. transform(generator: AsyncGenerator<RunInput>, options?: Partial<RunnableConfig>): AsyncGenerator<RunOutput>;
  646. stream(input: RunInput, options?: Partial<RunnableConfig>): Promise<IterableReadableStream<RunOutput>>;
  647. }
  648. type AnyTraceableFunction = TraceableFunction<(...any: any[]) => any>;
  649. /**
  650. * A runnable that wraps a traced LangSmith function.
  651. */
  652. export declare class RunnableTraceable<RunInput, RunOutput> extends Runnable<RunInput, RunOutput> {
  653. lc_serializable: boolean;
  654. lc_namespace: string[];
  655. protected func: AnyTraceableFunction;
  656. constructor(fields: {
  657. func: AnyTraceableFunction;
  658. });
  659. invoke(input: RunInput, options?: Partial<RunnableConfig>): Promise<RunOutput>;
  660. _streamIterator(input: RunInput, options?: Partial<RunnableConfig>): AsyncGenerator<RunOutput>;
  661. static from(func: AnyTraceableFunction): RunnableTraceable<unknown, unknown>;
  662. }
  663. /**
  664. * A runnable that wraps an arbitrary function that takes a single argument.
  665. * @example
  666. * ```typescript
  667. * import { RunnableLambda } from "@langchain/core/runnables";
  668. *
  669. * const add = (input: { x: number; y: number }) => input.x + input.y;
  670. *
  671. * const multiply = (input: { value: number; multiplier: number }) =>
  672. * input.value * input.multiplier;
  673. *
  674. * // Create runnables for the functions
  675. * const addLambda = RunnableLambda.from(add);
  676. * const multiplyLambda = RunnableLambda.from(multiply);
  677. *
  678. * // Chain the lambdas for a mathematical operation
  679. * const chainedLambda = addLambda.pipe((result) =>
  680. * multiplyLambda.invoke({ value: result, multiplier: 2 })
  681. * );
  682. *
  683. * // Example invocation of the chainedLambda
  684. * const result = await chainedLambda.invoke({ x: 2, y: 3 });
  685. *
  686. * // Will log "10" (since (2 + 3) * 2 = 10)
  687. * ```
  688. */
  689. export declare class RunnableLambda<RunInput, RunOutput, CallOptions extends RunnableConfig = RunnableConfig> extends Runnable<RunInput, RunOutput, CallOptions> {
  690. static lc_name(): string;
  691. lc_namespace: string[];
  692. protected func: RunnableFunc<RunInput, RunOutput | Runnable<RunInput, RunOutput, CallOptions>, CallOptions>;
  693. constructor(fields: {
  694. func: RunnableFunc<RunInput, RunOutput | Runnable<RunInput, RunOutput, CallOptions>, CallOptions> | TraceableFunction<RunnableFunc<RunInput, RunOutput | Runnable<RunInput, RunOutput, CallOptions>, CallOptions>>;
  695. });
  696. static from<RunInput, RunOutput, CallOptions extends RunnableConfig = RunnableConfig>(func: RunnableFunc<RunInput, RunOutput | Runnable<RunInput, RunOutput, CallOptions>, CallOptions>): RunnableLambda<RunInput, RunOutput, CallOptions>;
  697. static from<RunInput, RunOutput, CallOptions extends RunnableConfig = RunnableConfig>(func: TraceableFunction<RunnableFunc<RunInput, RunOutput | Runnable<RunInput, RunOutput, CallOptions>, CallOptions>>): RunnableLambda<RunInput, RunOutput, CallOptions>;
  698. _invoke(input: RunInput, config?: Partial<CallOptions>, runManager?: CallbackManagerForChainRun): Promise<RunOutput>;
  699. invoke(input: RunInput, options?: Partial<CallOptions>): Promise<RunOutput>;
  700. _transform(generator: AsyncGenerator<RunInput>, runManager?: CallbackManagerForChainRun, config?: Partial<CallOptions>): AsyncGenerator<RunOutput>;
  701. transform(generator: AsyncGenerator<RunInput>, options?: Partial<CallOptions>): AsyncGenerator<RunOutput>;
  702. stream(input: RunInput, options?: Partial<CallOptions>): Promise<IterableReadableStream<RunOutput>>;
  703. }
  704. /**
  705. * A runnable that runs a mapping of runnables in parallel,
  706. * and returns a mapping of their outputs.
  707. * @example
  708. * ```typescript
  709. * import {
  710. * RunnableLambda,
  711. * RunnableParallel,
  712. * } from "@langchain/core/runnables";
  713. *
  714. * const addYears = (age: number): number => age + 5;
  715. * const yearsToFifty = (age: number): number => 50 - age;
  716. * const yearsToHundred = (age: number): number => 100 - age;
  717. *
  718. * const addYearsLambda = RunnableLambda.from(addYears);
  719. * const milestoneFiftyLambda = RunnableLambda.from(yearsToFifty);
  720. * const milestoneHundredLambda = RunnableLambda.from(yearsToHundred);
  721. *
  722. * // Pipe will coerce objects into RunnableParallel by default, but we
  723. * // explicitly instantiate one here to demonstrate
  724. * const sequence = addYearsLambda.pipe(
  725. * RunnableParallel.from({
  726. * years_to_fifty: milestoneFiftyLambda,
  727. * years_to_hundred: milestoneHundredLambda,
  728. * })
  729. * );
  730. *
  731. * // Invoke the sequence with a single age input
  732. * const res = sequence.invoke(25);
  733. *
  734. * // { years_to_fifty: 25, years_to_hundred: 75 }
  735. * ```
  736. */
  737. export declare class RunnableParallel<RunInput> extends RunnableMap<RunInput> {
  738. }
  739. /**
  740. * A Runnable that can fallback to other Runnables if it fails.
  741. * External APIs (e.g., APIs for a language model) may at times experience
  742. * degraded performance or even downtime.
  743. *
  744. * In these cases, it can be useful to have a fallback Runnable that can be
  745. * used in place of the original Runnable (e.g., fallback to another LLM provider).
  746. *
  747. * Fallbacks can be defined at the level of a single Runnable, or at the level
  748. * of a chain of Runnables. Fallbacks are tried in order until one succeeds or
  749. * all fail.
  750. *
  751. * While you can instantiate a `RunnableWithFallbacks` directly, it is usually
  752. * more convenient to use the `withFallbacks` method on an existing Runnable.
  753. *
  754. * When streaming, fallbacks will only be called on failures during the initial
  755. * stream creation. Errors that occur after a stream starts will not fallback
  756. * to the next Runnable.
  757. *
  758. * @example
  759. * ```typescript
  760. * import {
  761. * RunnableLambda,
  762. * RunnableWithFallbacks,
  763. * } from "@langchain/core/runnables";
  764. *
  765. * const primaryOperation = (input: string): string => {
  766. * if (input !== "safe") {
  767. * throw new Error("Primary operation failed due to unsafe input");
  768. * }
  769. * return `Processed: ${input}`;
  770. * };
  771. *
  772. * // Define a fallback operation that processes the input differently
  773. * const fallbackOperation = (input: string): string =>
  774. * `Fallback processed: ${input}`;
  775. *
  776. * const primaryRunnable = RunnableLambda.from(primaryOperation);
  777. * const fallbackRunnable = RunnableLambda.from(fallbackOperation);
  778. *
  779. * // Apply the fallback logic using the .withFallbacks() method
  780. * const runnableWithFallback = primaryRunnable.withFallbacks([fallbackRunnable]);
  781. *
  782. * // Alternatively, create a RunnableWithFallbacks instance manually
  783. * const manualFallbackChain = new RunnableWithFallbacks({
  784. * runnable: primaryRunnable,
  785. * fallbacks: [fallbackRunnable],
  786. * });
  787. *
  788. * // Example invocation using .withFallbacks()
  789. * const res = await runnableWithFallback
  790. * .invoke("unsafe input")
  791. * .catch((error) => {
  792. * console.error("Failed after all attempts:", error.message);
  793. * });
  794. *
  795. * // "Fallback processed: unsafe input"
  796. *
  797. * // Example invocation using manual instantiation
  798. * const res = await manualFallbackChain
  799. * .invoke("safe")
  800. * .catch((error) => {
  801. * console.error("Failed after all attempts:", error.message);
  802. * });
  803. *
  804. * // "Processed: safe"
  805. * ```
  806. */
  807. export declare class RunnableWithFallbacks<RunInput, RunOutput> extends Runnable<RunInput, RunOutput> {
  808. static lc_name(): string;
  809. lc_namespace: string[];
  810. lc_serializable: boolean;
  811. runnable: Runnable<RunInput, RunOutput>;
  812. fallbacks: Runnable<RunInput, RunOutput>[];
  813. constructor(fields: {
  814. runnable: Runnable<RunInput, RunOutput>;
  815. fallbacks: Runnable<RunInput, RunOutput>[];
  816. });
  817. runnables(): Generator<Runnable<RunInput, RunOutput, RunnableConfig<Record<string, any>>>, void, unknown>;
  818. invoke(input: RunInput, options?: Partial<RunnableConfig>): Promise<RunOutput>;
  819. _streamIterator(input: RunInput, options?: Partial<RunnableConfig> | undefined): AsyncGenerator<RunOutput>;
  820. batch(inputs: RunInput[], options?: Partial<RunnableConfig> | Partial<RunnableConfig>[], batchOptions?: RunnableBatchOptions & {
  821. returnExceptions?: false;
  822. }): Promise<RunOutput[]>;
  823. batch(inputs: RunInput[], options?: Partial<RunnableConfig> | Partial<RunnableConfig>[], batchOptions?: RunnableBatchOptions & {
  824. returnExceptions: true;
  825. }): Promise<(RunOutput | Error)[]>;
  826. batch(inputs: RunInput[], options?: Partial<RunnableConfig> | Partial<RunnableConfig>[], batchOptions?: RunnableBatchOptions): Promise<(RunOutput | Error)[]>;
  827. }
  828. export declare function _coerceToRunnable<RunInput, RunOutput, CallOptions extends RunnableConfig = RunnableConfig>(coerceable: RunnableLike<RunInput, RunOutput, CallOptions>): Runnable<RunInput, Exclude<RunOutput, Error>, CallOptions>;
  829. export interface RunnableAssignFields<RunInput> {
  830. mapper: RunnableMap<RunInput>;
  831. }
  832. /**
  833. * A runnable that assigns key-value pairs to inputs of type `Record<string, unknown>`.
  834. * @example
  835. * ```typescript
  836. * import {
  837. * RunnableAssign,
  838. * RunnableLambda,
  839. * RunnableParallel,
  840. * } from "@langchain/core/runnables";
  841. *
  842. * const calculateAge = (x: { birthYear: number }): { age: number } => {
  843. * const currentYear = new Date().getFullYear();
  844. * return { age: currentYear - x.birthYear };
  845. * };
  846. *
  847. * const createGreeting = (x: { name: string }): { greeting: string } => {
  848. * return { greeting: `Hello, ${x.name}!` };
  849. * };
  850. *
  851. * const mapper = RunnableParallel.from({
  852. * age_step: RunnableLambda.from(calculateAge),
  853. * greeting_step: RunnableLambda.from(createGreeting),
  854. * });
  855. *
  856. * const runnableAssign = new RunnableAssign({ mapper });
  857. *
  858. * const res = await runnableAssign.invoke({ name: "Alice", birthYear: 1990 });
  859. *
  860. * // { name: "Alice", birthYear: 1990, age_step: { age: 34 }, greeting_step: { greeting: "Hello, Alice!" } }
  861. * ```
  862. */
  863. export declare class RunnableAssign<RunInput extends Record<string, any> = Record<string, any>, RunOutput extends Record<string, any> = Record<string, any>, CallOptions extends RunnableConfig = RunnableConfig> extends Runnable<RunInput, RunOutput> implements RunnableAssignFields<RunInput> {
  864. static lc_name(): string;
  865. lc_namespace: string[];
  866. lc_serializable: boolean;
  867. mapper: RunnableMap<RunInput>;
  868. constructor(fields: RunnableMap<RunInput> | RunnableAssignFields<RunInput>);
  869. invoke(input: RunInput, options?: Partial<CallOptions>): Promise<RunOutput>;
  870. _transform(generator: AsyncGenerator<RunInput>, runManager?: CallbackManagerForChainRun, options?: Partial<RunnableConfig>): AsyncGenerator<RunOutput>;
  871. transform(generator: AsyncGenerator<RunInput>, options?: Partial<RunnableConfig>): AsyncGenerator<RunOutput>;
  872. stream(input: RunInput, options?: Partial<RunnableConfig>): Promise<IterableReadableStream<RunOutput>>;
  873. }
  874. export interface RunnablePickFields {
  875. keys: string | string[];
  876. }
  877. /**
  878. * A runnable that assigns key-value pairs to inputs of type `Record<string, unknown>`.
  879. * Useful for streaming, can be automatically created and chained by calling `runnable.pick();`.
  880. * @example
  881. * ```typescript
  882. * import { RunnablePick } from "@langchain/core/runnables";
  883. *
  884. * const inputData = {
  885. * name: "John",
  886. * age: 30,
  887. * city: "New York",
  888. * country: "USA",
  889. * email: "john.doe@example.com",
  890. * phone: "+1234567890",
  891. * };
  892. *
  893. * const basicInfoRunnable = new RunnablePick(["name", "city"]);
  894. *
  895. * // Example invocation
  896. * const res = await basicInfoRunnable.invoke(inputData);
  897. *
  898. * // { name: 'John', city: 'New York' }
  899. * ```
  900. */
  901. export declare class RunnablePick<RunInput extends Record<string, any> = Record<string, any>, RunOutput extends Record<string, any> | any = Record<string, any> | any, CallOptions extends RunnableConfig = RunnableConfig> extends Runnable<RunInput, RunOutput> implements RunnablePickFields {
  902. static lc_name(): string;
  903. lc_namespace: string[];
  904. lc_serializable: boolean;
  905. keys: string | string[];
  906. constructor(fields: string | string[] | RunnablePickFields);
  907. _pick(input: RunInput): Promise<RunOutput>;
  908. invoke(input: RunInput, options?: Partial<CallOptions>): Promise<RunOutput>;
  909. _transform(generator: AsyncGenerator<RunInput>): AsyncGenerator<RunOutput>;
  910. transform(generator: AsyncGenerator<RunInput>, options?: Partial<RunnableConfig>): AsyncGenerator<RunOutput>;
  911. stream(input: RunInput, options?: Partial<RunnableConfig>): Promise<IterableReadableStream<RunOutput>>;
  912. }
  913. export interface RunnableToolLikeArgs<RunInput extends z.ZodType = z.ZodType, RunOutput = unknown> extends Omit<RunnableBindingArgs<z.infer<RunInput>, RunOutput>, "config"> {
  914. name: string;
  915. description?: string;
  916. schema: RunInput;
  917. config?: RunnableConfig;
  918. }
  919. export declare class RunnableToolLike<RunInput extends z.ZodType = z.ZodType, RunOutput = unknown> extends RunnableBinding<z.infer<RunInput>, RunOutput> {
  920. name: string;
  921. description?: string;
  922. schema: RunInput;
  923. constructor(fields: RunnableToolLikeArgs<RunInput, RunOutput>);
  924. static lc_name(): string;
  925. }
  926. /**
  927. * Given a runnable and a Zod schema, convert the runnable to a tool.
  928. *
  929. * @template RunInput The input type for the runnable.
  930. * @template RunOutput The output type for the runnable.
  931. *
  932. * @param {Runnable<RunInput, RunOutput>} runnable The runnable to convert to a tool.
  933. * @param fields
  934. * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable.
  935. * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided.
  936. * @param {z.ZodType<RunInput>} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable.
  937. * @returns {RunnableToolLike<z.ZodType<RunInput>, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool.
  938. */
  939. export declare function convertRunnableToTool<RunInput, RunOutput>(runnable: Runnable<RunInput, RunOutput>, fields: {
  940. name?: string;
  941. description?: string;
  942. schema: z.ZodType<RunInput>;
  943. }): RunnableToolLike<z.ZodType<RunInput | ToolCall>, RunOutput>;