Reducers and Annotated types

Topic 3 of 4 in State management28 min readBeginnerFree course

Overview

In the previous lesson, State schemas — TypedDict, Pydantic and dataclasses, you learned how to define the structure of a LangGraph application’s state. A schema specifies which fields exist, their expected data types, and the information that nodes can exchange.

However, defining the structure of state answers only half of an important question.

What should happen when a node returns a new value for a field that already contains data?

Consider an AI-powered research assistant. One node searches product documentation, another retrieves database records, and a third analyzes the collected information.

Each retrieval node produces a list of findings. If every new list replaces the previous list, valuable information disappears before the analysis node receives it.

We want the lists to accumulate instead.

Other fields require different behavior:

  • A conversation history should accumulate messages.
  • A processing cost should increase as operations execute.
  • A collection of tags should combine values without duplicates.
  • A workflow status should replace its previous value.
  • A temporary error buffer should accumulate errors until explicitly cleared.

LangGraph supports these behaviors through reducers.

A reducer defines how an incoming state update combines with the value already stored for a particular state field. Rather than implementing merge logic separately inside every node, you declare the merge behavior once in the state schema.

This separation allows nodes to concentrate on their individual responsibilities while LangGraph manages state aggregation.

Environment setup

The examples use Python 3.10 or later and current LangGraph 1.x APIs, including Overwrite.

Terminal
pip install -U "langgraph>=1.2,<2"

No language model, API key, database, or external service is required. The examples deliberately use deterministic Python functions so that you can understand state behavior independently of LLM responses.

Each complete example can be saved and run as a separate Python script. The APIs have been checked against the official documentation; the expected outputs are illustrative and the scripts have not been executed in the course-authoring environment.

The default: overwrite

Every field in a LangGraph state schema has an associated update behavior.

When you declare an ordinary field without a custom reducer, LangGraph uses replacement semantics. A new update replaces the existing value for that field.

For example, suppose the current state contains:

Python
{
    "status": "pending",
    "findings": ["Initial finding"],
    "attempts": 1,
}

A node returns:

Python
{
    "status": "processing",
    "findings": ["New finding"],
}

The resulting state contains:

Python
{
    "status": "processing",
    "findings": ["New finding"],
    "attempts": 1,
}

Notice that attempts remains unchanged because the node did not return an update for it.

However, the original findings list has been replaced.

LangGraph does not automatically concatenate lists, increment numbers, or recursively merge dictionaries simply because of their data types.

Example: observing the default behavior

The following workflow simulates two stages of a research operation. Both stages write to the same findings field.

Python
from typing import TypedDict

from langgraph.graph import StateGraph, START, END

class ResearchState(TypedDict):
    topic: str
    findings: list[str]
    status: str

def search_documentation(state: ResearchState):
    return {
        "findings": ["Documentation contains installation instructions."],
        "status": "researching",
    }

def search_database(state: ResearchState):
    return {
        "findings": ["Database contains three related records."],
        "status": "completed",
    }

builder = StateGraph(ResearchState)

builder.add_node("documentation", search_documentation)
builder.add_node("database", search_database)

builder.add_edge(START, "documentation")
builder.add_edge("documentation", "database")
builder.add_edge("database", END)

graph = builder.compile()

result = graph.invoke({
    "topic": "LangGraph",
    "findings": [],
    "status": "pending",
})

print(result)

Expected output:

Text
{
    'topic': 'LangGraph',
    'findings': ['Database contains three related records.'],
    'status': 'completed'
}

The documentation finding disappears because the database node replaces the entire findings list.

For status, replacement is desirable. The application should expose its current status rather than every status it previously held.

For findings, replacement causes information loss.

This illustrates why update behavior must be chosen separately for each field.

Partial updates versus complete state

A node does not normally need to return the complete state dictionary.

If a node changes only the status, its return value can be as simple as {"status": "completed"}.

LangGraph preserves other fields automatically.

This becomes particularly important when using reducers because returning unchanged accumulated values can accidentally apply those values again.

Treat a node’s return value as a collection of proposed state updates, not necessarily a replacement for the complete application state.

Adding a reducer with Annotated

Python provides a special typing construct called Annotated.

It allows developers to associate additional metadata with a type.

The general syntax is:

Python
Annotated[UnderlyingType, Metadata]

LangGraph interprets a suitable reducer function supplied as this metadata as the merge operation for that state field.

For example:

Python
import operator
from typing import Annotated, TypedDict

class State(TypedDict):
    findings: Annotated[list[str], operator.add]
    total_cost: Annotated[int, operator.add]
    status: str

Here, findings remains a list of strings, and total_cost remains an integer.

The annotation tells LangGraph how to combine updates. It does not convert those fields into functions or special container objects.

When the graph is constructed, LangGraph examines the state schema, including its annotation metadata, and configures the corresponding state channels.

Python itself does not automatically execute the reducer when you assign a dictionary value. The merging behavior belongs to the LangGraph runtime.

Understanding operator.add

The Python standard library’s operator.add function performs the same operation as the + operator.

For lists, addition concatenates the lists.

For integers, addition calculates their sum.

The following standalone example demonstrates this behavior.

Python
import operator

print(operator.add(["A"], ["B"]))
print(operator.add(10, 5))
print(operator.add("Hello ", "World"))

Expected output:

Text
['A', 'B']
15
Hello World

The operation depends on the types of its operands.

When attached to a list field, operator.add produces an accumulating list. When attached to an integer field, it produces an accumulating counter.

Example: accumulating findings and processing costs

This improved research workflow preserves findings from both nodes and tracks their processing costs.

Costs are represented as integer cents to avoid floating-point rounding problems.

Python
import operator
from typing import Annotated, TypedDict

from langgraph.graph import StateGraph, START, END

class ResearchState(TypedDict):
    topic: str
    findings: Annotated[list[str], operator.add]
    cost_cents: Annotated[int, operator.add]
    status: str

def search_documentation(state: ResearchState):
    return {
        "findings": ["Installation instructions found."],
        "cost_cents": 3,
        "status": "researching",
    }

def search_database(state: ResearchState):
    return {
        "findings": ["Three related records found."],
        "cost_cents": 5,
        "status": "completed",
    }

builder = StateGraph(ResearchState)

builder.add_node("documentation", search_documentation)
builder.add_node("database", search_database)

builder.add_edge(START, "documentation")
builder.add_edge("documentation", "database")
builder.add_edge("database", END)

graph = builder.compile()

result = graph.invoke({
    "topic": "LangGraph",
    "findings": [],
    "cost_cents": 0,
    "status": "pending",
})

print("Findings:", result["findings"])
print("Cost:", result["cost_cents"])
print("Status:", result["status"])

Expected output:

Text
Findings: ['Installation instructions found.', 'Three related records found.']
Cost: 8
Status: completed

The graph now combines three distinct update behaviors.

Field Initial value After documentation After database
findings [] ["Installation instructions found."] Both findings
cost_cents 0 3 8
status "pending" "researching" "completed"

The nodes do not need to implement their own accumulation logic.

Each node returns only the findings it produced and the cost it incurred.

How reducers work internally

Conceptually, a reducer is a function that receives two arguments:

Python
def reducer(current_value, incoming_update):
    return merged_value

The first argument represents the value currently stored in the channel. The second represents a new contribution to that channel.

LangGraph stores state through internal channels. Ordinary fields generally use a last-value channel, while fields annotated with binary reducers use an aggregating channel called BinaryOperatorAggregate.

When updates are applied, the runtime combines the channel’s existing value with incoming contributions using the configured function.

The following diagram illustrates how two sequential updates accumulate.

Adding a reducer with Annotated diagram: START to Initial State; Initial State to Documentation Node; Documentation Node to Merge First Update; Merge First Update to Database Node; Database Node to Merge Second Update; Merge Second Update to Final State; Final State to END.

For the processing cost, the conceptual operations are:

Python
current_cost = 0

current_cost = operator.add(current_cost, 3)
current_cost = operator.add(current_cost, 5)

print(current_cost)  # 8

For ordinary fields, a single incoming update simply replaces the previous value.

The runtime applies these updates before downstream nodes read the resulting state.

Choosing initial values

A reducer needs a suitable starting value.

For common additive fields, LangGraph can initialize supported channel types using their empty values, such as an empty list or zero. Nevertheless, explicitly supplying initial values makes beginner examples easier to understand and application behavior easier to reason about.

Typical starting values include:

Reducer behavior Initial value
List concatenation []
Integer addition 0
String concatenation ""
Dictionary merging {}
Set union set()

These values act as identities for their respective operations. Combining them with a contribution does not change that contribution.

Not every reducer has an obvious default identity. For example, zero is not an appropriate initial maximum when all legitimate values may be negative.

Avoiding double accumulation

Suppose a reduced counter currently contains 10.

This update is incorrect if the intention is to increase the counter by one:

Python
return {"count": state["count"] + 1}

The node returns 11, which the reducer adds to the existing 10, producing 21.

The correct update is:

Python
return {"count": 1}

The same principle applies to lists. Returning the existing findings plus a new finding causes the previous findings to be appended again.

Note: For accumulating fields, return the new contribution rather than the complete accumulated value. Let LangGraph apply the reducer.

Writing your own reducer

Built-in addition works well for simple accumulation, but real applications often require more sophisticated merge behavior.

For example, an AI assistant may classify customer requests using multiple specialized nodes. Each node produces tags such as billing, technical, or urgent.

If both nodes return the urgent tag, ordinary list concatenation produces duplicate entries.

A custom reducer can eliminate those duplicates.

Example: merging unique tags

The following complete workflow combines tags from two classification stages and stores them in a predictable alphabetical order.

Python
from typing import Annotated, TypedDict

from langgraph.graph import StateGraph, START, END

def merge_unique_tags(
    existing: list[str],
    incoming: list[str],
) -> list[str]:
    return sorted(set(existing) | set(incoming))

class TicketState(TypedDict):
    ticket: str
    tags: Annotated[list[str], merge_unique_tags]

def classify_billing(state: TicketState):
    return {
        "tags": ["billing", "urgent"],
    }

def classify_technical(state: TicketState):
    return {
        "tags": ["technical", "urgent"],
    }

builder = StateGraph(TicketState)

builder.add_node("billing", classify_billing)
builder.add_node("technical", classify_technical)

builder.add_edge(START, "billing")
builder.add_edge("billing", "technical")
builder.add_edge("technical", END)

graph = builder.compile()

result = graph.invoke({
    "ticket": "Payment failed and account access is blocked.",
    "tags": ["customer"],
})

print(result["tags"])

Expected output:

Text
['billing', 'customer', 'technical', 'urgent']

The reducer converts both lists into sets, combines them using set union, and converts the result into a sorted list.

Although the function uses sets internally, the stored state remains a list of strings.

This makes the resulting data straightforward to serialize as JSON and ensures consistent ordering.

Choosing the right merge semantics

Different state fields represent different business requirements.

Requirement Reducer Behavior
Current workflow status No custom reducer Replace previous value
Research findings operator.add Concatenate lists
Processing costs operator.add Add increments
Unique classifications Custom set union Remove duplicates
Nonnegative maximum score max Retain highest score
Minimum threshold Custom binary minimum Retain lowest applicable value
Structured records Custom dictionary merge Combine keyed entries
Conversation history add_messages Merge messages by identity

A custom reducer is useful whenever the standard behavior does not accurately represent the meaning of your data.

Example: merging retrieval scores

Imagine two search systems returning document IDs and relevance scores.

When the same document appears in both systems, you want to retain its highest score instead of arbitrarily replacing one result with another.

The following runnable Python example demonstrates and tests such a reducer independently of LangGraph.

Python
def merge_scores(
    existing: dict[str, int],
    incoming: dict[str, int],
) -> dict[str, int]:
    result = existing.copy()

    for document_id, score in incoming.items():
        if document_id in result:
            result[document_id] = max(
                result[document_id],
                score,
            )
        else:
            result[document_id] = score

    return result

first = {
    "doc_1": 80,
    "doc_2": 65,
}

second = {
    "doc_1": 90,
    "doc_3": 75,
}

result = merge_scores(first, second)

print(result)

assert result == {
    "doc_1": 90,
    "doc_2": 65,
    "doc_3": 75,
}

assert first["doc_1"] == 80
assert merge_scores(result, second) == result

Expected output:

Text
{'doc_1': 90, 'doc_2': 65, 'doc_3': 75}

To use this reducer in a graph, attach it to a field using Annotated[dict[str, int], merge_scores].

This pattern is particularly valuable in retrieval-augmented generation systems, where several retrieval strategies may discover overlapping documents.

Properties of reliable reducers

A production-quality reducer should ideally have several mathematical and programming properties.

Determinism: Given the same inputs, the reducer should produce the same result. Avoid random values, current timestamps, and external service calls inside reducers.

Purity: A reducer should not modify its input objects or perform external side effects. It should calculate and return a merged value.

Associativity: Grouping updates differently should not change the result.

Text
merge(merge(a, b), c) = merge(a, merge(b, c))

Commutativity: Changing the order of updates should not change the result.

Text
merge(a, b) = merge(b, a)

Idempotency: Applying the same contribution repeatedly should not change the result after its first application.

Text
merge(merge(a, b), b) = merge(a, b)

Not every reducer needs all these properties.

List concatenation is associative but not commutative or idempotent. Integer addition is associative and commutative but not idempotent.

Deduplicating tags through sorted set union satisfies all three mathematical properties for the intended tag-collection semantics.

These properties become especially valuable when applications combine parallel results or handle repeated logical contributions.

They are design considerations, not requirements that LangGraph automatically enforces.

Replacing a reduced value

Once a field has an additive reducer, returning an ordinary value always applies that merge behavior.

Suppose an error buffer currently contains:

Python
["Database timeout", "Invalid response"]

Returning an empty list does not clear it.

Python
return {"errors": []}

The effective operation is concatenation with an empty list, which preserves the previous errors.

Similarly, returning zero to an additive counter does not reset it.

You need a way to explicitly bypass the reducer.

Using Overwrite

LangGraph provides the Overwrite wrapper for directly replacing a reducer-managed value.

Import it from langgraph.types.

The following workflow accumulates processing errors, clears them, and then records a successful validation event.

Python
import operator
from typing import Annotated, TypedDict

from langgraph.graph import StateGraph, START, END
from langgraph.types import Overwrite

class ProcessingState(TypedDict):
    errors: Annotated[list[str], operator.add]
    attempts: Annotated[int, operator.add]
    events: Annotated[list[str], operator.add]

def process_request(state: ProcessingState):
    return {
        "errors": ["Invalid request format"],
        "attempts": 1,
        "events": ["Processing failed"],
    }

def reset_processing(state: ProcessingState):
    return {
        "errors": Overwrite(value=[]),
        "attempts": Overwrite(value=0),
        "events": ["Processing state reset"],
    }

def validate_request(state: ProcessingState):
    return {
        "attempts": 1,
        "events": ["Validation succeeded"],
    }

builder = StateGraph(ProcessingState)

builder.add_node("process", process_request)
builder.add_node("reset", reset_processing)
builder.add_node("validate", validate_request)

builder.add_edge(START, "process")
builder.add_edge("process", "reset")
builder.add_edge("reset", "validate")
builder.add_edge("validate", END)

graph = builder.compile()

result = graph.invoke({
    "errors": [],
    "attempts": 0,
    "events": [],
})

print(result)

Expected output:

Text
{
    'errors': [],
    'attempts': 1,
    'events': [
        'Processing failed',
        'Processing state reset',
        'Validation succeeded'
    ]
}

The reset node clears errors and resets the attempt counter without affecting the accumulated event history.

Importantly, Overwrite bypasses the reducer for that particular update. It does not remove the reducer from the state schema.

The validation node’s subsequent increment is therefore processed normally.

Ordinary updates versus Overwrite

Assume the current list contains ["A", "B"] and uses operator.add.

Returned update Resulting value
["C"] ["A", "B", "C"]
[] ["A", "B"]
["A"] ["A", "B", "A"]
Overwrite(value=["C"]) ["C"]
Overwrite(value=[]) []
Field omitted ["A", "B"]

Use Overwrite for intentional replacement, resetting temporary buffers, or replacing an aggregate with a compacted representation.

If checkpointing is enabled, replacing the current value does not automatically erase historical checkpoints containing earlier values. State replacement and historical data deletion are different operations.

See the official Overwrite API reference for its supported semantics.

Reducers and parallel branches

Reducers become especially important when multiple graph nodes execute concurrently.

Consider a research assistant that needs to search both product documentation and an internal knowledge base.

Neither search depends on the other’s result, so they can execute in parallel.

After both searches finish, a synthesis node receives their combined findings.

This pattern is known as fan-out and fan-in.

The following diagram shows parallel retrieval followed by aggregation and synthesis.

Reducers and parallel branches diagram: START to Search Documentation; START to Search Knowledge Base; Search Documentation to Merge Findings; Search Knowledge Base to Merge Findings; Merge Findings to Synthesize Results; Synthesize Results to END.

Understanding super-steps

LangGraph’s execution model is based on a message-passing system inspired by Pregel.

A graph advances through execution rounds called super-steps.

During a parallel super-step, sibling nodes read the available state from the beginning of that round and produce their own updates.

Their contributions are subsequently applied to the relevant channels. Downstream nodes then receive the merged state.

One parallel branch should not assume that it can immediately read an update produced by another branch in the same super-step.

Reducers resolve the data aggregation problem, while graph edges determine when downstream processing takes place.

What happens without a reducer?

If two parallel nodes return updates to the same ordinary state field, LangGraph cannot safely determine which value should be retained.

Instead of silently choosing one, it raises an InvalidUpdateError, associated with the INVALID_CONCURRENT_GRAPH_UPDATE error.

This restriction applies even if both nodes happen to return identical values.

The following runnable example deliberately demonstrates the problem.

Python
from typing import TypedDict

from langgraph.graph import StateGraph, START, END
from langgraph.errors import InvalidUpdateError

class State(TypedDict):
    findings: list[str]

def search_a(state: State):
    return {"findings": ["Finding A"]}

def search_b(state: State):
    return {"findings": ["Finding B"]}

builder = StateGraph(State)

builder.add_node("search_a", search_a)
builder.add_node("search_b", search_b)

builder.add_edge(START, "search_a")
builder.add_edge(START, "search_b")

builder.add_edge("search_a", END)
builder.add_edge("search_b", END)

graph = builder.compile()

try:
    graph.invoke({"findings": []})
except InvalidUpdateError:
    print("Concurrent state update detected.")
else:
    raise AssertionError("Expected a concurrent update error.")

Expected output:

Text
Concurrent state update detected.

This is a state design problem rather than a temporary infrastructure failure.

Retrying the graph without changing its merge strategy will not resolve the underlying conflict.

Example: combining parallel retrieval results

The following complete workflow fixes the conflict using an additive reducer and an explicit join edge.

Python
import operator
from typing import Annotated, TypedDict

from langgraph.graph import StateGraph, START, END

class ResearchState(TypedDict):
    query: str
    findings: Annotated[list[str], operator.add]
    documents_searched: Annotated[int, operator.add]
    report: str

def search_documentation(state: ResearchState):
    return {
        "findings": [
            "Documentation: Reducers combine state updates."
        ],
        "documents_searched": 2,
    }

def search_knowledge_base(state: ResearchState):
    return {
        "findings": [
            "Knowledge base: Parallel branches need merge rules."
        ],
        "documents_searched": 3,
    }

def synthesize(state: ResearchState):
    ordered_findings = sorted(state["findings"])

    report = (
        f"Query: {state['query']}\n"
        f"Documents searched: {state['documents_searched']}\n"
        + "\n".join(ordered_findings)
    )

    return {"report": report}

builder = StateGraph(ResearchState)

builder.add_node("documentation", search_documentation)
builder.add_node("knowledge_base", search_knowledge_base)
builder.add_node("synthesize", synthesize)

builder.add_edge(START, "documentation")
builder.add_edge(START, "knowledge_base")

builder.add_edge(
    ["documentation", "knowledge_base"],
    "synthesize",
)

builder.add_edge("synthesize", END)

graph = builder.compile()

result = graph.invoke({
    "query": "How do reducers work?",
    "findings": [],
    "documents_searched": 0,
    "report": "",
})

print(result["report"])

assert result["documents_searched"] == 5
assert len(result["findings"]) == 2

Expected output:

Text
Query: How do reducers work?
Documents searched: 5
Documentation: Reducers combine state updates.
Knowledge base: Parallel branches need merge rules.

Both retrieval branches contribute to the same findings list and numeric counter.

The list-form edge ensures that synthesis waits for both named retrieval nodes to complete.

Only the synthesis node writes to report, so that field does not need an accumulating reducer.

Ordering and concurrent replacements

Do not depend on the order in which parallel list contributions appear in state.

Even when a particular graph consistently produces the same order during testing, that order should not become an implicit business requirement.

When ordering matters, attach explicit ordering information to each contribution and sort the merged results in a downstream node.

For example, research findings could include a relevance score, source identifier, or sequence number.

Concurrent use of Overwrite also requires special care. Multiple overwrite operations targeting the same reduced field within one super-step raise an InvalidUpdateError. A single overwrite can also discard ordinary contributions targeting that field during the same step.

Perform resets and replacements in a dedicated sequential node after all contributing branches have completed.

Tip: A reducer solves how values are combined; a join edge solves when the combined values are ready to use. Parallel workflows frequently require both.

For more details, consult the official documentation on parallel control flow and concurrent update errors.

Common mistakes and production best practices

Mutating state directly

Avoid calling methods such as state["findings"].append(...) inside a node and assuming that the runtime will handle the change correctly.

Instead, return a new contribution.

Treat incoming state as read-only application data. Likewise, custom reducers should return newly constructed collections rather than modifying their arguments.

This prevents unintended shared-object changes and makes behavior easier to test.

Using reducers on every field

Not every field benefits from accumulation.

Current status, selected model, final answer, active task, and most configuration-like values generally require replacement semantics.

Adding reducers unnecessarily can produce invalid application behavior, obscure ownership of state fields, and increase debugging complexity.

Choose reducers based on the meaning of the data.

Allowing state to grow indefinitely

An additive list continues growing as new contributions arrive.

In long-running agents, this can increase memory consumption, checkpoint storage requirements, serialization overhead, and potentially model input token usage.

Use bounded buffers, deduplication, explicit compaction nodes, or external storage for large collections.

Be deliberate about which information belongs in active graph state and which information belongs in durable application storage.

Confusing accumulation with persistence

Reducers control how state changes. They do not automatically preserve state between independent graph invocations.

Persistent conversational sessions require a checkpointer and a thread identifier.

When persistence is introduced later in the course, remember that new input updates can also merge into existing checkpointed state. Avoid repeatedly supplying historical accumulated values as though they were new contributions.

Testing merge behavior

Test custom reducers independently before integrating them into a graph.

Include empty inputs, overlapping records, duplicate contributions, conflicting values, and reversed update ordering where appropriate.

Then test the compiled graph to verify that the runtime applies those reducers correctly.

An idempotent reducer can protect against duplicate logical contributions, but it does not guarantee exactly-once execution of external API calls, payments, or database writes.

Those side effects require separate reliability mechanisms.

The official state management guide provides additional details about configuring state fields and replacement behavior.

Connecting reducers to conversational agents

The chapter’s hands-on project involves building a stateful conversational application.

A conversation naturally requires accumulation: when a user sends another message, the assistant generally needs access to previous messages.

An additive list reducer appears to be a reasonable starting point.

However, real conversations require more than list concatenation. Applications may need to edit existing messages, remove selected messages, deserialize incoming message representations, and associate tool results with earlier tool calls.

LangGraph provides a specialized reducer named add_messages for message-oriented state.

Unlike ordinary list concatenation, it understands message identities and supports updating existing messages by ID.

The next lesson, MessagesState and add_messages, explores this specialized reducer and LangGraph’s built-in MessagesState schema.

You will apply the state-merging principles learned here to build conversation histories that support human messages, AI responses, tool results, and subsequent conversational turns.

Exercise

Build a parallel support ticket processor

Build a LangGraph workflow that processes a customer support ticket through two parallel branches for billing analysis and technical analysis. Use a custom reducer to combine unique tags, an additive reducer to accumulate processing costs in cents, and a regular state field to track the current status. Add a final node that waits for both branches, generates a report, and clears temporary processing notes using Overwrite.

Python
import operator
from typing import Annotated, TypedDict

from langgraph.graph import StateGraph, START, END
from langgraph.types import Overwrite


def merge_tags(
    existing: list[str],
    incoming: list[str],
) -> list[str]:
    # TODO: Combine tags, remove duplicates, and sort them.
    raise NotImplementedError


class TicketState(TypedDict):
    ticket: str
    status: str

    # TODO: Attach the appropriate reducers.
    tags: list[str]
    cost_cents: int
    notes: list[str]

    report: str


def billing_analysis(state: TicketState):
    # TODO: Return billing and urgent tags,
    # a cost of 3 cents, and a processing note.
    raise NotImplementedError


def technical_analysis(state: TicketState):
    # TODO: Return technical and urgent tags,
    # a cost of 5 cents, and a processing note.
    raise NotImplementedError


def finalize_ticket(state: TicketState):
    # TODO: Generate a report using the merged state.
    # Set status to completed and clear the notes.
    raise NotImplementedError


builder = StateGraph(TicketState)

builder.add_node("billing", billing_analysis)
builder.add_node("technical", technical_analysis)
builder.add_node("finalize", finalize_ticket)

# TODO: Connect START to both analysis nodes.
# TODO: Join both branches before running finalize.
# TODO: Connect finalize to END.

graph = builder.compile()

result = graph.invoke({
    "ticket": "Charged twice and unable to log in.",
    "status": "pending",
    "tags": [],
    "cost_cents": 0,
    "notes": [],
    "report": "",
})

print(result)

assert result["tags"] == ["billing", "technical", "urgent"]
assert result["cost_cents"] == 8
assert result["status"] == "completed"
assert result["notes"] == []

Summary

  • LangGraph replaces existing state values by default unless a field declares a custom reducer.
  • Python's Annotated type attaches reducer functions to individual state fields without changing their underlying data types.
  • The operator.add reducer concatenates lists and adds numeric increments to existing values.
  • Nodes should return partial updates containing new contributions rather than complete accumulated state.
  • Custom reducers should be deterministic, free of side effects, and designed to handle the expected merge semantics.
  • The Overwrite wrapper bypasses a reducer and directly replaces or resets an accumulated state value.
  • Parallel nodes writing to the same state field require an appropriate reducer or an alternative strategy for resolving concurrent updates.