How LangGraph.js Agents Work
LangGraph decomposes agents into discrete nodes (functions) connected through shared state. Execution flows through a graph where nodes do work and edges determine what runs next.
1. State-First Design
State is the shared memory accessible to all nodes. Design state before nodes:
import { Annotation, MessagesAnnotation } from "@langchain/langgraph";
const AgentState = Annotation.Root({
...MessagesAnnotation.spec,
// Add custom fields with reducers
context: Annotation<string[]>({
reducer: (x, y) => x.concat(y),
default: () => [],
}),
});
Critical rules:
- Store raw data, not formatted text (format in nodes)
- Use reducers for fields that accumulate (messages, lists)
- Keep state minimal - only persist what's needed across steps
2. Nodes Do Work, Edges Route
// Node: receives state, returns partial update
async function callModel(state: typeof AgentState.State) {
const response = await model.invoke(state.messages);
return { messages: [response] };
}
// Edge: determines next node
function shouldContinue(state: typeof AgentState.State) {
const lastMessage = state.messages.at(-1);
if (lastMessage?.tool_calls?.length) return "tools";
return END;
}
3. Always Compile Before Use
const graph = new StateGraph(AgentState)
.addNode("agent", callModel)
.addNode("tools", toolNode)
.addEdge(START, "agent")
.addConditionalEdges("agent", shouldContinue)
.addEdge("tools", "agent")
.compile(); // Required!
4. Checkpointers Enable Persistence
For conversation memory, human-in-the-loop, or fault tolerance:
import { MemorySaver } from "@langchain/langgraph";
const graph = workflow.compile({
checkpointer: new MemorySaver()
});
// Invoke with thread_id
await graph.invoke(input, {
configurable: { thread_id: "user-123" }
});
What would you like to do?
- Build a new agent from scratch
- Add a feature to an existing agent
- Audit/review an agent's architecture
- Debug an agent issue
- Write tests for an agent
- Optimize agent performance
- Something else
Wait for response, then read the matching workflow from workflows/ and follow it.
| Response |
Workflow |
| 1, "new", "create", "build", "start", "scaffold" |
workflows/build-new-agent.md |
| 2, "add", "feature", "implement", "extend" |
workflows/add-feature.md |
| 3, "audit", "review", "check", "assess", "evaluate" |
workflows/audit-agent.md |
| 4, "debug", "fix", "broken", "error", "bug", "issue" |
workflows/debug-agent.md |
| 5, "test", "tests", "testing", "coverage" |
workflows/write-tests.md |
| 6, "optimize", "performance", "slow", "fast", "improve" |
workflows/optimize-agent.md |
| 7, other |
Clarify intent, then select appropriate workflow |
After Every Change
# 1. TypeScript compiles?
npx tsc --noEmit
# 2. Tests pass?
npm test
# 3. Agent runs?
npx ts-node src/agent.ts
Report:
- "Build: ✓" or "Build: ✗ [error]"
- "Tests: X pass, Y fail"
- "Agent executed successfully" or "Runtime error: [details]"
Domain Knowledge
All in references/:
LangChain Fundamentals:
- langchain-fundamentals.md - Messages, chat models, structured output, retrieval, guardrails
Architecture:
- graph-api.md - StateGraph, nodes, edges, compilation
- functional-api.md - Tasks, entrypoints, when to use
- state-management.md - Annotations, reducers, state design
Features:
- tools.md - Creating and binding tools
- persistence.md - Checkpointers, memory, threads
- streaming.md - Real-time output modes
- interrupts.md - Human-in-the-loop patterns
- subgraphs.md - Composing multi-agent systems
- agent-chat-ui.md - Chat UI setup and integration
- agent-inbox.md - Inbox UI for interrupt management, ambient agents
- deployment.md - Local server, LangSmith Cloud, Studio, observability, time-travel
Patterns:
- common-patterns.md - ReAct, RAG, routing patterns
- multi-agent.md - Supervisor, hierarchical, network architectures
- agent-skills.md - Modular capabilities and skill loading
- anti-patterns.md - Common mistakes to avoid
Workflows
All in workflows/:
| File |
Purpose |
| build-new-agent.md |
Create a new LangGraph.js agent from scratch |
| add-feature.md |
Add capabilities to an existing agent |
| audit-agent.md |
Review architecture and identify issues |
| debug-agent.md |
Find and fix agent bugs |
| write-tests.md |
Test nodes, graphs, and integrations |
| optimize-agent.md |
Improve performance and reduce latency |
Templates
All in templates/:
| File |
Purpose |
| basic-agent.ts |
Minimal ReAct agent scaffold |
| rag-agent.ts |
Retrieval-augmented agent |
| multi-agent.ts |
Multi-agent system with subgraphs |
Official Documentation
For topics not fully covered here, consult:
1---2name: developing-langgraph-js-agents3description: Build, audit, review, and update LangGraph.js agents. Use PROACTIVELY when working with LangGraph, @langchain/langgraph, agent graphs, state machines, or AI workflows in TypeScript/JavaScript. Covers creating new agents, adding features, debugging, testing, and optimizing. (user)4---56<essential_principles>78## How LangGraph.js Agents Work910LangGraph decomposes agents into **discrete nodes** (functions) connected through **shared state**. Execution flows through a graph where nodes do work and edges determine what runs next.1112### 1. State-First Design1314State is the shared memory accessible to all nodes. Design state before nodes:1516```typescript17import { Annotation, MessagesAnnotation } from "@langchain/langgraph";1819const AgentState = Annotation.Root({20 ...MessagesAnnotation.spec,21 // Add custom fields with reducers22 context: Annotation<string[]>({23 reducer: (x, y) => x.concat(y),24 default: () => [],25 }),26});27```2829**Critical rules:**30- Store raw data, not formatted text (format in nodes)31- Use reducers for fields that accumulate (messages, lists)32- Keep state minimal - only persist what's needed across steps3334### 2. Nodes Do Work, Edges Route3536```typescript37// Node: receives state, returns partial update38async function callModel(state: typeof AgentState.State) {39 const response = await model.invoke(state.messages);40 return { messages: [response] };41}4243// Edge: determines next node44function shouldContinue(state: typeof AgentState.State) {45 const lastMessage = state.messages.at(-1);46 if (lastMessage?.tool_calls?.length) return "tools";47 return END;48}49```5051### 3. Always Compile Before Use5253```typescript54const graph = new StateGraph(AgentState)55 .addNode("agent", callModel)56 .addNode("tools", toolNode)57 .addEdge(START, "agent")58 .addConditionalEdges("agent", shouldContinue)59 .addEdge("tools", "agent")60 .compile(); // Required!61```6263### 4. Checkpointers Enable Persistence6465For conversation memory, human-in-the-loop, or fault tolerance:6667```typescript68import { MemorySaver } from "@langchain/langgraph";6970const graph = workflow.compile({71 checkpointer: new MemorySaver()72});7374// Invoke with thread_id75await graph.invoke(input, {76 configurable: { thread_id: "user-123" }77});78```7980</essential_principles>8182<intake>8384What would you like to do?85861. Build a new agent from scratch872. Add a feature to an existing agent883. Audit/review an agent's architecture894. Debug an agent issue905. Write tests for an agent916. Optimize agent performance927. Something else9394**Wait for response, then read the matching workflow from `workflows/` and follow it.**9596</intake>9798<routing>99100| Response | Workflow |101|----------|----------|102| 1, "new", "create", "build", "start", "scaffold" | `workflows/build-new-agent.md` |103| 2, "add", "feature", "implement", "extend" | `workflows/add-feature.md` |104| 3, "audit", "review", "check", "assess", "evaluate" | `workflows/audit-agent.md` |105| 4, "debug", "fix", "broken", "error", "bug", "issue" | `workflows/debug-agent.md` |106| 5, "test", "tests", "testing", "coverage" | `workflows/write-tests.md` |107| 6, "optimize", "performance", "slow", "fast", "improve" | `workflows/optimize-agent.md` |108| 7, other | Clarify intent, then select appropriate workflow |109110</routing>111112<verification_loop>113114## After Every Change115116```bash117# 1. TypeScript compiles?118npx tsc --noEmit119120# 2. Tests pass?121npm test122123# 3. Agent runs?124npx ts-node src/agent.ts125```126127Report:128- "Build: ✓" or "Build: ✗ [error]"129- "Tests: X pass, Y fail"130- "Agent executed successfully" or "Runtime error: [details]"131132</verification_loop>133134<reference_index>135136## Domain Knowledge137138All in `references/`:139140**LangChain Fundamentals:**141- langchain-fundamentals.md - Messages, chat models, structured output, retrieval, guardrails142143**Architecture:**144- graph-api.md - StateGraph, nodes, edges, compilation145- functional-api.md - Tasks, entrypoints, when to use146- state-management.md - Annotations, reducers, state design147148**Features:**149- tools.md - Creating and binding tools150- persistence.md - Checkpointers, memory, threads151- streaming.md - Real-time output modes152- interrupts.md - Human-in-the-loop patterns153- subgraphs.md - Composing multi-agent systems154- agent-chat-ui.md - Chat UI setup and integration155- agent-inbox.md - Inbox UI for interrupt management, ambient agents156- deployment.md - Local server, LangSmith Cloud, Studio, observability, time-travel157158**Patterns:**159- common-patterns.md - ReAct, RAG, routing patterns160- multi-agent.md - Supervisor, hierarchical, network architectures161- agent-skills.md - Modular capabilities and skill loading162- anti-patterns.md - Common mistakes to avoid163164</reference_index>165166<workflows_index>167168## Workflows169170All in `workflows/`:171172| File | Purpose |173|------|---------|174| build-new-agent.md | Create a new LangGraph.js agent from scratch |175| add-feature.md | Add capabilities to an existing agent |176| audit-agent.md | Review architecture and identify issues |177| debug-agent.md | Find and fix agent bugs |178| write-tests.md | Test nodes, graphs, and integrations |179| optimize-agent.md | Improve performance and reduce latency |180181</workflows_index>182183<templates_index>184185## Templates186187All in `templates/`:188189| File | Purpose |190|------|---------|191| basic-agent.ts | Minimal ReAct agent scaffold |192| rag-agent.ts | Retrieval-augmented agent |193| multi-agent.ts | Multi-agent system with subgraphs |194195</templates_index>196197<external_docs>198199## Official Documentation200201For topics not fully covered here, consult:202203- **LangGraph.js Docs**: https://docs.langchain.com/oss/javascript/langgraph/overview.md204- **API Reference**: https://langchain-ai.github.io/langgraphjs/reference/205- **GitHub Examples**: https://github.com/langchain-ai/langgraphjs/tree/main/examples206- **LangChain Tools**: https://docs.langchain.com/oss/javascript/langchain/tools.md207208</external_docs>