RunnableBranch.
Objectives
- Implement conditional branching using
RunnableBranchin LCEL. - Build a sentiment classification chain to automatically categorize text inputs.
- Route input dynamically to dedicated specialized response chains depending on classification results.
Branching Chains Plan
Goal
Classify the sentiment of user feedback (positive, negative, neutral, or escalate) and dynamically route execution to the appropriate support responder chain.Sample Input
Sample Output
An automated customer service response addressing the negative sentiment of the feedback.Plan
- Create specialized prompt templates for positive, negative, neutral, and escalation feedback.
- Construct a classification chain that analyzes feedback and returns a category string (“positive”, “negative”, “neutral”, “escalate”).
- Set up a
RunnableBranchthat contains conditional checks mapped to each responder chain, plus a default fallback. - Compose the final pipeline by connecting the classification chain to the branching router:
chain = classification_chain | branches. - Invoke the pipeline with user feedback.
Step-by-Step Implementation
Step 1: Define Specialized Responder Chains
First, we create prompt templates and chains tailored to specific sentiment reactions: positive thank-yous, negative issue handling, neutral detail gathering, and an escalation fallback.Step 2: Define the Sentiment Classifier Chain
We create a classifier chain that acts as the entry node. It prompts the model to classify the user’s feedback into one of the four categories: positive, negative, neutral, or escalate.Step 3: Configure routing conditions via RunnableBranch
Now, we define conditional checks mapped to the corresponding chains we set up in Step 1. RunnableBranch takes pairs of (condition_callable, runnable_chain) and a final fallback chain.
Step 4: Compose Classifier and Router
Finally, we connect the classifier chain directly to the router branches using the pipe operator. The classification result is forwarded directly to the branches logic to select the correct execution path.Complete Combined Code
Below is the complete, consolidated Python script uniting all of the steps above:Practice & Exercises
To reinforce what you’ve learned in this section, practice with the interactive notebook:Practice & Exercises
Practice setting up conditional logic nodes, routing user inputs to custom domains, and implementing fallback handlers.💻 VS Code | 🚀 Colab | 📥 Download