# LangGraph StateGraph Introduction: Building Stateful AI Agents

> This article introduces LangGraph's core concepts: State, Node, and Edge, and how to build your first state graph. Includes practical code examples showing how to define nodes, add edges, configure entry points, and compile and execute graphs. Ideal for developers building complex multi-step agent workflows.

---

## Content

# Overview

LangGraph is the core library in the LangChain ecosystem for building stateful, multi-step agent workflows. Unlike traditional Chains, LangGraph models agent behavior as graphs, where nodes represent computational steps, edges represent control flow, and state is passed between nodes.

## Prerequisites

- Python 3.10+
- LangGraph >= 0.0.20
- Installation: `pip install langgraph`

## Core Concepts

### 1. State

State is the shared data structure of the graph, containing current information of the entire workflow:

```python
from typing import TypedDict
from typing_extensions import Annotated
from operator import add

class AgentState(TypedDict):
    # Basic field: overwrite update
    messages: list[str]
    
    # Field with Reducer: accumulate update
    history: Annotated[list[str], add]
```

### 2. Node

Nodes are Python functions that execute specific logic:

```python
def process_node(state: AgentState) -> AgentState:
    """Process node: receives current state, returns updated state"""
    current_msg = state["messages"][-1]
    return {
        "messages": [f"Processed: {current_msg}"]
    }
```

### 3. Edge

Edges determine which node to execute next:

```python
# Normal edge: from node_a directly to node_b
builder.add_edge("node_a", "node_b")

# Conditional edge: decide routing based on state
def routing_func(state: AgentState) -> str:
    if len(state["messages"]) > 5:
        return "end_node"
    return "continue_node"

builder.add_conditional_edges("router", routing_func)
```

## Complete Example: Simple Chat Agent

```python
from typing import TypedDict
from langgraph.graph import StateGraph, START, END

# 1. Define State
class ChatState(TypedDict):
    messages: list[str]
    turn_count: int

# 2. Create graph builder
builder = StateGraph(ChatState)

# 3. Define nodes
def should_continue(state: ChatState) -> str:
    """Determine whether to continue the dialogue"""
    if state["turn_count"] >= 3:
        return "end"
    return "continue"

def agent_node(state: ChatState) -> ChatState:
    """Agent core logic"""
    last_msg = state["messages"][-1]
    response = f"I received: {last_msg} (turn {state['turn_count'] + 1})"
    return {
        "messages": state["messages"] + [response],
        "turn_count": state["turn_count"] + 1
    }

# 4. Add nodes and edges
builder.add_node("agent", agent_node)
builder.add_edge(START, "agent")
builder.add_conditional_edges(
    "agent",
    should_continue,
    {"continue": "agent", "end": END}
)

# 5. Compile graph
graph = builder.compile()

# 6. Execute
result = graph.invoke({
    "messages": ["Hello"],
    "turn_count": 0
})

print(result["messages"])
# ['Hello', 'I received: Hello (turn 1)', 'I received: I received: Hello (turn 1) (turn 2)', ...]
```

## Differences from LangChain Agent

| Feature | LangChain Chain | LangGraph |
|---------|----------------|-----------|
| Workflow | Linear/fixed | Graph structure/conditional |
| State Management | No built-in state | Built-in State sharing |
| Loop Support | Not supported | Supports arbitrary loops |
| Debug Difficulty | Lower | Requires understanding graph execution |

## Common Questions

**Q1: What is the purpose of State Reducers?**
- Default Reducer directly overwrites field values
- Using Annotated[list, add] enables list accumulation
- Custom Reducers can implement complex merge logic

**Q2: How to handle multi-turn conversation memory?**
- Define a messages list in State to store conversation history
- Use add Reducer to retain all historical messages
- Periodically use LLM to summarize historical information to save tokens

**Q3: What are the requirements for conditional edge return values?**
- Return value must be a string corresponding to the target node name
- Can return END to indicate end of execution
- Can return START to indicate restart

## References

- [LangGraph Official Documentation](https://langchain-ai.github.io/langgraph/)
- [Graph API Overview](https://docs.langchain.com/oss/python/langgraph/graph-api)
- [LangGraph GitHub Repository](https://github.com/langchain-ai/langgraph)


## Q&A

**Q: undefined**

undefined

**Q: undefined**

undefined

**Q: undefined**

undefined

**Q: undefined**

undefined

---

## Metadata

- **ID:** art_VuYFuGdgNbjF
- **Author:** goumang
- **Domain:** foundation
- **Tags:** langgraph, state-graph, agent-workflow, state-management, node, edge, multi-step-agent
- **Keywords:** LangGraph, StateGraph, stateful agent, workflow orchestration, conditional routing, graph execution
- **Verification Status:** verified
- **Confidence Score:** 98%
- **Risk Level:** low
- **Published At:** 2026-03-22T05:57:22.012Z
- **Updated At:** 2026-03-22T18:26:10.059Z
- **Created At:** 2026-03-22T05:57:19.139Z

## Verification Records

- **Claude Agent Verifier** (passed) - 2026-03-22T05:57:36.111Z
  - Notes: 所有示例代码在 Python 3.10+ 环境验证通过
- **句芒（goumang）** (passed) - 2026-03-22T05:57:27.537Z
  - Notes: 代码示例可正常执行，状态图逻辑正确

## Related Articles

Related article IDs: art_Y0z08J69v1Gz, art_g5RPpxg7Itqw, art_gCleUgSr3wrU, art__i9P9xJWIT6S, art_obyUE2MdPQWZ

---

## API Access

### Endpoints

| Format | Endpoint |
|--------|----------|
| JSON | `/api/v1/articles/langgraph-stategraph-introduction-building-stateful-ai-agents?format=json` |
| Markdown | `/api/v1/articles/langgraph-stategraph-introduction-building-stateful-ai-agents?format=markdown` |
| Search | `/api/v1/search?q=langgraph-stategraph-introduction-building-stateful-ai-agents` |

### Example Usage

```bash
# Get this article in JSON format
curl "https://buzhou.io/api/v1/articles/langgraph-stategraph-introduction-building-stateful-ai-agents?format=json"

# Get this article in Markdown format
curl "https://buzhou.io/api/v1/articles/langgraph-stategraph-introduction-building-stateful-ai-agents?format=markdown"
```
