Bird
Raised Fist0
LangChainframework~20 mins

Conditional routing in graphs in LangChain - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
LangChain Conditional Routing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this LangChain graph with conditional routing?

Consider a LangChain graph where the routing depends on the input text length. The graph routes to NodeA if the input length is less than 10, otherwise to NodeB. What will be the output if the input is 'Hello'?

LangChain
from langchain.graphs import Graph
from langchain.chains import LLMChain

class NodeA(LLMChain):
    def run(self, input_text):
        return f"Short input processed: {input_text}"

class NodeB(LLMChain):
    def run(self, input_text):
        return f"Long input processed: {input_text}"

class ConditionalGraph(Graph):
    def route(self, input_text):
        if len(input_text) < 10:
            return NodeA()
        else:
            return NodeB()

graph = ConditionalGraph()
result = graph.route('Hello').run('Hello')
print(result)
ATypeError at runtime
B"Long input processed: Hello"
C"Short input processed: Hello"
DSyntaxError at runtime
Attempts:
2 left
💡 Hint

Check the length of the input string and which node the graph routes to.

state_output
intermediate
2:00remaining
What is the state of the graph after routing with input 'This is a test input'?

Given a LangChain graph that stores the last routed node name in its state, what will be the value of graph.state['last_node'] after routing the input 'This is a test input'?

LangChain
from langchain.graphs import Graph

class StatefulGraph(Graph):
    def __init__(self):
        super().__init__()
        self.state = {}

    def route(self, input_text):
        if len(input_text) < 10:
            self.state['last_node'] = 'NodeA'
            return 'NodeA'
        else:
            self.state['last_node'] = 'NodeB'
            return 'NodeB'

graph = StatefulGraph()
graph.route('This is a test input')
print(graph.state['last_node'])
A"NodeB"
BNone
C"NodeA"
DKeyError: 'last_node'
Attempts:
2 left
💡 Hint

Check the length of the input and which node the graph sets in its state.

📝 Syntax
advanced
2:00remaining
Which option will cause a syntax error in defining a conditional routing graph?

Identify the code snippet that will cause a syntax error when defining a LangChain graph with conditional routing.

LangChain
from langchain.graphs import Graph

class MyGraph(Graph):
    def route(self, input_text):
        match input_text:
            case str() if len(input_text) < 5:
                return 'ShortNode'
            case str() if len(input_text) >= 5:
                return 'LongNode'

graph = MyGraph()
AMissing colon after 'case str() if len(input_text) >= 5' causes SyntaxError
BUsing 'match' without 'case' causes SyntaxError
CIndentation error in 'return' statement causes SyntaxError
DNo syntax error in the code
Attempts:
2 left
💡 Hint

Look carefully at the syntax of the match-case statements.

🔧 Debug
advanced
2:00remaining
Why does this LangChain graph raise a KeyError during routing?

Given the following graph code, why does calling graph.route('test') raise a KeyError?

LangChain
from langchain.graphs import Graph

class DebugGraph(Graph):
    def __init__(self):
        super().__init__()
        self.state = {}

    def route(self, input_text):
        if input_text == 'test':
            return self.state['node']
        else:
            self.state['node'] = 'NodeX'
            return 'NodeX'

graph = DebugGraph()
graph.route('test')
AThe 'state' dictionary is not initialized, causing AttributeError
BThe 'input_text' variable is undefined causing NameError
CThe 'route' method returns None causing TypeError
DThe 'node' key is not set in state before access, causing KeyError
Attempts:
2 left
💡 Hint

Check when the 'node' key is added to the state dictionary.

🧠 Conceptual
expert
2:00remaining
Which option best describes conditional routing in LangChain graphs?

Choose the most accurate description of how conditional routing works in LangChain graphs.

ARouting is fixed at graph creation and cannot change based on input or state.
BRouting decisions are made dynamically based on input data or state, allowing different nodes to process different inputs.
CRouting depends only on the order nodes were added to the graph, ignoring input content.
DRouting is random and does not consider input or state.
Attempts:
2 left
💡 Hint

Think about how graphs can adapt to different inputs.

Practice

(1/5)
1. What is the main purpose of conditional routing in Langchain graphs?
easy
A. To randomly select a node without any rules
B. To execute all nodes in parallel regardless of conditions
C. To stop the graph execution immediately
D. To choose the next node based on specific conditions

Solution

  1. Step 1: Understand conditional routing concept

    Conditional routing means selecting the next step based on rules or conditions.
  2. Step 2: Match purpose with options

    Only To choose the next node based on specific conditions describes choosing the next node based on conditions, which fits the concept.
  3. Final Answer:

    To choose the next node based on specific conditions -> Option D
  4. Quick Check:

    Conditional routing = choose next node by condition [OK]
Hint: Think: routing means choosing path by rules [OK]
Common Mistakes:
  • Confusing routing with parallel execution
  • Assuming routing stops the graph
  • Thinking routing is random
2. Which of the following is the correct way to define a condition function for routing in Langchain?
easy
A. def condition(context): return context['value'] > 10
B. condition = context => context.value > 10
C. def condition(): return context['value'] > 10
D. condition(context): return context.value > 10

Solution

  1. Step 1: Check function syntax in Python

    Python functions require 'def' keyword, a parameter list, and a return statement.
  2. Step 2: Validate each option

    def condition(context): return context['value'] > 10 correctly defines a function with one parameter and returns a boolean. condition = context => context.value > 10 uses JavaScript syntax. def condition(): return context['value'] > 10 misses the parameter. condition(context): return context.value > 10 misses 'def' keyword.
  3. Final Answer:

    def condition(context): return context['value'] > 10 -> Option A
  4. Quick Check:

    Python function with parameter and return = def condition(context): return context['value'] > 10 [OK]
Hint: Remember Python function syntax: def name(params): return value [OK]
Common Mistakes:
  • Using JavaScript arrow function syntax in Python
  • Omitting function parameters
  • Missing 'def' keyword
3. Given this routing setup in Langchain graph:
conditions = [
  lambda ctx: ctx['score'] > 80,
  lambda ctx: ctx['score'] > 50
]
routes = ['high', 'medium', 'low']
context = {'score': 65}

Which route will be chosen?
medium
A. "high"
B. "medium"
C. "low"
D. Error due to missing condition

Solution

  1. Step 1: Evaluate conditions in order with context

    First condition: score > 80? 65 > 80 is False. Second condition: score > 50? 65 > 50 is True.
  2. Step 2: Match true condition to route

    Second condition matches, so route at index 1 is chosen, which is "medium".
  3. Final Answer:

    "medium" -> Option B
  4. Quick Check:

    First true condition index = route chosen [OK]
Hint: Check conditions top to bottom, pick first true route [OK]
Common Mistakes:
  • Choosing 'high' because 65 > 50 but ignoring order
  • Picking 'low' when conditions match
  • Assuming error if not all conditions true
4. Identify the error in this Langchain routing code snippet:
def route_condition(context):
  if context['value'] > 10:
    return True
  elif context['value'] < 5:
    return False

routes = ['path1', 'path2']
# Routing uses route_condition
medium
A. Routes list should have three paths
B. The function uses wrong comparison operators
C. The function does not return a value for all cases
D. The function should return strings, not booleans

Solution

  1. Step 1: Check function return paths

    The function returns True if value > 10, False if value < 5, but returns nothing if value is between 5 and 10.
  2. Step 2: Understand routing condition requirements

    Routing conditions must return a boolean for every input to decide path. Missing return causes errors or unexpected behavior.
  3. Final Answer:

    The function does not return a value for all cases -> Option C
  4. Quick Check:

    All code paths must return a boolean [OK]
Hint: Ensure all if/else paths return a value [OK]
Common Mistakes:
  • Ignoring missing return in some cases
  • Thinking routes count must match conditions exactly
  • Returning wrong data types
5. You want to route a Langchain graph node based on user input where:
- If input contains "urgent", go to 'priority' node
- If input length > 100, go to 'long' node
- Otherwise, go to 'normal' node

Which conditional routing setup correctly implements this logic?
hard
A. conditions = [lambda ctx: 'urgent' in ctx['input'], lambda ctx: len(ctx['input']) > 100] routes = ['priority', 'long', 'normal']
B. conditions = [lambda ctx: len(ctx['input']) > 100, lambda ctx: 'urgent' in ctx['input']] routes = ['long', 'priority', 'normal']
C. conditions = [lambda ctx: 'urgent' in ctx['input'] and len(ctx['input']) > 100] routes = ['priority', 'long', 'normal']
D. conditions = [lambda ctx: 'urgent' not in ctx['input'], lambda ctx: len(ctx['input']) <= 100] routes = ['normal', 'long', 'priority']

Solution

  1. Step 1: Match conditions to requirements in order

    First condition checks if 'urgent' is in input, matching priority route. Second checks input length > 100 for long route.
  2. Step 2: Confirm routes order matches conditions plus default

    Routes list has 'priority', 'long', then 'normal' as default if no condition matches.
  3. Final Answer:

    conditions = [lambda ctx: 'urgent' in ctx['input'], lambda ctx: len(ctx['input']) > 100] routes = ['priority', 'long', 'normal'] -> Option A
  4. Quick Check:

    Order and logic match requirements [OK]
Hint: Order conditions by priority, add default route last [OK]
Common Mistakes:
  • Swapping condition order and routes
  • Combining conditions incorrectly
  • Using negated conditions that break logic