From aa3e3cfa402105cb9dd5c92f73ceeaf769981b54 Mon Sep 17 00:00:00 2001 From: Leonid Ganeline Date: Fri, 12 Jul 2024 08:27:06 -0700 Subject: [PATCH] core[patch]: docstrings `runnables` update (#24161) Added missed docstrings. Formatted docstrings to the consistent form. --- libs/core/langchain_core/runnables/base.py | 585 ++++++++++++++---- libs/core/langchain_core/runnables/branch.py | 61 +- libs/core/langchain_core/runnables/config.py | 30 +- .../langchain_core/runnables/configurable.py | 40 +- .../langchain_core/runnables/fallbacks.py | 6 +- libs/core/langchain_core/runnables/graph.py | 168 ++++- .../langchain_core/runnables/graph_ascii.py | 1 + .../langchain_core/runnables/graph_mermaid.py | 38 +- .../langchain_core/runnables/graph_png.py | 39 +- libs/core/langchain_core/runnables/history.py | 22 +- .../langchain_core/runnables/passthrough.py | 42 +- libs/core/langchain_core/runnables/retry.py | 2 +- libs/core/langchain_core/runnables/router.py | 5 +- libs/core/langchain_core/runnables/schema.py | 46 +- libs/core/langchain_core/runnables/utils.py | 248 +++++++- 15 files changed, 1099 insertions(+), 234 deletions(-) diff --git a/libs/core/langchain_core/runnables/base.py b/libs/core/langchain_core/runnables/base.py index 97138c79a46..a410672a07b 100644 --- a/libs/core/langchain_core/runnables/base.py +++ b/libs/core/langchain_core/runnables/base.py @@ -118,11 +118,11 @@ class Runnable(Generic[Input, Output], ABC): Built-in optimizations: - **Batch**: By default, batch runs invoke() in parallel using a thread pool executor. - Override to optimize batching. + Override to optimize batching. - **Async**: Methods with "a" suffix are asynchronous. By default, they execute - the sync counterpart using asyncio's thread pool. - Override for native async. + the sync counterpart using asyncio's thread pool. + Override for native async. All methods accept an optional config argument, which can be used to configure execution, add tags and metadata for tracing and debugging etc. @@ -139,11 +139,11 @@ class Runnable(Generic[Input, Output], ABC): The main composition primitives are RunnableSequence and RunnableParallel. - RunnableSequence invokes a series of runnables sequentially, with one runnable's - output serving as the next's input. Construct using the `|` operator or by - passing a list of runnables to RunnableSequence. + **RunnableSequence** invokes a series of runnables sequentially, with + one Runnable's output serving as the next's input. Construct using + the `|` operator or by passing a list of runnables to RunnableSequence. - RunnableParallel invokes runnables concurrently, providing the same input + **RunnableParallel** invokes runnables concurrently, providing the same input to each. Construct it using a dict literal within a sequence or by passing a dict to RunnableParallel. @@ -235,12 +235,12 @@ class Runnable(Generic[Input, Output], ABC): """ # noqa: E501 name: Optional[str] = None - """The name of the runnable. Used for debugging and tracing.""" + """The name of the Runnable. Used for debugging and tracing.""" def get_name( self, suffix: Optional[str] = None, *, name: Optional[str] = None ) -> str: - """Get the name of the runnable.""" + """Get the name of the Runnable.""" name = name or self.name or self.__class__.__name__ if suffix: if name[0].isupper(): @@ -252,7 +252,7 @@ class Runnable(Generic[Input, Output], ABC): @property def InputType(self) -> Type[Input]: - """The type of input this runnable accepts specified as a type annotation.""" + """The type of input this Runnable accepts specified as a type annotation.""" for cls in self.__class__.__orig_bases__: # type: ignore[attr-defined] type_args = get_args(cls) if type_args and len(type_args) == 2: @@ -265,7 +265,7 @@ class Runnable(Generic[Input, Output], ABC): @property def OutputType(self) -> Type[Output]: - """The type of output this runnable produces specified as a type annotation.""" + """The type of output this Runnable produces specified as a type annotation.""" for cls in self.__class__.__orig_bases__: # type: ignore[attr-defined] type_args = get_args(cls) if type_args and len(type_args) == 2: @@ -278,17 +278,17 @@ class Runnable(Generic[Input, Output], ABC): @property def input_schema(self) -> Type[BaseModel]: - """The type of input this runnable accepts specified as a pydantic model.""" + """The type of input this Runnable accepts specified as a pydantic model.""" return self.get_input_schema() def get_input_schema( self, config: Optional[RunnableConfig] = None ) -> Type[BaseModel]: - """Get a pydantic model that can be used to validate input to the runnable. + """Get a pydantic model that can be used to validate input to the Runnable. Runnables that leverage the configurable_fields and configurable_alternatives methods will have a dynamic input schema that depends on which - configuration the runnable is invoked with. + configuration the Runnable is invoked with. This method allows to get an input schema for a specific configuration. @@ -310,17 +310,17 @@ class Runnable(Generic[Input, Output], ABC): @property def output_schema(self) -> Type[BaseModel]: - """The type of output this runnable produces specified as a pydantic model.""" + """The type of output this Runnable produces specified as a pydantic model.""" return self.get_output_schema() def get_output_schema( self, config: Optional[RunnableConfig] = None ) -> Type[BaseModel]: - """Get a pydantic model that can be used to validate output to the runnable. + """Get a pydantic model that can be used to validate output to the Runnable. Runnables that leverage the configurable_fields and configurable_alternatives methods will have a dynamic output schema that depends on which - configuration the runnable is invoked with. + configuration the Runnable is invoked with. This method allows to get an output schema for a specific configuration. @@ -342,13 +342,13 @@ class Runnable(Generic[Input, Output], ABC): @property def config_specs(self) -> List[ConfigurableFieldSpec]: - """List configurable fields for this runnable.""" + """List configurable fields for this Runnable.""" return [] def config_schema( self, *, include: Optional[Sequence[str]] = None ) -> Type[BaseModel]: - """The type of config this runnable accepts specified as a pydantic model. + """The type of config this Runnable accepts specified as a pydantic model. To mark a field as configurable, see the `configurable_fields` and `configurable_alternatives` methods. @@ -390,7 +390,7 @@ class Runnable(Generic[Input, Output], ABC): ) def get_graph(self, config: Optional[RunnableConfig] = None) -> Graph: - """Return a graph representation of this runnable.""" + """Return a graph representation of this Runnable.""" from langchain_core.runnables.graph import Graph graph = Graph() @@ -412,6 +412,7 @@ class Runnable(Generic[Input, Output], ABC): def get_prompts( self, config: Optional[RunnableConfig] = None ) -> List[BasePromptTemplate]: + """Return a list of prompts used by this Runnable.""" from langchain_core.prompts.base import BasePromptTemplate prompts = [] @@ -429,7 +430,7 @@ class Runnable(Generic[Input, Output], ABC): Mapping[str, Union[Runnable[Any, Other], Callable[[Any], Other], Any]], ], ) -> RunnableSerializable[Input, Other]: - """Compose this runnable with another object to create a RunnableSequence.""" + """Compose this Runnable with another object to create a RunnableSequence.""" return RunnableSequence(self, coerce_to_runnable(other)) def __ror__( @@ -441,7 +442,7 @@ class Runnable(Generic[Input, Output], ABC): Mapping[str, Union[Runnable[Other, Any], Callable[[Other], Any], Any]], ], ) -> RunnableSerializable[Other, Output]: - """Compose this runnable with another object to create a RunnableSequence.""" + """Compose this Runnable with another object to create a RunnableSequence.""" return RunnableSequence(coerce_to_runnable(other), self) def pipe( @@ -481,7 +482,7 @@ class Runnable(Generic[Input, Output], ABC): return RunnableSequence(self, *others, name=name) def pick(self, keys: Union[str, List[str]]) -> RunnableSerializable[Any, Any]: - """Pick keys from the dict output of this runnable. + """Pick keys from the dict output of this Runnable. Pick single key: .. code-block:: python @@ -544,8 +545,8 @@ class Runnable(Generic[Input, Output], ABC): ], ], ) -> RunnableSerializable[Any, Any]: - """Assigns new fields to the dict output of this runnable. - Returns a new runnable. + """Assigns new fields to the dict output of this Runnable. + Returns a new Runnable. .. code-block:: python @@ -585,15 +586,15 @@ class Runnable(Generic[Input, Output], ABC): """Transform a single input into an output. Override to implement. Args: - input: The input to the runnable. - config: A config to use when invoking the runnable. + input: The input to the Runnable. + config: A config to use when invoking the Runnable. The config supports standard keys like 'tags', 'metadata' for tracing purposes, 'max_concurrency' for controlling how much work to do in parallel, and other keys. Please refer to the RunnableConfig for more details. Returns: - The output of the runnable. + The output of the Runnable. """ async def ainvoke( @@ -602,7 +603,7 @@ class Runnable(Generic[Input, Output], ABC): """Default implementation of ainvoke, calls invoke from a thread. The default implementation allows usage of async code even if - the runnable did not implement a native async version of invoke. + the Runnable did not implement a native async version of invoke. Subclasses should override this method if they can run asynchronously. """ @@ -621,7 +622,7 @@ class Runnable(Generic[Input, Output], ABC): The default implementation of batch works well for IO bound runnables. Subclasses should override this method if they can batch more efficiently; - e.g., if the underlying runnable uses an API which supports a batch mode. + e.g., if the underlying Runnable uses an API which supports a batch mode. """ if not inputs: return [] @@ -725,7 +726,21 @@ class Runnable(Generic[Input, Output], ABC): The default implementation of batch works well for IO bound runnables. Subclasses should override this method if they can batch more efficiently; - e.g., if the underlying runnable uses an API which supports a batch mode. + e.g., if the underlying Runnable uses an API which supports a batch mode. + + Args: + inputs: A list of inputs to the Runnable. + config: A config to use when invoking the Runnable. + The config supports standard keys like 'tags', 'metadata' for tracing + purposes, 'max_concurrency' for controlling how much work to do + in parallel, and other keys. Please refer to the RunnableConfig + for more details. Defaults to None. + return_exceptions: Whether to return exceptions instead of raising them. + Defaults to False. + **kwargs: Additional keyword arguments to pass to the Runnable. + + Returns: + A list of outputs from the Runnable. """ if not inputs: return [] @@ -775,7 +790,22 @@ class Runnable(Generic[Input, Output], ABC): **kwargs: Optional[Any], ) -> AsyncIterator[Tuple[int, Union[Output, Exception]]]: """Run ainvoke in parallel on a list of inputs, - yielding results as they complete.""" + yielding results as they complete. + + Args: + inputs: A list of inputs to the Runnable. + config: A config to use when invoking the Runnable. + The config supports standard keys like 'tags', 'metadata' for tracing + purposes, 'max_concurrency' for controlling how much work to do + in parallel, and other keys. Please refer to the RunnableConfig + for more details. Defaults to None. Defaults to None. + return_exceptions: Whether to return exceptions instead of raising them. + Defaults to False. + **kwargs: Additional keyword arguments to pass to the Runnable. + + Yields: + A tuple of the index of the input and the output from the Runnable. + """ if not inputs: return @@ -811,6 +841,14 @@ class Runnable(Generic[Input, Output], ABC): """ Default implementation of stream, which calls invoke. Subclasses should override this method if they support streaming output. + + Args: + input: The input to the Runnable. + config: The config to use for the Runnable. Defaults to None. + **kwargs: Additional keyword arguments to pass to the Runnable. + + Yields: + The output of the Runnable. """ yield self.invoke(input, config, **kwargs) @@ -823,6 +861,14 @@ class Runnable(Generic[Input, Output], ABC): """ Default implementation of astream, which calls ainvoke. Subclasses should override this method if they support streaming output. + + Args: + input: The input to the Runnable. + config: The config to use for the Runnable. Defaults to None. + **kwargs: Additional keyword arguments to pass to the Runnable. + + Yields: + The output of the Runnable. """ yield await self.ainvoke(input, config, **kwargs) @@ -876,19 +922,19 @@ class Runnable(Generic[Input, Output], ABC): **kwargs: Any, ) -> Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]: """ - Stream all output from a runnable, as reported to the callback system. + Stream all output from a Runnable, as reported to the callback system. This includes all inner runs of LLMs, Retrievers, Tools, etc. Output is streamed as Log objects, which include a list of - jsonpatch ops that describe how the state of the run has changed in each + Jsonpatch ops that describe how the state of the run has changed in each step, and the final state of the run. - The jsonpatch ops can be applied in order to construct state. + The Jsonpatch ops can be applied in order to construct state. Args: - input: The input to the runnable. - config: The config to use for the runnable. - diff: Whether to yield diffs between each step, or the current state. + input: The input to the Runnable. + config: The config to use for the Runnable. + diff: Whether to yield diffs between each step or the current state. with_streamed_output_list: Whether to yield the streamed_output list. include_names: Only include logs with these names. include_types: Only include logs with these types. @@ -896,6 +942,10 @@ class Runnable(Generic[Input, Output], ABC): exclude_names: Exclude logs with these names. exclude_types: Exclude logs with these types. exclude_tags: Exclude logs with these tags. + **kwargs: Additional keyword arguments to pass to the Runnable. + + Yields: + A RunLogPatch or RunLog object. """ from langchain_core.tracers.log_stream import ( LogStreamCallbackHandler, @@ -945,26 +995,26 @@ class Runnable(Generic[Input, Output], ABC): """Generate a stream of events. Use to create an iterator over StreamEvents that provide real-time information - about the progress of the runnable, including StreamEvents from intermediate + about the progress of the Runnable, including StreamEvents from intermediate results. A StreamEvent is a dictionary with the following schema: - ``event``: **str** - Event names are of the format: on_[runnable_type]_(start|stream|end). - - ``name``: **str** - The name of the runnable that generated the event. + - ``name``: **str** - The name of the Runnable that generated the event. - ``run_id``: **str** - randomly generated ID associated with the given execution of - the runnable that emitted the event. - A child runnable that gets invoked as part of the execution of a - parent runnable is assigned its own unique ID. + the Runnable that emitted the event. + A child Runnable that gets invoked as part of the execution of a + parent Runnable is assigned its own unique ID. - ``parent_ids``: **List[str]** - The IDs of the parent runnables that - generated the event. The root runnable will have an empty list. + generated the event. The root Runnable will have an empty list. The order of the parent IDs is from the root to the immediate parent. Only available for v2 version of the API. The v1 version of the API will return an empty list. - - ``tags``: **Optional[List[str]]** - The tags of the runnable that generated + - ``tags``: **Optional[List[str]]** - The tags of the Runnable that generated the event. - - ``metadata``: **Optional[Dict[str, Any]]** - The metadata of the runnable + - ``metadata``: **Optional[Dict[str, Any]]** - The metadata of the Runnable that generated the event. - ``data``: **Dict[str, Any]** @@ -1081,8 +1131,8 @@ class Runnable(Generic[Input, Output], ABC): ] Args: - input: The input to the runnable. - config: The config to use for the runnable. + input: The input to the Runnable. + config: The config to use for the Runnable. version: The version of the schema to use either `v2` or `v1`. Users should use `v2`. `v1` is for backwards compatibility and will be deprecated @@ -1094,12 +1144,15 @@ class Runnable(Generic[Input, Output], ABC): exclude_names: Exclude events from runnables with matching names. exclude_types: Exclude events from runnables with matching types. exclude_tags: Exclude events from runnables with matching tags. - kwargs: Additional keyword arguments to pass to the runnable. + kwargs: Additional keyword arguments to pass to the Runnable. These will be passed to astream_log as this implementation of astream_events is built on top of astream_log. - Returns: + Yields: An async stream of StreamEvents. + + Raises: + NotImplementedError: If the version is not `v1` or `v2`. """ # noqa: E501 from langchain_core.tracers.event_stream import ( _astream_events_implementation_v1, @@ -1153,6 +1206,14 @@ class Runnable(Generic[Input, Output], ABC): Default implementation of transform, which buffers input and then calls stream. Subclasses should override this method if they can start producing output while input is still being generated. + + Args: + input: An iterator of inputs to the Runnable. + config: The config to use for the Runnable. Defaults to None. + **kwargs: Additional keyword arguments to pass to the Runnable. + + Yields: + The output of the Runnable. """ final: Input got_first_val = False @@ -1187,6 +1248,14 @@ class Runnable(Generic[Input, Output], ABC): Default implementation of atransform, which buffers input and calls astream. Subclasses should override this method if they can start producing output while input is still being generated. + + Args: + input: An async iterator of inputs to the Runnable. + config: The config to use for the Runnable. Defaults to None. + **kwargs: Additional keyword arguments to pass to the Runnable. + + Yields: + The output of the Runnable. """ final: Input got_first_val = False @@ -1216,8 +1285,14 @@ class Runnable(Generic[Input, Output], ABC): """ Bind arguments to a Runnable, returning a new Runnable. - Useful when a runnable in a chain requires an argument that is not - in the output of the previous runnable or included in the user input. + Useful when a Runnable in a chain requires an argument that is not + in the output of the previous Runnable or included in the user input. + + Args: + kwargs: The arguments to bind to the Runnable. + + Returns: + A new Runnable with the arguments bound. Example: @@ -1257,6 +1332,13 @@ class Runnable(Generic[Input, Output], ABC): ) -> Runnable[Input, Output]: """ Bind config to a Runnable, returning a new Runnable. + + Args: + config: The config to bind to the Runnable. + kwargs: Additional keyword arguments to pass to the Runnable. + + Returns: + A new Runnable with the config bound. """ return RunnableBinding( bound=self, @@ -1283,14 +1365,22 @@ class Runnable(Generic[Input, Output], ABC): """ Bind lifecycle listeners to a Runnable, returning a new Runnable. - on_start: Called before the runnable starts running, with the Run object. - on_end: Called after the runnable finishes running, with the Run object. - on_error: Called if the runnable throws an error, with the Run object. + on_start: Called before the Runnable starts running, with the Run object. + on_end: Called after the Runnable finishes running, with the Run object. + on_error: Called if the Runnable throws an error, with the Run object. The Run object contains information about the run, including its id, type, input, output, error, start_time, end_time, and any tags or metadata added to the run. + Args: + on_start: Called before the Runnable starts running. Defaults to None. + on_end: Called after the Runnable finishes running. Defaults to None. + on_error: Called if the Runnable throws an error. Defaults to None. + + Returns: + A new Runnable with the listeners bound. + Example: .. code-block:: python @@ -1343,14 +1433,25 @@ class Runnable(Generic[Input, Output], ABC): """ Bind asynchronous lifecycle listeners to a Runnable, returning a new Runnable. - on_start: Asynchronously called before the runnable starts running. - on_end: Asynchronously called after the runnable finishes running. - on_error: Asynchronously called if the runnable throws an error. + on_start: Asynchronously called before the Runnable starts running. + on_end: Asynchronously called after the Runnable finishes running. + on_error: Asynchronously called if the Runnable throws an error. The Run object contains information about the run, including its id, type, input, output, error, start_time, end_time, and any tags or metadata added to the run. + Args: + on_start: Asynchronously called before the Runnable starts running. + Defaults to None. + on_end: Asynchronously called after the Runnable finishes running. + Defaults to None. + on_error: Asynchronously called if the Runnable throws an error. + Defaults to None. + + Returns: + A new Runnable with the listeners bound. + Example: .. code-block:: python @@ -1422,6 +1523,13 @@ class Runnable(Generic[Input, Output], ABC): ) -> Runnable[Input, Output]: """ Bind input and output types to a Runnable, returning a new Runnable. + + Args: + input_type: The input type to bind to the Runnable. Defaults to None. + output_type: The output type to bind to the Runnable. Defaults to None. + + Returns: + A new Runnable with the types bound. """ return RunnableBinding( bound=self, @@ -1437,7 +1545,18 @@ class Runnable(Generic[Input, Output], ABC): wait_exponential_jitter: bool = True, stop_after_attempt: int = 3, ) -> Runnable[Input, Output]: - """Create a new Runnable that retries the original runnable on exceptions. + """Create a new Runnable that retries the original Runnable on exceptions. + + Args: + retry_if_exception_type: A tuple of exception types to retry on. + Defaults to (Exception,). + wait_exponential_jitter: Whether to add jitter to the wait + time between retries. Defaults to True. + stop_after_attempt: The maximum number of attempts to make before + giving up. Defaults to 3. + + Returns: + A new Runnable that retries the original Runnable on exceptions. Example: @@ -1476,7 +1595,7 @@ class Runnable(Generic[Input, Output], ABC): stop_after_attempt: The maximum number of attempts to make before giving up Returns: - A new Runnable that retries the original runnable on exceptions. + A new Runnable that retries the original Runnable on exceptions. """ from langchain_core.runnables.retry import RunnableRetry @@ -1494,6 +1613,9 @@ class Runnable(Generic[Input, Output], ABC): Return a new Runnable that maps a list of inputs to a list of outputs, by calling invoke() with each input. + Returns: + A new Runnable that maps a list of inputs to a list of outputs. + Example: .. code-block:: python @@ -1515,7 +1637,23 @@ class Runnable(Generic[Input, Output], ABC): exceptions_to_handle: Tuple[Type[BaseException], ...] = (Exception,), exception_key: Optional[str] = None, ) -> RunnableWithFallbacksT[Input, Output]: - """Add fallbacks to a runnable, returning a new Runnable. + """Add fallbacks to a Runnable, returning a new Runnable. + + The new Runnable will try the original Runnable, and then each fallback + in order, upon failures. + + Args: + fallbacks: A sequence of runnables to try if the original Runnable fails. + exceptions_to_handle: A tuple of exception types to handle. + Defaults to (Exception,). + exception_key: If string is specified then handled exceptions will be passed + to fallbacks as part of the input under the specified key. If None, + exceptions will not be passed to fallbacks. If used, the base Runnable + and its fallbacks must accept a dictionary as input. Defaults to None. + + Returns: + A new Runnable that will try the original Runnable, and then each + fallback in order, upon failures. Example: @@ -1541,15 +1679,15 @@ class Runnable(Generic[Input, Output], ABC): print(''.join(runnable.stream({}))) #foo bar Args: - fallbacks: A sequence of runnables to try if the original runnable fails. + fallbacks: A sequence of runnables to try if the original Runnable fails. exceptions_to_handle: A tuple of exception types to handle. exception_key: If string is specified then handled exceptions will be passed to fallbacks as part of the input under the specified key. If None, - exceptions will not be passed to fallbacks. If used, the base runnable + exceptions will not be passed to fallbacks. If used, the base Runnable and its fallbacks must accept a dictionary as input. Returns: - A new Runnable that will try the original runnable, and then each + A new Runnable that will try the original Runnable, and then each fallback in order, upon failures. """ @@ -1825,7 +1963,7 @@ class Runnable(Generic[Input, Output], ABC): # tee the input so we can iterate over it twice input_for_tracing, input_for_transform = tee(input, 2) - # Start the input iterator to ensure the input runnable starts before this one + # Start the input iterator to ensure the input Runnable starts before this one final_input: Optional[Input] = next(input_for_tracing, None) final_input_supported = True final_output: Optional[Output] = None @@ -1925,7 +2063,7 @@ class Runnable(Generic[Input, Output], ABC): # tee the input so we can iterate over it twice input_for_tracing, input_for_transform = atee(input, 2) - # Start the input iterator to ensure the input runnable starts before this one + # Start the input iterator to ensure the input Runnable starts before this one final_input: Optional[Input] = await py_anext(input_for_tracing, None) final_input_supported = True final_output: Optional[Output] = None @@ -2020,11 +2158,19 @@ class Runnable(Generic[Input, Output], ABC): """Create a BaseTool from a Runnable. ``as_tool`` will instantiate a BaseTool with a name, description, and - ``args_schema`` from a runnable. Where possible, schemas are inferred + ``args_schema`` from a Runnable. Where possible, schemas are inferred from ``runnable.get_input_schema``. Alternatively (e.g., if the - runnable takes a dict as input and the specific dict keys are not typed), + Runnable takes a dict as input and the specific dict keys are not typed), pass ``arg_types`` to specify the required arguments. + Args: + name: The name of the tool. Defaults to None. + description: The description of the tool. Defaults to None. + arg_types: A dictionary of argument names to types. Defaults to None. + + Returns: + A BaseTool instance. + Typed dict input: .. code-block:: python @@ -2088,10 +2234,14 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]): """Runnable that can be serialized to JSON.""" name: Optional[str] = None - """The name of the runnable. Used for debugging and tracing.""" + """The name of the Runnable. Used for debugging and tracing.""" def to_json(self) -> Union[SerializedConstructor, SerializedNotImplemented]: - """Serialize the runnable to JSON.""" + """Serialize the Runnable to JSON. + + Returns: + A JSON-serializable representation of the Runnable. + """ dumped = super().to_json() try: dumped["name"] = self.get_name() @@ -2103,7 +2253,13 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]): def configurable_fields( self, **kwargs: AnyConfigurableField ) -> RunnableSerializable[Input, Output]: - """Configure particular runnable fields at runtime. + """Configure particular Runnable fields at runtime. + + Args: + **kwargs: A dictionary of ConfigurableField instances to configure. + + Returns: + A new Runnable with the fields configured. .. code-block:: python @@ -2149,7 +2305,20 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]): prefix_keys: bool = False, **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]], ) -> RunnableSerializable[Input, Output]: - """Configure alternatives for runnables that can be set at runtime. + """Configure alternatives for Runnables that can be set at runtime. + + Args: + which: The ConfigurableField instance that will be used to select the + alternative. + default_key: The default key to use if no alternative is selected. + Defaults to "default". + prefix_keys: Whether to prefix the keys with the ConfigurableField id. + Defaults to False. + **kwargs: A dictionary of keys to Runnable instances or callables that + return Runnable instances. + + Returns: + A new Runnable with the alternatives configured. .. code-block:: python @@ -2266,8 +2435,8 @@ def _seq_output_schema( class RunnableSequence(RunnableSerializable[Input, Output]): """Sequence of Runnables, where the output of each is the input of the next. - RunnableSequence is the most important composition operator in LangChain as it is - used in virtually every chain. + **RunnableSequence** is the most important composition operator in LangChain + as it is used in virtually every chain. A RunnableSequence can be instantiated directly or more commonly by using the `|` operator where either the left or right operands (or both) must be a Runnable. @@ -2346,11 +2515,11 @@ class RunnableSequence(RunnableSerializable[Input, Output]): # purposes. It allows specifying the `Input` on the first type, the `Output` of # the last type. first: Runnable[Input, Any] - """The first runnable in the sequence.""" + """The first Runnable in the sequence.""" middle: List[Runnable[Any, Any]] = Field(default_factory=list) - """The middle runnables in the sequence.""" + """The middle Runnables in the sequence.""" last: Runnable[Any, Output] - """The last runnable in the sequence.""" + """The last Runnable in the sequence.""" def __init__( self, @@ -2364,6 +2533,13 @@ class RunnableSequence(RunnableSerializable[Input, Output]): Args: steps: The steps to include in the sequence. + name: The name of the Runnable. Defaults to None. + first: The first Runnable in the sequence. Defaults to None. + middle: The middle Runnables in the sequence. Defaults to None. + last: The last Runnable in the sequence. Defaults to None. + + Raises: + ValueError: If the sequence has less than 2 steps. """ steps_flat: List[Runnable] = [] if not steps: @@ -2392,11 +2568,21 @@ class RunnableSequence(RunnableSerializable[Input, Output]): @property def steps(self) -> List[Runnable[Any, Any]]: - """All the runnables that make up the sequence in order.""" + """All the Runnables that make up the sequence in order. + + Returns: + A list of Runnables. + """ return [self.first] + self.middle + [self.last] @classmethod def is_lc_serializable(cls) -> bool: + """Check if the object is serializable. + + Returns: + True if the object is serializable, False otherwise. + Defaults to True. + """ return True class Config: @@ -2404,24 +2590,47 @@ class RunnableSequence(RunnableSerializable[Input, Output]): @property def InputType(self) -> Type[Input]: + """The type of the input to the Runnable.""" return self.first.InputType @property def OutputType(self) -> Type[Output]: + """The type of the output of the Runnable.""" return self.last.OutputType def get_input_schema( self, config: Optional[RunnableConfig] = None ) -> Type[BaseModel]: + """Get the input schema of the Runnable. + + Args: + config: The config to use. Defaults to None. + + Returns: + The input schema of the Runnable. + """ return _seq_input_schema(self.steps, config) def get_output_schema( self, config: Optional[RunnableConfig] = None ) -> Type[BaseModel]: + """Get the output schema of the Runnable. + + Args: + config: The config to use. Defaults to None. + + Returns: + The output schema of the Runnable. + """ return _seq_output_schema(self.steps, config) @property def config_specs(self) -> List[ConfigurableFieldSpec]: + """Get the config specs of the Runnable. + + Returns: + The config specs of the Runnable. + """ from langchain_core.beta.runnables.context import ( CONTEXT_CONFIG_PREFIX, _key_from_id, @@ -2467,6 +2676,17 @@ class RunnableSequence(RunnableSerializable[Input, Output]): return get_unique_config_specs(spec for spec, _ in all_specs) def get_graph(self, config: Optional[RunnableConfig] = None) -> Graph: + """Get the graph representation of the Runnable. + + Args: + config: The config to use. Defaults to None. + + Returns: + The graph representation of the Runnable. + + Raises: + ValueError: If a Runnable has no first or last node. + """ from langchain_core.runnables.graph import Graph graph = Graph() @@ -3101,11 +3321,21 @@ class RunnableParallel(RunnableSerializable[Input, Dict[str, Any]]): def get_name( self, suffix: Optional[str] = None, *, name: Optional[str] = None ) -> str: + """Get the name of the Runnable. + + Args: + suffix: The suffix to use. Defaults to None. + name: The name to use. Defaults to None. + + Returns: + The name of the Runnable. + """ name = name or self.name or f"RunnableParallel<{','.join(self.steps__.keys())}>" return super().get_name(suffix, name=name) @property def InputType(self) -> Any: + """The type of the input to the Runnable.""" for step in self.steps__.values(): if step.InputType: return step.InputType @@ -3115,6 +3345,14 @@ class RunnableParallel(RunnableSerializable[Input, Dict[str, Any]]): def get_input_schema( self, config: Optional[RunnableConfig] = None ) -> Type[BaseModel]: + """Get the input schema of the Runnable. + + Args: + config: The config to use. Defaults to None. + + Returns: + The input schema of the Runnable. + """ if all( s.get_input_schema(config).schema().get("type", "object") == "object" for s in self.steps__.values() @@ -3135,6 +3373,14 @@ class RunnableParallel(RunnableSerializable[Input, Dict[str, Any]]): def get_output_schema( self, config: Optional[RunnableConfig] = None ) -> Type[BaseModel]: + """Get the output schema of the Runnable. + + Args: + config: The config to use. Defaults to None. + + Returns: + The output schema of the Runnable. + """ # This is correct, but pydantic typings/mypy don't think so. return create_model( # type: ignore[call-overload] self.get_name("Output"), @@ -3143,11 +3389,27 @@ class RunnableParallel(RunnableSerializable[Input, Dict[str, Any]]): @property def config_specs(self) -> List[ConfigurableFieldSpec]: + """Get the config specs of the Runnable. + + Returns: + The config specs of the Runnable. + """ return get_unique_config_specs( spec for step in self.steps__.values() for spec in step.config_specs ) def get_graph(self, config: Optional[RunnableConfig] = None) -> Graph: + """Get the graph representation of the Runnable. + + Args: + config: The config to use. Defaults to None. + + Returns: + The graph representation of the Runnable. + + Raises: + ValueError: If a Runnable has no first or last node. + """ from langchain_core.runnables.graph import Graph graph = Graph() @@ -3509,6 +3771,15 @@ class RunnableGenerator(Runnable[Input, Output]): Callable[[AsyncIterator[Input]], AsyncIterator[Output]] ] = None, ) -> None: + """Initialize a RunnableGenerator. + + Args: + transform: The transform function. + atransform: The async transform function. Defaults to None. + + Raises: + TypeError: If the transform is not a generator function. + """ if atransform is not None: self._atransform = atransform func_for_name: Callable = atransform @@ -3726,6 +3997,12 @@ class RunnableLambda(Runnable[Input, Output]): Args: func: Either sync or async callable afunc: An async callable that takes an input and returns an output. + Defaults to None. + name: The name of the Runnable. Defaults to None. + + Raises: + TypeError: If the func is not a callable type. + TypeError: If both func and afunc are provided. """ if afunc is not None: self.afunc = afunc @@ -3759,7 +4036,7 @@ class RunnableLambda(Runnable[Input, Output]): @property def InputType(self) -> Any: - """The type of the input to this runnable.""" + """The type of the input to this Runnable.""" func = getattr(self, "func", None) or getattr(self, "afunc") try: params = inspect.signature(func).parameters @@ -3774,7 +4051,14 @@ class RunnableLambda(Runnable[Input, Output]): def get_input_schema( self, config: Optional[RunnableConfig] = None ) -> Type[BaseModel]: - """The pydantic schema for the input to this runnable.""" + """The pydantic schema for the input to this Runnable. + + Args: + config: The config to use. Defaults to None. + + Returns: + The input schema for this Runnable. + """ func = getattr(self, "func", None) or getattr(self, "afunc") if isinstance(func, itemgetter): @@ -3808,7 +4092,11 @@ class RunnableLambda(Runnable[Input, Output]): @property def OutputType(self) -> Any: - """The type of the output of this runnable as a type annotation.""" + """The type of the output of this Runnable as a type annotation. + + Returns: + The type of the output of this Runnable. + """ func = getattr(self, "func", None) or getattr(self, "afunc") try: sig = inspect.signature(func) @@ -3827,7 +4115,12 @@ class RunnableLambda(Runnable[Input, Output]): @property def deps(self) -> List[Runnable]: - """The dependencies of this runnable.""" + """The dependencies of this Runnable. + + Returns: + The dependencies of this Runnable. If the function has nonlocal + variables that are Runnables, they are considered dependencies. + """ if hasattr(self, "func"): objects = get_function_nonlocals(self.func) elif hasattr(self, "afunc"): @@ -3885,7 +4178,7 @@ class RunnableLambda(Runnable[Input, Output]): return False def __repr__(self) -> str: - """A string representation of this runnable.""" + """A string representation of this Runnable.""" if hasattr(self, "func") and isinstance(self.func, itemgetter): return f"RunnableLambda({str(self.func)[len('operator.'):]})" elif hasattr(self, "func"): @@ -3922,7 +4215,7 @@ class RunnableLambda(Runnable[Input, Output]): output = call_func_with_variable_args( self.func, input, config, run_manager, **kwargs ) - # If the output is a runnable, invoke it + # If the output is a Runnable, invoke it if isinstance(output, Runnable): recursion_limit = config["recursion_limit"] if recursion_limit <= 0: @@ -4021,7 +4314,7 @@ class RunnableLambda(Runnable[Input, Output]): output = await acall_func_with_variable_args( cast(Callable, afunc), input, config, run_manager, **kwargs ) - # If the output is a runnable, invoke it + # If the output is a Runnable, invoke it if isinstance(output, Runnable): recursion_limit = config["recursion_limit"] if recursion_limit <= 0: @@ -4049,7 +4342,19 @@ class RunnableLambda(Runnable[Input, Output]): config: Optional[RunnableConfig] = None, **kwargs: Optional[Any], ) -> Output: - """Invoke this runnable synchronously.""" + """Invoke this Runnable synchronously. + + Args: + input: The input to this Runnable. + config: The config to use. Defaults to None. + **kwargs: Additional keyword arguments. + + Returns: + The output of this Runnable. + + Raises: + TypeError: If the Runnable is a coroutine function. + """ if hasattr(self, "func"): return self._call_with_config( self._invoke, @@ -4069,7 +4374,16 @@ class RunnableLambda(Runnable[Input, Output]): config: Optional[RunnableConfig] = None, **kwargs: Optional[Any], ) -> Output: - """Invoke this runnable asynchronously.""" + """Invoke this Runnable asynchronously. + + Args: + input: The input to this Runnable. + config: The config to use. Defaults to None. + **kwargs: Additional keyword arguments. + + Returns: + The output of this Runnable. + """ the_func = self.afunc if hasattr(self, "afunc") else self.func return await self._acall_with_config( self._ainvoke, @@ -4119,7 +4433,7 @@ class RunnableLambda(Runnable[Input, Output]): self.func, cast(Input, final), config, run_manager, **kwargs ) - # If the output is a runnable, use its stream output + # If the output is a Runnable, use its stream output if isinstance(output, Runnable): recursion_limit = config["recursion_limit"] if recursion_limit <= 0: @@ -4241,7 +4555,7 @@ class RunnableLambda(Runnable[Input, Output]): cast(Callable, afunc), cast(Input, final), config, run_manager, **kwargs ) - # If the output is a runnable, use its astream output + # If the output is a Runnable, use its astream output if isinstance(output, Runnable): recursion_limit = config["recursion_limit"] if recursion_limit <= 0: @@ -4403,7 +4717,7 @@ class RunnableEach(RunnableEachBase[Input, Output]): It allows you to call multiple inputs with the bounded Runnable. - RunnableEach makes it easy to run multiple inputs for the runnable. + RunnableEach makes it easy to run multiple inputs for the Runnable. In the below example, we associate and run three inputs with a Runnable: @@ -4460,9 +4774,12 @@ class RunnableEach(RunnableEachBase[Input, Output]): """Bind lifecycle listeners to a Runnable, returning a new Runnable. Args: - on_start: Called before the runnable starts running, with the Run object. - on_end: Called after the runnable finishes running, with the Run object. - on_error: Called if the runnable throws an error, with the Run object. + on_start: Called before the Runnable starts running, with the Run object. + Defaults to None. + on_end: Called after the Runnable finishes running, with the Run object. + Defaults to None. + on_error: Called if the Runnable throws an error, with the Run object. + Defaults to None. Returns: A new Runnable with the listeners bound. @@ -4487,12 +4804,12 @@ class RunnableEach(RunnableEachBase[Input, Output]): """Bind async lifecycle listeners to a Runnable, returning a new Runnable. Args: - on_start: Called asynchronously before the runnable starts running, - with the Run object. - on_end: Called asynchronously after the runnable finishes running, - with the Run object. - on_error: Called asynchronously if the runnable throws an error, - with the Run object. + on_start: Called asynchronously before the Runnable starts running, + with the Run object. Defaults to None. + on_end: Called asynchronously after the Runnable finishes running, + with the Run object. Defaults to None. + on_error: Called asynchronously if the Runnable throws an error, + with the Run object. Defaults to None. Returns: A new Runnable with the listeners bound. @@ -4517,33 +4834,33 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]): """ bound: Runnable[Input, Output] - """The underlying runnable that this runnable delegates to.""" + """The underlying Runnable that this Runnable delegates to.""" kwargs: Mapping[str, Any] = Field(default_factory=dict) - """kwargs to pass to the underlying runnable when running. + """kwargs to pass to the underlying Runnable when running. - For example, when the runnable binding is invoked the underlying - runnable will be invoked with the same input but with these additional + For example, when the Runnable binding is invoked the underlying + Runnable will be invoked with the same input but with these additional kwargs. """ config: RunnableConfig = Field(default_factory=dict) - """The config to bind to the underlying runnable.""" + """The config to bind to the underlying Runnable.""" config_factories: List[Callable[[RunnableConfig], RunnableConfig]] = Field( default_factory=list ) - """The config factories to bind to the underlying runnable.""" + """The config factories to bind to the underlying Runnable.""" # Union[Type[Input], BaseModel] + things like List[str] custom_input_type: Optional[Any] = None - """Override the input type of the underlying runnable with a custom type. + """Override the input type of the underlying Runnable with a custom type. The type can be a pydantic model, or a type annotation (e.g., `List[str]`). """ # Union[Type[Output], BaseModel] + things like List[str] custom_output_type: Optional[Any] = None - """Override the output type of the underlying runnable with a custom type. + """Override the output type of the underlying Runnable with a custom type. The type can be a pydantic model, or a type annotation (e.g., `List[str]`). """ @@ -4564,19 +4881,23 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]): custom_output_type: Optional[Union[Type[Output], BaseModel]] = None, **other_kwargs: Any, ) -> None: - """Create a RunnableBinding from a runnable and kwargs. + """Create a RunnableBinding from a Runnable and kwargs. Args: - bound: The underlying runnable that this runnable delegates calls to. - kwargs: optional kwargs to pass to the underlying runnable, when running - the underlying runnable (e.g., via `invoke`, `batch`, + bound: The underlying Runnable that this Runnable delegates calls to. + kwargs: optional kwargs to pass to the underlying Runnable, when running + the underlying Runnable (e.g., via `invoke`, `batch`, `transform`, or `stream` or async variants) - config: config_factories: + Defaults to None. + config: optional config to bind to the underlying Runnable. + Defaults to None. config_factories: optional list of config factories to apply to the + config before binding to the underlying Runnable. + Defaults to None. custom_input_type: Specify to override the input type of the underlying - runnable with a custom type. + Runnable with a custom type. Defaults to None. custom_output_type: Specify to override the output type of the underlying - runnable with a custom type. + Runnable with a custom type. Defaults to None. **other_kwargs: Unpacked into the base class. """ super().__init__( # type: ignore[call-arg] @@ -4897,20 +5218,20 @@ class RunnableBinding(RunnableBindingBase[Input, Output]): `RunnableWithFallbacks`) that add additional functionality. These methods include: - - `bind`: Bind kwargs to pass to the underlying runnable when running it. - - `with_config`: Bind config to pass to the underlying runnable when running it. - - `with_listeners`: Bind lifecycle listeners to the underlying runnable. - - `with_types`: Override the input and output types of the underlying runnable. - - `with_retry`: Bind a retry policy to the underlying runnable. - - `with_fallbacks`: Bind a fallback policy to the underlying runnable. + - `bind`: Bind kwargs to pass to the underlying Runnable when running it. + - `with_config`: Bind config to pass to the underlying Runnable when running it. + - `with_listeners`: Bind lifecycle listeners to the underlying Runnable. + - `with_types`: Override the input and output types of the underlying Runnable. + - `with_retry`: Bind a retry policy to the underlying Runnable. + - `with_fallbacks`: Bind a fallback policy to the underlying Runnable. Example: - `bind`: Bind kwargs to pass to the underlying runnable when running it. + `bind`: Bind kwargs to pass to the underlying Runnable when running it. .. code-block:: python - # Create a runnable binding that invokes the ChatModel with the + # Create a Runnable binding that invokes the ChatModel with the # additional kwarg `stop=['-']` when running it. from langchain_community.chat_models import ChatOpenAI model = ChatOpenAI() @@ -4985,12 +5306,15 @@ class RunnableBinding(RunnableBindingBase[Input, Output]): """Bind lifecycle listeners to a Runnable, returning a new Runnable. Args: - on_start: Called before the runnable starts running, with the Run object. - on_end: Called after the runnable finishes running, with the Run object. - on_error: Called if the runnable throws an error, with the Run object. + on_start: Called before the Runnable starts running, with the Run object. + Defaults to None. + on_end: Called after the Runnable finishes running, with the Run object. + Defaults to None. + on_error: Called if the Runnable throws an error, with the Run object. + Defaults to None. Returns: - The Run object contains information about the run, including its id, + The Runnable object contains information about the run, including its id, type, input, output, error, start_time, end_time, and any tags or metadata added to the run. """ @@ -5091,13 +5415,16 @@ RunnableLike = Union[ def coerce_to_runnable(thing: RunnableLike) -> Runnable[Input, Output]: - """Coerce a runnable-like object into a Runnable. + """Coerce a Runnable-like object into a Runnable. Args: - thing: A runnable-like object. + thing: A Runnable-like object. Returns: A Runnable. + + Raises: + TypeError: If the object is not Runnable-like. """ if isinstance(thing, Runnable): return thing @@ -5147,7 +5474,7 @@ def chain( ], ) -> Runnable[Input, Output]: """Decorate a function to make it a Runnable. - Sets the name of the runnable to the name of the function. + Sets the name of the Runnable to the name of the function. Any runnables called by the function will be traced as dependencies. Args: diff --git a/libs/core/langchain_core/runnables/branch.py b/libs/core/langchain_core/runnables/branch.py index ddafdd2a6e7..b18f065926b 100644 --- a/libs/core/langchain_core/runnables/branch.py +++ b/libs/core/langchain_core/runnables/branch.py @@ -48,6 +48,10 @@ class RunnableBranch(RunnableSerializable[Input, Output]): If no condition evaluates to True, the default branch is run on the input. + Parameters: + branches: A list of (condition, Runnable) pairs. + default: A Runnable to run if no condition is met. + Examples: .. code-block:: python @@ -82,7 +86,18 @@ class RunnableBranch(RunnableSerializable[Input, Output]): RunnableLike, # To accommodate the default branch ], ) -> None: - """A Runnable that runs one of two branches based on a condition.""" + """A Runnable that runs one of two branches based on a condition. + + Args: + *branches: A list of (condition, Runnable) pairs. + Defaults a Runnable to run if no condition is met. + + Raises: + ValueError: If the number of branches is less than 2. + TypeError: If the default branch is not Runnable, Callable or Mapping. + TypeError: If a branch is not a tuple or list. + ValueError: If a branch is not of length 2. + """ if len(branches) < 2: raise ValueError("RunnableBranch requires at least two branches") @@ -93,7 +108,7 @@ class RunnableBranch(RunnableSerializable[Input, Output]): (Runnable, Callable, Mapping), # type: ignore[arg-type] ): raise TypeError( - "RunnableBranch default must be runnable, callable or mapping." + "RunnableBranch default must be Runnable, callable or mapping." ) default_ = cast( @@ -176,7 +191,19 @@ class RunnableBranch(RunnableSerializable[Input, Output]): def invoke( self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any ) -> Output: - """First evaluates the condition, then delegate to true or false branch.""" + """First evaluates the condition, then delegate to true or false branch. + + Args: + input: The input to the Runnable. + config: The configuration for the Runnable. Defaults to None. + **kwargs: Additional keyword arguments to pass to the Runnable. + + Returns: + The output of the branch that was run. + + Raises: + + """ config = ensure_config(config) callback_manager = get_callback_manager_for_config(config) run_manager = callback_manager.on_chain_start( @@ -277,7 +304,19 @@ class RunnableBranch(RunnableSerializable[Input, Output]): **kwargs: Optional[Any], ) -> Iterator[Output]: """First evaluates the condition, - then delegate to true or false branch.""" + then delegate to true or false branch. + + Args: + input: The input to the Runnable. + config: The configuration for the Runnable. Defaults to None. + **kwargs: Additional keyword arguments to pass to the Runnable. + + Yields: + The output of the branch that was run. + + Raises: + BaseException: If an error occurs during the execution of the Runnable. + """ config = ensure_config(config) callback_manager = get_callback_manager_for_config(config) run_manager = callback_manager.on_chain_start( @@ -352,7 +391,19 @@ class RunnableBranch(RunnableSerializable[Input, Output]): **kwargs: Optional[Any], ) -> AsyncIterator[Output]: """First evaluates the condition, - then delegate to true or false branch.""" + then delegate to true or false branch. + + Args: + input: The input to the Runnable. + config: The configuration for the Runnable. Defaults to None. + **kwargs: Additional keyword arguments to pass to the Runnable. + + Yields: + The output of the branch that was run. + + Raises: + BaseException: If an error occurs during the execution of the Runnable. + """ config = ensure_config(config) callback_manager = get_async_callback_manager_for_config(config) run_manager = await callback_manager.on_chain_start( diff --git a/libs/core/langchain_core/runnables/config.py b/libs/core/langchain_core/runnables/config.py index 4300da87725..a0e03703762 100644 --- a/libs/core/langchain_core/runnables/config.py +++ b/libs/core/langchain_core/runnables/config.py @@ -111,7 +111,7 @@ var_child_runnable_config = ContextVar( def _set_config_context(config: RunnableConfig) -> None: - """Set the child runnable config + tracing context + """Set the child Runnable config + tracing context Args: config (RunnableConfig): The config to set. @@ -216,7 +216,6 @@ def patch_config( Args: config (Optional[RunnableConfig]): The config to patch. - copy_locals (bool, optional): Whether to copy locals. Defaults to False. callbacks (Optional[BaseCallbackManager], optional): The callbacks to set. Defaults to None. recursion_limit (Optional[int], optional): The recursion limit to set. @@ -362,9 +361,9 @@ def call_func_with_variable_args( Callable[[Input, CallbackManagerForChainRun, RunnableConfig], Output]]): The function to call. input (Input): The input to the function. - run_manager (CallbackManagerForChainRun): The run manager to - pass to the function. config (RunnableConfig): The config to pass to the function. + run_manager (CallbackManagerForChainRun): The run manager to + pass to the function. Defaults to None. **kwargs (Any): The keyword arguments to pass to the function. Returns: @@ -395,7 +394,7 @@ def acall_func_with_variable_args( run_manager: Optional[AsyncCallbackManagerForChainRun] = None, **kwargs: Any, ) -> Awaitable[Output]: - """Call function that may optionally accept a run_manager and/or config. + """Async call function that may optionally accept a run_manager and/or config. Args: func (Union[Callable[[Input], Awaitable[Output]], Callable[[Input, @@ -403,9 +402,9 @@ def acall_func_with_variable_args( AsyncCallbackManagerForChainRun, RunnableConfig], Awaitable[Output]]]): The function to call. input (Input): The input to the function. - run_manager (AsyncCallbackManagerForChainRun): The run manager - to pass to the function. config (RunnableConfig): The config to pass to the function. + run_manager (AsyncCallbackManagerForChainRun): The run manager + to pass to the function. Defaults to None. **kwargs (Any): The keyword arguments to pass to the function. Returns: @@ -493,6 +492,18 @@ class ContextThreadPoolExecutor(ThreadPoolExecutor): timeout: float | None = None, chunksize: int = 1, ) -> Iterator[T]: + """Map a function to multiple iterables. + + Args: + fn (Callable[..., T]): The function to map. + *iterables (Iterable[Any]): The iterables to map over. + timeout (float | None, optional): The timeout for the map. + Defaults to None. + chunksize (int, optional): The chunksize for the map. Defaults to 1. + + Returns: + Iterator[T]: The iterator for the mapped function. + """ contexts = [copy_context() for _ in range(len(iterables[0]))] # type: ignore[arg-type] def _wrapped_fn(*args: Any) -> T: @@ -534,13 +545,16 @@ async def run_in_executor( """Run a function in an executor. Args: - executor (Executor): The executor. + executor_or_config: The executor or config to run in. func (Callable[P, Output]): The function. *args (Any): The positional arguments to the function. **kwargs (Any): The keyword arguments to the function. Returns: Output: The output of the function. + + Raises: + RuntimeError: If the function raises a StopIteration. """ def wrapper() -> T: diff --git a/libs/core/langchain_core/runnables/configurable.py b/libs/core/langchain_core/runnables/configurable.py index 1c1c9cf12ec..cf7e9ce1dc7 100644 --- a/libs/core/langchain_core/runnables/configurable.py +++ b/libs/core/langchain_core/runnables/configurable.py @@ -44,7 +44,15 @@ from langchain_core.runnables.utils import ( class DynamicRunnable(RunnableSerializable[Input, Output]): - """Serializable Runnable that can be dynamically configured.""" + """Serializable Runnable that can be dynamically configured. + + A DynamicRunnable should be initiated using the `configurable_fields` or + `configurable_alternatives` method of a Runnable. + + Parameters: + default: The default Runnable to use. + config: The configuration to use. + """ default: RunnableSerializable[Input, Output] @@ -99,6 +107,15 @@ class DynamicRunnable(RunnableSerializable[Input, Output]): def prepare( self, config: Optional[RunnableConfig] = None ) -> Tuple[Runnable[Input, Output], RunnableConfig]: + """Prepare the Runnable for invocation. + + Args: + config: The configuration to use. Defaults to None. + + Returns: + Tuple[Runnable[Input, Output], RunnableConfig]: The prepared Runnable and + configuration. + """ runnable: Runnable[Input, Output] = self while isinstance(runnable, DynamicRunnable): runnable, config = runnable._prepare(merge_configs(runnable.config, config)) @@ -284,6 +301,9 @@ class RunnableConfigurableFields(DynamicRunnable[Input, Output]): A RunnableConfigurableFields should be initiated using the `configurable_fields` method of a Runnable. + Parameters: + fields: The configurable fields to use. + Here is an example of using a RunnableConfigurableFields with LLMs: .. code-block:: python @@ -348,6 +368,11 @@ class RunnableConfigurableFields(DynamicRunnable[Input, Output]): @property def config_specs(self) -> List[ConfigurableFieldSpec]: + """Get the configuration specs for the RunnableConfigurableFields. + + Returns: + List[ConfigurableFieldSpec]: The configuration specs. + """ return get_unique_config_specs( [ ( @@ -374,6 +399,8 @@ class RunnableConfigurableFields(DynamicRunnable[Input, Output]): def configurable_fields( self, **kwargs: AnyConfigurableField ) -> RunnableSerializable[Input, Output]: + """Get a new RunnableConfigurableFields with the specified + configurable fields.""" return self.default.configurable_fields(**{**self.fields, **kwargs}) def _prepare( @@ -493,11 +520,13 @@ class RunnableConfigurableAlternatives(DynamicRunnable[Input, Output]): """ # noqa: E501 which: ConfigurableField + """The ConfigurableField to use to choose between alternatives.""" alternatives: Dict[ str, Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]], ] + """The alternatives to choose from.""" default_key: str = "default" """The enum value to use for the default option. Defaults to "default".""" @@ -619,7 +648,7 @@ def prefix_config_spec( prefix: The prefix to add. Returns: - + ConfigurableFieldSpec: The prefixed ConfigurableFieldSpec. """ return ( ConfigurableFieldSpec( @@ -641,6 +670,13 @@ def make_options_spec( ) -> ConfigurableFieldSpec: """Make a ConfigurableFieldSpec for a ConfigurableFieldSingleOption or ConfigurableFieldMultiOption. + + Args: + spec: The ConfigurableFieldSingleOption or ConfigurableFieldMultiOption. + description: The description to use if the spec does not have one. + + Returns: + The ConfigurableFieldSpec. """ with _enums_for_spec_lock: if enum := _enums_for_spec.get(spec): diff --git a/libs/core/langchain_core/runnables/fallbacks.py b/libs/core/langchain_core/runnables/fallbacks.py index 73e21593c26..5187e299c1f 100644 --- a/libs/core/langchain_core/runnables/fallbacks.py +++ b/libs/core/langchain_core/runnables/fallbacks.py @@ -91,7 +91,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]): """ runnable: Runnable[Input, Output] - """The runnable to run first.""" + """The Runnable to run first.""" fallbacks: Sequence[Runnable[Input, Output]] """A sequence of fallbacks to try.""" exceptions_to_handle: Tuple[Type[BaseException], ...] = (Exception,) @@ -102,7 +102,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]): exception_key: Optional[str] = None """If string is specified then handled exceptions will be passed to fallbacks as part of the input under the specified key. If None, exceptions - will not be passed to fallbacks. If used, the base runnable and its fallbacks + will not be passed to fallbacks. If used, the base Runnable and its fallbacks must accept a dictionary as input.""" class Config: @@ -554,7 +554,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]): await run_manager.on_chain_end(output) def __getattr__(self, name: str) -> Any: - """Get an attribute from the wrapped runnable and its fallbacks. + """Get an attribute from the wrapped Runnable and its fallbacks. Returns: If the attribute is anything other than a method that outputs a Runnable, diff --git a/libs/core/langchain_core/runnables/graph.py b/libs/core/langchain_core/runnables/graph.py index 48a68d58fd5..1c3638f48b1 100644 --- a/libs/core/langchain_core/runnables/graph.py +++ b/libs/core/langchain_core/runnables/graph.py @@ -57,7 +57,14 @@ def is_uuid(value: str) -> bool: class Edge(NamedTuple): - """Edge in a graph.""" + """Edge in a graph. + + Parameters: + source: The source node id. + target: The target node id. + data: Optional data associated with the edge. Defaults to None. + conditional: Whether the edge is conditional. Defaults to False. + """ source: str target: str @@ -67,6 +74,15 @@ class Edge(NamedTuple): def copy( self, *, source: Optional[str] = None, target: Optional[str] = None ) -> Edge: + """Return a copy of the edge with optional new source and target nodes. + + Args: + source: The new source node id. Defaults to None. + target: The new target node id. Defaults to None. + + Returns: + A copy of the edge with the new source and target nodes. + """ return Edge( source=source or self.source, target=target or self.target, @@ -76,7 +92,14 @@ class Edge(NamedTuple): class Node(NamedTuple): - """Node in a graph.""" + """Node in a graph. + + Parameters: + id: The unique identifier of the node. + name: The name of the node. + data: The data of the node. + metadata: Optional metadata for the node. Defaults to None. + """ id: str name: str @@ -84,6 +107,15 @@ class Node(NamedTuple): metadata: Optional[Dict[str, Any]] def copy(self, *, id: Optional[str] = None, name: Optional[str] = None) -> Node: + """Return a copy of the node with optional new id and name. + + Args: + id: The new node id. Defaults to None. + name: The new node name. Defaults to None. + + Returns: + A copy of the node with the new id and name. + """ return Node( id=id or self.id, name=name or self.name, @@ -93,7 +125,13 @@ class Node(NamedTuple): class Branch(NamedTuple): - """Branch in a graph.""" + """Branch in a graph. + + Parameters: + condition: A callable that returns a string representation of the condition. + ends: Optional dictionary of end node ids for the branches. Defaults + to None. + """ condition: Callable[..., str] ends: Optional[dict[str, str]] @@ -118,7 +156,13 @@ class CurveStyle(Enum): @dataclass class NodeStyles: - """Schema for Hexadecimal color codes for different node types""" + """Schema for Hexadecimal color codes for different node types. + + Parameters: + default: The default color code. Defaults to "fill:#f2f0ff,line-height:1.2". + first: The color code for the first node. Defaults to "fill-opacity:0". + last: The color code for the last node. Defaults to "fill:#bfb6fc". + """ default: str = "fill:#f2f0ff,line-height:1.2" first: str = "fill-opacity:0" @@ -161,7 +205,7 @@ def node_data_json( Args: node: The node to convert. with_schemas: Whether to include the schema of the data if - it is a Pydantic model. + it is a Pydantic model. Defaults to False. Returns: A dictionary with the type of the data and the data itself. @@ -209,13 +253,26 @@ def node_data_json( @dataclass class Graph: - """Graph of nodes and edges.""" + """Graph of nodes and edges. + + Parameters: + nodes: Dictionary of nodes in the graph. Defaults to an empty dictionary. + edges: List of edges in the graph. Defaults to an empty list. + """ nodes: Dict[str, Node] = field(default_factory=dict) edges: List[Edge] = field(default_factory=list) def to_json(self, *, with_schemas: bool = False) -> Dict[str, List[Dict[str, Any]]]: - """Convert the graph to a JSON-serializable format.""" + """Convert the graph to a JSON-serializable format. + + Args: + with_schemas: Whether to include the schemas of the nodes if they are + Pydantic models. Defaults to False. + + Returns: + A dictionary with the nodes and edges of the graph. + """ stable_node_ids = { node.id: i if is_uuid(node.id) else node.id for i, node in enumerate(self.nodes.values()) @@ -247,6 +304,8 @@ class Graph: return bool(self.nodes) def next_id(self) -> str: + """Return a new unique node + identifier that can be used to add a node to the graph.""" return uuid4().hex def add_node( @@ -256,7 +315,19 @@ class Graph: *, metadata: Optional[Dict[str, Any]] = None, ) -> Node: - """Add a node to the graph and return it.""" + """Add a node to the graph and return it. + + Args: + data: The data of the node. + id: The id of the node. Defaults to None. + metadata: Optional metadata for the node. Defaults to None. + + Returns: + The node that was added to the graph. + + Raises: + ValueError: If a node with the same id already exists. + """ if id is not None and id in self.nodes: raise ValueError(f"Node with id {id} already exists") id = id or self.next_id() @@ -265,7 +336,11 @@ class Graph: return node def remove_node(self, node: Node) -> None: - """Remove a node from the graph and all edges connected to it.""" + """Remove a node from the graph and all edges connected to it. + + Args: + node: The node to remove. + """ self.nodes.pop(node.id) self.edges = [ edge @@ -280,7 +355,20 @@ class Graph: data: Optional[Stringifiable] = None, conditional: bool = False, ) -> Edge: - """Add an edge to the graph and return it.""" + """Add an edge to the graph and return it. + + Args: + source: The source node of the edge. + target: The target node of the edge. + data: Optional data associated with the edge. Defaults to None. + conditional: Whether the edge is conditional. Defaults to False. + + Returns: + The edge that was added to the graph. + + Raises: + ValueError: If the source or target node is not in the graph. + """ if source.id not in self.nodes: raise ValueError(f"Source node {source.id} not in graph") if target.id not in self.nodes: @@ -295,7 +383,15 @@ class Graph: self, graph: Graph, *, prefix: str = "" ) -> Tuple[Optional[Node], Optional[Node]]: """Add all nodes and edges from another graph. - Note this doesn't check for duplicates, nor does it connect the graphs.""" + Note this doesn't check for duplicates, nor does it connect the graphs. + + Args: + graph: The graph to add. + prefix: The prefix to add to the node ids. Defaults to "". + + Returns: + A tuple of the first and last nodes of the subgraph. + """ if all(is_uuid(node.id) for node in graph.nodes.values()): prefix = "" @@ -350,7 +446,7 @@ class Graph: def first_node(self) -> Optional[Node]: """Find the single node that is not a target of any edge. If there is no such node, or there are multiple, return None. - When drawing the graph this node would be the origin.""" + When drawing the graph, this node would be the origin.""" targets = {edge.target for edge in self.edges} found: List[Node] = [] for node in self.nodes.values(): @@ -361,7 +457,7 @@ class Graph: def last_node(self) -> Optional[Node]: """Find the single node that is not a source of any edge. If there is no such node, or there are multiple, return None. - When drawing the graph this node would be the destination. + When drawing the graph, this node would be the destination. """ sources = {edge.source for edge in self.edges} found: List[Node] = [] @@ -372,7 +468,7 @@ class Graph: def trim_first_node(self) -> None: """Remove the first node if it exists and has a single outgoing edge, - ie. if removing it would not leave the graph without a "first" node.""" + i.e., if removing it would not leave the graph without a "first" node.""" first_node = self.first_node() if first_node: if ( @@ -384,7 +480,7 @@ class Graph: def trim_last_node(self) -> None: """Remove the last node if it exists and has a single incoming edge, - ie. if removing it would not leave the graph without a "last" node.""" + i.e., if removing it would not leave the graph without a "last" node.""" last_node = self.last_node() if last_node: if ( @@ -395,6 +491,7 @@ class Graph: self.remove_node(last_node) def draw_ascii(self) -> str: + """Draw the graph as an ASCII art string.""" from langchain_core.runnables.graph_ascii import draw_ascii return draw_ascii( @@ -403,6 +500,7 @@ class Graph: ) def print_ascii(self) -> None: + """Print the graph as an ASCII art string.""" print(self.draw_ascii()) # noqa: T201 @overload @@ -427,6 +525,17 @@ class Graph: fontname: Optional[str] = None, labels: Optional[LabelsDict] = None, ) -> Union[bytes, None]: + """Draw the graph as a PNG image. + + Args: + output_file_path: The path to save the image to. If None, the image + is not saved. Defaults to None. + fontname: The name of the font to use. Defaults to None. + labels: Optional labels for nodes and edges in the graph. Defaults to None. + + Returns: + The PNG image as bytes if output_file_path is None, None otherwise. + """ from langchain_core.runnables.graph_png import PngDrawer default_node_labels = {node.id: node.name for node in self.nodes.values()} @@ -450,6 +559,18 @@ class Graph: node_colors: NodeStyles = NodeStyles(), wrap_label_n_words: int = 9, ) -> str: + """Draw the graph as a Mermaid syntax string. + + Args: + with_styles: Whether to include styles in the syntax. Defaults to True. + curve_style: The style of the edges. Defaults to CurveStyle.LINEAR. + node_colors: The colors of the nodes. Defaults to NodeStyles(). + wrap_label_n_words: The number of words to wrap the node labels at. + Defaults to 9. + + Returns: + The Mermaid syntax string. + """ from langchain_core.runnables.graph_mermaid import draw_mermaid graph = self.reid() @@ -478,6 +599,23 @@ class Graph: background_color: str = "white", padding: int = 10, ) -> bytes: + """Draw the graph as a PNG image using Mermaid. + + Args: + curve_style: The style of the edges. Defaults to CurveStyle.LINEAR. + node_colors: The colors of the nodes. Defaults to NodeStyles(). + wrap_label_n_words: The number of words to wrap the node labels at. + Defaults to 9. + output_file_path: The path to save the image to. If None, the image + is not saved. Defaults to None. + draw_method: The method to use to draw the graph. + Defaults to MermaidDrawMethod.API. + background_color: The color of the background. Defaults to "white". + padding: The padding around the graph. Defaults to 10. + + Returns: + The PNG image as bytes. + """ from langchain_core.runnables.graph_mermaid import draw_mermaid_png mermaid_syntax = self.draw_mermaid( diff --git a/libs/core/langchain_core/runnables/graph_ascii.py b/libs/core/langchain_core/runnables/graph_ascii.py index 47992e2faa6..46677213f81 100644 --- a/libs/core/langchain_core/runnables/graph_ascii.py +++ b/libs/core/langchain_core/runnables/graph_ascii.py @@ -17,6 +17,7 @@ class VertexViewer: """ HEIGHT = 3 # top and bottom box edges + text + """Height of the box.""" def __init__(self, name: str) -> None: self._h = self.HEIGHT # top and bottom box edges + text diff --git a/libs/core/langchain_core/runnables/graph_mermaid.py b/libs/core/langchain_core/runnables/graph_mermaid.py index 18988d68a2b..cef9092cebb 100644 --- a/libs/core/langchain_core/runnables/graph_mermaid.py +++ b/libs/core/langchain_core/runnables/graph_mermaid.py @@ -23,18 +23,25 @@ def draw_mermaid( node_styles: NodeStyles = NodeStyles(), wrap_label_n_words: int = 9, ) -> str: - """Draws a Mermaid graph using the provided graph data + """Draws a Mermaid graph using the provided graph data. Args: - nodes (dict[str, str]): List of node ids - edges (List[Edge]): List of edges, object with source, - target and data. + nodes (dict[str, str]): List of node ids. + edges (List[Edge]): List of edges, object with a source, + target and data. + first_node (str, optional): Id of the first node. Defaults to None. + last_node (str, optional): Id of the last node. Defaults to None. + with_styles (bool, optional): Whether to include styles in the graph. + Defaults to True. curve_style (CurveStyle, optional): Curve style for the edges. - node_colors (NodeColors, optional): Node colors for different types. + Defaults to CurveStyle.LINEAR. + node_styles (NodeStyles, optional): Node colors for different types. + Defaults to NodeStyles(). wrap_label_n_words (int, optional): Words to wrap the edge labels. + Defaults to 9. Returns: - str: Mermaid graph syntax + str: Mermaid graph syntax. """ # Initialize Mermaid graph configuration mermaid_graph = ( @@ -139,7 +146,24 @@ def draw_mermaid_png( background_color: Optional[str] = "white", padding: int = 10, ) -> bytes: - """Draws a Mermaid graph as PNG using provided syntax.""" + """Draws a Mermaid graph as PNG using provided syntax. + + Args: + mermaid_syntax (str): Mermaid graph syntax. + output_file_path (str, optional): Path to save the PNG image. + Defaults to None. + draw_method (MermaidDrawMethod, optional): Method to draw the graph. + Defaults to MermaidDrawMethod.API. + background_color (str, optional): Background color of the image. + Defaults to "white". + padding (int, optional): Padding around the image. Defaults to 10. + + Returns: + bytes: PNG image bytes. + + Raises: + ValueError: If an invalid draw method is provided. + """ if draw_method == MermaidDrawMethod.PYPPETEER: import asyncio diff --git a/libs/core/langchain_core/runnables/graph_png.py b/libs/core/langchain_core/runnables/graph_png.py index 0fbeec7e354..ae3edaa7da0 100644 --- a/libs/core/langchain_core/runnables/graph_png.py +++ b/libs/core/langchain_core/runnables/graph_png.py @@ -6,7 +6,7 @@ from langchain_core.runnables.graph import Graph, LabelsDict class PngDrawer: """Helper class to draw a state graph into a PNG file. - It requires graphviz and pygraphviz to be installed. + It requires `graphviz` and `pygraphviz` to be installed. :param fontname: The font to use for the labels :param labels: A dictionary of label overrides. The dictionary should have the following format: @@ -33,7 +33,7 @@ class PngDrawer: """Initializes the PNG drawer. Args: - fontname: The font to use for the labels + fontname: The font to use for the labels. Defaults to "arial". labels: A dictionary of label overrides. The dictionary should have the following format: { @@ -48,6 +48,7 @@ class PngDrawer: } } The keys are the original labels, and the values are the new labels. + Defaults to None. """ self.fontname = fontname or "arial" self.labels = labels or LabelsDict(nodes={}, edges={}) @@ -56,7 +57,7 @@ class PngDrawer: """Returns the label to use for a node. Args: - label: The original label + label: The original label. Returns: The new label. @@ -68,7 +69,7 @@ class PngDrawer: """Returns the label to use for an edge. Args: - label: The original label + label: The original label. Returns: The new label. @@ -80,8 +81,8 @@ class PngDrawer: """Adds a node to the graph. Args: - viz: The graphviz object - node: The node to add + viz: The graphviz object. + node: The node to add. Returns: None @@ -106,9 +107,9 @@ class PngDrawer: """Adds an edge to the graph. Args: - viz: The graphviz object - source: The source node - target: The target node + viz: The graphviz object. + source: The source node. + target: The target node. label: The label for the edge. Defaults to None. conditional: Whether the edge is conditional. Defaults to False. @@ -127,7 +128,7 @@ class PngDrawer: def draw(self, graph: Graph, output_path: Optional[str] = None) -> Optional[bytes]: """Draw the given state graph into a PNG file. - Requires graphviz and pygraphviz to be installed. + Requires `graphviz` and `pygraphviz` to be installed. :param graph: The graph to draw :param output_path: The path to save the PNG. If None, PNG bytes are returned. """ @@ -156,14 +157,32 @@ class PngDrawer: viz.close() def add_nodes(self, viz: Any, graph: Graph) -> None: + """Add nodes to the graph. + + Args: + viz: The graphviz object. + graph: The graph to draw. + """ for node in graph.nodes: self.add_node(viz, node) def add_edges(self, viz: Any, graph: Graph) -> None: + """Add edges to the graph. + + Args: + viz: The graphviz object. + graph: The graph to draw. + """ for start, end, data, cond in graph.edges: self.add_edge(viz, start, end, str(data), cond) def update_styles(self, viz: Any, graph: Graph) -> None: + """Update the styles of the entrypoint and END nodes. + + Args: + viz: The graphviz object. + graph: The graph to draw. + """ if first := graph.first_node(): viz.get_node(first.id).attr.update(fillcolor="lightblue") if last := graph.last_node(): diff --git a/libs/core/langchain_core/runnables/history.py b/libs/core/langchain_core/runnables/history.py index b215d1532d0..96e901a5dae 100644 --- a/libs/core/langchain_core/runnables/history.py +++ b/libs/core/langchain_core/runnables/history.py @@ -45,13 +45,13 @@ class RunnableWithMessageHistory(RunnableBindingBase): history for it; it is responsible for reading and updating the chat message history. - The formats supports for the inputs and outputs of the wrapped Runnable + The formats supported for the inputs and outputs of the wrapped Runnable are described below. RunnableWithMessageHistory must always be called with a config that contains the appropriate parameters for the chat message history factory. - By default the Runnable is expected to take a single configuration parameter + By default, the Runnable is expected to take a single configuration parameter called `session_id` which is a string. This parameter is used to create a new or look up an existing chat message history that matches the given session_id. @@ -70,6 +70,19 @@ class RunnableWithMessageHistory(RunnableBindingBase): For production use cases, you will want to use a persistent implementation of chat message history, such as ``RedisChatMessageHistory``. + Parameters: + get_session_history: Function that returns a new BaseChatMessageHistory. + This function should either take a single positional argument + `session_id` of type string and return a corresponding + chat message history instance. + input_messages_key: Must be specified if the base runnable accepts a dict + as input. The key in the input dict that contains the messages. + output_messages_key: Must be specified if the base Runnable returns a dict + as output. The key in the output dict that contains the messages. + history_messages_key: Must be specified if the base runnable accepts a dict + as input and expects a separate key for historical messages. + history_factory_config: Configure fields that should be passed to the + chat history factory. See ``ConfigurableFieldSpec`` for more details. Example: Chat message history with an in-memory implementation for testing. @@ -287,9 +300,9 @@ class RunnableWithMessageHistory(RunnableBindingBase): ... input_messages_key: Must be specified if the base runnable accepts a dict - as input. + as input. Default is None. output_messages_key: Must be specified if the base runnable returns a dict - as output. + as output. Default is None. history_messages_key: Must be specified if the base runnable accepts a dict as input and expects a separate key for historical messages. history_factory_config: Configure fields that should be passed to the @@ -347,6 +360,7 @@ class RunnableWithMessageHistory(RunnableBindingBase): @property def config_specs(self) -> List[ConfigurableFieldSpec]: + """Get the configuration specs for the RunnableWithMessageHistory.""" return get_unique_config_specs( super().config_specs + list(self.history_factory_config) ) diff --git a/libs/core/langchain_core/runnables/passthrough.py b/libs/core/langchain_core/runnables/passthrough.py index f761e12ed22..fe89b1f9333 100644 --- a/libs/core/langchain_core/runnables/passthrough.py +++ b/libs/core/langchain_core/runnables/passthrough.py @@ -53,19 +53,33 @@ if TYPE_CHECKING: def identity(x: Other) -> Other: - """Identity function""" + """Identity function. + + Args: + x (Other): input. + + Returns: + Other: output. + """ return x async def aidentity(x: Other) -> Other: - """Async identity function""" + """Async identity function. + + Args: + x (Other): input. + + Returns: + Other: output. + """ return x class RunnablePassthrough(RunnableSerializable[Other, Other]): """Runnable to passthrough inputs unchanged or with additional keys. - This runnable behaves almost like the identity function, except that it + This Runnable behaves almost like the identity function, except that it can be configured to add additional keys to the output, if the input is a dict. @@ -73,6 +87,13 @@ class RunnablePassthrough(RunnableSerializable[Other, Other]): chains. The chains rely on simple lambdas to make the examples easy to execute and experiment with. + Parameters: + func (Callable[[Other], None], optional): Function to be called with the input. + afunc (Callable[[Other], Awaitable[None]], optional): Async function to + be called with the input. + input_type (Optional[Type[Other]], optional): Type of the input. + **kwargs (Any): Additional keyword arguments. + Examples: .. code-block:: python @@ -199,10 +220,11 @@ class RunnablePassthrough(RunnableSerializable[Other, Other]): """Merge the Dict input with the output produced by the mapping argument. Args: - mapping: A mapping from keys to runnables or callables. + **kwargs: Runnable, Callable or a Mapping from keys to Runnables + or Callables. Returns: - A runnable that merges the Dict input with the output produced by the + A Runnable that merges the Dict input with the output produced by the mapping argument. """ return RunnableAssign(RunnableParallel(kwargs)) @@ -336,6 +358,10 @@ class RunnableAssign(RunnableSerializable[Dict[str, Any], Dict[str, Any]]): these with the original data, introducing new key-value pairs based on the mapper's logic. + Parameters: + mapper (RunnableParallel[Dict[str, Any]]): A `RunnableParallel` instance + that will be used to transform the input dictionary. + Examples: .. code-block:: python @@ -627,11 +653,15 @@ class RunnableAssign(RunnableSerializable[Dict[str, Any], Dict[str, Any]]): class RunnablePick(RunnableSerializable[Dict[str, Any], Dict[str, Any]]): """Runnable that picks keys from Dict[str, Any] inputs. - RunnablePick class represents a runnable that selectively picks keys from a + RunnablePick class represents a Runnable that selectively picks keys from a dictionary input. It allows you to specify one or more keys to extract from the input dictionary. It returns a new dictionary containing only the selected keys. + Parameters: + keys (Union[str, List[str]]): A single key or a list of keys to pick from + the input dictionary. + Example : .. code-block:: python diff --git a/libs/core/langchain_core/runnables/retry.py b/libs/core/langchain_core/runnables/retry.py index bb1d08eaf1b..7bcc21c48a5 100644 --- a/libs/core/langchain_core/runnables/retry.py +++ b/libs/core/langchain_core/runnables/retry.py @@ -112,7 +112,7 @@ class RunnableRetry(RunnableBindingBase[Input, Output]): """Whether to add jitter to the exponential backoff.""" max_attempt_number: int = 3 - """The maximum number of attempts to retry the runnable.""" + """The maximum number of attempts to retry the Runnable.""" @classmethod def get_lc_namespace(cls) -> List[str]: diff --git a/libs/core/langchain_core/runnables/router.py b/libs/core/langchain_core/runnables/router.py index 82587b3e207..0e1224f0792 100644 --- a/libs/core/langchain_core/runnables/router.py +++ b/libs/core/langchain_core/runnables/router.py @@ -38,7 +38,7 @@ class RouterInput(TypedDict): Attributes: key: The key to route on. - input: The input to pass to the selected runnable. + input: The input to pass to the selected Runnable. """ key: str @@ -50,6 +50,9 @@ class RouterRunnable(RunnableSerializable[RouterInput, Output]): Runnable that routes to a set of Runnables based on Input['key']. Returns the output of the selected Runnable. + Parameters: + runnables: A mapping of keys to Runnables. + For example, .. code-block:: python diff --git a/libs/core/langchain_core/runnables/schema.py b/libs/core/langchain_core/runnables/schema.py index 1a447a74734..2695cfc444c 100644 --- a/libs/core/langchain_core/runnables/schema.py +++ b/libs/core/langchain_core/runnables/schema.py @@ -1,4 +1,4 @@ -"""Module contains typedefs that are used with runnables.""" +"""Module contains typedefs that are used with Runnables.""" from __future__ import annotations @@ -11,7 +11,7 @@ class EventData(TypedDict, total=False): """Data associated with a streaming event.""" input: Any - """The input passed to the runnable that generated the event. + """The input passed to the Runnable that generated the event. Inputs will sometimes be available at the *START* of the Runnable, and sometimes at the *END* of the Runnable. @@ -85,40 +85,43 @@ class BaseStreamEvent(TypedDict): event: str """Event names are of the format: on_[runnable_type]_(start|stream|end). - Runnable types are one of: - * llm - used by non chat models - * chat_model - used by chat models - * prompt -- e.g., ChatPromptTemplate - * tool -- from tools defined via @tool decorator or inheriting from Tool/BaseTool - * chain - most Runnables are of this type + Runnable types are one of: + + - **llm** - used by non chat models + - **chat_model** - used by chat models + - **prompt** -- e.g., ChatPromptTemplate + - **tool** -- from tools defined via @tool decorator or inheriting + from Tool/BaseTool + - **chain** - most Runnables are of this type Further, the events are categorized as one of: - * start - when the runnable starts - * stream - when the runnable is streaming - * end - when the runnable ends + + - **start** - when the Runnable starts + - **stream** - when the Runnable is streaming + - **end* - when the Runnable ends start, stream and end are associated with slightly different `data` payload. Please see the documentation for `EventData` for more details. """ run_id: str - """An randomly generated ID to keep track of the execution of the given runnable. + """An randomly generated ID to keep track of the execution of the given Runnable. - Each child runnable that gets invoked as part of the execution of a parent runnable + Each child Runnable that gets invoked as part of the execution of a parent Runnable is assigned its own unique ID. """ tags: NotRequired[List[str]] - """Tags associated with the runnable that generated this event. + """Tags associated with the Runnable that generated this event. - Tags are always inherited from parent runnables. + Tags are always inherited from parent Runnables. - Tags can either be bound to a runnable using `.with_config({"tags": ["hello"]})` + Tags can either be bound to a Runnable using `.with_config({"tags": ["hello"]})` or passed at run time using `.astream_events(..., {"tags": ["hello"]})`. """ metadata: NotRequired[Dict[str, Any]] - """Metadata associated with the runnable that generated this event. + """Metadata associated with the Runnable that generated this event. - Metadata can either be bound to a runnable using + Metadata can either be bound to a Runnable using `.with_config({"metadata": { "foo": "bar" }})` @@ -150,21 +153,20 @@ class StandardStreamEvent(BaseStreamEvent): The contents of the event data depend on the event type. """ name: str - """The name of the runnable that generated the event.""" + """The name of the Runnable that generated the event.""" class CustomStreamEvent(BaseStreamEvent): - """A custom stream event created by the user. + """Custom stream event created by the user. .. versionadded:: 0.2.14 """ # Overwrite the event field to be more specific. event: Literal["on_custom_event"] # type: ignore[misc] - """The event type.""" name: str - """A user defined name for the event.""" + """User defined name for the event.""" data: Any """The data associated with the event. Free form and can be anything.""" diff --git a/libs/core/langchain_core/runnables/utils.py b/libs/core/langchain_core/runnables/utils.py index 8908220cf24..e40c5da89e6 100644 --- a/libs/core/langchain_core/runnables/utils.py +++ b/libs/core/langchain_core/runnables/utils.py @@ -43,6 +43,7 @@ Output = TypeVar("Output", covariant=True) async def gated_coro(semaphore: asyncio.Semaphore, coro: Coroutine) -> Any: """Run a coroutine with a semaphore. + Args: semaphore: The semaphore to use. coro: The coroutine to run. @@ -59,7 +60,7 @@ async def gather_with_concurrency(n: Union[int, None], *coros: Coroutine) -> lis Args: n: The number of coroutines to run concurrently. - coros: The coroutines to run. + *coros: The coroutines to run. Returns: The results of the coroutines. @@ -73,7 +74,14 @@ async def gather_with_concurrency(n: Union[int, None], *coros: Coroutine) -> lis def accepts_run_manager(callable: Callable[..., Any]) -> bool: - """Check if a callable accepts a run_manager argument.""" + """Check if a callable accepts a run_manager argument. + + Args: + callable: The callable to check. + + Returns: + bool: True if the callable accepts a run_manager argument, False otherwise. + """ try: return signature(callable).parameters.get("run_manager") is not None except ValueError: @@ -81,7 +89,14 @@ def accepts_run_manager(callable: Callable[..., Any]) -> bool: def accepts_config(callable: Callable[..., Any]) -> bool: - """Check if a callable accepts a config argument.""" + """Check if a callable accepts a config argument. + + Args: + callable: The callable to check. + + Returns: + bool: True if the callable accepts a config argument, False otherwise. + """ try: return signature(callable).parameters.get("config") is not None except ValueError: @@ -89,7 +104,14 @@ def accepts_config(callable: Callable[..., Any]) -> bool: def accepts_context(callable: Callable[..., Any]) -> bool: - """Check if a callable accepts a context argument.""" + """Check if a callable accepts a context argument. + + Args: + callable: The callable to check. + + Returns: + bool: True if the callable accepts a context argument, False otherwise. + """ try: return signature(callable).parameters.get("context") is not None except ValueError: @@ -100,10 +122,24 @@ class IsLocalDict(ast.NodeVisitor): """Check if a name is a local dict.""" def __init__(self, name: str, keys: Set[str]) -> None: + """Initialize the visitor. + + Args: + name: The name to check. + keys: The keys to populate. + """ self.name = name self.keys = keys def visit_Subscript(self, node: ast.Subscript) -> Any: + """Visit a subscript node. + + Args: + node: The node to visit. + + Returns: + Any: The result of the visit. + """ if ( isinstance(node.ctx, ast.Load) and isinstance(node.value, ast.Name) @@ -115,6 +151,14 @@ class IsLocalDict(ast.NodeVisitor): self.keys.add(node.slice.value) def visit_Call(self, node: ast.Call) -> Any: + """Visit a call node. + + Args: + node: The node to visit. + + Returns: + Any: The result of the visit. + """ if ( isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name) @@ -135,18 +179,42 @@ class IsFunctionArgDict(ast.NodeVisitor): self.keys: Set[str] = set() def visit_Lambda(self, node: ast.Lambda) -> Any: + """Visit a lambda function. + + Args: + node: The node to visit. + + Returns: + Any: The result of the visit. + """ if not node.args.args: return input_arg_name = node.args.args[0].arg IsLocalDict(input_arg_name, self.keys).visit(node.body) def visit_FunctionDef(self, node: ast.FunctionDef) -> Any: + """Visit a function definition. + + Args: + node: The node to visit. + + Returns: + Any: The result of the visit. + """ if not node.args.args: return input_arg_name = node.args.args[0].arg IsLocalDict(input_arg_name, self.keys).visit(node) def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> Any: + """Visit an async function definition. + + Args: + node: The node to visit. + + Returns: + Any: The result of the visit. + """ if not node.args.args: return input_arg_name = node.args.args[0].arg @@ -161,12 +229,28 @@ class NonLocals(ast.NodeVisitor): self.stores: Set[str] = set() def visit_Name(self, node: ast.Name) -> Any: + """Visit a name node. + + Args: + node: The node to visit. + + Returns: + Any: The result of the visit. + """ if isinstance(node.ctx, ast.Load): self.loads.add(node.id) elif isinstance(node.ctx, ast.Store): self.stores.add(node.id) def visit_Attribute(self, node: ast.Attribute) -> Any: + """Visit an attribute node. + + Args: + node: The node to visit. + + Returns: + Any: The result of the visit. + """ if isinstance(node.ctx, ast.Load): parent = node.value attr_expr = node.attr @@ -185,16 +269,40 @@ class FunctionNonLocals(ast.NodeVisitor): self.nonlocals: Set[str] = set() def visit_FunctionDef(self, node: ast.FunctionDef) -> Any: + """Visit a function definition. + + Args: + node: The node to visit. + + Returns: + Any: The result of the visit. + """ visitor = NonLocals() visitor.visit(node) self.nonlocals.update(visitor.loads - visitor.stores) def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> Any: + """Visit an async function definition. + + Args: + node: The node to visit. + + Returns: + Any: The result of the visit. + """ visitor = NonLocals() visitor.visit(node) self.nonlocals.update(visitor.loads - visitor.stores) def visit_Lambda(self, node: ast.Lambda) -> Any: + """Visit a lambda function. + + Args: + node: The node to visit. + + Returns: + Any: The result of the visit. + """ visitor = NonLocals() visitor.visit(node) self.nonlocals.update(visitor.loads - visitor.stores) @@ -209,14 +317,29 @@ class GetLambdaSource(ast.NodeVisitor): self.count = 0 def visit_Lambda(self, node: ast.Lambda) -> Any: - """Visit a lambda function.""" + """Visit a lambda function. + + Args: + node: The node to visit. + + Returns: + Any: The result of the visit. + """ self.count += 1 if hasattr(ast, "unparse"): self.source = ast.unparse(node) def get_function_first_arg_dict_keys(func: Callable) -> Optional[List[str]]: - """Get the keys of the first argument of a function if it is a dict.""" + """Get the keys of the first argument of a function if it is a dict. + + Args: + func: The function to check. + + Returns: + Optional[List[str]]: The keys of the first argument if it is a dict, + None otherwise. + """ try: code = inspect.getsource(func) tree = ast.parse(textwrap.dedent(code)) @@ -231,10 +354,10 @@ def get_lambda_source(func: Callable) -> Optional[str]: """Get the source code of a lambda function. Args: - func: a callable that can be a lambda function + func: a Callable that can be a lambda function. Returns: - str: the source code of the lambda function + str: the source code of the lambda function. """ try: name = func.__name__ if func.__name__ != "" else None @@ -251,7 +374,14 @@ def get_lambda_source(func: Callable) -> Optional[str]: def get_function_nonlocals(func: Callable) -> List[Any]: - """Get the nonlocal variables accessed by a function.""" + """Get the nonlocal variables accessed by a function. + + Args: + func: The function to check. + + Returns: + List[Any]: The nonlocal variables accessed by the function. + """ try: code = inspect.getsource(func) tree = ast.parse(textwrap.dedent(code)) @@ -283,11 +413,11 @@ def indent_lines_after_first(text: str, prefix: str) -> str: """Indent all lines of text after the first line. Args: - text: The text to indent - prefix: Used to determine the number of spaces to indent + text: The text to indent. + prefix: Used to determine the number of spaces to indent. Returns: - str: The indented text + str: The indented text. """ n_spaces = len(prefix) spaces = " " * n_spaces @@ -341,7 +471,14 @@ Addable = TypeVar("Addable", bound=SupportsAdd[Any, Any]) def add(addables: Iterable[Addable]) -> Optional[Addable]: - """Add a sequence of addable objects together.""" + """Add a sequence of addable objects together. + + Args: + addables: The addable objects to add. + + Returns: + Optional[Addable]: The result of adding the addable objects. + """ final = None for chunk in addables: if final is None: @@ -352,7 +489,14 @@ def add(addables: Iterable[Addable]) -> Optional[Addable]: async def aadd(addables: AsyncIterable[Addable]) -> Optional[Addable]: - """Asynchronously add a sequence of addable objects together.""" + """Asynchronously add a sequence of addable objects together. + + Args: + addables: The addable objects to add. + + Returns: + Optional[Addable]: The result of adding the addable objects. + """ final = None async for chunk in addables: if final is None: @@ -363,7 +507,15 @@ async def aadd(addables: AsyncIterable[Addable]) -> Optional[Addable]: class ConfigurableField(NamedTuple): - """Field that can be configured by the user.""" + """Field that can be configured by the user. + + Parameters: + id: The unique identifier of the field. + name: The name of the field. Defaults to None. + description: The description of the field. Defaults to None. + annotation: The annotation of the field. Defaults to None. + is_shared: Whether the field is shared. Defaults to False. + """ id: str @@ -377,7 +529,16 @@ class ConfigurableField(NamedTuple): class ConfigurableFieldSingleOption(NamedTuple): - """Field that can be configured by the user with a default value.""" + """Field that can be configured by the user with a default value. + + Parameters: + id: The unique identifier of the field. + options: The options for the field. + default: The default value for the field. + name: The name of the field. Defaults to None. + description: The description of the field. Defaults to None. + is_shared: Whether the field is shared. Defaults to False. + """ id: str options: Mapping[str, Any] @@ -392,7 +553,16 @@ class ConfigurableFieldSingleOption(NamedTuple): class ConfigurableFieldMultiOption(NamedTuple): - """Field that can be configured by the user with multiple default values.""" + """Field that can be configured by the user with multiple default values. + + Parameters: + id: The unique identifier of the field. + options: The options for the field. + default: The default values for the field. + name: The name of the field. Defaults to None. + description: The description of the field. Defaults to None. + is_shared: Whether the field is shared. Defaults to False. + """ id: str options: Mapping[str, Any] @@ -412,7 +582,17 @@ AnyConfigurableField = Union[ class ConfigurableFieldSpec(NamedTuple): - """Field that can be configured by the user. It is a specification of a field.""" + """Field that can be configured by the user. It is a specification of a field. + + Parameters: + id: The unique identifier of the field. + annotation: The annotation of the field. + name: The name of the field. Defaults to None. + description: The description of the field. Defaults to None. + default: The default value for the field. Defaults to None. + is_shared: Whether the field is shared. Defaults to False. + dependencies: The dependencies of the field. Defaults to None. + """ id: str annotation: Any @@ -427,7 +607,17 @@ class ConfigurableFieldSpec(NamedTuple): def get_unique_config_specs( specs: Iterable[ConfigurableFieldSpec], ) -> List[ConfigurableFieldSpec]: - """Get the unique config specs from a sequence of config specs.""" + """Get the unique config specs from a sequence of config specs. + + Args: + specs: The config specs. + + Returns: + List[ConfigurableFieldSpec]: The unique config specs. + + Raises: + ValueError: If the runnable sequence contains conflicting config specs. + """ grouped = groupby( sorted(specs, key=lambda s: (s.id, *(s.dependencies or []))), lambda s: s.id ) @@ -542,7 +732,15 @@ def _create_model_cached( def is_async_generator( func: Any, ) -> TypeGuard[Callable[..., AsyncIterator]]: - """Check if a function is an async generator.""" + """Check if a function is an async generator. + + Args: + func: The function to check. + + Returns: + TypeGuard[Callable[..., AsyncIterator]: True if the function is + an async generator, False otherwise. + """ return ( inspect.isasyncgenfunction(func) or hasattr(func, "__call__") @@ -553,7 +751,15 @@ def is_async_generator( def is_async_callable( func: Any, ) -> TypeGuard[Callable[..., Awaitable]]: - """Check if a function is async.""" + """Check if a function is async. + + Args: + func: The function to check. + + Returns: + TypeGuard[Callable[..., Awaitable]: True if the function is async, + False otherwise. + """ return ( asyncio.iscoroutinefunction(func) or hasattr(func, "__call__")