๐Ÿš€
๐Ÿ•ธ๏ธ LangGraph
6. Looping Graph
AI

Looping Graph ๐ŸŒŒ

1. Implement looping logic to route the flow of data to different nodes.

Mar 202510 min read

Looping Graph ๐ŸŒŒ

Objectives โœ…
  1. Implement looping logic to route the flow of data to different nodes.
  2. Create a single condition edge to handle decision-making and control graph flow.
from typing import TypedDict, List
import random
from langgraph.graph import StateGraph, START, END
 
class AgentState(TypedDict):
    name: str
    number: List[int]
    counter: int
def greeting_node(state: AgentState) -> AgentState:
    """Greet the user and ask for their name."""
 
    state['name'] = f"Hi, there, {state['name']}"
    state["counter"] = 0
 
    return state
 
def random_node(state: AgentState) -> AgentState:
    """Generate a random number and add it to the list."""
 
    state['number'].append(random.randint(1, 100))
    state["counter"] += 1
 
    return state
 
 
def should_continue(state: AgentState) -> AgentState:
    """Decide whether to continue looping based on the counter."""
 
    if state["counter"] < 5:
        print("ENTERING LOOP", state["counter"])
        return "loop"
    else:
        print("EXITING LOOP", state["counter"])
        return "end"
graph = StateGraph(AgentState)
 
graph.add_node("greeting_node", greeting_node)
graph.add_node("random_node", random_node)
 
graph.add_edge(START, "greeting_node")
graph.add_edge("greeting_node", "random_node")
 
graph.add_conditional_edges(
    "random_node",
    should_continue,
    {
        # Edge: Node
        "loop": "random_node",
        "end": END,
    },
)
 
app = graph.compile()
 

"looping graph"

app.invoke({"name": "Alice", "number": [], "counter": -1})
OUTPUT:
 
ENTERING LOOP 1
ENTERING LOOP 2
ENTERING LOOP 3
ENTERING LOOP 4
EXITING LOOP 5
{'name': 'Hi, there, Alice', 'number': [97, 13, 7, 70, 58], 'counter': 5}

ยฉ 2026 Driptanil Datta. All rights reserved.

Software Developer & Engineer

Disclaimer:The content provided on this blog is for educational and informational purposes only. While I strive for accuracy, all information is provided "as is" without any warranties of completeness, reliability, or accuracy. Any action you take upon the information found on this website is strictly at your own risk.

Copyright & IP:Certain technical content, interview questions, and datasets are curated from external educational sources to provide a centralized learning resource. Respect for original authorship is maintained; no copyright infringement is intended. All trademarks, logos, and brand names are the property of their respective owners.

System Operational

Built with Love โค๏ธ | Last updated: Mar 16 2026