MCPcopy
hub / github.com/langchain-ai/langchain / RunnableBranch

Class RunnableBranch

libs/core/langchain_core/runnables/branch.py:40–421  ·  view source on GitHub ↗

Runnable that selects which branch to run based on a condition. The Runnable is initialized with a list of (condition, Runnable) pairs and a default branch. When operating on an input, the first condition that evaluates to True is selected, and the corresponding Runnable is run on

Source from the content-addressed store, hash-verified

38
39
40class RunnableBranch(RunnableSerializable[Input, Output]):
41 """Runnable that selects which branch to run based on a condition.
42
43 The Runnable is initialized with a list of (condition, Runnable) pairs and
44 a default branch.
45
46 When operating on an input, the first condition that evaluates to True is
47 selected, and the corresponding Runnable is run on the input.
48
49 If no condition evaluates to True, the default branch is run on the input.
50
51 Examples:
52
53 .. code-block:: python
54
55 from langchain_core.runnables import RunnableBranch
56
57 branch = RunnableBranch(
58 (lambda x: isinstance(x, str), lambda x: x.upper()),
59 (lambda x: isinstance(x, int), lambda x: x + 1),
60 (lambda x: isinstance(x, float), lambda x: x * 2),
61 lambda x: "goodbye",
62 )
63
64 branch.invoke("hello") # "HELLO"
65 branch.invoke(None) # "goodbye"
66 """
67
68 branches: Sequence[Tuple[Runnable[Input, bool], Runnable[Input, Output]]]
69 default: Runnable[Input, Output]
70
71 def __init__(
72 self,
73 *branches: Union[
74 Tuple[
75 Union[
76 Runnable[Input, bool],
77 Callable[[Input], bool],
78 Callable[[Input], Awaitable[bool]],
79 ],
80 RunnableLike,
81 ],
82 RunnableLike, # To accommodate the default branch
83 ],
84 ) -> None:
85 """A Runnable that runs one of two branches based on a condition."""
86 if len(branches) < 2:
87 raise ValueError("RunnableBranch requires at least two branches")
88
89 default = branches[-1]
90
91 if not isinstance(
92 default,
93 (Runnable, Callable, Mapping), # type: ignore[arg-type]
94 ):
95 raise TypeError(
96 "RunnableBranch default must be runnable, callable or mapping."
97 )

Callers 8

chain.pyFile · 0.90
router.pyFile · 0.90
chain.pyFile · 0.90
chain.pyFile · 0.90
revise_loopFunction · 0.90
__init__Method · 0.90

Calls

no outgoing calls

Tested by 1