04. LLM chain routing (RunnableLambda, RunnableBranch)
RunnableBranch Is a powerful tool that allows you to dynamically route logic based on input. Through this, the developer Flexible definition of various processing paths based on the characteristics of the input data You can.
RunnableBranch Helps to implement complex decision trees in a simple and intuitive way. This greatly improves the readability and maintainability of the code, and promotes the modularity and reusability of the logic.
Also, RunnableBranch At runtime, you can dynamically evaluate the branch conditions and choose the appropriate processing routine, which increases the adaptability and scalability of the system.
Due to these features, RunnableBranch can be utilized in a variety of domains, especially useful for developing applications with high diversity and volatility of input data. RunnableBranch Effectively utilizing it can reduce the complexity of your code and improve the flexibility and performance of your system.
Dynamic logic routing by input
LangChain Expression Language covers how to perform routing.
Routing allows the output of the previous step to create an indeterminate chain that defines the next step. Routing helps to provide structure and consistency to interaction with LLM.
There are two ways to do routing.
RunnableLambdaReturns a conditionally viable object from (recommended)RunnableBranchuse
Both methods ask input questions in the first step 수학 , 과학 or 기타 I'll explain it using a two-step sequence that categorizes it as for and then routes it to that prompt chain.
Copy
# Configuration file for managing API keys as environment variables
from dotenv import load_dotenv
# Load API key information
load_dotenv()Copy
Copy
Copy
Simple example
First, the incoming question math , science , or etc I'll create a Chain that categorizes it as one of them.
Copy
Classify questions using the chain you created.
Copy
Copy
Copy
Copy
Copy
Copy
Now let's create three subchains.
Copy
Using custom functions
This is the method recommended by the LangChain official dock, for routing between different outputs Custom function for RunnableLambda You can also use it by wrapping it with.
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Copy
RunnableBranch
RunnableBranch A special type that can define the conditions to run and the Runnable according to the input value Runnable is.
However, we do not provide any functionality that cannot be implemented with the custom functions described above, so we recommend using custom functions.
grammar
RunnableBranchIs initialized with a (condition, Runnable) pair of list and basic Runnable.Select the branch by passing the input value passed at the time of call to each condition.
Select the first condition that is evaluated as True, and run the Runnable corresponding to that condition with the input value.
If nothing matches the conditions provided basic
RunnableRun.
Copy
Copy
Copy
Copy
Copy
Copy
Copy
Last updated