Your first graph
Overview
In the previous lesson, you installed LangGraph and prepared your Python development environment. You are now ready to build your first working LangGraph application.
Every sophisticated agentic AI system begins with a fundamental engineering problem: how do we coordinate multiple operations while maintaining the information they need to communicate?
Consider a document-processing application that must clean incoming text, extract important information, generate a summary, validate the summary, and eventually return a response. Each operation depends on information produced by earlier operations.
You could implement this using ordinary Python function calls. However, as the workflow grows to include branching decisions, repeated model calls, tool execution, error recovery, and human approval, manually managing execution becomes increasingly difficult.
LangGraph provides a structured execution model for these workflows.
In this lesson, you will build a two-step sequential graph that cleans an input string and counts the words in the cleaned text.
The application intentionally does not use a language model. This allows you to understand the orchestration mechanics without introducing API credentials, model latency, unpredictable responses, or inference costs.
By the end of the lesson, you will be able to:
- Define a graph’s shared state using
TypedDict. - Implement nodes as ordinary Python functions.
- Register nodes and connect them with directed edges.
- Compile and execute a graph.
- Observe intermediate state updates.
- Construct sequential workflows using
add_sequence.
Preparing the environment
Continue using the virtual environment created in the previous lesson. If necessary, install or update LangGraph:
python -m pip install "langgraph>=1.1,<2"Use Python 3.11 or later for the examples in this lesson. The minimum LangGraph version above also supports the v2 streaming format used later.
No OpenAI API key, database, or separate LangChain installation is required for these examples.
Note: The examples use the current LangGraph 1.x API documented in the official LangGraph Graph API reference. The displayed outputs are expected results; the examples have been reviewed against the API documentation but were not executed in a live LangGraph environment during lesson preparation.
Understanding the application architecture
Our application accepts text containing unnecessary whitespace. The first node normalizes that whitespace, and the second node counts the resulting words.
The following diagram represents the complete execution path.
This graph is directed because its edges have a specific direction. It is sequential because each processing node runs after its predecessor. It is also acyclic because no execution path leads back to an earlier node.
LangGraph also supports cyclic graphs, which are particularly important when building agents that repeatedly reason, call tools, and evaluate results. For now, we will concentrate on the simplest execution pattern.
The Graph API revolves around three primary components.
| Component | Responsibility | Example |
|---|---|---|
| State | Holds information used during execution | Original text and word count |
| Node | Performs an operation | Clean the text |
| Edge | Controls execution flow | Run counting after cleaning |
| START | Identifies the workflow entry | Activate the cleaning node |
| END | Marks a terminating path | Finish processing |
| Compiled graph | Executes the defined workflow | Process an input dictionary |
A useful mental model is that nodes perform the work, state carries information, and edges coordinate when the work happens.
Step 1: define the state
State is the information available to a graph while it executes.
Imagine a shared document that each processing step can read and contribute to. One step adds cleaned text, another adds statistics, and a later step might add a summary.
Instead of manually passing separate variables between every function, you define a common structure that represents the workflow’s data.
Creating a state schema
For our text-processing application, we need three fields:
text: the original input.cleaned_text: the normalized text produced by the first node.word_count: the number produced by the second node.
The following schema describes these fields:
from typing import TypedDict, NotRequired
class TextState(TypedDict):
text: str
cleaned_text: NotRequired[str]
word_count: NotRequired[int]TypedDict comes from Python’s standard library. It describes the expected keys and value types of a dictionary.
Unlike a regular class with instance attributes, a TypedDict is used through normal dictionary operations:
state: TextState = {
"text": " LangGraph makes workflows clear. "
}
print(state["text"])We use NotRequired for cleaned_text and word_count because those fields do not exist when the application first receives its input.
They are populated as the workflow progresses.
Importantly, NotRequired[str] means that a key may be absent. It does not mean that the value may automatically be None.
Understanding state evolution
The state changes throughout execution.
| Execution stage | text | cleaned_text | word_count |
|---|---|---|---|
| Initial input | Original text | Absent | Absent |
| After cleaning | Original text | Normalized text | Absent |
| After counting | Original text | Normalized text | 4 |
Each node receives the relevant current state and returns the fields it wants to update.
LangGraph incorporates those updates into the state before subsequent sequential nodes execute.
This means the second node can access both the original input and the cleaned result, even though the first node returns only cleaned_text.
State is not automatically persistent
A workflow can maintain state during a single execution without remembering anything between separate executions.
Our application is stateful within each individual run. However, because we have not configured a checkpointer, it does not provide durable workflow state or automatic conversation memory between invocations.
This distinction becomes important in production applications.
| Run-scoped state | Persistent state |
|---|---|
| Available during execution | Can survive beyond execution |
| Sufficient for simple workflows | Useful for long-running workflows |
| Does not require a checkpointer | Uses checkpointing for graph state persistence |
| Used in this lesson | Introduced later in the course |
Also remember that TypedDict provides type information rather than comprehensive runtime validation. It does not guarantee that incoming REST requests contain valid values.
Production applications should validate external inputs before relying on them.
Step 2: write the nodes
A node is a callable responsible for performing a unit of work.
Nodes can execute ordinary calculations, query databases, call external APIs, invoke language models, process documents, or perform many other operations.
For this application, both nodes are simple Python functions.
Node 1: clean the text
The first node reads the original input and normalizes its whitespace.
def clean_text(state: TextState) -> dict:
cleaned = " ".join(state["text"].split())
return {"cleaned_text": cleaned}Python’s split() method, when called without a separator, divides a string into whitespace-separated components.
The join() method then combines those components using exactly one space.
For example:
Input: " LangGraph makes workflows clear. "
Output: "LangGraph makes workflows clear."Notice that the node does not return the original text field.
It returns only the new information:
{"cleaned_text": "LangGraph makes workflows clear."}LangGraph applies that update while retaining the other existing state fields.
Node 2: count the words
The second node reads the cleaned text and calculates its word count.
def count_words(state: TextState) -> dict:
count = len(state["cleaned_text"].split())
return {"word_count": count}This node depends on the first node having executed successfully.
If you call count_words() with a dictionary that contains only text, Python raises a KeyError because cleaned_text is missing.
Our graph’s execution order will guarantee that the cleaning node runs first.
The counting method here treats whitespace-separated components as words. It is not a linguistic tokenizer or an LLM token counter.
Return updates instead of mutating state
A common beginner mistake is modifying the state dictionary directly.
Avoid this pattern:
def clean_text_bad(state: TextState) -> dict:
state["cleaned_text"] = " ".join(state["text"].split())
return stateInstead, return a separate update dictionary.
def clean_text_good(state: TextState) -> dict:
return {
"cleaned_text": " ".join(state["text"].split())
}This approach makes it easier to identify which node produced each update. It also prepares your code for workflows involving parallel execution, state reducers, retries, and checkpointing.
For ordinary state fields without custom reducers, a new update replaces the previous value of that field. Fields omitted from the update remain unchanged.
LangGraph supports custom merge behavior through reducers, which will become important when multiple nodes contribute to the same collection or conversation history.
Designing focused nodes
A well-designed node should have a clear responsibility.
Cleaning text and counting words could easily be combined into one function. However, keeping them separate gives us independently testable operations and observable intermediate results.
In a larger document-processing system, the cleaning step might eventually perform HTML removal, Unicode normalization, or metadata extraction. The counting step could calculate document statistics without needing to know those implementation details.
This separation allows individual parts of the workflow to evolve without redesigning the entire application.
Step 3: add nodes and edges
Now that we have a state schema and two node functions, we can describe their execution structure.
Start by importing the Graph API:
from langgraph.graph import StateGraph, START, ENDCreate a graph builder using the state schema:
builder = StateGraph(TextState)At this point, the builder describes a graph with an associated state structure, but no processing nodes have been registered.
Registering nodes
Use add_node() to register each function:
builder.add_node("clean_text", clean_text)
builder.add_node("count_words", count_words)The first argument is the node’s graph identifier. The second argument is the callable that executes when the node is activated.
Node names are important because they appear in edges, streaming events, traces, and graph visualizations.
Prefer descriptive names such as clean_text, retrieve_documents, or validate_response rather than ambiguous names like step1.
LangGraph can also infer a node’s name from a function:
builder.add_node(clean_text)Explicit names are particularly useful when multiple graph nodes use related implementations.
Registering a node does not execute it.
Connecting the nodes
Use add_edge() to establish the execution order:
builder.add_edge(START, "clean_text")
builder.add_edge("clean_text", "count_words")
builder.add_edge("count_words", END)Each edge identifies a source and destination.
The first edge establishes the entry point. The second edge establishes the dependency between the processing steps. The third edge explicitly connects the final processing node to the graph’s termination marker.
START and END are special graph markers, not business-logic functions that you need to implement.
The order in which you register nodes does not determine execution order. The edges determine the workflow structure.
For example, registering count_words before clean_text would not change execution order as long as the edges remain unchanged.
Fixed execution paths
The edges in this example are unconditional.
Every successful execution follows the same sequence, regardless of the input text.
Later, conditional edges will allow a graph to make decisions based on its state. For example, a document-processing workflow could choose between summarization and rejection depending on whether the document passes validation.
Sequential workflows are appropriate when all inputs must pass through the same processing stages.
Step 4: compile and run
A StateGraph object is a builder, not the executable application itself.
Before running the workflow, compile it:
graph = builder.compile()Compilation validates the graph structure and prepares the executable runtime representation.
For example, it can detect edges referencing unknown nodes or a missing entry point.
However, successful compilation does not prove that the business logic is correct. It cannot guarantee that your functions calculate the correct values or that external services will succeed.
Once compiled, the graph exposes methods such as invoke(), stream(), ainvoke(), and astream().
Complete runnable example
Create a file named first_graph.py. The following program combines all four construction steps into one reusable application.
from typing import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
class TextState(TypedDict):
text: str
cleaned_text: NotRequired[str]
word_count: NotRequired[int]
def clean_text(state: TextState) -> dict:
cleaned = " ".join(state["text"].split())
return {"cleaned_text": cleaned}
def count_words(state: TextState) -> dict:
count = len(state["cleaned_text"].split())
return {"word_count": count}
builder = StateGraph(TextState)
builder.add_node("clean_text", clean_text)
builder.add_node("count_words", count_words)
builder.add_edge(START, "clean_text")
builder.add_edge("clean_text", "count_words")
builder.add_edge("count_words", END)
graph = builder.compile()
if __name__ == "__main__":
result = graph.invoke({
"text": " LangGraph makes workflows clear. "
})
print(result)
print("Word count:", result["word_count"])Run the program from your terminal:
python first_graph.pyExpected output:
{'text': ' LangGraph makes workflows clear. ', 'cleaned_text': 'LangGraph makes workflows clear.', 'word_count': 4}
Word count: 4The invoke() method performs a synchronous execution. It returns after the workflow finishes successfully.
The returned dictionary contains the final graph state rather than only the last node’s return value.
The if __name__ == "__main__": guard lets other Python files import the compiled graph without automatically executing the demonstration.
What happens internally?
LangGraph uses a graph execution runtime called Pregel. At a high level, execution progresses through scheduling, computation, and state-update phases.
The following diagram illustrates how state moves through our sequential application.
Initially, the runtime receives the input and schedules the cleaning node. The cleaning operation produces an update, which becomes part of the state. The counting node then runs using the updated information.
These logical execution rounds are called super-steps.
Our two processing nodes execute in separate super-steps. In future workflows, multiple independent nodes may execute during the same super-step.
The runtime controls when updates become visible to subsequent operations. Understanding this distinction will help when you later encounter parallel branches and conflicting state updates.
You can read more about this execution model in the official LangGraph runtime documentation.
Reusing a compiled graph
A compiled graph can process multiple inputs. You do not need to rebuild and compile the workflow for every request.
Create test_graph.py alongside the previous file to verify this behavior:
from first_graph import graph
examples = [
("Hello world", 2),
(" Agentic AI engineering ", 3),
("", 0),
(" ", 0),
("LangGraph", 1),
]
for text, expected_count in examples:
result = graph.invoke({"text": text})
assert result["word_count"] == expected_count
print(
f"{text!r} -> "
f"{result['word_count']} words"
)
print("All tests passed.")Expected output:
'Hello world' -> 2 words
' Agentic AI engineering ' -> 3 words
'' -> 0 words
' ' -> 0 words
'LangGraph' -> 1 words
All tests passed.Each invocation starts with its own supplied input. Without a checkpointer or external shared mutable data, previous runs do not contribute state to subsequent runs.
In production, compiling once and reusing the executable graph is preferable to reconstructing the same workflow repeatedly.
Watching each step
Receiving the final state is useful, but it does not show how the application arrived at that result.
When workflows contain many nodes, intermediate visibility becomes essential for debugging, progress reporting, and understanding unexpected behavior.
LangGraph provides streaming through the compiled graph’s stream() method.
Streaming is not limited to language model tokens. You can stream ordinary Python workflow updates even when no AI model is involved.
Streaming node updates
The updates streaming mode exposes the partial state updates produced by individual nodes.
Create a file named watch_graph.py alongside first_graph.py:
from first_graph import graph
inputs = {
"text": " LangGraph makes workflows clear. "
}
for chunk in graph.stream(
inputs,
stream_mode="updates",
version="v2",
):
if chunk["type"] == "updates":
for node_name, update in chunk["data"].items():
print(f"{node_name}: {update}")Expected output:
clean_text: {'cleaned_text': 'LangGraph makes workflows clear.'}
count_words: {'word_count': 4}The v2 streaming format provides a consistent dictionary structure.
Important fields include:
type: identifies the streaming event category.data: contains the event’s actual payload.ns: identifies the graph or subgraph namespace.
For our simple root graph, ns is an empty tuple.
The update payload associates each node name with the information that node produced.
This allows you to determine which operation contributed a particular field without manually inserting print statements into every node.
Streaming the complete state
Sometimes you need the accumulated state rather than individual changes.
The values streaming mode provides state snapshots.
The following standalone runner demonstrates the difference:
from first_graph import graph
for chunk in graph.stream(
{"text": " Hello LangGraph "},
stream_mode="values",
version="v2",
):
if chunk["type"] == "values":
print(chunk["data"])Expected output:
{'text': ' Hello LangGraph '}
{'text': ' Hello LangGraph ', 'cleaned_text': 'Hello LangGraph'}
{'text': ' Hello LangGraph ', 'cleaned_text': 'Hello LangGraph', 'word_count': 2}The first snapshot contains the supplied input. Subsequent snapshots show the accumulated state after each processing step.
Choosing the appropriate execution method
| Method or mode | Information returned | Best use |
|---|---|---|
invoke() |
Final graph output | Standard synchronous requests |
stream() with updates |
Individual node updates | Debugging workflow stages |
stream() with values |
Accumulated state snapshots | Inspecting state evolution |
stream() with messages |
Model message chunks and metadata | Streaming LLM responses |
stream() with custom |
Application-defined events | Progress notifications |
For this lesson, updates and values are the most relevant modes.
You can also request multiple streaming modes during one execution:
from first_graph import graph
for chunk in graph.stream(
{"text": "Learn LangGraph"},
stream_mode=["updates", "values"],
version="v2",
):
print(chunk["type"], chunk["data"])This produces both individual updates and accumulated snapshots. The event’s type tells you how to interpret its payload.
Tip: Calling
invoke()and then callingstream()executes the workflow twice. If nodes perform paid model calls or modify external systems, those operations may happen again. Choose one execution method when processing a real request.
For additional streaming formats and capabilities, consult the official LangGraph streaming documentation.
Shortcut: add_sequence
Writing each node and edge explicitly provides excellent control. However, it becomes repetitive when a workflow consists entirely of consecutive steps.
LangGraph offers the add_sequence() method to simplify this pattern.
Instead of manually registering the processing nodes and adding the edges between them, you provide an ordered collection of callables.
builder = StateGraph(TextState)
builder.add_sequence([
clean_text,
count_words,
])
builder.add_edge(START, "clean_text")
builder.add_edge("count_words", END)
graph = builder.compile()The method registers the functions and connects consecutive nodes in the supplied order.
Their names are inferred from the callable names. We explicitly connect the entry and termination markers to make the workflow boundaries clear.
You can also provide named tuples when you want explicit graph identifiers:
builder.add_sequence([
("normalize", clean_text),
("analyze", count_words),
])In this case, subsequent edges must reference normalize and analyze, not the original function names.
The current method signature is documented in the official StateGraph.add_sequence reference.
Practical example: customer support preprocessing
Consider a support application that receives customer messages.
Before an AI assistant processes a message, the application could normalize its whitespace and assign a priority using deterministic business rules.
The following complete example demonstrates this workflow using add_sequence().
from typing import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
class TicketState(TypedDict):
message: str
normalized_message: NotRequired[str]
priority: NotRequired[str]
def normalize_message(state: TicketState) -> dict:
normalized = " ".join(
state["message"].lower().split()
)
return {"normalized_message": normalized}
def assign_priority(state: TicketState) -> dict:
message = state["normalized_message"]
urgent_phrases = [
"payment failed",
"service unavailable",
"account locked",
]
urgent = any(
phrase in message
for phrase in urgent_phrases
)
return {
"priority": "high" if urgent else "normal"
}
builder = StateGraph(TicketState)
builder.add_sequence([
normalize_message,
assign_priority,
])
builder.add_edge(START, "normalize_message")
builder.add_edge("assign_priority", END)
graph = builder.compile()
result = graph.invoke({
"message": " My PAYMENT FAILED twice today. "
})
print("Message:", result["normalized_message"])
print("Priority:", result["priority"])
assert result["priority"] == "high"Expected output:
Message: my payment failed twice today.
Priority: highThis example demonstrates how deterministic processing nodes can form the foundation of an agentic application.
A later version might introduce an LLM-based classifier, database retrieval, conditional routing, or escalation to a human support specialist.
The keyword rules are intentionally simplistic. A production classifier must account for negation, ambiguous requests, and context rather than treating every phrase match as urgent.
Common mistakes and troubleshooting
The following problems frequently occur when developers build their first graph.
| Problem | Likely cause | Solution |
|---|---|---|
Cannot call invoke() |
Attempting to execute the builder | Call compile() first |
| Unknown node error | Incorrect edge identifier | Match registered node names |
| Missing entry point | No edge from START | Connect START to the first node |
KeyError inside a node |
Missing input or incorrect execution order | Validate inputs and inspect dependencies |
| Invalid node return | Returning a string instead of an update dictionary | Return a dictionary containing state fields |
| Unexpected state replacement | Returning an existing field with a new value | Return only intended updates |
| Unexpected streaming structure | Mixing streaming format versions | Specify version="v2" |
When troubleshooting, test the individual node functions before investigating the graph runtime.
For example, because our cleaning node is an ordinary Python function, it can be tested without compiling anything.
from first_graph import clean_text, count_words
assert clean_text({
"text": " Hello world "
}) == {
"cleaned_text": "Hello world"
}
assert count_words({
"text": "Hello world",
"cleaned_text": "Hello world",
}) == {
"word_count": 2
}
print("Node tests passed.")Expected output:
Node tests passed.Separating node-level tests from graph-level tests helps distinguish business-logic failures from orchestration failures.
Engineering practices for sequential workflows
Although these applications are small, the design practices they introduce remain valuable in production systems.
Keep node responsibilities focused, use descriptive names, and define state fields deliberately. Avoid storing unnecessary information, particularly credentials or sensitive customer data that could later appear in logs, traces, or persisted checkpoints.
Prefer returning partial updates over mutating shared objects. Validate external inputs before processing them, and test both ordinary and edge-case inputs.
Use explicit graph construction when learning or when the workflow requires complex control flow. Use add_sequence() when the structure is genuinely linear and its execution order is straightforward.
For simple calculations involving only two functions, ordinary Python may be sufficient. LangGraph becomes increasingly valuable when those operations form part of a workflow requiring observable execution, branching, persistence, interruption, or recovery.
This is an important engineering principle: adopt orchestration because the application benefits from it, not merely because the framework makes it possible.
Connecting to the next lesson
You have now moved from installing LangGraph to constructing an executable, state-driven application.
The next lesson, Visualizing graphs with Mermaid, will show how to inspect the structure of a compiled graph programmatically, generate Mermaid representations, and render workflow diagrams.
As applications grow beyond two processing nodes, visualization becomes an important development tool for identifying incorrect connections, understanding conditional routes, reviewing cyclic execution paths, and communicating workflow architecture to other engineers.
Build an order pricing graph
Build a two-step sequential graph that calculates the subtotal of an order and then adds a shipping charge. Define a typed state containing the unit price in cents, quantity, shipping charge, subtotal, and final total. Connect both nodes using START and END, compile the graph, and stream the updates produced by each node. Verify that an order containing three items priced at 1500 cents each with a shipping charge of 500 cents produces a total of 5000 cents.
from typing import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
class OrderState(TypedDict):
unit_price_cents: int
quantity: int
shipping_cents: int
subtotal_cents: NotRequired[int]
total_cents: NotRequired[int]
def calculate_subtotal(state: OrderState) -> dict:
# TODO: Calculate and return the subtotal.
raise NotImplementedError
def calculate_total(state: OrderState) -> dict:
# TODO: Add shipping to the subtotal.
raise NotImplementedError
builder = StateGraph(OrderState)
# TODO: Register both nodes.
# TODO: Connect START, both nodes, and END.
# TODO: Compile the graph.
order = {
"unit_price_cents": 1500,
"quantity": 3,
"shipping_cents": 500,
}
# TODO: Invoke the graph and print the result.
# TODO: Assert that the total is 5000 cents.
# TODO: Stream node updates using version="v2".from typing import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
class OrderState(TypedDict):
unit_price_cents: int
quantity: int
shipping_cents: int
subtotal_cents: NotRequired[int]
total_cents: NotRequired[int]
def calculate_subtotal(state: OrderState) -> dict:
subtotal = state["unit_price_cents"] * state["quantity"]
return {"subtotal_cents": subtotal}
def calculate_total(state: OrderState) -> dict:
total = state["subtotal_cents"] + state["shipping_cents"]
return {"total_cents": total}
builder = StateGraph(OrderState)
builder.add_node("calculate_subtotal", calculate_subtotal)
builder.add_node("calculate_total", calculate_total)
builder.add_edge(START, "calculate_subtotal")
builder.add_edge("calculate_subtotal", "calculate_total")
builder.add_edge("calculate_total", END)
graph = builder.compile()
order = {
"unit_price_cents": 1500,
"quantity": 3,
"shipping_cents": 500,
}
result = graph.invoke(order)
print("Final state:", result)
print(f"Order total: ${result['total_cents'] / 100:.2f}")
assert result["subtotal_cents"] == 4500
assert result["total_cents"] == 5000
print("\nNode updates:")
for chunk in graph.stream(
order,
stream_mode="updates",
version="v2",
):
if chunk["type"] == "updates":
print(chunk["data"])Summary
- StateGraph defines a workflow whose nodes communicate through shared state.
- A state schema describes the fields available to the graph during execution.
- Nodes perform work and return partial state updates instead of directly mutating shared state.
- Directed edges determine execution order, while START and END mark the workflow boundaries.
- Compiling a StateGraph creates an executable graph that supports invocation and streaming.
- Streaming with updates or values exposes intermediate execution results for debugging and monitoring.
- The add_sequence method simplifies the construction of workflows with a fixed execution order.