Graph Execution and Streaming

Back

Loading concept...

🎬 LangGraph: The Movie Director of AI Workflows

Imagine you’re a movie director. You have actors (AI nodes), a script (your logic), and scenes that flow from one to another. LangGraph is your director’s chair—it helps you orchestrate everything perfectly!


🎯 What We’ll Learn

Think of building an AI app like making a stop-motion movie:

  • Graph Compilation → Writing your script and getting cameras ready
  • Graph Execution → Yelling “Action!” and filming the scenes
  • Graph Streaming → Watching playback in real-time as you film
  • Graph Visualization → Drawing a storyboard of your movie
  • Send API → Filming multiple scenes at once with different crews
  • Command Pattern → Giving special director instructions mid-scene

📝 Graph Compilation: Getting Your Movie Ready

The Story

Before you film a movie, you need to:

  1. Write the script ✍️
  2. Hire the actors 🎭
  3. Set up the cameras 📷
  4. Make sure everything connects

Graph compilation is exactly this! You define your nodes (actors), edges (how scenes connect), and then “compile” it all into a ready-to-run movie.

How It Works

from langgraph.graph import StateGraph

# 1. Define your "movie state" - what info
#    passes between scenes
class MovieState:
    script: str
    scene_number: int

# 2. Create the graph (your movie blueprint)
graph = StateGraph(MovieState)

# 3. Add nodes (actors/scenes)
graph.add_node("opening", opening_scene)
graph.add_node("middle", middle_scene)
graph.add_node("finale", finale_scene)

# 4. Add edges (scene order)
graph.add_edge("opening", "middle")
graph.add_edge("middle", "finale")

# 5. COMPILE! 🎬 (Get cameras ready)
movie = graph.compile()

What Compilation Does

graph TD A["Define State"] --> B["Add Nodes"] B --> C["Add Edges"] C --> D["Set Entry Point"] D --> E["Compile!"] E --> F["Ready to Run ✅"]

Compilation checks:

  • ✅ All nodes are connected
  • ✅ No dead ends (orphan nodes)
  • ✅ Entry and exit points exist
  • ✅ State flows correctly

🎬 Graph Execution: Lights, Camera, Action!

The Story

Now your movie is ready. Time to yell “ACTION!” and watch everything unfold!

Graph execution runs your compiled graph from start to finish, passing data through each node like actors passing a baton in a relay race.

Simple Execution

# Your compiled graph from before
movie = graph.compile()

# Run it! Pass initial state.
result = movie.invoke({
    "script": "A hero's journey",
    "scene_number": 1
})

print(result)
# Output: Final state after all
# nodes have processed

The Flow

graph TD A["Start"] --> B["Node 1 Runs"] B --> C{Check Condition} C -->|Path A| D["Node 2A"] C -->|Path B| E["Node 2B"] D --> F["Final Node"] E --> F F --> G["Return Result"]

Key Point 🔑

Each node:

  1. Receives the current state
  2. Processes it (does its job)
  3. Returns updated state
  4. Passes it to the next node

📺 Graph Streaming: Watch the Magic Happen Live!

The Story

Imagine watching your movie being filmed through a live camera feed. You see each scene as it happens, not just the final cut!

Streaming lets you see results from each node as they complete—perfect for long-running AI tasks where you want progress updates.

Basic Streaming

# Stream mode shows output as it happens
for chunk in movie.stream({
    "script": "Epic adventure",
    "scene_number": 1
}):
    print(chunk)
    # See each node's output live!

Streaming Modes

Mode What You See Like…
values Full state after each node Watching full scene replays
updates Only what changed Seeing just the new footage
debug Everything! Director’s commentary on

Example with Mode

# Get only the changes
for update in movie.stream(
    {"script": "Mystery story"},
    stream_mode="updates"
):
    node_name = list(update.keys())[0]
    changes = update[node_name]
    print(f"Scene '{node_name}' added: {changes}")

Visual Flow

graph LR A["Node 1"] -->|stream| B["You See Output"] A --> C["Node 2"] C -->|stream| B C --> D["Node 3"] D -->|stream| B

🗺️ Graph Visualization: Draw Your Storyboard

The Story

Every good movie has a storyboard—a visual map of all the scenes. Graph visualization creates this map for your AI workflow!

Generate a Visual

# Get the visual representation
print(movie.get_graph().draw_ascii())

Output looks like:

    +-----------+
    | __start__ |
    +-----------+
          |
          v
    +-----------+
    |  opening  |
    +-----------+
          |
          v
    +-----------+
    |  middle   |
    +-----------+
          |
          v
    +-----------+
    |  finale   |
    +-----------+
          |
          v
    +-----------+
    |  __end__  |
    +-----------+

Mermaid Export

# Export as Mermaid diagram
mermaid_code = movie.get_graph().draw_mermaid()
print(mermaid_code)

Why Visualize?

  • 🐛 Debug: See if nodes connect correctly
  • 📖 Document: Share your workflow visually
  • 🧠 Understand: Complex graphs become clear
  • Validate: Spot missing connections

🚀 Send API: Film Multiple Scenes at Once!

The Story

What if you could film 3 different scenes simultaneously with 3 camera crews? That’s parallelism!

The Send API lets you spawn multiple paths from one node, running them all at the same time.

The Magic of Send

from langgraph.types import Send

def director_node(state):
    # Send work to 3 different actors
    # at the same time!
    return [
        Send("actor_1", {"line": "Hello!"}),
        Send("actor_2", {"line": "World!"}),
        Send("actor_3", {"line": "Wow!"}),
    ]

Visual: Fan-Out Pattern

graph TD A["Director"] --> B["Actor 1"] A --> C["Actor 2"] A --> D["Actor 3"] B --> E["Collector"] C --> E D --> E

Real Example: Parallel Research

def research_coordinator(state):
    topics = state["topics"]
    # Research all topics at once!
    return [
        Send("researcher", {"topic": t})
        for t in topics
    ]

graph.add_conditional_edges(
    "coordinator",
    research_coordinator
)

Key Benefits

Without Send With Send
Research Topic 1… wait Research ALL topics
Research Topic 2… wait …at the same time!
Research Topic 3… wait 3x faster! 🚀

🎮 Command Pattern: Director’s Special Instructions

The Story

Sometimes during filming, the director needs to give special instructions:

  • “Cut! Go back to scene 2!”
  • “Skip the next scene!”
  • “Update the script right now!”

The Command pattern lets you do exactly this—modify state AND control flow at the same time.

Basic Command

from langgraph.types import Command

def smart_node(state):
    if state["emergency"]:
        # COMMAND: Update state AND jump
        # to a specific node!
        return Command(
            update={"status": "handling emergency"},
            goto="emergency_handler"
        )
    else:
        return {"status": "all good"}

Command vs Regular Return

graph TD subgraph Regular Return A1["Node"] -->|follows edges| B1["Next Node"] end subgraph Command Pattern A2["Node"] -->|JUMP anywhere!| C2["Any Node"] A2 -->|Update state too| D2["New State"] end

Command Options

# Option 1: Just update state
Command(update={"score": 100})

# Option 2: Just jump to node
Command(goto="special_node")

# Option 3: Both at once!
Command(
    update={"score": 100},
    goto="celebration_node"
)

# Option 4: Jump and resume
Command(
    goto="checkpoint",
    resume=True  # Come back after!
)

When to Use Command

Situation Use Command?
Normal flow ❌ Regular return
Error handling ✅ Jump to error node
Dynamic routing ✅ Choose path at runtime
State + routing ✅ Update and jump
Loops/retries ✅ Go back to retry

🎯 Putting It All Together

Here’s a mini-movie that uses everything:

from langgraph.graph import StateGraph
from langgraph.types import Send, Command

class MovieState:
    scenes_done: list
    final_cut: str

def opening(state):
    return {"scenes_done": ["opening"]}

def parallel_filming(state):
    # Use Send for parallel work
    return [
        Send("scene_a", state),
        Send("scene_b", state),
    ]

def finale(state):
    if "error" in state:
        # Use Command for special routing
        return Command(
            update={"status": "fixing"},
            goto="error_handler"
        )
    return {"final_cut": "Complete!"}

# Build the graph
graph = StateGraph(MovieState)
graph.add_node("opening", opening)
graph.add_conditional_edges("opening",
    parallel_filming)
graph.add_node("scene_a", lambda s: s)
graph.add_node("scene_b", lambda s: s)
graph.add_node("finale", finale)

# Compile
movie = graph.compile()

# Execute with streaming
for frame in movie.stream({"scenes_done": []}):
    print(f"🎬 {frame}")

# Visualize
print(movie.get_graph().draw_ascii())

🏆 Summary: Your Director’s Toolkit

Tool Purpose Like…
Compile Prepare your graph Writing the script
Execute Run start to finish Filming the movie
Stream See live progress Live camera feed
Visualize Draw the flow Storyboard
Send Parallel paths Multiple crews
Command Dynamic control Director’s orders

💡 Remember

🎬 Compile once, Execute many times

📺 Stream when you need live updates

🗺️ Visualize to debug and document

🚀 Send when tasks can run in parallel

🎮 Command when you need dynamic control

You’re now ready to direct your own AI movies with LangGraph! 🎥✨

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.