Conditional Chain Execution
Real-world workflows aren't always linear. Conditional execution allows your chains to take different paths based on the content being processed or results from previous steps.
Why Conditional Execution?
Consider these scenarios where you need different processing paths:
- Support tickets: Technical issues need different handling than billing questions
- Content moderation: Safe content proceeds, flagged content goes to review
- Document processing: Contracts need legal review, invoices go to accounting
Basic Conditional Patterns
If-Then-Else
The simplest conditional pattern:
┌─── [condition A] ─── Path A ───┐
Input ─────┤ ├─── Output
└─── [else] ─── Path B ──────────┘
Multi-Way Branch
When multiple paths are possible:
┌─── Path A (if type = 'technical')
│
Input ─── ? ───┼─── Path B (if type = 'billing')
│
├─── Path C (if type = 'general')
│
└─── Path D (default)
Implementing Conditions
Condition Step
Create a dedicated classification step:
Loading Prompt Playground...
Threshold-Based Routing
Route based on scores or metrics:
async function routeByConfidence(analysis) {
if (analysis.confidence >= 0.9) {
return 'automated_response';
} else if (analysis.confidence >= 0.7) {
return 'suggested_response';
} else {
return 'human_review';
}
}
Content-Based Routing
Route based on what's in the content:
async function routeByContent(extracted) {
if (extracted.entities.includes('pii')) {
return 'privacy_pipeline';
}
if (extracted.sentiment_score < -0.5) {
return 'escalation_pipeline';
}
if (extracted.language !== 'en') {
return 'translation_first_pipeline';
}
return 'standard_pipeline';
}
Building Conditional Chains
The Router Pattern
const conditionalChain = {
steps: {
classify: {
prompt: classificationPrompt,
outputs: ['category', 'confidence']
},
router: {
type: 'conditional',
conditions: [
{
if: 'category === "technical"',
then: 'technicalPipeline'
},
{
if: 'category === "billing"',
then: 'billingPipeline'
},
{
default: 'generalPipeline'
}
]
},
technicalPipeline: {
steps: ['diagnoseTechnical', 'suggestSolution', 'formatTechnicalResponse']
},
billingPipeline: {
steps: ['lookupAccount', 'analyzeBilling', 'formatBillingResponse']
},
generalPipeline: {
steps: ['generateGeneralResponse']
}
}
};
Condition Evaluation
Loading Prompt Playground...
Multi-Condition Logic
AND Conditions
All conditions must be true:
const conditions = [
'sentiment_score > 0.5',
'category === "feedback"',
'length > 100'
];
const shouldPublish = conditions.every(c => evaluate(c, data));
OR Conditions
Any condition can be true:
const urgentConditions = [
'contains_urgent_keywords',
'sentiment_score < -0.8',
'customer_tier === "enterprise"'
];
const isUrgent = urgentConditions.some(c => evaluate(c, data));
Nested Conditions
Complex logic with nesting:
const routing = {
if: 'isAuthenticated',
then: {
if: 'hasSubscription',
then: {
if: 'subscription.tier === "premium"',
then: 'premiumPipeline',
else: 'standardPipeline'
},
else: 'freeTrialPipeline'
},
else: 'anonymousPipeline'
};
Exercise: Design Conditional Logic
Design the conditional routing for this scenario:
Loading Prompt Playground...
Handling Edge Cases
No Matching Condition
Always have a default:
async function safeRoute(conditions, data) {
for (const condition of conditions) {
if (evaluate(condition.if, data)) {
return condition.then;
}
}
// Always have a fallback
return 'default_pipeline';
}
Multiple Matching Conditions
Decide on priority or combination:
// Priority-based: First match wins
const firstMatch = conditions.find(c => evaluate(c.if, data));
// Collect all: Gather all matching paths
const allMatches = conditions.filter(c => evaluate(c.if, data));
// Weighted: Choose by confidence
const weightedMatch = conditions
.filter(c => evaluate(c.if, data))
.sort((a, b) => b.weight - a.weight)[0];
Low Confidence Classifications
Handle uncertain classifications:
async function handleLowConfidence(classification) {
if (classification.confidence < 0.5) {
// Ask for clarification or use multi-path
return {
action: 'clarify',
possiblePaths: [
classification.primary,
classification.secondary
]
};
}
return { action: 'proceed', path: classification.primary };
}
Key Takeaways
- Conditional execution enables dynamic chain behavior
- Use dedicated classification steps to determine routing
- Support multiple condition types: threshold, content, rule-based
- Implement AND/OR/nested logic for complex conditions
- Always include default paths for unmatched cases
- Handle low-confidence classifications gracefully
- Log routing decisions for debugging
Next, we'll explore classification-based routing in more depth.

