Generative AIby Dhruv Narang

The Problem: Three Nodes, One Key

All three checks write their score into the same state key, at the same time.

The issue
The three nodes finish at the same moment. Each one returns an update for safety_scores.
The first try
Declare the key as a plain dictionary: safety_scores: dict[str, int].
Why it fails
LangGraph does not know how to combine three updates for one key in one step. It stops with an error.
The fix
Tell LangGraph how to merge them: a reducer.
The error, with a plain dictionary
InvalidUpdateError: Can receive only one value per step
The same error is in your teaching plan, where you break the code on purpose. We also got it when we tested on the installed LangGraph.

The Reducer: merge_score_dicts

A reducer tells LangGraph how to combine the updates instead of overwriting.

def merge_score_dicts(existing : dict , newUpdate:dict) -> dict:
    if existing is None:
        return newUpdate
    return {**existing, **newUpdate}

class AnlayzerState(TypedDict):
    raw_text : str
    safety_scores :Annotated[dict[str,int],merge_score_dicts]
Update arrivessafety_scores becomes
the start{}
{'toxicity': 50}{'toxicity': 50}
{'copyright_risk': 85}{'toxicity': 50, 'copyright_risk': 85}
{'cultural_insensitivity': 78}{'toxicity': 50, 'copyright_risk': 85, 'cultural_insensitivity': 78}
Example numbers, taken from your teaching plan. The three updates can arrive in any order, and the result has the same three keys.
existing
What safety_scores holds now.
newUpdate
The small dictionary a node just returned.
The merge
{**existing, **newUpdate} copies the old keys and adds the new ones. Nothing is lost.

Run It and Read the Result

We start with an empty dictionary and invoke the graph.

inital_state = {
    "raw_text":sample_script,
    "safety_scores":{}
}

res = app.invoke(inital_state)
print(res['safety_scores'])
Start
safety_scores begins as {}. The reducer adds each score to it.
Result
{'copyright_risk': 85, 'cultural_insensitivity': 78, 'toxicity': 50}
A clean text
Change sample_script to a clean text and the scores go down.
The result is from your teaching plan: your own run on the sample script. Your model may give other numbers. The sample script is deliberately bad, so the scores are high.

Other Reducers, and When to Use Parallel

You will meet two more reducers soon. Parallel flow is not always the right choice.

ReducerWhat it doesUsed for
merge_score_dictsmerges dictionaries (yours)scores from parallel checks
operator.adda ready-made reducer from Python: it joins listscollecting results from parallel nodes into one list
add_messagesa ready-made reducer from LangGraph: it adds chat messageschat history. MessagesState uses it.
Use parallel flow when…Be careful when…
the steps do not need each other's resultsone step needs another's output: that is sequential
you need all the results before moving onthe model API has a rate limit: three calls at once may be refused
waiting time mattersthe parallel nodes write the same key and you forgot the reducer
We tested operator.add and add_messages on the installed LangGraph, and both work as reducers.

Quick Revision

The whole lesson on one page.

Shape
Fan-out and fan-in
Several edges leave one node, the branches run together, and the graph continues when all are done.
The problem
One key, three writers
Without a reducer, LangGraph raises InvalidUpdateError when parallel nodes write the same key.
The fix
A reducer
Annotated[type, reducer] tells LangGraph how to merge. Yours merges dictionaries. operator.add joins lists.
Code
Parallel checks with a merge reducer01_parallel_reducers.py · 114 linesShow code
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import re
from typing import TypedDict , Annotated
from dotenv import load_dotenv

load_dotenv()

from langchain.chat_models import init_chat_model
from langgraph.graph import StateGraph , END , START
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from rich import print
parser = StrOutputParser()

model = init_chat_model("mistralai:open-mistral-nemo")



"""Reducer: tells LangGraph how to MERGE updates from parallel nodes, instead of overwriting"""
def merge_score_dicts(existing : dict , newUpdate:dict) -> dict:
    if existing is None:
        return newUpdate
    return {**existing, **newUpdate}


"""Annotated[type, reducer]: this key uses our reducer"""
class AnlayzerState(TypedDict):
    raw_text : str
    safety_scores :Annotated[dict[str,int],merge_score_dicts]


toxicity_prompt = ChatPromptTemplate.from_messages(
    [
    ("system","""Analyze the following text for profanity, aggression, hate speech, or toxicity. 
        Provide a score from 0 to 100, where 0 means perfectly clean and 100 means highly toxic. 
        Return ONLY the plain integer number, nothing else.\n\n"""),
    ("human", "Text:\n{raw_text}")
    ])

copyright_prompt = ChatPromptTemplate.from_messages(
    [
    ("system","""Analyze the following text. Judge if it sounds heavily plagiarized, unoriginal,
        or presents a corporate trademark risk. Provide a score from 0 to 100,
        where 0 means entirely original and 100 means high risk
        Return ONLY the plain integer number, nothing else.\n\n"""),
    ("human", "Text:\n{raw_text}")
    ])

culture_prompt = ChatPromptTemplate.from_messages(
    [
    ("system","""Analyze the following text for regional sensitivities, political landmines,
        or cultural insensitivity that might offend a global audience. Provide a score from 0 to 100,
        where 0 means completely safe and 100 means highly offensive.
        Return ONLY the plain integer number, nothing else.\n\n"""),
    ("human", "Text:\n{raw_text}")
    ])




def to_score(text:str) -> int:
    """LLM returns text like '85' or '85.' -> pull out the number so state really holds an int"""
    match = re.search(r"\d+", text)
    return int(match.group()) if match else -1


def toxicity_node(state :AnlayzerState) -> dict:
    chain = toxicity_prompt | model | parser
    score = chain.invoke({"raw_text":state["raw_text"]})
    return {"safety_scores":{"toxicity":to_score(score)}}

def copyright_node(state :AnlayzerState) -> dict:
    chain = copyright_prompt | model | parser
    score = chain.invoke({"raw_text":state["raw_text"]})
    return {"safety_scores":{"copyright_risk":to_score(score)}}

def culture_node(state :AnlayzerState) -> dict:
    chain = culture_prompt | model | parser
    score = chain.invoke({"raw_text":state["raw_text"]})
    return {"safety_scores":{"cultural_insensitivity":to_score(score)}}


builder = StateGraph(AnlayzerState)


builder.add_node("toxicity_node",toxicity_node)
builder.add_node("copyright_node",copyright_node)
builder.add_node("culture_node",culture_node)


"""Parallel: START goes to all 3 nodes, they run at the same time"""
builder.add_edge(START ,"toxicity_node")
builder.add_edge(START ,"copyright_node")
builder.add_edge(START ,"culture_node")


builder.add_edge("toxicity_node",END)
builder.add_edge("copyright_node",END)
builder.add_edge("culture_node",END)

app = builder.compile()

sample_script = """
    Yo guys! Welcome back to the stream. Today I am going to show you how to hack into 
    your friend's system using a script I copied directly from an online forum. 
    Honestly, traditional security protocols are absolute garbage and anyone still using 
    them is an absolute idiot. Let's dive into the code!
    """
    
inital_state = {
    "raw_text":sample_script,
    "safety_scores":{}
}
res = app.invoke(inital_state)
print(res['safety_scores'])