Skip to content

The agent engineering platform.

merge

Bagatur25cbcd937468
diff --cc libs/langchain/langchain/schema/runnable/base.py
index 38a84ead2a,c9d836cfd8..9354355fa2
--- a/libs/langchain/langchain/schema/runnable/base.py
+++ b/libs/langchain/langchain/schema/runnable/base.py
@@@ -26,79 -23,16 +24,41 @@@ from typing import
cast,
)
- from pydantic import Field
-
- from langchain.callbacks.base import BaseCallbackManager, Callbacks
+ from langchain.callbacks.base import BaseCallbackManager
from langchain.load.dump import dumpd
from langchain.load.serializable import Serializable
+ from langchain.pydantic_v1 import Field
+ from langchain.schema.runnable.config import RunnableConfig
+ from langchain.schema.runnable.utils import (
+ gather_with_concurrency,
+ )
from langchain.utils.aiter import atee, py_anext
+
- async def _gated_coro(semaphore: asyncio.Semaphore, coro: Coroutine) -> Any:
- async with semaphore:
- return await coro
-
-
- async def _gather_with_concurrency(n: Union[int, None], *coros: Coroutine) -> list:
- if n is None:
- return await asyncio.gather(*coros)
-
- semaphore = asyncio.Semaphore(n)
-
- return await asyncio.gather(*(_gated_coro(semaphore, c) for c in coros))
-
-
- class RunnableConfig(TypedDict, total=False):
- """Configuration for a Runnable."""
-
- tags: List[str]
- """
- Tags for this call and any sub-calls (eg. a Chain calling an LLM).
- You can use these to filter calls.
- """
-
- metadata: Dict[str, Any]
- """
- Metadata for this call and any sub-calls (eg. a Chain calling an LLM).
- Keys should be strings, values should be JSON-serializable.
- """
-
- callbacks: Callbacks
- """
- Callbacks for this call and any sub-calls (eg. a Chain calling an LLM).
- Tags are passed to all callbacks, metadata is passed to handle*Start callbacks.
- """
-
- _locals: Dict[str, Any]
- """
- Local variables
- """
-
-
+def _empty_config() -> RunnableConfig:
+ return RunnableConfig(tags=[], metadata={}, callbacks=None, _locals={})
+
+
+def _get_callback_manager(config: Mapping) -> Any:
+ from langchain.callbacks.manager import CallbackManager
+
+ return CallbackManager.configure(
+ inheritable_callbacks=config.get("callbacks"),
+ inheritable_tags=config.get("tags"),
+ inheritable_metadata=config.get("metadata"),
+ )
+
+
+def _get_async_callback_manager(config: Mapping) -> Any:
+ from langchain.callbacks.manager import AsyncCallbackManager
+
+ return AsyncCallbackManager.configure(
+ inheritable_callbacks=config.get("callbacks"),
+ inheritable_tags=config.get("tags"),
+ inheritable_metadata=config.get("metadata"),
+ )
+
+
Input = TypeVar("Input")
# Output type should implement __concat__, as eg str, list, dict do
Output = TypeVar("Output")
@@@ -1304,163 -1304,8 +1276,10 @@@ class RunnableBinding(Serializable, Run
yield item
- class RouterInput(TypedDict):
- """A Router input.
-
- Attributes:
- key: The key to route on.
- input: The input to pass to the selected runnable.
- """
-
- key: str
- input: Any
-
-
- class RouterRunnable(
- Serializable, Generic[Input, Output], Runnable[RouterInput, Output]
- ):
- """
- A runnable that routes to a set of runnables based on Input['key'].
- Returns the output of the selected runnable.
- """
-
- runnables: Mapping[str, Runnable[Input, Output]]
-
- def __init__(
- self,
- runnables: Mapping[
- str, Union[Runnable[Input, Output], Callable[[Input], Output]]
- ],
- ) -> None:
- super().__init__(
- runnables={key: _coerce_to_runnable(r) for key, r in runnables.items()}
- )
-
- class Config:
- arbitrary_types_allowed = True
-
- @property
- def lc_serializable(self) -> bool:
- return True
-
- def __or__(
- self,
- other: Union[
- Runnable[Any, Other],
- Callable[[Any], Other],
- Mapping[str, Union[Runnable[Any, Other], Callable[[Any], Other]]],
- Mapping[str, Any],
- ],
- ) -> RunnableSequence[RouterInput, Other]:
- return RunnableSequence(first=self, last=_coerce_to_runnable(other))
-
- def __ror__(
- self,
- other: Union[
- Runnable[Other, Any],
- Callable[[Any], Other],
- Mapping[str, Union[Runnable[Other, Any], Callable[[Other], Any]]],
- Mapping[str, Any],
- ],
- ) -> RunnableSequence[Other, Output]:
- return RunnableSequence(first=_coerce_to_runnable(other), last=self)
-
- def invoke(
- self, input: RouterInput, config: Optional[RunnableConfig] = None
- ) -> Output:
- key = input["key"]
- actual_input = input["input"]
- if key not in self.runnables:
- raise ValueError(f"No runnable associated with key '{key}'")
-
- runnable = self.runnables[key]
- return runnable.invoke(actual_input, config)
-
- async def ainvoke(
- self, input: RouterInput, config: Optional[RunnableConfig] = None
- ) -> Output:
- key = input["key"]
- actual_input = input["input"]
- if key not in self.runnables:
- raise ValueError(f"No runnable associated with key '{key}'")
-
- runnable = self.runnables[key]
- return await runnable.ainvoke(actual_input, config)
-
- def batch(
- self,
- inputs: List[RouterInput],
- config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,
- *,
- max_concurrency: Optional[int] = None,
- ) -> List[Output]:
- keys = [input["key"] for input in inputs]
- actual_inputs = [input["input"] for input in inputs]
- if any(key not in self.runnables for key in keys):
- raise ValueError("One or more keys do not have a corresponding runnable")
-
- runnables = [self.runnables[key] for key in keys]
- configs = self._get_config_list(config, len(inputs))
- with ThreadPoolExecutor(max_workers=max_concurrency) as executor:
- return list(
- executor.map(
- lambda runnable, input, config: runnable.invoke(input, config),
- runnables,
- actual_inputs,
- configs,
- )
- )
-
- async def abatch(
- self,
- inputs: List[RouterInput],
- config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None,
- *,
- max_concurrency: Optional[int] = None,
- ) -> List[Output]:
- keys = [input["key"] for input in inputs]
- actual_inputs = [input["input"] for input in inputs]
- if any(key not in self.runnables for key in keys):
- raise ValueError("One or more keys do not have a corresponding runnable")
-
- runnables = [self.runnables[key] for key in keys]
- configs = self._get_config_list(config, len(inputs))
- return await _gather_with_concurrency(
- max_concurrency,
- *(
- runnable.ainvoke(input, config)
- for runnable, input, config in zip(runnables, actual_inputs, configs)
- ),
- )
-
- def stream(
- self, input: RouterInput, config: Optional[RunnableConfig] = None
- ) -> Iterator[Output]:
- key = input["key"]
- actual_input = input["input"]
- if key not in self.runnables:
- raise ValueError(f"No runnable associated with key '{key}'")
-
- runnable = self.runnables[key]
- yield from runnable.stream(actual_input, config)
-
- async def astream(
- self, input: RouterInput, config: Optional[RunnableConfig] = None
- ) -> AsyncIterator[Output]:
- key = input["key"]
- actual_input = input["input"]
- if key not in self.runnables:
- raise ValueError(f"No runnable associated with key '{key}'")
-
- runnable = self.runnables[key]
- async for output in runnable.astream(actual_input, config):
- yield output
-
-
- def _patch_config(
+ def patch_config(
- config: RunnableConfig, callback_manager: BaseCallbackManager
+ config: RunnableConfig,
+ callback_manager: BaseCallbackManager,
+ _locals: Optional[Dict[str, Any]] = None,
) -> RunnableConfig:
config = config.copy()
config["callbacks"] = callback_manager
diff --cc libs/langchain/langchain/schema/runnable/config.py
index 0000000000,715b79fd9f..f2bf28fcb5
mode 000000,100644..100644
--- a/libs/langchain/langchain/schema/runnable/config.py
+++ b/libs/langchain/langchain/schema/runnable/config.py
@@@ -1,0 -1,27 +1,32 @@@
+ from __future__ import annotations
+
+ from typing import Any, Dict, List, TypedDict
+
+ from langchain.callbacks.base import Callbacks
+
+
+ class RunnableConfig(TypedDict, total=False):
+ """Configuration for a Runnable."""
+
+ tags: List[str]
+ """
+ Tags for this call and any sub-calls (eg. a Chain calling an LLM).
+ You can use these to filter calls.
+ """
+
+ metadata: Dict[str, Any]
+ """
+ Metadata for this call and any sub-calls (eg. a Chain calling an LLM).
+ Keys should be strings, values should be JSON-serializable.
+ """
+
+ callbacks: Callbacks
+ """
+ Callbacks for this call and any sub-calls (eg. a Chain calling an LLM).
+ Tags are passed to all callbacks, metadata is passed to handle*Start callbacks.
+ """
++
++ _locals: Dict[str, Any]
++ """
++ Local variables
++ """