@langchain/core
Version:
Core LangChain.js abstractions and schemas
1 lines • 150 kB
Source Map (JSON)
{"version":3,"file":"base.cjs","names":["Serializable","ensureConfig","AsyncCaller","AsyncGeneratorWithSetup","IterableReadableStream","getCallbackManagerForConfig","raceWithSignal","concat","pipeGeneratorWithSetup","isStreamEventsHandler","isLogStreamHandler","Graph","z","LogStreamCallbackHandler","RunLogPatch","convertToHttpEventStream","EventStreamCallbackHandler","uuidv7","_RootEventFilter","RunLog","isRunnableInterface","RootListenersTracer","mergeConfigs","patchConfig","pRetry","getAbortSignalError","atee","isAsyncIterable","isIterator","AsyncLocalStorageProviderSingleton","pickRunnableConfigKeys","consumeAsyncIterableInContext","isIterableIterator","consumeIteratorInContext","_isToolCall","interopParseAsync","ToolInputParsingException","getSchemaDescription","isSimpleStringZodSchema"],"sources":["../../src/runnables/base.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { v7 as uuidv7 } from \"../utils/uuid/index.js\";\n\nimport {\n type TraceableFunction,\n isTraceableFunction,\n} from \"langsmith/singletons/traceable\";\nimport type {\n RunnableInterface,\n RunnableBatchOptions,\n RunnableConfig,\n} from \"./types.js\";\nimport { CallbackManagerForChainRun } from \"../callbacks/manager.js\";\nimport {\n LogStreamCallbackHandler,\n LogStreamCallbackHandlerInput,\n RunLog,\n RunLogPatch,\n isLogStreamHandler,\n} from \"../tracers/log_stream.js\";\nimport {\n EventStreamCallbackHandler,\n EventStreamCallbackHandlerInput,\n StreamEvent,\n StreamEventData,\n isStreamEventsHandler,\n} from \"../tracers/event_stream.js\";\nimport { Serializable } from \"../load/serializable.js\";\nimport pRetry from \"../utils/p-retry/index.js\";\nimport {\n IterableReadableStream,\n concat,\n atee,\n pipeGeneratorWithSetup,\n AsyncGeneratorWithSetup,\n} from \"../utils/stream.js\";\nimport { raceWithSignal, getAbortSignalError } from \"../utils/signal.js\";\nimport {\n DEFAULT_RECURSION_LIMIT,\n ensureConfig,\n getCallbackManagerForConfig,\n mergeConfigs,\n patchConfig,\n pickRunnableConfigKeys,\n} from \"./config.js\";\nimport { AsyncCaller } from \"../utils/async_caller.js\";\nimport { Run } from \"../tracers/base.js\";\nimport { RootListenersTracer } from \"../tracers/root_listener.js\";\nimport { _RootEventFilter, isRunnableInterface } from \"./utils.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../singletons/index.js\";\nimport { Graph } from \"./graph.js\";\nimport { convertToHttpEventStream } from \"./wrappers.js\";\nimport {\n consumeAsyncIterableInContext,\n consumeIteratorInContext,\n isAsyncIterable,\n isIterableIterator,\n isIterator,\n} from \"./iter.js\";\nimport { _isToolCall, ToolInputParsingException } from \"../tools/utils.js\";\nimport { ToolCall } from \"../messages/tool.js\";\nimport {\n getSchemaDescription,\n InferInteropZodOutput,\n interopParseAsync,\n InteropZodType,\n isSimpleStringZodSchema,\n} from \"../utils/types/zod.js\";\n\nexport { type RunnableInterface, RunnableBatchOptions };\n\nexport type RunnableFunc<\n RunInput,\n RunOutput,\n CallOptions extends RunnableConfig = RunnableConfig,\n> = (\n input: RunInput,\n options:\n | CallOptions\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | (Record<string, any> & CallOptions)\n) => RunOutput | Promise<RunOutput>;\n\nexport type RunnableMapLike<RunInput, RunOutput> = {\n [K in keyof RunOutput]: RunnableLike<RunInput, RunOutput[K]>;\n};\n\nexport type RunnableLike<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput = any,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput = any,\n CallOptions extends RunnableConfig = RunnableConfig,\n> =\n | RunnableInterface<RunInput, RunOutput, CallOptions>\n | RunnableFunc<RunInput, RunOutput, CallOptions>\n | RunnableMapLike<RunInput, RunOutput>;\n\nexport type RunnableRetryFailedAttemptHandler = (\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n error: any,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n input: any\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n) => any;\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _coerceToDict(value: any, defaultKey: string) {\n return value &&\n !Array.isArray(value) &&\n // oxlint-disable-next-line no-instanceof/no-instanceof\n !(value instanceof Date) &&\n typeof value === \"object\"\n ? value\n : { [defaultKey]: value };\n}\n\n/**\n * A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or\n * transformed.\n */\nexport abstract class Runnable<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput = any,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput = any,\n CallOptions extends RunnableConfig = RunnableConfig,\n>\n extends Serializable\n implements RunnableInterface<RunInput, RunOutput, CallOptions>\n{\n protected lc_runnable = true;\n\n name?: string;\n\n getName(suffix?: string): string {\n const name =\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n this.name ?? (this.constructor as any).lc_name() ?? this.constructor.name;\n return suffix ? `${name}${suffix}` : name;\n }\n\n abstract invoke(\n input: RunInput,\n options?: Partial<CallOptions>\n ): Promise<RunOutput>;\n\n /**\n * Add retry logic to an existing runnable.\n * @param fields.stopAfterAttempt The number of attempts to retry.\n * @param fields.onFailedAttempt A function that is called when a retry fails.\n * @returns A new RunnableRetry that, when invoked, will retry according to the parameters.\n */\n withRetry(fields?: {\n stopAfterAttempt?: number;\n onFailedAttempt?: RunnableRetryFailedAttemptHandler;\n }): RunnableRetry<RunInput, RunOutput, CallOptions> {\n // oxlint-disable-next-line @typescript-eslint/no-use-before-define\n return new RunnableRetry({\n bound: this,\n kwargs: {},\n config: {},\n maxAttemptNumber: fields?.stopAfterAttempt,\n ...fields,\n });\n }\n\n /**\n * Bind config to a Runnable, returning a new Runnable.\n * @param config New configuration parameters to attach to the new runnable.\n * @returns A new RunnableBinding with a config matching what's passed.\n */\n withConfig(\n config: Partial<CallOptions>\n ): Runnable<RunInput, RunOutput, CallOptions> {\n // oxlint-disable-next-line @typescript-eslint/no-use-before-define\n return new RunnableBinding({\n bound: this,\n config,\n kwargs: {},\n });\n }\n\n /**\n * Create a new runnable from the current one that will try invoking\n * other passed fallback runnables if the initial invocation fails.\n * @param fields.fallbacks Other runnables to call if the runnable errors.\n * @returns A new RunnableWithFallbacks.\n */\n withFallbacks(\n fields:\n | {\n fallbacks: Runnable<RunInput, RunOutput>[];\n }\n | Runnable<RunInput, RunOutput>[]\n ): RunnableWithFallbacks<RunInput, RunOutput> {\n const fallbacks = Array.isArray(fields) ? fields : fields.fallbacks;\n // oxlint-disable-next-line @typescript-eslint/no-use-before-define\n return new RunnableWithFallbacks<RunInput, RunOutput>({\n runnable: this,\n fallbacks,\n });\n }\n\n protected _getOptionsList<O extends CallOptions & { runType?: string }>(\n options: Partial<O> | Partial<O>[],\n length = 0\n ): Partial<O>[] {\n if (Array.isArray(options) && options.length !== length) {\n throw new Error(\n `Passed \"options\" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`\n );\n }\n\n if (Array.isArray(options)) {\n return options.map(ensureConfig);\n }\n if (length > 1 && !Array.isArray(options) && options.runId) {\n console.warn(\n \"Provided runId will be used only for the first element of the batch.\"\n );\n const subsequent = Object.fromEntries(\n Object.entries(options).filter(([key]) => key !== \"runId\")\n );\n\n return Array.from({ length }, (_, i) =>\n ensureConfig(i === 0 ? options : subsequent)\n ) as Partial<O>[];\n }\n return Array.from({ length }, () => ensureConfig(options));\n }\n\n /**\n * Default implementation of batch, which calls invoke N times.\n * Subclasses should override this method if they can batch more efficiently.\n * @param inputs Array of inputs to each batch call.\n * @param options Either a single call options object to apply to each batch call or an array for each call.\n * @param batchOptions.returnExceptions Whether to return errors rather than throwing on the first one\n * @returns An array of RunOutputs, or mixed RunOutputs and errors if batchOptions.returnExceptions is set\n */\n async batch(\n inputs: RunInput[],\n options?: Partial<CallOptions> | Partial<CallOptions>[],\n batchOptions?: RunnableBatchOptions & { returnExceptions?: false }\n ): Promise<RunOutput[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<CallOptions> | Partial<CallOptions>[],\n batchOptions?: RunnableBatchOptions & { returnExceptions: true }\n ): Promise<(RunOutput | Error)[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<CallOptions> | Partial<CallOptions>[],\n batchOptions?: RunnableBatchOptions\n ): Promise<(RunOutput | Error)[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<CallOptions> | Partial<CallOptions>[],\n batchOptions?: RunnableBatchOptions\n ): Promise<(RunOutput | Error)[]> {\n const configList = this._getOptionsList(options ?? {}, inputs.length);\n const maxConcurrency =\n configList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency;\n const caller = new AsyncCaller({\n maxConcurrency,\n onFailedAttempt: (e) => {\n throw e;\n },\n });\n const batchCalls = inputs.map((input, i) =>\n caller.call(async () => {\n try {\n const result = await this.invoke(input, configList[i]);\n return result;\n } catch (e) {\n if (batchOptions?.returnExceptions) {\n return e as Error;\n }\n throw e;\n }\n })\n );\n return Promise.all(batchCalls);\n }\n\n /**\n * Default streaming implementation.\n * Subclasses should override this method if they support streaming output.\n * @param input\n * @param options\n */\n async *_streamIterator(\n input: RunInput,\n options?: Partial<CallOptions>\n ): AsyncGenerator<RunOutput> {\n yield this.invoke(input, options);\n }\n\n /**\n * Stream output in chunks.\n * @param input\n * @param options\n * @returns A readable stream that is also an iterable.\n */\n async stream(\n input: RunInput,\n options?: Partial<CallOptions>\n ): Promise<IterableReadableStream<RunOutput>> {\n // Buffer the first streamed chunk to allow for initial errors\n // to surface immediately.\n const config = ensureConfig(options);\n const wrappedGenerator = new AsyncGeneratorWithSetup({\n generator: this._streamIterator(input, config),\n config,\n });\n await wrappedGenerator.setup;\n return IterableReadableStream.fromAsyncGenerator(wrappedGenerator);\n }\n\n protected _separateRunnableConfigFromCallOptions(\n options?: Partial<CallOptions>\n ): [RunnableConfig, Omit<Partial<CallOptions>, keyof RunnableConfig>] {\n let runnableConfig;\n if (options === undefined) {\n runnableConfig = ensureConfig(options);\n } else {\n runnableConfig = ensureConfig({\n callbacks: options.callbacks,\n tags: options.tags,\n metadata: options.metadata,\n runName: options.runName,\n configurable: options.configurable,\n recursionLimit: options.recursionLimit,\n maxConcurrency: options.maxConcurrency,\n runId: options.runId,\n timeout: options.timeout,\n signal: options.signal,\n });\n }\n const callOptions = { ...(options as Partial<CallOptions>) };\n delete callOptions.callbacks;\n delete callOptions.tags;\n delete callOptions.metadata;\n delete callOptions.runName;\n delete callOptions.configurable;\n delete callOptions.recursionLimit;\n delete callOptions.maxConcurrency;\n delete callOptions.runId;\n delete callOptions.timeout;\n delete callOptions.signal;\n return [runnableConfig, callOptions];\n }\n\n protected async _callWithConfig<T extends RunInput>(\n func:\n | ((input: T) => Promise<RunOutput>)\n | ((\n input: T,\n config?: Partial<CallOptions>,\n runManager?: CallbackManagerForChainRun\n ) => Promise<RunOutput>),\n input: T,\n options?: Partial<CallOptions> & { runType?: string }\n ) {\n const config = ensureConfig(options);\n const callbackManager_ = await getCallbackManagerForConfig(config);\n const runManager = await callbackManager_?.handleChainStart(\n this.toJSON(),\n _coerceToDict(input, \"input\"),\n config.runId,\n config?.runType,\n undefined,\n undefined,\n config?.runName ?? this.getName()\n );\n delete config.runId;\n let output;\n try {\n const promise = func.call(this, input, config, runManager);\n output = await raceWithSignal(promise, config.signal);\n } catch (e) {\n await runManager?.handleChainError(e);\n throw e;\n }\n await runManager?.handleChainEnd(_coerceToDict(output, \"output\"));\n return output;\n }\n\n /**\n * Internal method that handles batching and configuration for a runnable\n * It takes a function, input values, and optional configuration, and\n * returns a promise that resolves to the output values.\n * @param func The function to be executed for each input value.\n * @param input The input values to be processed.\n * @param config Optional configuration for the function execution.\n * @returns A promise that resolves to the output values.\n */\n async _batchWithConfig<T extends RunInput>(\n func: (\n inputs: T[],\n options?: Partial<CallOptions>[],\n runManagers?: (CallbackManagerForChainRun | undefined)[],\n batchOptions?: RunnableBatchOptions\n ) => Promise<(RunOutput | Error)[]>,\n inputs: T[],\n options?:\n | Partial<CallOptions & { runType?: string }>\n | Partial<CallOptions & { runType?: string }>[],\n batchOptions?: RunnableBatchOptions\n ): Promise<(RunOutput | Error)[]> {\n const optionsList = this._getOptionsList(options ?? {}, inputs.length);\n const callbackManagers = await Promise.all(\n optionsList.map(getCallbackManagerForConfig)\n );\n const runManagers = await Promise.all(\n callbackManagers.map(async (callbackManager, i) => {\n const handleStartRes = await callbackManager?.handleChainStart(\n this.toJSON(),\n _coerceToDict(inputs[i], \"input\"),\n optionsList[i].runId,\n optionsList[i].runType,\n undefined,\n undefined,\n optionsList[i].runName ?? this.getName()\n );\n delete optionsList[i].runId;\n return handleStartRes;\n })\n );\n let outputs: (RunOutput | Error)[];\n try {\n const promise = func.call(\n this,\n inputs,\n optionsList,\n runManagers,\n batchOptions\n );\n outputs = await raceWithSignal(promise, optionsList?.[0]?.signal);\n } catch (e) {\n await Promise.all(\n runManagers.map((runManager) => runManager?.handleChainError(e))\n );\n throw e;\n }\n await Promise.all(\n runManagers.map((runManager) =>\n runManager?.handleChainEnd(_coerceToDict(outputs, \"output\"))\n )\n );\n return outputs;\n }\n\n /** @internal */\n _concatOutputChunks<O>(first: O, second: O): O {\n return concat(first, second);\n }\n\n /**\n * Helper method to transform an Iterator of Input values into an Iterator of\n * Output values, with callbacks.\n * Use this to implement `stream()` or `transform()` in Runnable subclasses.\n */\n protected async *_transformStreamWithConfig<\n I extends RunInput,\n O extends RunOutput,\n >(\n inputGenerator: AsyncGenerator<I>,\n transformer: (\n generator: AsyncGenerator<I>,\n runManager?: CallbackManagerForChainRun,\n options?: Partial<CallOptions>\n ) => AsyncGenerator<O>,\n options?: Partial<CallOptions> & { runType?: string }\n ): AsyncGenerator<O> {\n let finalInput: I | undefined;\n let finalInputSupported = true;\n let finalOutput: O | undefined;\n let finalOutputSupported = true;\n\n const config = ensureConfig(options);\n const callbackManager_ = await getCallbackManagerForConfig(config);\n const outerThis = this;\n async function* wrapInputForTracing() {\n for await (const chunk of inputGenerator) {\n if (finalInputSupported) {\n if (finalInput === undefined) {\n finalInput = chunk;\n } else {\n try {\n finalInput = outerThis._concatOutputChunks(\n finalInput,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n chunk as any\n );\n } catch {\n finalInput = undefined;\n finalInputSupported = false;\n }\n }\n }\n yield chunk;\n }\n }\n\n let runManager: CallbackManagerForChainRun | undefined;\n try {\n const pipe = await pipeGeneratorWithSetup(\n transformer.bind(this),\n wrapInputForTracing(),\n async () =>\n callbackManager_?.handleChainStart(\n this.toJSON(),\n { input: \"\" },\n config.runId,\n config.runType,\n undefined,\n undefined,\n config.runName ?? this.getName(),\n undefined,\n { lc_defers_inputs: true }\n ),\n config.signal,\n config\n );\n delete config.runId;\n runManager = pipe.setup;\n\n const streamEventsHandler = runManager?.handlers.find(\n isStreamEventsHandler\n );\n let iterator = pipe.output;\n if (streamEventsHandler !== undefined && runManager !== undefined) {\n iterator = streamEventsHandler.tapOutputIterable(\n runManager.runId,\n iterator\n );\n }\n\n const streamLogHandler = runManager?.handlers.find(isLogStreamHandler);\n if (streamLogHandler !== undefined && runManager !== undefined) {\n iterator = streamLogHandler.tapOutputIterable(\n runManager.runId,\n iterator\n );\n }\n\n for await (const chunk of iterator) {\n yield chunk;\n if (finalOutputSupported) {\n if (finalOutput === undefined) {\n finalOutput = chunk;\n } else {\n try {\n finalOutput = this._concatOutputChunks(\n finalOutput,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n chunk as any\n );\n } catch {\n finalOutput = undefined;\n finalOutputSupported = false;\n }\n }\n }\n }\n } catch (e) {\n await runManager?.handleChainError(e, undefined, undefined, undefined, {\n inputs: _coerceToDict(finalInput, \"input\"),\n });\n throw e;\n }\n await runManager?.handleChainEnd(\n finalOutput ?? {},\n undefined,\n undefined,\n undefined,\n { inputs: _coerceToDict(finalInput, \"input\") }\n );\n }\n\n getGraph(_?: RunnableConfig): Graph {\n const graph = new Graph();\n\n // TODO: Add input schema for runnables\n const inputNode = graph.addNode({\n name: `${this.getName()}Input`,\n schema: z.any(),\n });\n\n const runnableNode = graph.addNode(this);\n\n // TODO: Add output schemas for runnables\n const outputNode = graph.addNode({\n name: `${this.getName()}Output`,\n schema: z.any(),\n });\n\n graph.addEdge(inputNode, runnableNode);\n graph.addEdge(runnableNode, outputNode);\n return graph;\n }\n\n /**\n * Create a new runnable sequence that runs each individual runnable in series,\n * piping the output of one runnable into another runnable or runnable-like.\n * @param coerceable A runnable, function, or object whose values are functions or runnables.\n * @returns A new runnable sequence.\n */\n pipe<NewRunOutput>(\n coerceable: RunnableLike<RunOutput, NewRunOutput>\n ): Runnable<RunInput, Exclude<NewRunOutput, Error>> {\n // oxlint-disable-next-line @typescript-eslint/no-use-before-define\n return new RunnableSequence({\n first: this,\n last: _coerceToRunnable(coerceable),\n });\n }\n\n /**\n * Pick keys from the dict output of this runnable. Returns a new runnable.\n */\n pick(keys: string | string[]): Runnable {\n // oxlint-disable-next-line @typescript-eslint/no-use-before-define\n return this.pipe(new RunnablePick(keys) as Runnable);\n }\n\n /**\n * Assigns new fields to the dict output of this runnable. Returns a new runnable.\n */\n assign(\n mapping: RunnableMapLike<Record<string, unknown>, Record<string, unknown>>\n ): Runnable {\n return this.pipe(\n // oxlint-disable-next-line @typescript-eslint/no-use-before-define\n new RunnableAssign(\n // oxlint-disable-next-line @typescript-eslint/no-use-before-define\n new RunnableMap<Record<string, unknown>>({ steps: mapping })\n ) as Runnable\n );\n }\n\n /**\n * Default implementation of transform, which buffers input and then calls stream.\n * Subclasses should override this method if they can start producing output while\n * input is still being generated.\n * @param generator\n * @param options\n */\n async *transform(\n generator: AsyncGenerator<RunInput>,\n options: Partial<CallOptions>\n ): AsyncGenerator<RunOutput> {\n let finalChunk;\n for await (const chunk of generator) {\n if (finalChunk === undefined) {\n finalChunk = chunk;\n } else {\n // Make a best effort to gather, for any type that supports concat.\n // This method should throw an error if gathering fails.\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n finalChunk = this._concatOutputChunks(finalChunk, chunk as any);\n }\n }\n yield* this._streamIterator(finalChunk, ensureConfig(options));\n }\n\n /**\n * Stream all output from a runnable, as reported to the callback system.\n * This includes all inner runs of LLMs, Retrievers, Tools, etc.\n * Output is streamed as Log objects, which include a list of\n * jsonpatch ops that describe how the state of the run has changed in each\n * step, and the final state of the run.\n * The jsonpatch ops can be applied in order to construct state.\n *\n * @deprecated Use `.stream()` instead.\n *\n * @param input\n * @param options\n * @param streamOptions\n */\n async *streamLog(\n input: RunInput,\n options?: Partial<CallOptions>,\n streamOptions?: Omit<LogStreamCallbackHandlerInput, \"autoClose\">\n ): AsyncGenerator<RunLogPatch> {\n const logStreamCallbackHandler = new LogStreamCallbackHandler({\n ...streamOptions,\n autoClose: false,\n _schemaFormat: \"original\",\n });\n const config = ensureConfig(options);\n yield* this._streamLog(input, logStreamCallbackHandler, config);\n }\n\n protected async *_streamLog(\n input: RunInput,\n logStreamCallbackHandler: LogStreamCallbackHandler,\n config: Partial<CallOptions>\n ): AsyncGenerator<RunLogPatch> {\n const { callbacks } = config;\n if (callbacks === undefined) {\n config.callbacks = [logStreamCallbackHandler];\n } else if (Array.isArray(callbacks)) {\n config.callbacks = callbacks.concat([logStreamCallbackHandler]);\n } else {\n const copiedCallbacks = callbacks.copy();\n copiedCallbacks.addHandler(logStreamCallbackHandler, true);\n config.callbacks = copiedCallbacks;\n }\n const runnableStreamPromise = this.stream(input, config);\n async function consumeRunnableStream() {\n try {\n const runnableStream = await runnableStreamPromise;\n for await (const chunk of runnableStream) {\n const patch = new RunLogPatch({\n ops: [\n {\n op: \"add\",\n path: \"/streamed_output/-\",\n value: chunk,\n },\n ],\n });\n await logStreamCallbackHandler.writer.write(patch);\n }\n } finally {\n await logStreamCallbackHandler.writer.close();\n }\n }\n const runnableStreamConsumePromise = consumeRunnableStream();\n try {\n for await (const log of logStreamCallbackHandler) {\n yield log;\n }\n } finally {\n await runnableStreamConsumePromise;\n }\n }\n\n /**\n * Generate a stream of events emitted by the internal steps of the runnable.\n *\n * Use to create an iterator over StreamEvents that provide real-time information\n * about the progress of the runnable, including StreamEvents from intermediate\n * results.\n *\n * A StreamEvent is a dictionary with the following schema:\n *\n * - `event`: string - Event names are of the format: on_[runnable_type]_(start|stream|end).\n * - `name`: string - The name of the runnable that generated the event.\n * - `run_id`: string - Randomly generated ID associated with the given execution of\n * the runnable that emitted the event. A child runnable that gets invoked as part of the execution of a\n * parent runnable is assigned its own unique ID.\n * - `tags`: string[] - The tags of the runnable that generated the event.\n * - `metadata`: Record<string, any> - The metadata of the runnable that generated the event.\n * - `data`: Record<string, any>\n *\n * Below is a table that illustrates some events that might be emitted by various\n * chains. Metadata fields have been omitted from the table for brevity.\n * Chain definitions have been included after the table.\n *\n * **ATTENTION** This reference table is for the V2 version of the schema.\n *\n * ```md\n * +----------------------+-----------------------------+------------------------------------------+\n * | event | input | output/chunk |\n * +======================+=============================+==========================================+\n * | on_chat_model_start | {\"messages\": BaseMessage[]} | |\n * +----------------------+-----------------------------+------------------------------------------+\n * | on_chat_model_stream | | AIMessageChunk(\"hello\") |\n * +----------------------+-----------------------------+------------------------------------------+\n * | on_chat_model_end | {\"messages\": BaseMessage[]} | AIMessageChunk(\"hello world\") |\n * +----------------------+-----------------------------+------------------------------------------+\n * | on_llm_start | {'input': 'hello'} | |\n * +----------------------+-----------------------------+------------------------------------------+\n * | on_llm_stream | | 'Hello' |\n * +----------------------+-----------------------------+------------------------------------------+\n * | on_llm_end | 'Hello human!' | |\n * +----------------------+-----------------------------+------------------------------------------+\n * | on_chain_start | | |\n * +----------------------+-----------------------------+------------------------------------------+\n * | on_chain_stream | | \"hello world!\" |\n * +----------------------+-----------------------------+------------------------------------------+\n * | on_chain_end | [Document(...)] | \"hello world!, goodbye world!\" |\n * +----------------------+-----------------------------+------------------------------------------+\n * | on_tool_start | {\"x\": 1, \"y\": \"2\"} | |\n * +----------------------+-----------------------------+------------------------------------------+\n * | on_tool_end | | {\"x\": 1, \"y\": \"2\"} |\n * +----------------------+-----------------------------+------------------------------------------+\n * | on_retriever_start | {\"query\": \"hello\"} | |\n * +----------------------+-----------------------------+------------------------------------------+\n * | on_retriever_end | {\"query\": \"hello\"} | [Document(...), ..] |\n * +----------------------+-----------------------------+------------------------------------------+\n * | on_prompt_start | {\"question\": \"hello\"} | |\n * +----------------------+-----------------------------+------------------------------------------+\n * | on_prompt_end | {\"question\": \"hello\"} | ChatPromptValue(messages: BaseMessage[]) |\n * +----------------------+-----------------------------+------------------------------------------+\n * ```\n *\n * The \"on_chain_*\" events are the default for Runnables that don't fit one of the above categories.\n *\n * In addition to the standard events above, users can also dispatch custom events.\n *\n * Custom events will be only be surfaced with in the `v2` version of the API!\n *\n * A custom event has following format:\n *\n * ```md\n * +-----------+------+------------------------------------------------------------+\n * | Attribute | Type | Description |\n * +===========+======+============================================================+\n * | name | str | A user defined name for the event. |\n * +-----------+------+------------------------------------------------------------+\n * | data | Any | The data associated with the event. This can be anything. |\n * +-----------+------+------------------------------------------------------------+\n * ```\n *\n * Here's an example:\n *\n * ```ts\n * import { RunnableLambda } from \"@langchain/core/runnables\";\n * import { dispatchCustomEvent } from \"@langchain/core/callbacks/dispatch\";\n * // Use this import for web environments that don't support \"async_hooks\"\n * // and manually pass config to child runs.\n * // import { dispatchCustomEvent } from \"@langchain/core/callbacks/dispatch/web\";\n *\n * const slowThing = RunnableLambda.from(async (someInput: string) => {\n * // Placeholder for some slow operation\n * await new Promise((resolve) => setTimeout(resolve, 100));\n * await dispatchCustomEvent(\"progress_event\", {\n * message: \"Finished step 1 of 2\",\n * });\n * await new Promise((resolve) => setTimeout(resolve, 100));\n * return \"Done\";\n * });\n *\n * const eventStream = await slowThing.streamEvents(\"hello world\", {\n * version: \"v2\",\n * });\n *\n * for await (const event of eventStream) {\n * if (event.event === \"on_custom_event\") {\n * console.log(event);\n * }\n * }\n * ```\n */\n streamEvents(\n input: RunInput,\n options: Partial<CallOptions> & { version: \"v2\" },\n streamOptions?: Omit<EventStreamCallbackHandlerInput, \"autoClose\">\n ): IterableReadableStream<StreamEvent>;\n\n streamEvents(\n input: RunInput,\n options: Partial<CallOptions> & {\n version: \"v2\";\n encoding: \"text/event-stream\";\n },\n streamOptions?: Omit<EventStreamCallbackHandlerInput, \"autoClose\">\n ): IterableReadableStream<Uint8Array>;\n\n /**\n * @deprecated Use version \"v2\" or `.stream()` instead.\n */\n streamEvents(\n input: RunInput,\n options: Partial<CallOptions> & { version: \"v1\" },\n streamOptions?: Omit<EventStreamCallbackHandlerInput, \"autoClose\">\n ): IterableReadableStream<StreamEvent>;\n\n /**\n * @deprecated Use version \"v2\" or `.stream()` instead.\n */\n streamEvents(\n input: RunInput,\n options: Partial<CallOptions> & {\n version: \"v1\";\n encoding: \"text/event-stream\";\n },\n streamOptions?: Omit<EventStreamCallbackHandlerInput, \"autoClose\">\n ): IterableReadableStream<Uint8Array>;\n\n streamEvents(\n input: RunInput,\n options: Partial<CallOptions> & { version: \"v1\" | \"v2\" },\n streamOptions?: Omit<EventStreamCallbackHandlerInput, \"autoClose\">\n ): IterableReadableStream<StreamEvent>;\n\n streamEvents(\n input: RunInput,\n options: Partial<CallOptions> & {\n version: \"v1\" | \"v2\";\n encoding: \"text/event-stream\";\n },\n streamOptions?: Omit<EventStreamCallbackHandlerInput, \"autoClose\">\n ): IterableReadableStream<Uint8Array>;\n\n streamEvents(\n input: RunInput,\n options: Partial<CallOptions> & {\n version: \"v1\" | \"v2\";\n encoding?: \"text/event-stream\" | undefined;\n },\n streamOptions?: Omit<EventStreamCallbackHandlerInput, \"autoClose\">\n ): IterableReadableStream<StreamEvent | Uint8Array> {\n let stream;\n if (options.version === \"v1\") {\n stream = this._streamEventsV1(input, options, streamOptions);\n } else if (options.version === \"v2\") {\n stream = this._streamEventsV2(input, options, streamOptions);\n } else {\n throw new Error(\n `Only versions \"v1\" and \"v2\" of the schema are currently supported.`\n );\n }\n\n if (options.encoding === \"text/event-stream\") {\n return convertToHttpEventStream(stream);\n } else {\n return IterableReadableStream.fromAsyncGenerator(stream);\n }\n }\n\n private async *_streamEventsV2(\n input: RunInput,\n options: Partial<CallOptions> & { version: \"v1\" | \"v2\" },\n streamOptions?: Omit<EventStreamCallbackHandlerInput, \"autoClose\">\n ): AsyncGenerator<StreamEvent> {\n const eventStreamer = new EventStreamCallbackHandler({\n ...streamOptions,\n autoClose: false,\n });\n const config = ensureConfig(options);\n const runId = config.runId ?? uuidv7();\n config.runId = runId;\n const callbacks = config.callbacks;\n if (callbacks === undefined) {\n config.callbacks = [eventStreamer];\n } else if (Array.isArray(callbacks)) {\n config.callbacks = callbacks.concat(eventStreamer);\n } else {\n const copiedCallbacks = callbacks.copy();\n copiedCallbacks.addHandler(eventStreamer, true);\n config.callbacks = copiedCallbacks;\n }\n const abortController = new AbortController();\n // Call the runnable in streaming mode,\n // add each chunk to the output stream\n const outerThis = this;\n async function consumeRunnableStream() {\n let signal;\n\n try {\n if (config.signal) {\n if (\"any\" in AbortSignal) {\n // Use native AbortSignal.any() if available (Node 19+)\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n signal = (AbortSignal as any).any([\n abortController.signal,\n config.signal,\n ]);\n } else {\n // Fallback for Node 18 and below - compose both signals\n // through a bridging controller so that either source\n // (timeout/user signal OR early consumer break) cancels\n // the inner stream.\n const composed = new AbortController();\n\n config.signal.addEventListener(\"abort\", () => composed.abort(), {\n once: true,\n });\n abortController.signal.addEventListener(\n \"abort\",\n () => composed.abort(),\n { once: true }\n );\n\n signal = composed.signal;\n }\n } else {\n signal = abortController.signal;\n }\n const runnableStream = await outerThis.stream(input, {\n ...config,\n signal,\n });\n const tappedStream = eventStreamer.tapOutputIterable(\n runId,\n runnableStream\n );\n for await (const _ of tappedStream) {\n // Just iterate so that the callback handler picks up events\n if (abortController.signal.aborted) break;\n }\n } finally {\n await eventStreamer.finish();\n }\n }\n const runnableStreamConsumePromise = consumeRunnableStream();\n let firstEventSent = false;\n let firstEventRunId;\n try {\n for await (const event of eventStreamer) {\n // This is a work-around an issue where the inputs into the\n // chain are not available until the entire input is consumed.\n // As a temporary solution, we'll modify the input to be the input\n // that was passed into the chain.\n if (!firstEventSent) {\n event.data.input = input;\n firstEventSent = true;\n firstEventRunId = event.run_id;\n yield event;\n continue;\n }\n if (event.run_id === firstEventRunId && event.event.endsWith(\"_end\")) {\n // If it's the end event corresponding to the root runnable\n // we dont include the input in the event since it's guaranteed\n // to be included in the first event.\n if (event.data?.input) {\n delete event.data.input;\n }\n }\n yield event;\n }\n } finally {\n abortController.abort();\n await runnableStreamConsumePromise;\n }\n }\n\n private async *_streamEventsV1(\n input: RunInput,\n options: Partial<CallOptions> & { version: \"v1\" | \"v2\" },\n streamOptions?: Omit<LogStreamCallbackHandlerInput, \"autoClose\">\n ): AsyncGenerator<StreamEvent> {\n let runLog;\n let hasEncounteredStartEvent = false;\n const config = ensureConfig(options);\n const rootTags = config.tags ?? [];\n const rootMetadata = config.metadata ?? {};\n const rootName = config.runName ?? this.getName();\n const logStreamCallbackHandler = new LogStreamCallbackHandler({\n ...streamOptions,\n autoClose: false,\n _schemaFormat: \"streaming_events\",\n });\n const rootEventFilter = new _RootEventFilter({\n ...streamOptions,\n });\n const logStream = this._streamLog(input, logStreamCallbackHandler, config);\n for await (const log of logStream) {\n if (!runLog) {\n runLog = RunLog.fromRunLogPatch(log);\n } else {\n runLog = runLog.concat(log);\n }\n if (runLog.state === undefined) {\n throw new Error(\n `Internal error: \"streamEvents\" state is missing. Please open a bug report.`\n );\n }\n // Yield the start event for the root runnable if it hasn't been seen.\n // The root run is never filtered out\n if (!hasEncounteredStartEvent) {\n hasEncounteredStartEvent = true;\n const state = { ...runLog.state };\n const event: StreamEvent = {\n run_id: state.id,\n event: `on_${state.type}_start`,\n name: rootName,\n tags: rootTags,\n metadata: rootMetadata,\n data: {\n input,\n },\n };\n if (rootEventFilter.includeEvent(event, state.type)) {\n yield event;\n }\n }\n const paths = log.ops\n .filter((op) => op.path.startsWith(\"/logs/\"))\n .map((op) => op.path.split(\"/\")[2]);\n const dedupedPaths = [...new Set(paths)];\n for (const path of dedupedPaths) {\n let eventType;\n let data: StreamEventData = {};\n const logEntry = runLog.state.logs[path];\n if (logEntry.end_time === undefined) {\n if (logEntry.streamed_output.length > 0) {\n eventType = \"stream\";\n } else {\n eventType = \"start\";\n }\n } else {\n eventType = \"end\";\n }\n if (eventType === \"start\") {\n // Include the inputs with the start event if they are available.\n // Usually they will NOT be available for components that operate\n // on streams, since those components stream the input and\n // don't know its final value until the end of the stream.\n if (logEntry.inputs !== undefined) {\n data.input = logEntry.inputs;\n }\n } else if (eventType === \"end\") {\n if (logEntry.inputs !== undefined) {\n data.input = logEntry.inputs;\n }\n data.output = logEntry.final_output;\n } else if (eventType === \"stream\") {\n const chunkCount = logEntry.streamed_output.length;\n if (chunkCount !== 1) {\n throw new Error(\n `Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: \"${logEntry.name}\"`\n );\n }\n data = { chunk: logEntry.streamed_output[0] };\n // Clean up the stream, we don't need it anymore.\n // And this avoids duplicates as well!\n logEntry.streamed_output = [];\n }\n yield {\n event: `on_${logEntry.type}_${eventType}`,\n name: logEntry.name,\n run_id: logEntry.id,\n tags: logEntry.tags,\n metadata: logEntry.metadata,\n data,\n };\n }\n // Finally, we take care of the streaming output from the root chain\n // if there is any.\n const { state } = runLog;\n if (state.streamed_output.length > 0) {\n const chunkCount = state.streamed_output.length;\n if (chunkCount !== 1) {\n throw new Error(\n `Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: \"${state.name}\"`\n );\n }\n const data = { chunk: state.streamed_output[0] };\n // Clean up the stream, we don't need it anymore.\n state.streamed_output = [];\n const event = {\n event: `on_${state.type}_stream`,\n run_id: state.id,\n tags: rootTags,\n metadata: rootMetadata,\n name: rootName,\n data,\n };\n if (rootEventFilter.includeEvent(event, state.type)) {\n yield event;\n }\n }\n }\n const state = runLog?.state;\n if (state !== undefined) {\n // Finally, yield the end event for the root runnable.\n const event = {\n event: `on_${state.type}_end`,\n name: rootName,\n run_id: state.id,\n tags: rootTags,\n metadata: rootMetadata,\n data: {\n output: state.final_output,\n },\n };\n if (rootEventFilter.includeEvent(event, state.type)) yield event;\n }\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n static isRunnable(thing: any): thing is Runnable {\n return isRunnableInterface(thing);\n }\n\n /**\n * Bind lifecycle listeners to a Runnable, returning a new Runnable.\n * The Run object contains information about the run, including its id,\n * type, input, output, error, startTime, endTime, and any tags or metadata\n * added to the run.\n *\n * @param {Object} params - The object containing the callback functions.\n * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.\n * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.\n * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.\n */\n withListeners({\n onStart,\n onEnd,\n onError,\n }: {\n onStart?: (run: Run, config?: RunnableConfig) => void | Promise<void>;\n onEnd?: (run: Run, config?: RunnableConfig) => void | Promise<void>;\n onError?: (run: Run, config?: RunnableConfig) => void | Promise<void>;\n }): Runnable<RunInput, RunOutput, CallOptions> {\n // oxlint-disable-next-line @typescript-eslint/no-use-before-define\n return new RunnableBinding<RunInput, RunOutput, CallOptions>({\n bound: this,\n config: {},\n configFactories: [\n (config) => ({\n callbacks: [\n new RootListenersTracer({\n config,\n onStart,\n onEnd,\n onError,\n }),\n ],\n }),\n ],\n });\n }\n\n /**\n * Convert a runnable to a tool. Return a new instance of `RunnableToolLike`\n * which contains the runnable, name, description and schema.\n *\n * @template {T extends RunInput = RunInput} RunInput - The input type of the runnable. Should be the same as the `RunInput` type of the runnable.\n *\n * @param fields\n * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable.\n * @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.\n * @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.\n * @returns {RunnableToolLike<z.ZodType<T>, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool.\n */\n asTool<T extends RunInput = RunInput>(fields: {\n name?: string;\n description?: string;\n schema: InteropZodType<T>;\n }): RunnableToolLike<InteropZodType<T | ToolCall>, RunOutput> {\n return convertRunnableToTool<T, RunOutput>(this, fields);\n }\n}\n\nexport type RunnableBindingArgs<\n RunInput,\n RunOutput,\n CallOptions extends RunnableConfig = RunnableConfig,\n> = {\n bound: Runnable<RunInput, RunOutput, CallOptions>;\n /** @deprecated Use {@link config} instead. */\n kwargs?: Partial<CallOptions>;\n config: RunnableConfig;\n configFactories?: Array<\n (config: RunnableConfig) => RunnableConfig | Promise<RunnableConfig>\n >;\n};\n\n/**\n * Wraps a runnable and applies partial config upon invocation.\n *\n * @example\n * ```typescript\n * import {\n * type RunnableConfig,\n * RunnableLambda,\n * } from \"@langchain/core/runnables\";\n *\n * const enhanceProfile = (\n * profile: Record<string, any>,\n * config?: RunnableConfig\n * ) => {\n * if (config?.configurable?.role) {\n * return { ...profile, role: config.configurable.role };\n * }\n * return profile;\n * };\n *\n * const runnable = RunnableLambda.from(enhanceProfile);\n *\n * // Bind configuration to the runnable to set the user's role dynamically\n * const adminRunnable = runnable.withConfig({ configurable: { role: \"Admin\" } });\n * const userRunnable = runnable.withConfig({ configurable: { role: \"User\" } });\n *\n * const result1 = await adminRunnable.invoke({\n * name: \"Alice\",\n * email: \"alice@example.com\"\n * });\n *\n * // { name: \"Alice\", email: \"alice@example.com\", role: \"Admin\" }\n *\n * const result2 = await userRunnable.invoke({\n * name: \"Bob\",\n * email: \"bob@example.com\"\n * });\n *\n * // { name: \"Bob\", email: \"bob@example.com\", role: \"User\" }\n * ```\n */\nexport class RunnableBinding<\n RunInput,\n RunOutput,\n CallOptions extends RunnableConfig = RunnableConfig,\n> extends Runnable<RunInput, RunOutput, CallOptions> {\n static lc_name() {\n return \"RunnableBinding\";\n }\n\n lc_namespace = [\"langchain_core\", \"runnables\"];\n\n lc_serializable = true;\n\n bound: Runnable<RunInput, RunOutput, CallOptions>;\n\n config: RunnableConfig;\n\n kwargs?: Partial<CallOptions>;\n\n configFactories?: Array<\n (config: RunnableConfig) => RunnableConfig | Promise<RunnableConfig>\n >;\n\n constructor(fields: RunnableBindingArgs<RunInput, RunOutput, CallOptions>) {\n super(fields);\n this.bound = fields.bound;\n this.kwargs = fields.kwargs;\n this.config = fields.config;\n this.configFactories = fields.configFactories;\n }\n\n getName(suffix?: string | undefined): string {\n return this.bound.getName(suffix);\n }\n\n async _mergeConfig(\n ...options: (Partial<CallOptions> | RunnableConfig | undefined)[]\n ): Promise<Partial<CallOptions>> {\n const config = mergeConfigs(this.config, ...options);\n return mergeConfigs(\n config,\n ...(this.configFactories\n ? await Promise.all(\n this.configFactories.map(\n async (configFactory) => await configFactory(config)\n )\n )\n : [])\n );\n }\n\n withConfig(\n config: Partial<CallOptions>\n ): Runnable<RunInput, RunOutput, CallOptions> {\n return new (this.constructor as {\n new (\n fields: RunnableBindingArgs<RunInput, RunOutput, CallOptions>\n ): RunnableBinding<RunInput, RunOutput, CallOptions>;\n })({\n bound: this.bound,\n kwargs: this.kwargs,\n config: { ...this.config, ...config },\n });\n }\n\n withRetry(fields?: {\n stopAfterAttempt?: number;\n onFailedAttempt?: RunnableRetryFailedAttemptHandler;\n }): RunnableRetry<RunInput, RunOutput, CallOptions> {\n // oxlint-disable-next-line @typescript-eslint/no-use-before-define\n return new RunnableRetry({\n bound: this.bound,\n kwargs: this.kwargs,\n config: this.config,\n maxAttemptNumber: fields?.stopAfterAttempt,\n ...fields,\n });\n }\n\n async invoke(\n input: RunInput,\n options?: Partial<CallOptions>\n ): Promise<RunOutput> {\n return this.bound.invoke(\n input,\n await this._mergeConfig(options, this.kwargs)\n );\n }\n\n async batch(\n inputs: RunInput[],\n options?: Partial<CallOptions> | Partial<CallOptions>[],\n batchOptions?: RunnableBatchOptions & { returnExceptions?: false }\n ): Promise<RunOutput[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<CallOptions> | Partial<CallOptions>[],\n batchOptions?: RunnableBatchOptions & { returnExceptions: true }\n ): Promise<(RunOutput | Error)[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<CallOptions> | Partial<CallOptions>[],\n batchOptions?: RunnableBatchOptions\n ): Promise<(RunOutput | Error)[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<CallOptions> | Partial<CallOptions>[],\n batchOptions?: RunnableBatchOptions\n ): Promise<(RunOutput | Error)[]> {\n const mergedOptions = Array.isArray(options)\n ? await Promise.all(\n options.map(async (individualOption) =>\n this._mergeConfig(ensureConfig(individualOption), this.kwargs)\n )\n )\n : await this._mergeConfig(ensureConfig(options), this.kwargs);\n return this.bound.batch(inputs, mergedOptions, batchOptions);\n }\n\n /** @internal */\n override _concatOutputChunks<O>(first: O, second: O): O {\n return this.bound._concatOutputChunks(first, second);\n }\n\n async *_streamIterator(\n input: RunInput,\n options?: Partial<CallOptions> | undefined\n ) {\n yield* this.bound._streamIterator(\n input,\n await this._mergeConfig(ensureConfig(options), this.kwargs)\n );\n }\n\n async stream(\n input: RunInput,\n options?: Partial<CallOptions> | undefined\n ): Promise<IterableReadableStream<RunOutput>> {\n return this.bound.stream(\n input,\n await this._mergeConfig(ensureConfig(options), this.kwargs)\n );\n }\n\n async *transform(\n generator: AsyncGenerator<RunInput>,\n options?: Partial<CallOptions>\n ): AsyncGenerator<RunOutput> {\n yield* this.bound.transform(\n generator,\n await this._mergeConfig(ensureConfig(options), this.kwargs)\n );\n }\n\n streamEvents(\n input: RunInput,\n options: Partial<CallOptions> & { version: \"v2\" },\n streamOptions?: Omit<LogStreamCallbackHandlerInput, \"autoClose\">\n ): IterableReadableStream<StreamEvent>;\n\n streamEvents(\n input: RunInput,\n options: Partial<CallOptions> & {\n version: \"v2\";\n encoding: \"text/event-stream\";\n },\n streamOptions?: Omit<LogStreamCallbackHandlerInput, \"autoClose\">\n ): IterableReadableStream<Uint8Array>;\n\n /**\n * @deprecated Use version \"v2\" or `.stream()` instead.\n */\n streamEvents(\n input: RunInput,\n options: Partial<CallOptions> & { version: \"v1\" },\n streamOptions?: Omit<LogStreamCallbackHandlerInput, \"autoClose\">\n ): IterableReadableStream<StreamEvent>;\n\n /**\n * @deprecated Use version \"v2\" or `.stream()` instead.\n */\n streamEvents(\n input: RunInput,\n options: Partial<CallOptions> & {\n version: \"v1\";\n encoding: \"text/event-stream\";\n },\n streamOptions?: Omit<LogStreamCallbackHandlerInput, \"autoClose\">\n ): IterableReadableStream<Uint8Array>;\n\n streamEvents(\n input: RunInput,\n options: Partial<CallOptions> & { version: \"v1\" | \"v2\" },\n streamOptions?: Omit<LogStreamCallbackHandlerInput, \"autoClose\">\n ): IterableReadableStream<StreamEvent>;\n\n streamEvents(\n input: RunInput,\n options: Partial<CallOptions> & {\n version: \"v1\" | \"v2\";\n encoding: \"text/event-stream\";\n },\n streamOptions?: Omit<LogStreamCallbackHandlerInput, \"autoClose\">\n ): IterableReadableStream<Uint8Array>;\n\n streamEvents(\n input: RunInput,\n options: Partial<CallOptions> & {\n version: \"v1\" | \"v2\";\n encoding?: \"text/event-stream\" | undefined;\n },\n streamOptions?: Omit<LogStreamCallbackHandlerInput, \"autoClose\">\n ): IterableReadableStream<StreamEvent | Uint8Array> {\n const outerThis = this;\n const generator = async function* () {\n yield* outerThis.bound.streamEvents(\n input,\n {\n ...(await outerThis._mergeConfig(\n ensureConfig(options),\n outerThis.kwargs\n )),\n version: options.version,\n },\n streamOptions\n );\n };\n return IterableReadableStream.fromAsyncGenerator(generator());\n }\n\n static isRunnableBinding(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n thing: any\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n ): thing is RunnableBinding<any, any, any> {\n return thing.bound && Runnable.isRunnable(thing.bound);\n }\n\n /**\n * Bind lifecycle listeners to a Runnable, returning a new Runnable.\n * The Run object contains information about the run, including its id,\n * type, input, output, error, startTime, endTime, and any tags or metadata\n * added to the run.\n *\n * @param {Object} params - The object containing the callback functions.\n * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.\n * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.\n * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.\n */\n withListeners({\n onStart,\n onEnd,\n onError,\n }: {\n onStart?: (run: Run, config?: RunnableConfig) => void | Promise<void>;\n onEnd?: (run: Run, config?: RunnableConfig) => void | Promise<void>;\n onError?: (run: Run, config?: RunnableConfig) => void | Promise<void>;\n }): Runnable<RunInput, RunOutput, CallOptions> {\n return new RunnableBinding<RunInput, RunOutput, CallOptions>({\n bound: this.bound,\n kwargs: this.kwargs,\n config: this.config,\n configFactories: [\n (config) => ({\n callbacks: [\n new RootListenersTracer({\n config,\n onStart,\n onEnd,\n onError,\n }),\n ],\n }),\n ],\n });\n }\n}\n\n/**\n * A runnable that delegates calls to another runnable\n * with each element of the input sequence.\n * @example\n * ```typescript\n * import { RunnableEach, RunnableLambda } from \"@langchain/core/runnables\";\n *\n * const toUpperCase = (input: string): string => input.toUpperCase();\n * const addGreeting = (input: string): string => `Hello, ${input}!`;\n *\n * const upperCaseLambda = RunnableLambda.from(toUpperCase);\n * const greetingLambda = RunnableLambda.from(addGreeting);\n *\n * const chain = new RunnableEach({\n * bound: upperCaseLambda.pipe(greetingLambda),\n * });\n *\n * const result = await chain.invoke([\"alice\", \"bob\", \"carol\"])\n *\n * // [\"Hello, ALICE!\", \"Hello, BOB!\", \"Hello, CAROL!\"]\n * ```\n */\nexport class RunnableEach<\n RunInputItem,\n RunOutputItem,\n CallOptions extends RunnableConfig,\n> extends Runnable<RunInputItem[], RunOutputItem[], CallOptions> {\n static lc_name() {\n return \"RunnableEach\";\n }\n\n lc_serializable = true;\n\n lc_namespace = [\"langchain_core\", \"runnables\"];\n\n bound: Runnable<RunInputItem, RunOutputItem, CallOptions>;\n\n constructor(fields: {\n bound: Runnable<RunInputItem, RunOutputItem, CallOptions>;\n }) {\n super(fields);\n this.bound = fields.bound;\n }\n\n /**\n * Invokes the runnable with the specified input and configuration.\n * @param input The input to invoke the runnable with.\n * @param config The configuration to invoke the runnable with.\n * @returns A promise that resolves to the output of the runnable.\n */\n async invoke(\n inputs: RunInputItem[],\n config?: Partial<CallOptions>\n ): Promise<RunOutputItem[]> {\n return this._callWithConfig(this._invoke.bind(this), inputs, config);\n }\n\n /**\n * A helper method that is used to invoke the runnable with the specified input and configuration.\n * @param input The input to invoke the runnable with.\n * @param config The configuration to invoke the runnable with.\n * @returns A promise that resolves to the output of the runnable.\n */\n protected async _invoke(\n inputs: RunInputItem[],\n config?: Partial<CallOptions>,\n runManager?: CallbackManagerForChainRun\n ): Promise<RunOutputItem[]> {\n return this.bound.batch(\n inputs,\n patchConfig(config, { callbacks: runManager?.getChild() })\n );\n }\n\n /**\n * Bind lifecycle listeners to a Runnable, returning a new Runnable.\n * The Run object contains information about the run, including its id,\n * type, input, output, error, startTime, endTime, and any tags or metadata\n * added to the run.\n *\n * @param {Object} params - The object containing the callback functions.\n * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.\n * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.\n * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.\n */\n withListeners({\n onStart,\n onEnd,\n onError,\n }: {\n onStart?: (run: Run, config?: RunnableConfig) => void | Promise<void>;\n onEnd?: (run: Run, config?: RunnableConfig) => void | Promise<void>;\n onError?: (run: Run, config?: RunnableConfig) => void | Promise<void>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n }): Runnable<any, any, CallOptions> {\n return new RunnableEach<RunInputItem, RunOutputItem, CallOptions>({\n bound: this.bound.withListeners({ onStart, onEnd, onError }),\n });\n }\n}\n\n/**\n * Base class for runnables that can be retried a\n * specified number of times.\n * @example\n * ```typescript\n * import {\n * RunnableLambda,\n * RunnableRetry,\n * } from \"@langchain/core/runnables\";\n *\n * // Simulate an API call that fails\n * const simulateApiCall = (input: string): string => {\n * console.log(`Attempting API call with input: ${input}`);\n * throw new Error(\"API call failed due to network issue\");\n * };\n *\n * const apiCallLambda = RunnableLambda.from(simulateApiCall);\n *\n * // Apply retry logic using the .withRetry() method\n * const apiCallWithRetry = apiCallLambda.withRetry({ stopAfterAttempt: 3 });\n *\n * // Alternatively, create a RunnableRetry instance manually\n * const manualRetry = new RunnableRetry({\n * bound: apiCallLambda,\n * maxAttemptNumber: 3,\n * config: {},\n * });\n *\n * // Example invocation using the .withRetry() method\n * const res = await apiCallWithRetry\n * .invoke(\"Request 1\")\n * .catch((error) => {\n * console.error(\"Failed after multiple retries:\", error.message);\n * });\n *\n * // Example invocation using the manual retry instance\n * const res2 = await manualRetry\n * .invoke(\"Request 2\")\n * .catch((error) => {\n * console.error(\"Failed after multiple retries:\", error.message);\n * });\n * ```\n */\nexport class RunnableRetry<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput = any,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput = any,\n CallOptions extends RunnableConfig = RunnableConfig,\n> extends RunnableBinding<RunInput, RunOutput, CallOptions> {\n static lc_name() {\n return \"RunnableRetry\";\n }\n\n lc_namespace = [\"langchain_core\", \"runnables\"];\n\n protected maxAttemptNumber = 3;\n\n onFailedAttempt: RunnableRetryFailedAttemptHandler = () => {\n // empty\n };\n\n constructor(\n fields: RunnableBindingArgs<RunInput, RunOutput, CallOptions> & {\n maxAttemptNumber?: number;\n onFailedAttempt?: RunnableRetryFailedAttemptHandler;\n }\n ) {\n super(fields);\n this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber;\n this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt;\n }\n\n _patchConfigForRetry(\n attempt: number,\n config?: Partial<CallOptions>,\n runManager?: CallbackManagerForChainRun\n ): Partial<CallOptions> {\n const tag = attempt > 1 ? `retry:attempt:${attempt}` : undefined;\n return patchConfig(config, { callbacks: runManager?.getChild(tag) });\n }\n\n protected async _invoke(\n input: RunInput,\n config?: Partial<CallOptions>,\n runManager?: CallbackManagerForChainRun\n ): Promise<RunOutput> {\n return pRetry(\n (attemptNumber: number) =>\n super.invoke(\n input,\n this._patchConfigForRetry(attemptNumber, config, runManager)\n ),\n {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n onFailedAttempt: ({ error }: { error: any }) =>\n this.onFailedAttempt(error, input),\n retries: Math.max(this.maxAttemptNumber - 1, 0),\n randomize: true,\n }\n );\n }\n\n /**\n * Method that invokes the runnable with the specified input, run manager,\n * and config. It handles the retry logic by catching any errors and\n * recursively invoking itself with the updated config for the next retry\n * attempt.\n * @param input The input for the runnable.\n * @param runManager The run manager for the runnable.\n * @param config The config for the runnable.\n * @returns A promise that resolves to the output of the runnable.\n */\n async invoke(\n input: RunInput,\n config?: Partial<CallOptions>\n ): Promise<RunOutput> {\n return this._callWithConfig(this._invoke.bind(this), input, config);\n }\n\n async _batch<ReturnExceptions extends boolean = false>(\n inputs: RunInput[],\n configs?: RunnableConfig[],\n runManagers?: (CallbackManagerForChainRun | undefined)[],\n batchOptions?: RunnableBatchOptions\n ) {\n const resultsMap: Record<string, RunOutput | Error> = {};\n try {\n await pRetry(\n async (attemptNumber: number) => {\n const remainingIndexes = inputs\n .map((_, i) => i)\n .filter(\n (i) =>\n resultsMap[i.toString()] === undefined ||\n // oxlint-disable-next-line no-instanceof/no-instanceof\n resultsMap[i.toString()] instanceof Error\n );\n const remainingInputs = remainingIndexes.map((i) => inputs[i]);\n const patchedConfigs = remainingIndexes.map((i) =>\n this._patchConfigForRetry(\n attemptNumber,\n configs?.[i] as CallOptions,\n runManagers?.[i]\n )\n );\n const results = await super.batch(remainingInputs, patchedConfigs, {\n ...batchOptions,\n returnExceptions: true,\n });\n let firstException;\n for (let i = 0; i < results.length; i += 1) {\n const result = results[i];\n const resultMapIndex = remainingIndexes[i];\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (result instanceof Error) {\n if (firstException === undefined) {\n firstException = result;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n (firstException as any).input = remainingInputs[i];\n }\n }\n resultsMap[resultMapIndex.toString()] = result;\n }\n if (firstException) {\n throw firstException;\n }\n return results;\n },\n {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n onFailedAttempt: ({ error }: { error: any }) =>\n this.onFailedAttempt(error, error.input),\n retries: Math.max(this.maxAttemptNumber - 1, 0),\n randomize: true,\n }\n );\n } catch (e) {\n if (batchOptions?.returnExceptions !== true) {\n throw e;\n }\n }\n return Object.keys(resultsMap)\n .sort((a, b) => parseInt(a, 10) - parseInt(b, 10))\n .map(\n (key) => resultsMap[parseInt(key, 10)]\n ) as ReturnExceptions extends false ? RunOutput[] : (RunOutput | Error)[];\n }\n\n async batch(\n inputs: RunInput[],\n options?: Partial<CallOptions> | Partial<CallOptions>[],\n batchOptions?: RunnableBatchOptions & { returnExceptions?: false }\n ): Promise<RunOutput[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<CallOptions> | Partial<CallOptions>[],\n batchOptions?: RunnableBatchOptions & { returnExceptions: true }\n ): Promise<(RunOutput | Error)[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<CallOptions> | Partial<CallOptions>[],\n batchOptions?: RunnableBatchOptions\n ): Promise<(RunOutput | Error)[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<CallOptions> | Partial<CallOptions>[],\n batchOptions?: RunnableBatchOptions\n ): Promise<(RunOutput | Error)[]> {\n return this._batchWithConfig(\n this._batch.bind(this),\n inputs,\n options,\n batchOptions\n );\n }\n}\n\nexport type RunnableSequenceFields<RunInput, RunOutput> = {\n first: Runnable<RunInput>;\n middle?: Runnable[];\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n last: Runnable<any, RunOutput>;\n name?: string;\n omitSequenceTags?: boolean;\n};\n\n/**\n * A sequence of runnables, where the output of each is the input of the next.\n * @example\n * ```typescript\n * const promptTemplate = PromptTemplate.fromTemplate(\n * \"Tell me a joke about {topic}\",\n * );\n * const chain = RunnableSequence.from([promptTemplate, new ChatOpenAI({ model: \"gpt-4o-mini\" })]);\n * const result = await chain.invoke({ topic: \"bears\" });\n * ```\n */\nexport class RunnableSequence<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput = any,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput = any,\n> extends Runnable<RunInput, RunOutput> {\n static lc_name() {\n return \"RunnableSequence\";\n }\n\n protected first: Runnable<RunInput>;\n\n protected middle: Runnable[] = [];\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n protected last: Runnable<any, RunOutput>;\n\n omitSequenceTags = false;\n\n lc_serializable = true;\n\n lc_namespace = [\"langchain_core\", \"runnables\"];\n\n constructor(fields: RunnableSequenceFields<RunInput, RunOutput>) {\n super(fields);\n this.first = fields.first;\n this.middle = fields.middle ?? this.middle;\n this.last = fields.last;\n this.name = fields.name;\n this.omitSequenceTags = fields.omitSequenceTags ?? this.omitSequenceTags;\n }\n\n get steps() {\n return [this.first, ...this.middle, this.last];\n }\n\n async invoke(input: RunInput, options?: RunnableConfig): Promise<RunOutput> {\n const config = ensureConfig(options);\n const callbackManager_ = await getCallbackManagerForConfig(config);\n const runManager = await callbackManager_?.handleChainStart(\n this.toJSON(),\n _coerceToDict(input, \"input\"),\n config.runId,\n undefined,\n undefined,\n undefined,\n config?.runName\n );\n delete config.runId;\n let nextStepInput = input;\n let finalOutput: RunOutput;\n try {\n const initialSteps = [this.first, ...this.middle];\n for (let i = 0; i < initialSteps.length; i += 1) {\n const step = initialSteps[i];\n const promise = step.invoke(\n nextStepInput,\n patchConfig(config, {\n callbacks: runManager?.getChild(\n this.omitSequenceTags ? undefined : `seq:step:${i + 1}`\n ),\n })\n );\n nextStepInput = await raceWithSignal(promise, config.signal);\n }\n // TypeScript can't detect that the last output of the sequence returns RunOutput, so call it out of the loop here\n if (config.signal?.aborted) {\n throw getAbortSignalError(config.signal);\n }\n finalOutput = await this.last.invoke(\n nextStepInput,\n patchConfig(config, {\n callbacks: runManager?.getChild(\n this.omitSequenceTags ? undefined : `seq:step:${this.steps.length}`\n ),\n })\n );\n } catch (e) {\n await runManager?.handleChainError(e);\n throw e;\n }\n await runManager?.handleChainEnd(_coerceToDict(finalOutput, \"output\"));\n return finalOutput;\n }\n\n async batch(\n inputs: RunInput[],\n options?: Partial<RunnableConfig> | Partial<RunnableConfig>[],\n batchOptions?: RunnableBatchOptions & { returnExceptions?: false }\n ): Promise<RunOutput[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<RunnableConfig> | Partial<RunnableConfig>[],\n batchOptions?: RunnableBatchOptions & { returnExceptions: true }\n ): Promise<(RunOutput | Error)[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<RunnableConfig> | Partial<RunnableConfig>[],\n batchOptions?: RunnableBatchOptions\n ): Promise<(RunOutput | Error)[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<RunnableConfig> | Partial<RunnableConfig>[],\n batchOptions?: RunnableBatchOptions\n ): Promise<(RunOutput | Error)[]> {\n const configList = this._getOptionsList(options ?? {}, inputs.length);\n const callbackManagers = await Promise.all(\n configList.map(getCallbackManagerForConfig)\n );\n const runManagers = await Promise.all(\n callbackManagers.map(async (callbackManager, i) => {\n const handleStartRes = await callbackManager?.handleChainStart(\n this.toJSON(),\n _coerceToDict(inputs[i], \"input\"),\n configList[i].runId,\n undefined,\n undefined,\n undefined,\n configList[i].runName\n );\n delete configList[i].runId;\n return handleStartRes;\n })\n );\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n let nextStepInputs: any = inputs;\n try {\n for (let i = 0; i < this.steps.length; i += 1) {\n const step = this.steps[i];\n const promise = step.batch(\n nextStepInputs,\n runManagers.map((runManager, j) => {\n const childRunManager = runManager?.getChild(\n this.omitSequenceTags ? undefined : `seq:step:${i + 1}`\n );\n return patchConfig(configList[j], { callbacks: childRunManager });\n }),\n batchOptions\n );\n nextStepInputs = await raceWithSignal(promise, configList[0]?.signal);\n }\n } catch (e) {\n await Promise.all(\n runManagers.map((runManager) => runManager?.handleChainError(e))\n );\n throw e;\n }\n await Promise.all(\n runManagers.map((runManager) =>\n runManager?.handleChainEnd(_coerceToDict(nextStepInputs, \"output\"))\n )\n );\n return nextStepInputs;\n }\n\n /** @internal */\n override _concatOutputChunks<O>(first: O, second: O): O {\n return this.last._concatOutputChunks(first, second);\n }\n\n async *_streamIterator(\n input: RunInput,\n options?: RunnableConfig\n ): AsyncGenerator<RunOutput> {\n const callbackManager_ = await getCallbackManagerForConfig(options);\n const { runId, ...otherOptions } = options ?? {};\n const runManager = await callbackManager_?.handleChainStart(\n this.toJSON(),\n _coerceToDict(input, \"input\"),\n runId,\n undefined,\n undefined,\n undefined,\n otherOptions?.runName\n );\n const steps = [this.first, ...this.middle, this.last];\n let concatSupported = true;\n let finalOutput;\n async function* inputGenerator() {\n yield input;\n }\n try {\n let finalGenerator = steps[0].transform(\n inputGenerator(),\n patchConfig(otherOptions, {\n callbacks: runManager?.getChild(\n this.omitSequenceTags ? undefined : `seq:step:1`\n ),\n })\n );\n for (let i = 1; i < steps.length; i += 1) {\n const step = steps[i];\n finalGenerator = await step.transform(\n finalGenerator,\n patchConfig(otherOptions, {\n callbacks: runManager?.getChild(\n this.omitSequenceTags ? undefined : `seq:step:${i + 1}`\n ),\n })\n );\n }\n for await (const chunk of finalGenerator) {\n options?.signal?.throwIfAborted();\n yield chunk;\n if (concatSupported) {\n if (finalOutput === undefined) {\n finalOutput = chunk;\n } else {\n try {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n finalOutput = this._concatOutputChunks(finalOutput, chunk as any);\n } catch {\n finalOutput = undefined;\n concatSupported = false;\n }\n }\n }\n }\n } catch (e) {\n await runManager?.handleChainError(e);\n throw e;\n }\n await runManager?.handleChainEnd(_coerceToDict(finalOutput, \"output\"));\n }\n\n getGraph(config?: RunnableConfig): Graph {\n const graph = new Graph();\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n let currentLastNode: any = null;\n\n this.steps.forEach((step, index) => {\n const stepGraph = step.getGraph(config);\n\n if (index !== 0) {\n stepGraph.trimFirstNode();\n }\n\n if (index !== this.steps.length - 1) {\n stepGraph.trimLastNode();\n }\n\n graph.extend(stepGraph);\n\n const stepFirstNode = stepGraph.firstNode();\n if (!stepFirstNode) {\n throw new Error(`Runnable ${step} has no first node`);\n }\n\n if (currentLastNode) {\n graph.addEdge(currentLastNode, stepFirstNode);\n }\n\n currentLastNode = stepGraph.lastNode();\n });\n\n return graph;\n }\n\n pipe<NewRunOutput>(\n coerceable: RunnableLike<RunOutput, NewRunOutput>\n ): RunnableSequence<RunInput, Exclude<NewRunOutput, Error>> {\n if (RunnableSequence.isRunnableSequence(coerceable)) {\n return new RunnableSequence({\n first: this.first,\n middle: this.middle.concat([\n this.last,\n coerceable.first,\n ...coerceable.middle,\n ]),\n last: coerceable.last,\n name: this.name ?? coerceable.name,\n });\n } else {\n return new RunnableSequence({\n first: this.first,\n middle: [...this.middle, this.last],\n last: _coerceToRunnable(coerceable),\n name: this.name,\n });\n }\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n static isRunnableSequence(thing: any): thing is RunnableSequence {\n return Array.isArray(thing.middle) && Runnable.isRunnable(thing);\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n static from<RunInput = any, RunOutput = any>(\n [first, ...runnables]: [\n RunnableLike<RunInput>,\n ...RunnableLike[],\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunnableLike<any, RunOutput>,\n ],\n nameOrFields?:\n | string\n | Omit<\n RunnableSequenceFields<RunInput, RunOutput>,\n \"first\" | \"middle\" | \"last\"\n >\n ) {\n let extra: Record<string, unknown> = {};\n if (typeof nameOrFields === \"string\") {\n extra.name = nameOrFields;\n } else if (nameOrFields !== undefined) {\n extra = nameOrFields;\n }\n return new RunnableSequence<RunInput, Exclude<RunOutput, Error>>({\n ...extra,\n first: _coerceToRunnable(first),\n middle: runnables.slice(0, -1).map(_coerceToRunnable),\n last: _coerceToRunnable(runnables[runnables.length - 1]),\n });\n }\n}\n\n/**\n * A runnable that runs a mapping of runnables in parallel,\n * and returns a mapping of their outputs.\n * @example\n * ```typescript\n * const mapChain = RunnableMap.from({\n * joke: PromptTemplate.fromTemplate(\"Tell me a joke about {topic}\").pipe(\n * new ChatAnthropic({}),\n * ),\n * poem: PromptTemplate.fromTemplate(\"write a 2-line poem about {topic}\").pipe(\n * new ChatAnthropic({}),\n * ),\n * });\n * const result = await mapChain.invoke({ topic: \"bear\" });\n * ```\n */\nexport class RunnableMap<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput = any,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n> extends Runnable<RunInput, RunOutput> {\n static lc_name() {\n return \"RunnableMap\";\n }\n\n lc_namespace = [\"langchain_core\", \"runnables\"];\n\n lc_serializable = true;\n\n protected steps: Record<string, Runnable<RunInput>>;\n\n public getStepsKeys(): string[] {\n return Object.keys(this.steps);\n }\n\n constructor(fields: { steps: RunnableMapLike<RunInput, RunOutput> }) {\n super(fields);\n this.steps = {};\n for (const [key, value] of Object.entries(fields.steps)) {\n this.steps[key] = _coerceToRunnable(value);\n }\n }\n\n static from<\n RunInput,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n steps: RunnableMapLike<RunInput, RunOutput>\n ): RunnableMap<RunInput, RunOutput> {\n return new RunnableMap<RunInput, RunOutput>({ steps });\n }\n\n async invoke(\n input: RunInput,\n options?: Partial<RunnableConfig>\n ): Promise<RunOutput> {\n const config = ensureConfig(options);\n const callbackManager_ = await getCallbackManagerForConfig(config);\n const runManager = await callbackManager_?.handleChainStart(\n this.toJSON(),\n {\n input,\n },\n config.runId,\n undefined,\n undefined,\n undefined,\n config?.runName\n );\n delete config.runId;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n const output: Record<string, any> = {};\n try {\n const promises = Object.entries(this.steps).map(\n async ([key, runnable]) => {\n output[key] = await runnable.invoke(\n input,\n patchConfig(config, {\n callbacks: runManager?.getChild(`map:key:${key}`),\n })\n );\n }\n );\n await raceWithSignal(Promise.all(promises), config.signal);\n } catch (e) {\n await runManager?.handleChainError(e);\n throw e;\n }\n await runManager?.handleChainEnd(output);\n return output as RunOutput;\n }\n\n async *_transform(\n generator: AsyncGenerator<RunInput>,\n runManager?: CallbackManagerForChainRun,\n options?: Partial<RunnableConfig>\n ): AsyncGenerator<RunOutput> {\n // shallow copy steps to ignore changes while iterating\n const steps = { ...this.steps };\n // each step gets a copy of the input iterator\n const inputCopies = atee(generator, Object.keys(steps).length);\n // start the first iteration of each output iterator\n const tasks = new Map(\n Object.entries(steps).map(([key, runnable], i) => {\n const gen = runnable.transform(\n inputCopies[i],\n patchConfig(options, {\n callbacks: runManager?.getChild(`map:key:${key}`),\n })\n );\n return [key, gen.next().then((result) => ({ key, gen, result }))];\n })\n );\n // yield chunks as they become available,\n // starting new iterations as needed,\n // until all iterators are done\n while (tasks.size) {\n const promise = Promise.race(tasks.values());\n const { key, result, gen } = await raceWithSignal(\n promise,\n options?.signal\n );\n tasks.delete(key);\n if (!result.done) {\n yield { [key]: result.value } as unknown as RunOutput;\n tasks.set(\n key,\n gen.next().then((result) => ({ key, gen, result }))\n );\n }\n }\n }\n\n transform(\n generator: AsyncGenerator<RunInput>,\n options?: Partial<RunnableConfig>\n ): AsyncGenerator<RunOutput> {\n return this._transformStreamWithConfig(\n generator,\n this._transform.bind(this),\n options\n );\n }\n\n async stream(\n input: RunInput,\n options?: Partial<RunnableConfig>\n ): Promise<IterableReadableStream<RunOutput>> {\n async function* generator() {\n yield input;\n }\n const config = ensureConfig(options);\n const wrappedGenerator = new AsyncGeneratorWithSetup({\n generator: this.transform(generator(), config),\n config,\n });\n await wrappedGenerator.setup;\n return IterableReadableStream.fromAsyncGenerator(wrappedGenerator);\n }\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyTraceableFunction = TraceableFunction<(...any: any[]) => any>;\n\n/**\n * A runnable that wraps a traced LangSmith function.\n */\nexport class RunnableTraceable<RunInput, RunOutput> extends Runnable<\n RunInput,\n RunOutput\n> {\n lc_serializable = false;\n\n lc_namespace = [\"langchain_core\", \"runnables\"];\n\n protected func: AnyTraceableFunction;\n\n constructor(fields: { func: AnyTraceableFunction }) {\n super(fields);\n\n if (!isTraceableFunction(fields.func)) {\n throw new Error(\n \"RunnableTraceable requires a function that is wrapped in traceable higher-order function\"\n );\n }\n\n this.func = fields.func;\n }\n\n async invoke(input: RunInput, options?: Partial<RunnableConfig>) {\n const [config] = this._getOptionsList(options ?? {}, 1);\n const callbacks = await getCallbackManagerForConfig(config);\n const promise = this.func(\n patchConfig(config, { callbacks }),\n input\n ) as Promise<RunOutput>;\n\n return raceWithSignal(promise, config?.signal);\n }\n\n async *_streamIterator(\n input: RunInput,\n options?: Partial<RunnableConfig>\n ): AsyncGenerator<RunOutput> {\n const [config] = this._getOptionsList(options ?? {}, 1);\n const result = await this.invoke(input, options);\n\n if (isAsyncIterable(result)) {\n for await (const item of result) {\n config?.signal?.throwIfAborted();\n yield item as RunOutput;\n }\n return;\n }\n\n if (isIterator(result)) {\n while (true) {\n config?.signal?.throwIfAborted();\n const state: IteratorResult<unknown> = result.next();\n if (state.done) break;\n yield state.value as RunOutput;\n }\n return;\n }\n\n yield result;\n }\n\n static from(func: AnyTraceableFunction) {\n return new RunnableTraceable({ func });\n }\n}\n\nfunction assertNonTraceableFunction<\n RunInput,\n RunOutput,\n CallOptions extends RunnableConfig = RunnableConfig,\n>(\n func:\n | RunnableFunc<\n RunInput,\n RunOutput | Runnable<RunInput, RunOutput, CallOptions>,\n CallOptions\n >\n | TraceableFunction<\n RunnableFunc<\n RunInput,\n RunOutput | Runnable<RunInput, RunOutput, CallOptions>,\n CallOptions\n >\n >\n): asserts func is RunnableFunc<\n RunInput,\n RunOutput | Runnable<RunInput, RunOutput, CallOptions>,\n CallOptions\n> {\n if (isTraceableFunction(func)) {\n throw new Error(\n \"RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.\"\n );\n }\n}\n\n/**\n * A runnable that wraps an arbitrary function that takes a single argument.\n * @example\n * ```typescript\n * import { RunnableLambda } from \"@langchain/core/runnables\";\n *\n * const add = (input: { x: number; y: number }) => input.x + input.y;\n *\n * const multiply = (input: { value: number; multiplier: number }) =>\n * input.value * input.multiplier;\n *\n * // Create runnables for the functions\n * const addLambda = RunnableLambda.from(add);\n * const multiplyLambda = RunnableLambda.from(multiply);\n *\n * // Chain the lambdas for a mathematical operation\n * const chainedLambda = addLambda.pipe((result) =>\n * multiplyLambda.invoke({ value: result, multiplier: 2 })\n * );\n *\n * // Example invocation of the chainedLambda\n * const result = await chainedLambda.invoke({ x: 2, y: 3 });\n *\n * // Will log \"10\" (since (2 + 3) * 2 = 10)\n * ```\n */\nexport class RunnableLambda<\n RunInput,\n RunOutput,\n CallOptions extends RunnableConfig = RunnableConfig,\n> extends Runnable<RunInput, RunOutput, CallOptions> {\n static lc_name() {\n return \"RunnableLambda\";\n }\n\n lc_namespace = [\"langchain_core\", \"runnables\"];\n\n protected func: RunnableFunc<\n RunInput,\n RunOutput | Runnable<RunInput, RunOutput, CallOptions>,\n CallOptions\n >;\n\n constructor(fields: {\n func:\n | RunnableFunc<\n RunInput,\n RunOutput | Runnable<RunInput, RunOutput, CallOptions>,\n CallOptions\n >\n | TraceableFunction<\n RunnableFunc<\n RunInput,\n RunOutput | Runnable<RunInput, RunOutput, CallOptions>,\n CallOptions\n >\n >;\n }) {\n if (isTraceableFunction(fields.func)) {\n // oxlint-disable-next-line no-constructor-return\n return RunnableTraceable.from(fields.func) as unknown as RunnableLambda<\n RunInput,\n RunOutput,\n CallOptions\n >;\n }\n\n super(fields);\n\n assertNonTraceableFunction(fields.func);\n this.func = fields.func;\n }\n\n static from<\n RunInput,\n RunOutput,\n CallOptions extends RunnableConfig = RunnableConfig,\n >(\n func: RunnableFunc<\n RunInput,\n RunOutput | Runnable<RunInput, RunOutput, CallOptions>,\n CallOptions\n >\n ): RunnableLambda<RunInput, RunOutput, CallOptions>;\n\n static from<\n RunInput,\n RunOutput,\n CallOptions extends RunnableConfig = RunnableConfig,\n >(\n func: TraceableFunction<\n RunnableFunc<\n RunInput,\n RunOutput | Runnable<RunInput, RunOutput, CallOptions>,\n CallOptions\n >\n >\n ): RunnableLambda<RunInput, RunOutput, CallOptions>;\n\n static from<\n RunInput,\n RunOutput,\n CallOptions extends RunnableConfig = RunnableConfig,\n >(\n func:\n | RunnableFunc<\n RunInput,\n RunOutput | Runnable<RunInput, RunOutput, CallOptions>,\n CallOptions\n >\n | TraceableFunction<\n RunnableFunc<\n RunInput,\n RunOutput | Runnable<RunInput, RunOutput, CallOptions>,\n CallOptions\n >\n >\n ): RunnableLambda<RunInput, RunOutput, CallOptions> {\n return new RunnableLambda({\n func,\n });\n }\n\n async _invoke(\n input: RunInput,\n config?: Partial<CallOptions>,\n runManager?: CallbackManagerForChainRun\n ) {\n return new Promise<RunOutput>((resolve, reject) => {\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1,\n });\n // oxlint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n let output = await this.func(input, {\n ...childConfig,\n });\n if (output && Runnable.isRunnable(output)) {\n if (config?.recursionLimit === 0) {\n throw new Error(\"Recursion limit reached.\");\n }\n output = await output.invoke(input, {\n ...childConfig,\n recursionLimit:\n (childConfig.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1,\n });\n } else if (isAsyncIterable(output)) {\n let finalOutput: RunOutput | undefined;\n for await (const chunk of consumeAsyncIterableInContext(\n childConfig,\n output\n )) {\n config?.signal?.throwIfAborted();\n if (finalOutput === undefined) {\n finalOutput = chunk as RunOutput;\n } else {\n // Make a best effort to gather, for any type that supports concat.\n try {\n finalOutput = this._concatOutputChunks(\n finalOutput,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n chunk as any\n );\n } catch {\n finalOutput = chunk as RunOutput;\n }\n }\n }\n output = finalOutput as typeof output;\n } else if (isIterableIterator(output)) {\n let finalOutput: RunOutput | undefined;\n for (const chunk of consumeIteratorInContext(\n childConfig,\n output\n )) {\n config?.signal?.throwIfAborted();\n if (finalOutput === undefined) {\n finalOutput = chunk as RunOutput;\n } else {\n // Make a best effort to gather, for any type that supports concat.\n try {\n finalOutput = this._concatOutputChunks(\n finalOutput,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n chunk as any\n );\n } catch {\n finalOutput = chunk as RunOutput;\n }\n }\n }\n output = finalOutput as typeof output;\n }\n resolve(output);\n } catch (e) {\n reject(e);\n }\n }\n );\n });\n }\n\n async invoke(\n input: RunInput,\n options?: Partial<CallOptions>\n ): Promise<RunOutput> {\n return this._callWithConfig(this._invoke.bind(this), input, options);\n }\n\n async *_transform(\n generator: AsyncGenerator<RunInput>,\n runManager?: CallbackManagerForChainRun,\n config?: Partial<CallOptions>\n ): AsyncGenerator<RunOutput> {\n let finalChunk: RunInput | undefined;\n for await (const chunk of generator) {\n if (finalChunk === undefined) {\n finalChunk = chunk;\n } else {\n // Make a best effort to gather, for any type that supports concat.\n try {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n finalChunk = this._concatOutputChunks(finalChunk, chunk as any);\n } catch {\n finalChunk = chunk;\n }\n }\n }\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1,\n });\n const output = await new Promise<RunOutput | Runnable>(\n (resolve, reject) => {\n // oxlint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n const res = await this.func(finalChunk as RunInput, {\n ...childConfig,\n config: childConfig,\n });\n resolve(res);\n } catch (e) {\n reject(e);\n }\n }\n );\n }\n );\n if (output && Runnable.isRunnable(output)) {\n if (config?.recursionLimit === 0) {\n throw new Error(\"Recursion limit reached.\");\n }\n const stream = await output.stream(finalChunk as RunInput, childConfig);\n for await (const chunk of stream) {\n yield chunk;\n }\n } else if (isAsyncIterable(output)) {\n for await (const chunk of consumeAsyncIterableInContext(\n childConfig,\n output\n )) {\n config?.signal?.throwIfAborted();\n yield chunk as RunOutput;\n }\n } else if (isIterableIterator(output)) {\n for (const chunk of consumeIteratorInContext(childConfig, output)) {\n config?.signal?.throwIfAborted();\n yield chunk as RunOutput;\n }\n } else {\n yield output;\n }\n }\n\n transform(\n generator: AsyncGenerator<RunInput>,\n options?: Partial<CallOptions>\n ): AsyncGenerator<RunOutput> {\n return this._transformStreamWithConfig(\n generator,\n this._transform.bind(this),\n options\n );\n }\n\n async stream(\n input: RunInput,\n options?: Partial<CallOptions>\n ): Promise<IterableReadableStream<RunOutput>> {\n async function* generator() {\n yield input;\n }\n const config = ensureConfig(options);\n const wrappedGenerator = new AsyncGeneratorWithSetup({\n generator: this.transform(generator(), config),\n config,\n });\n await wrappedGenerator.setup;\n return IterableReadableStream.fromAsyncGenerator(wrappedGenerator);\n }\n}\n\n/**\n * A runnable that runs a mapping of runnables in parallel,\n * and returns a mapping of their outputs.\n * @example\n * ```typescript\n * import {\n * RunnableLambda,\n * RunnableParallel,\n * } from \"@langchain/core/runnables\";\n *\n * const addYears = (age: number): number => age + 5;\n * const yearsToFifty = (age: number): number => 50 - age;\n * const yearsToHundred = (age: number): number => 100 - age;\n *\n * const addYearsLambda = RunnableLambda.from(addYears);\n * const milestoneFiftyLambda = RunnableLambda.from(yearsToFifty);\n * const milestoneHundredLambda = RunnableLambda.from(yearsToHundred);\n *\n * // Pipe will coerce objects into RunnableParallel by default, but we\n * // explicitly instantiate one here to demonstrate\n * const sequence = addYearsLambda.pipe(\n * RunnableParallel.from({\n * years_to_fifty: milestoneFiftyLambda,\n * years_to_hundred: milestoneHundredLambda,\n * })\n * );\n *\n * // Invoke the sequence with a single age input\n * const res = await sequence.invoke(25);\n *\n * // { years_to_fifty: 20, years_to_hundred: 70 }\n * ```\n */\nexport class RunnableParallel<RunInput> extends RunnableMap<RunInput> {}\n\n/**\n * A Runnable that can fallback to other Runnables if it fails.\n * External APIs (e.g., APIs for a language model) may at times experience\n * degraded performance or even downtime.\n *\n * In these cases, it can be useful to have a fallback Runnable that can be\n * used in place of the original Runnable (e.g., fallback to another LLM provider).\n *\n * Fallbacks can be defined at the level of a single Runnable, or at the level\n * of a chain of Runnables. Fallbacks are tried in order until one succeeds or\n * all fail.\n *\n * While you can instantiate a `RunnableWithFallbacks` directly, it is usually\n * more convenient to use the `withFallbacks` method on an existing Runnable.\n *\n * When streaming, fallbacks will only be called on failures during the initial\n * stream creation. Errors that occur after a stream starts will not fallback\n * to the next Runnable.\n *\n * @example\n * ```typescript\n * import {\n * RunnableLambda,\n * RunnableWithFallbacks,\n * } from \"@langchain/core/runnables\";\n *\n * const primaryOperation = (input: string): string => {\n * if (input !== \"safe\") {\n * throw new Error(\"Primary operation failed due to unsafe input\");\n * }\n * return `Processed: ${input}`;\n * };\n *\n * // Define a fallback operation that processes the input differently\n * const fallbackOperation = (input: string): string =>\n * `Fallback processed: ${input}`;\n *\n * const primaryRunnable = RunnableLambda.from(primaryOperation);\n * const fallbackRunnable = RunnableLambda.from(fallbackOperation);\n *\n * // Apply the fallback logic using the .withFallbacks() method\n * const runnableWithFallback = primaryRunnable.withFallbacks([fallbackRunnable]);\n *\n * // Alternatively, create a RunnableWithFallbacks instance manually\n * const manualFallbackChain = new RunnableWithFallbacks({\n * runnable: primaryRunnable,\n * fallbacks: [fallbackRunnable],\n * });\n *\n * // Example invocation using .withFallbacks()\n * const res = await runnableWithFallback\n * .invoke(\"unsafe input\")\n * .catch((error) => {\n * console.error(\"Failed after all attempts:\", error.message);\n * });\n *\n * // \"Fallback processed: unsafe input\"\n *\n * // Example invocation using manual instantiation\n * const res = await manualFallbackChain\n * .invoke(\"safe\")\n * .catch((error) => {\n * console.error(\"Failed after all attempts:\", error.message);\n * });\n *\n * // \"Processed: safe\"\n * ```\n */\nexport class RunnableWithFallbacks<RunInput, RunOutput> extends Runnable<\n RunInput,\n RunOutput\n> {\n static lc_name() {\n return \"RunnableWithFallbacks\";\n }\n\n lc_namespace = [\"langchain_core\", \"runnables\"];\n\n lc_serializable = true;\n\n runnable: Runnable<RunInput, RunOutput>;\n\n fallbacks: Runnable<RunInput, RunOutput>[];\n\n constructor(fields: {\n runnable: Runnable<RunInput, RunOutput>;\n fallbacks: Runnable<RunInput, RunOutput>[];\n }) {\n super(fields);\n this.runnable = fields.runnable;\n this.fallbacks = fields.fallbacks;\n }\n\n *runnables() {\n yield this.runnable;\n for (const fallback of this.fallbacks) {\n yield fallback;\n }\n }\n\n async invoke(\n input: RunInput,\n options?: Partial<RunnableConfig>\n ): Promise<RunOutput> {\n const config = ensureConfig(options);\n const callbackManager_ = await getCallbackManagerForConfig(config);\n const { runId, ...otherConfigFields } = config;\n const runManager = await callbackManager_?.handleChainStart(\n this.toJSON(),\n _coerceToDict(input, \"input\"),\n runId,\n undefined,\n undefined,\n undefined,\n otherConfigFields?.runName\n );\n const childConfig = patchConfig(otherConfigFields, {\n callbacks: runManager?.getChild(),\n });\n const res = await AsyncLocalStorageProviderSingleton.runWithConfig(\n childConfig,\n async () => {\n let firstError;\n for (const runnable of this.runnables()) {\n config?.signal?.throwIfAborted();\n try {\n const output = await runnable.invoke(input, childConfig);\n await runManager?.handleChainEnd(_coerceToDict(output, \"output\"));\n return output;\n } catch (e) {\n if (firstError === undefined) {\n firstError = e;\n }\n }\n }\n if (firstError === undefined) {\n throw new Error(\"No error stored at end of fallback.\");\n }\n await runManager?.handleChainError(firstError);\n throw firstError;\n }\n );\n return res;\n }\n\n async *_streamIterator(\n input: RunInput,\n options?: Partial<RunnableConfig> | undefined\n ): AsyncGenerator<RunOutput> {\n const config = ensureConfig(options);\n const callbackManager_ = await getCallbackManagerForConfig(config);\n const { runId, ...otherConfigFields } = config;\n const runManager = await callbackManager_?.handleChainStart(\n this.toJSON(),\n _coerceToDict(input, \"input\"),\n runId,\n undefined,\n undefined,\n undefined,\n otherConfigFields?.runName\n );\n let firstError;\n let stream;\n for (const runnable of this.runnables()) {\n config?.signal?.throwIfAborted();\n const childConfig = patchConfig(otherConfigFields, {\n callbacks: runManager?.getChild(),\n });\n try {\n const originalStream = await runnable.stream(input, childConfig);\n stream = consumeAsyncIterableInContext(childConfig, originalStream);\n break;\n } catch (e) {\n if (firstError === undefined) {\n firstError = e;\n }\n }\n }\n if (stream === undefined) {\n const error =\n firstError ?? new Error(\"No error stored at end of fallback.\");\n await runManager?.handleChainError(error);\n throw error;\n }\n let output;\n try {\n for await (const chunk of stream) {\n yield chunk;\n try {\n output =\n output === undefined\n ? output\n : this._concatOutputChunks(output, chunk);\n } catch {\n output = undefined;\n }\n }\n } catch (e) {\n await runManager?.handleChainError(e);\n throw e;\n }\n await runManager?.handleChainEnd(_coerceToDict(output, \"output\"));\n }\n\n async batch(\n inputs: RunInput[],\n options?: Partial<RunnableConfig> | Partial<RunnableConfig>[],\n batchOptions?: RunnableBatchOptions & { returnExceptions?: false }\n ): Promise<RunOutput[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<RunnableConfig> | Partial<RunnableConfig>[],\n batchOptions?: RunnableBatchOptions & { returnExceptions: true }\n ): Promise<(RunOutput | Error)[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<RunnableConfig> | Partial<RunnableConfig>[],\n batchOptions?: RunnableBatchOptions\n ): Promise<(RunOutput | Error)[]>;\n\n async batch(\n inputs: RunInput[],\n options?: Partial<RunnableConfig> | Partial<RunnableConfig>[],\n batchOptions?: RunnableBatchOptions\n ): Promise<(RunOutput | Error)[]> {\n if (batchOptions?.returnExceptions) {\n throw new Error(\"Not implemented.\");\n }\n const configList = this._getOptionsList(options ?? {}, inputs.length);\n const callbackManagers = await Promise.all(\n configList.map((config) => getCallbackManagerForConfig(config))\n );\n const runManagers = await Promise.all(\n callbackManagers.map(async (callbackManager, i) => {\n const handleStartRes = await callbackManager?.handleChainStart(\n this.toJSON(),\n _coerceToDict(inputs[i], \"input\"),\n configList[i].runId,\n undefined,\n undefined,\n undefined,\n configList[i].runName\n );\n delete configList[i].runId;\n return handleStartRes;\n })\n );\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n let firstError: any;\n for (const runnable of this.runnables()) {\n configList[0].signal?.throwIfAborted();\n try {\n const outputs = await runnable.batch(\n inputs,\n runManagers.map((runManager, j) =>\n patchConfig(configList[j], {\n callbacks: runManager?.getChild(),\n })\n ),\n batchOptions\n );\n await Promise.all(\n runManagers.map((runManager, i) =>\n runManager?.handleChainEnd(_coerceToDict(outputs[i], \"output\"))\n )\n );\n return outputs;\n } catch (e) {\n if (firstError === undefined) {\n firstError = e;\n }\n }\n }\n if (!firstError) {\n throw new Error(\"No error stored at end of fallbacks.\");\n }\n await Promise.all(\n runManagers.map((runManager) => runManager?.handleChainError(firstError))\n );\n throw firstError;\n }\n}\n\n// TODO: Figure out why the compiler needs help eliminating Error as a RunOutput type\nexport function _coerceToRunnable<\n RunInput,\n RunOutput,\n CallOptions extends RunnableConfig = RunnableConfig,\n>(\n coerceable: RunnableLike<RunInput, RunOutput, CallOptions>\n): Runnable<RunInput, Exclude<RunOutput, Error>, CallOptions> {\n if (typeof coerceable === \"function\") {\n return new RunnableLambda({ func: coerceable }) as Runnable<\n RunInput,\n Exclude<RunOutput, Error>,\n CallOptions\n >;\n } else if (Runnable.isRunnable(coerceable)) {\n return coerceable as Runnable<\n RunInput,\n Exclude<RunOutput, Error>,\n CallOptions\n >;\n } else if (!Array.isArray(coerceable) && typeof coerceable === \"object\") {\n const runnables: Record<string, Runnable<RunInput>> = {};\n for (const [key, value] of Object.entries(coerceable)) {\n runnables[key] = _coerceToRunnable(value as RunnableLike);\n }\n return new RunnableMap({\n steps: runnables,\n }) as unknown as Runnable<RunInput, Exclude<RunOutput, Error>, CallOptions>;\n } else {\n throw new Error(\n `Expected a Runnable, function or object.\\nInstead got an unsupported type.`\n );\n }\n}\n\nexport interface RunnableAssignFields<RunInput> {\n mapper: RunnableMap<RunInput>;\n}\n\n/**\n * A runnable that assigns key-value pairs to inputs of type `Record<string, unknown>`.\n * @example\n * ```typescript\n * import {\n * RunnableAssign,\n * RunnableLambda,\n * RunnableParallel,\n * } from \"@langchain/core/runnables\";\n *\n * const calculateAge = (x: { birthYear: number }): { age: number } => {\n * const currentYear = new Date().getFullYear();\n * return { age: currentYear - x.birthYear };\n * };\n *\n * const createGreeting = (x: { name: string }): { greeting: string } => {\n * return { greeting: `Hello, ${x.name}!` };\n * };\n *\n * const mapper = RunnableParallel.from({\n * age_step: RunnableLambda.from(calculateAge),\n * greeting_step: RunnableLambda.from(createGreeting),\n * });\n *\n * const runnableAssign = new RunnableAssign({ mapper });\n *\n * const res = await runnableAssign.invoke({ name: \"Alice\", birthYear: 1990 });\n *\n * // { name: \"Alice\", birthYear: 1990, age_step: { age: 34 }, greeting_step: { greeting: \"Hello, Alice!\" } }\n * ```\n */\nexport class RunnableAssign<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends Record<string, any> = Record<string, any>,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n CallOptions extends RunnableConfig = RunnableConfig,\n>\n extends Runnable<RunInput, RunOutput>\n implements RunnableAssignFields<RunInput>\n{\n static lc_name() {\n return \"RunnableAssign\";\n }\n\n lc_namespace = [\"langchain_core\", \"runnables\"];\n\n lc_serializable = true;\n\n mapper: RunnableMap<RunInput>;\n\n constructor(fields: RunnableMap<RunInput> | RunnableAssignFields<RunInput>) {\n // oxlint-disable-next-line no-instanceof/no-instanceof\n if (fields instanceof RunnableMap) {\n // oxlint-disable-next-line no-param-reassign\n fields = { mapper: fields };\n }\n super(fields);\n this.mapper = fields.mapper;\n }\n\n async invoke(\n input: RunInput,\n options?: Partial<CallOptions>\n ): Promise<RunOutput> {\n const mapperResult = await this.mapper.invoke(input, options);\n\n return {\n ...input,\n ...mapperResult,\n } as RunOutput;\n }\n\n async *_transform(\n generator: AsyncGenerator<RunInput>,\n runManager?: CallbackManagerForChainRun,\n options?: Partial<RunnableConfig>\n ): AsyncGenerator<RunOutput> {\n // collect mapper keys\n const mapperKeys = this.mapper.getStepsKeys();\n // create two input gens, one for the mapper, one for the input\n const [forPassthrough, forMapper] = atee(generator);\n // create mapper output gen\n const mapperOutput = this.mapper.transform(\n forMapper,\n patchConfig(options, { callbacks: runManager?.getChild() })\n );\n // start the mapper\n const firstMapperChunkPromise = mapperOutput.next();\n // yield the passthrough\n for await (const chunk of forPassthrough) {\n if (typeof chunk !== \"object\" || Array.isArray(chunk)) {\n throw new Error(\n `RunnableAssign can only be used with objects as input, got ${typeof chunk}`\n );\n }\n const filtered = Object.fromEntries(\n Object.entries(chunk).filter(([key]) => !mapperKeys.includes(key))\n );\n if (Object.keys(filtered).length > 0) {\n yield filtered as unknown as RunOutput;\n }\n }\n // yield the mapper output\n yield (await firstMapperChunkPromise).value;\n for await (const chunk of mapperOutput) {\n yield chunk as unknown as RunOutput;\n }\n }\n\n transform(\n generator: AsyncGenerator<RunInput>,\n options?: Partial<RunnableConfig>\n ): AsyncGenerator<RunOutput> {\n return this._transformStreamWithConfig(\n generator,\n this._transform.bind(this),\n options\n );\n }\n\n async stream(\n input: RunInput,\n options?: Partial<RunnableConfig>\n ): Promise<IterableReadableStream<RunOutput>> {\n async function* generator() {\n yield input;\n }\n const config = ensureConfig(options);\n const wrappedGenerator = new AsyncGeneratorWithSetup({\n generator: this.transform(generator(), config),\n config,\n });\n await wrappedGenerator.setup;\n return IterableReadableStream.fromAsyncGenerator(wrappedGenerator);\n }\n}\n\nexport interface RunnablePickFields {\n keys: string | string[];\n}\n\n/**\n * A runnable that assigns key-value pairs to inputs of type `Record<string, unknown>`.\n * Useful for streaming, can be automatically created and chained by calling `runnable.pick();`.\n * @example\n * ```typescript\n * import { RunnablePick } from \"@langchain/core/runnables\";\n *\n * const inputData = {\n * name: \"John\",\n * age: 30,\n * city: \"New York\",\n * country: \"USA\",\n * email: \"john.doe@example.com\",\n * phone: \"+1234567890\",\n * };\n *\n * const basicInfoRunnable = new RunnablePick([\"name\", \"city\"]);\n *\n * // Example invocation\n * const res = await basicInfoRunnable.invoke(inputData);\n *\n * // { name: 'John', city: 'New York' }\n * ```\n */\nexport class RunnablePick<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends Record<string, any> = Record<string, any>,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> | any = Record<string, any> | any,\n CallOptions extends RunnableConfig = RunnableConfig,\n>\n extends Runnable<RunInput, RunOutput>\n implements RunnablePickFields\n{\n static lc_name() {\n return \"RunnablePick\";\n }\n\n lc_namespace = [\"langchain_core\", \"runnables\"];\n\n lc_serializable = true;\n\n keys: string | string[];\n\n constructor(fields: string | string[] | RunnablePickFields) {\n if (typeof fields === \"string\" || Array.isArray(fields)) {\n // oxlint-disable-next-line no-param-reassign\n fields = { keys: fields };\n }\n super(fields);\n this.keys = fields.keys;\n }\n\n async _pick(input: RunInput): Promise<RunOutput> {\n if (typeof this.keys === \"string\") {\n return input[this.keys];\n } else {\n const picked = this.keys\n .map((key) => [key, input[key]])\n .filter((v) => v[1] !== undefined);\n return picked.length === 0\n ? (undefined as RunOutput)\n : Object.fromEntries(picked);\n }\n }\n\n async invoke(\n input: RunInput,\n options?: Partial<CallOptions>\n ): Promise<RunOutput> {\n return this._callWithConfig(this._pick.bind(this), input, options);\n }\n\n async *_transform(\n generator: AsyncGenerator<RunInput>\n ): AsyncGenerator<RunOutput> {\n for await (const chunk of generator) {\n const picked = await this._pick(chunk);\n if (picked !== undefined) {\n yield picked;\n }\n }\n }\n\n transform(\n generator: AsyncGenerator<RunInput>,\n options?: Partial<RunnableConfig>\n ): AsyncGenerator<RunOutput> {\n return this._transformStreamWithConfig(\n generator,\n this._transform.bind(this),\n options\n );\n }\n\n async stream(\n input: RunInput,\n options?: Partial<RunnableConfig>\n ): Promise<IterableReadableStream<RunOutput>> {\n async function* generator() {\n yield input;\n }\n const config = ensureConfig(options);\n const wrappedGenerator = new AsyncGeneratorWithSetup({\n generator: this.transform(generator(), config),\n config,\n });\n await wrappedGenerator.setup;\n return IterableReadableStream.fromAsyncGenerator(wrappedGenerator);\n }\n}\n\nexport interface RunnableToolLikeArgs<\n RunInput extends InteropZodType = InteropZodType,\n RunOutput = unknown,\n> extends Omit<\n RunnableBindingArgs<InferInteropZodOutput<RunInput>, RunOutput>,\n \"config\"\n> {\n name: string;\n\n description?: string;\n\n schema: RunInput;\n\n config?: RunnableConfig;\n}\n\nexport class RunnableToolLike<\n RunInput extends InteropZodType = InteropZodType,\n RunOutput = unknown,\n> extends RunnableBinding<InferInteropZodOutput<RunInput>, RunOutput> {\n name: string;\n\n description?: string;\n\n schema: RunInput;\n\n constructor(fields: RunnableToolLikeArgs<RunInput, RunOutput>) {\n const sequence = RunnableSequence.from([\n RunnableLambda.from<\n InferInteropZodOutput<RunInput> | ToolCall,\n InferInteropZodOutput<RunInput>\n >(async (input) => {\n let toolInput: InferInteropZodOutput<RunInput>;\n\n if (_isToolCall(input)) {\n try {\n toolInput = await interopParseAsync(this.schema, input.args);\n } catch {\n throw new ToolInputParsingException(\n `Received tool input did not match expected schema`,\n JSON.stringify(input.args)\n );\n }\n } else {\n toolInput = input;\n }\n return toolInput;\n }).withConfig({ runName: `${fields.name}:parse_input` }),\n fields.bound,\n ]).withConfig({ runName: fields.name });\n\n super({\n bound: sequence,\n config: fields.config ?? {},\n });\n\n this.name = fields.name;\n this.description = fields.description;\n this.schema = fields.schema;\n }\n\n static lc_name() {\n return \"RunnableToolLike\";\n }\n}\n\n/**\n * Given a runnable and a Zod schema, convert the runnable to a tool.\n *\n * @template RunInput The input type for the runnable.\n * @template RunOutput The output type for the runnable.\n *\n * @param {Runnable<RunInput, RunOutput>} runnable The runnable to convert to a tool.\n * @param fields\n * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable.\n * @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.\n * @param {InteropZodType<RunInput>} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable.\n * @returns {RunnableToolLike<InteropZodType<RunInput>, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool.\n */\nexport function convertRunnableToTool<RunInput, RunOutput>(\n runnable: Runnable<RunInput, RunOutput>,\n fields: {\n name?: string;\n description?: string;\n schema: InteropZodType<RunInput>;\n }\n): RunnableToolLike<InteropZodType<RunInput | ToolCall>, RunOutput> {\n const name = fields.name ?? runnable.getName();\n const description = fields.description ?? getSchemaDescription(fields.schema);\n\n if (isSimpleStringZodSchema(fields.schema)) {\n return new RunnableToolLike<InteropZodType<RunInput | ToolCall>, RunOutput>(\n {\n name,\n description,\n schema: z\n .object({ input: z.string() })\n .transform((input) => input.input) as InteropZodType,\n bound: runnable,\n }\n );\n }\n\n return new RunnableToolLike<InteropZodType<RunInput | ToolCall>, RunOutput>({\n name,\n description,\n schema: fields.schema,\n bound: runnable,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA6GA,SAAgB,cAAc,OAAY,YAAoB;CAC5D,OAAO,SACL,CAAC,MAAM,QAAQ,KAAK,KAEpB,EAAE,iBAAiB,SACnB,OAAO,UAAU,WACf,QACA,GAAG,aAAa,MAAM;AAC5B;;;;;AAMA,IAAsB,WAAtB,cAOUA,0BAAAA,aAEV;CACE,cAAwB;CAExB;CAEA,QAAQ,QAAyB;EAC/B,MAAM,OAEJ,KAAK,QAAS,KAAK,YAAoB,QAAQ,KAAK,KAAK,YAAY;EACvE,OAAO,SAAS,GAAG,OAAO,WAAW;CACvC;;;;;;;CAaA,UAAU,QAG0C;EAElD,OAAO,IAAI,cAAc;GACvB,OAAO;GACP,QAAQ,CAAC;GACT,QAAQ,CAAC;GACT,kBAAkB,QAAQ;GAC1B,GAA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