AI Hints
Home›LangGraph Tutorial›Send and Map-Reduce
LangGraph · Lesson 65 of 120

Map-Reduce with Send

Many in parallel.

⏱ 2 min read▶ Video at 1:09:12🎓 Free
Watch this lesson in the LangGraph courseWatch on YouTube ↗Full LangGraph course

Map reduce has two phases. Map, process every item in parallel. Reduce, combine the results into one answer. With Send for the map, and a normal node for the reduce, it fits naturally in a graph.

Map-Reduce with Send
From the video: Map-Reduce with Send
  • Map: each item
  • Reduce: combine
  • Send + a normal node

Pricing a basket

Fan out sends each basket line to the price line node. Each one works out its line total, in parallel. Then the edge to total waits for every branch. Total adds up the lines, and applies free delivery over twenty five pounds. Run it. Each line is priced, and the reduce step gives one final total.

map_reduce.pypython
import operator
from typing import Annotated, TypedDict
from langgraph.graph import StateGraph, START
from langgraph.types import Send

PRICES = {"Dune": 9.99, "Emma": 7.99, "Circe": 10.99}
class State(TypedDict):
    basket: dict
    lines: Annotated[list[float], operator.add]
    total: str

def fan_out(s): return [Send("price_line", {"title": t, "qty": q}) for t, q in s["basket"].items()]
def price_line(x): return {"lines": [round(PRICES[x["title"]] * x["qty"], 2)]}
def total(s):
    goods = round(sum(s["lines"]), 2)
    return {"total": f"lines {sorted(s['lines'])} = £{goods}, delivery {'free' if goods > 25 else '£2.99'}"}
b = StateGraph(State); b.add_node(price_line); b.add_node(total)
b.add_conditional_edges(START, fan_out, ["price_line"]); b.add_edge("price_line", "total")
print(b.compile().invoke({"basket": {"Dune": 2, "Emma": 1}, "lines": []})["total"])
Output
lines [7.99, 19.98] = £27.97, delivery free

Map-reduce shape

The shape is always the same. Start. A fan out function sends each item. The map node runs once per item, in parallel. The reduce node waits for all of them. Then the run ends.

  1. START
  2. fan_out → Send
  3. Map node × N
  4. Reduce node
  5. END
Map-reduce shape
From the video: Map-reduce shape

Summary

Map with Send, then reduce in a normal node that waits for every branch. Next, practise with model calls in the map step.

Key takeaways
  • Send for the map
  • Reducer collects
  • Reduce node combines
Next up: Practice: Review Summaries — Send in action