LangGraph Agents
Complex workflows with conditional branching and dynamic routing
LangGraph agents orchestrate sophisticated workflows with conditional branching, dynamic routing, and state-dependent decisions. Think of them as the master conductors for complex, multi-path processes where the next step depends on the results of previous steps.
Unlike simple workflow patterns (sequential, parallel, loop), LangGraph agents handle complex decision trees, conditional flows, and dynamic routing based on content analysis, user preferences, or business rules.
Advanced Orchestration
- Power: Handle complex branching logic and conditional workflows - Flexibility: Dynamic routing based on content, context, or business rules
- Best for: Sophisticated processes that require intelligent decision-making
Quick Start Example
Here's a customer support system that intelligently routes inquiries based on analysis:
import { LlmAgent, LangGraphAgent } from "@iqai/adk";
// Analyze incoming customer inquiry
const inquiryAnalyzerAgent = new LlmAgent({
name: "inquiry_analyzer_agent",
model: "gemini-2.5-flash",
description:
"Analyzes customer inquiries to determine category, urgency, and routing",
instruction: `
Analyze the customer inquiry and determine:
- Category: technical, billing, refund, general, complaint
- Urgency: low, medium, high, critical
- Complexity: simple, moderate, complex
- Sentiment: positive, neutral, negative, angry
Output as JSON with these exact fields: category, urgency, complexity, sentiment.
`,
outputKey: "inquiry_analysis",
});
// Specialized support agents
const technicalSupportAgent = new LlmAgent({
name: "technical_support_agent",
model: "gemini-2.5-flash",
description: "Handles technical issues with step-by-step troubleshooting",
instruction: `
Provide technical support for the customer's issue:
- Diagnose the technical problem
- Provide step-by-step troubleshooting guidance
- Offer workarounds or solutions
- Escalate to engineering if needed
Be patient, clear, and technically accurate.
`,
outputKey: "technical_response",
});
const billingSupportAgent = new LlmAgent({
name: "billing_support_agent",
model: "gemini-2.5-flash",
description: "Handles billing inquiries and payment issues",
instruction: `
Handle billing and payment-related inquiries:
- Review account charges and billing history
- Explain billing policies and charges
- Process refunds or adjustments when appropriate
- Escalate complex billing disputes
Be transparent about charges and helpful with resolutions.
`,
outputKey: "billing_response",
});
const escalationHandlerAgent = new LlmAgent({
name: "escalation_handler_agent",
model: "gemini-2.5-flash",
description: "Handles escalated cases requiring human intervention",
instruction: `
Handle escalated customer cases with empathy and urgency:
- Acknowledge the customer's frustration
- Provide immediate relief or compensation if appropriate
- Escalate to appropriate internal teams
- Provide clear next steps and timelines
- Follow up personally on resolution
Show genuine concern and commitment to resolution.
`,
outputKey: "escalation_response",
});
const generalSupportAgent = new LlmAgent({
name: "general_support_agent",
model: "gemini-2.5-flash",
description: "Handles general inquiries and provides information",
instruction: `
Provide helpful information and support for general inquiries:
- Answer questions about products/services
- Provide account information and guidance
- Direct to appropriate resources
- Offer proactive assistance
Be friendly, informative, and proactive.
`,
outputKey: "general_response",
});
/**
* Customer Support Workflow
*
* Implements the following routing logic:
* 1. Analyze Inquiry -> Decision
* 2. Decision Branches:
* - Critical/Angry -> Escalation Handler
* - Technical -> Technical Support -> End
* - Billing/Refund -> Billing Support -> Resolved?
* - No -> Escalation Handler -> End
* - Yes -> End
* - General -> General Support -> End
*/
const supportWorkflowAgent = new LangGraphAgent({
name: "support_workflow_agent",
description:
"Intelligent customer support routing and handling system using LangGraph for agent orchestration.",
rootNode: "analyze",
maxSteps: 10,
nodes: [
{
name: "analyze",
agent: inquiryAnalyzerAgent,
targets: ["escalate", "technical", "billing", "general"],
},
{
name: "technical",
agent: technicalSupportAgent,
condition: (event: any) => {
try {
// Parse JSON analysis from the previous event
const analysis = JSON.parse(
event.content.match(/\{[\s\S]*\}/)?.[0] || "{}"
);
// Route to technical support if category matches and not critical/angry
return (
analysis.category === "technical" &&
analysis.urgency !== "critical" &&
analysis.sentiment !== "angry"
);
} catch {
return false;
}
},
},
{
name: "billing",
agent: billingSupportAgent,
targets: ["escalate"], // Can escalate if unresolved
condition: (event: any) => {
try {
// Parse JSON analysis from the previous event
const analysis = JSON.parse(
event.content.match(/\{[\s\S]*\}/)?.[0] || "{}"
);
// Route to billing support if category matches and not critical/angry
return (
["billing", "refund"].includes(analysis.category) &&
analysis.urgency !== "critical" &&
analysis.sentiment !== "angry"
);
} catch {
return false;
}
},
},
{
name: "escalate",
agent: escalationHandlerAgent,
condition: (event: any) => {
try {
// Parse JSON analysis from the previous event
const analysis = JSON.parse(
event.content.match(/\{[\s\S]*\}/)?.[0] || "{}"
);
// Escalate if critical, angry, or complaint
if (
analysis.urgency === "critical" ||
analysis.sentiment === "angry" ||
analysis.category === "complaint"
) {
return true;
}
// Also escalate if billing agent mentions escalation
return event.content.toLowerCase().includes("escalate");
} catch {
return false;
}
},
},
{
name: "general",
agent: generalSupportAgent,
condition: (event: any) => {
try {
// Parse JSON analysis from the previous event
const analysis = JSON.parse(
event.content.match(/\{[\s\S]*\}/)?.[0] || "{}"
);
// Route to general support if category matches and not critical/angry
return (
analysis.category === "general" &&
analysis.urgency !== "critical" &&
analysis.sentiment !== "angry"
);
} catch {
return false;
}
},
},
],
});
// Export the main workflow agent for use in other modules
export { supportWorkflowAgent };Visual Flow
How LangGraph Processing Works
LangGraph agents enable sophisticated workflow orchestration through conditional routing and state-dependent decisions:
🌐 Node-Based Architecture
- Nodes: Individual processing steps (typically agents)
- Edges: Conditional transitions between nodes
- State: Shared context that influences routing decisions
- Dynamic routing: Next step determined by current state and results
🧠 Intelligent Decision Making
- Execute current node - Run the agent at current workflow position
- Evaluate state - Analyze results and current context
- Determine next step - Use conditional logic to choose next node
- Route dynamically - Move to appropriate next node or terminate
🔀 Conditional Flows
Conditional flows determine which path the workflow takes based on the results of previous steps. Each node can have a condition function that evaluates the current context and returns true to execute that node, or routes to alternative targets when conditions aren't met.
// Example: Route based on analysis results
{
name: "technical-support",
agent: technicalSupportAgent,
condition: (event: any) => {
try {
const analysis = JSON.parse(event.content);
// Execute this node if category is technical and not critical
return analysis.category === "technical" &&
analysis.urgency !== "critical";
} catch {
return false;
}
},
}📊 State Management
- All nodes share the same session state
- Previous results influence future routing decisions
- Context accumulates throughout the workflow
- Decisions can reference any previous step's output
Graph Design Patterns
- Start simple: Begin with basic routing logic, add complexity gradually
- Plan thoroughly: Map out all possible paths before implementation
- Handle edge cases: Always have fallback routes for unexpected conditions
Real-World Use Cases
🏥 Medical Diagnosis Workflow
Symptoms → Initial Assessment → Specialist Routing → Tests → Diagnosis → Treatment Plan
⚖️ Legal Document Review
Document Analysis → Risk Assessment → Complexity Routing → Specialist Review → Approval Flow
💼 Loan Application Processing
Application Review → Risk Assessment → Manual/Auto Route → Verification → Decision → Notification
📱 App Feature Requests
Request Analysis → Category Assignment → Feasibility Check → Priority Routing → Development Queue
🎯 Content Moderation
Content Analysis → Risk Scoring → Auto-Approve/Review Route → Human Review → Action Decision
🔍 Fraud Detection
Transaction Analysis → Risk Scoring → Investigation Routing → Evidence Gathering → Resolution
When to Choose LangGraph Agents
Perfect for Complex Decision Trees
- Use when: You need sophisticated branching logic and conditional workflows - Benefit: Handle complex processes that simple linear or parallel patterns can't address
✅ Choose LangGraph When:
- Complex routing logic - Next step depends on content analysis or business rules
- Multi-path workflows - Different paths through the process based on conditions
- State-dependent decisions - Routing changes based on accumulated context
- Exception handling - Need sophisticated error handling and escalation paths
- Adaptive processes - Workflow adapts based on intermediate results
- Integration of patterns - Combining sequential, parallel, and loop behaviors
❌ Don't Use LangGraph When:
- Simple linear workflows are sufficient (use Sequential)
- All tasks can run independently (use Parallel)
- Simple iteration is needed (use Loop)
- Workflow complexity outweighs the benefits
- Debugging and maintenance overhead is too high
Advanced Patterns
Multi-Stage Decision Trees
Build complex workflows with multiple evaluation points and conditional routing based on accumulated results. Use when you need sophisticated decision trees that adapt based on intermediate outcomes, such as triage systems that require multiple assessment stages before final resolution.
const multiStageWorkflow = new LangGraphAgent({
name: "multi_stage_workflow",
description: "Multi-stage decision tree with triage and processing phases",
rootNode: "initial-triage",
maxSteps: 10,
nodes: [
{
name: "initial-triage",
agent: triageAgent,
targets: ["automated-processing", "human-review"],
},
{
name: "automated-processing",
agent: automatedProcessor,
targets: ["finalize", "human-review"],
condition: (event: any) => {
// Route based on confidence score
const result = JSON.parse(event.content);
return result.confidence > 0.9;
},
},
{
name: "human-review",
agent: humanReviewAgent,
targets: ["finalize"],
},
{
name: "finalize",
agent: finalizationAgent,
},
],
});Loop Within Graph
Create iterative workflows that can repeat processing steps until conditions are met. Use for quality assurance, iterative improvement, or validation loops where work needs to be refined through multiple cycles before completion.
const iterativeWorkflow = new LangGraphAgent({
name: "iterative_workflow",
description: "Quality improvement loop with maximum attempts",
rootNode: "process",
maxSteps: 15, // Allow more steps for iterations
nodes: [
{
name: "process",
agent: contentProcessor,
targets: ["quality-check"],
},
{
name: "quality-check",
agent: qualityAssessor,
targets: ["approve", "improve", "escalate"],
condition: (event: any) => {
const quality = JSON.parse(event.content);
const attempts =
event.session?.state?.get("improvement_attempts", 0) || 0;
if (quality.score >= 8) return true; // Approve
if (attempts >= 3) return false; // Escalate (condition false means try next target)
return false; // Improve (loop back)
},
},
{
name: "improve",
agent: improvementAgent,
targets: ["process"], // Loop back to process
},
{
name: "approve",
agent: approvalAgent,
},
{
name: "escalate",
agent: escalationAgent,
},
],
});Parallel Processing Integration
Integrate parallel processing capabilities within graph workflows to handle concurrent tasks. Use when you need to combine the benefits of parallel execution with conditional routing, such as consensus-based decision making or multi-perspective analysis.
const parallelIntegratedWorkflow = new LangGraphAgent({
name: "parallel_integrated_workflow",
description: "Workflow integrating parallel analysis for consensus decisions",
rootNode: "parallel-analysis",
maxSteps: 8,
nodes: [
{
name: "parallel-analysis",
agent: parallelAnalysisAgent, // ParallelAgent handling concurrent tasks
targets: ["proceed", "additional-review"],
condition: (event: any) => {
const results = JSON.parse(event.content);
const consensus = analyzeConsensus(results);
return consensus.agreement > 0.8; // Proceed if high agreement
},
},
{
name: "proceed",
agent: nextStepAgent,
},
{
name: "additional-review",
agent: reviewAgent,
},
],
});Design Best Practices
Design Principles
Start Simple: Begin with basic routing logic and add complexity gradually. Map out all possible paths before implementation to avoid unexpected edge cases and ensure comprehensive coverage.
Keep Nodes Focused: Design each node with a single, clear responsibility. A routing node should only handle decision logic, while processing nodes focus solely on their specific tasks. This separation improves maintainability and testing.
Handle Edge Cases: Always provide fallback routes for unexpected conditions and malformed data. Include error handling nodes and default paths to ensure your graph can reach a terminal state under all circumstances.
Test Thoroughly: Validate every possible execution path through your graph with real data. Test both expected scenarios and edge cases to ensure robust error handling and predictable behavior.
Communication Patterns
State Management: Use descriptive, unique state keys and document data flow between nodes. Clear state contracts prevent conflicts and make debugging easier when nodes don't receive expected data.
Progress Feedback: Provide meaningful progress updates during execution. Users need visibility into long-running workflows, especially those with multiple decision points and processing stages.
Development Tips
Flow Mapping: Plan your graph structure thoroughly before coding. Identify all entry points, decision criteria, and exit conditions to create a comprehensive workflow design.
Documentation: Document complex routing logic and state dependencies. Clear documentation is essential for maintaining and debugging sophisticated graph workflows.
Complexity Awareness: Be mindful of debugging challenges with complex graphs. Start with simpler patterns and gradually add sophistication as you understand the interaction patterns.
Graph Complexity Warning
- Start simple: Complex graphs are hard to debug and maintain - Document thoroughly: Clear documentation is crucial for complex flows - Test extensively: Every path and edge case should be tested
Related Topics
🔄 Sequential Agents
Building blocks that can be nodes within LangGraph workflows
⚡ Parallel Agents
Can be integrated as nodes for concurrent processing steps
🔁 Loop Agents
Can be used as nodes for iterative processing within graphs
🏗️ Agent Builder
Fluent API for creating LangGraph workflows with asLangGraph()
🤖 LLM Agents
Individual agents that serve as nodes in LangGraph workflows
How is this guide?