1
---
2
name: langchain-architecture
3
description: Design LLM applications using LangChain 1.x and LangGraph for agents, memory, and tool integration. Use when building LangChain applications, implementing AI agents, or creating complex LLM workflows.
4
---
5
6
# LangChain & LangGraph Architecture
7
8
Master modern LangChain 1.x and LangGraph for building sophisticated LLM applications with agents, state management, memory, and tool integration.
9
10
## When to Use This Skill
11
12
- Building autonomous AI agents with tool access
13
- Implementing complex multi-step LLM workflows
14
- Managing conversation memory and state
15
- Integrating LLMs with external data sources and APIs
16
- Creating modular, reusable LLM application components
17
- Implementing document processing pipelines
18
- Building production-grade LLM applications
19
20
## Package Structure (LangChain 1.x)
21
22
```
23
langchain (1.2.x) # High-level orchestration
24
langchain-core (1.2.x) # Core abstractions (messages, prompts, tools)
25
langchain-community # Third-party integrations
26
langgraph # Agent orchestration and state management
27
langchain-openai # OpenAI integrations
28
langchain-anthropic # Anthropic/Claude integrations
29
langchain-voyageai # Voyage AI embeddings
30
langchain-pinecone # Pinecone vector store
31
```
32
33
## Core Concepts
34
35
### 1. LangGraph Agents
36
37
LangGraph is the standard for building agents in 2026. It provides:
38
39
**Key Features:**
40
41
- **StateGraph**: Explicit state management with typed state
42
- **Durable Execution**: Agents persist through failures
43
- **Human-in-the-Loop**: Inspect and modify state at any point
44
- **Memory**: Short-term and long-term memory across sessions
45
- **Checkpointing**: Save and resume agent state
46
47
**Agent Patterns:**
48
49
- **ReAct**: Reasoning + Acting with `create_react_agent`
50
- **Plan-and-Execute**: Separate planning and execution nodes
51
- **Multi-Agent**: Supervisor routing between specialized agents
52
- **Tool-Calling**: Structured tool invocation with Pydantic schemas
53
54
### 2. State Management
55
56
LangGraph uses TypedDict for explicit state:
57
58
```python
59
from typing import Annotated, TypedDict
60
from langgraph.graph import MessagesState
61
62
# Simple message-based state
63
class AgentState(MessagesState):
64
"""Extends MessagesState with custom fields."""
65
context: Annotated[list, "retrieved documents"]
66
67
# Custom state for complex agents
68
class CustomState(TypedDict):
69
messages: Annotated[list, "conversation history"]
70
context: Annotated[dict, "retrieved context"]
71
current_step: str
72
results: list
73
```
74
75
### 3. Memory Systems
76
77
Modern memory implementations:
78
79
- **ConversationBufferMemory**: Stores all messages (short conversations)
80
- **ConversationSummaryMemory**: Summarizes older messages (long conversations)
81
- **ConversationTokenBufferMemory**: Token-based windowing
82
- **VectorStoreRetrieverMemory**: Semantic similarity retrieval
83
- **LangGraph Checkpointers**: Persistent state across sessions
84
85
### 4. Document Processing
86
87
Loading, transforming, and storing documents:
88
89
**Components:**
90
91
- **Document Loaders**: Load from various sources
92
- **Text Splitters**: Chunk documents intelligently
93
- **Vector Stores**: Store and retrieve embeddings
94
- **Retrievers**: Fetch relevant documents
95
96
### 5. Callbacks & Tracing
97
98
LangSmith is the standard for observability:
99
100
- Request/response logging
101
- Token usage tracking
102
- Latency monitoring
103
- Error tracking
104
- Trace visualization
105
106
## Quick Start
107
108
### Modern ReAct Agent with LangGraph
109
110
```python
111
from langgraph.prebuilt import create_react_agent
112
from langgraph.checkpoint.memory import MemorySaver
113
from langchain_anthropic import ChatAnthropic
114
from langchain_core.tools import tool
115
import ast
116
import operator
117
118
# Initialize LLM (Claude Sonnet 5 recommended)
119
llm = ChatAnthropic(model="claude-sonnet-5")
120
121
# Define tools with Pydantic schemas
122
@tool
123
def search_database(query: str) -> str:
124
"""Search internal database for information."""
125
# Your database search logic
126
return f"Results for: {query}"
127
128
@tool
129
def calculate(expression: str) -> str:
130
"""Safely evaluate a mathematical expression.
131
132
Supports: +, -, *, /, **, %, parentheses
133
Example: '(2 + 3) * 4' returns '20'
134
"""
135
# Safe math evaluation using ast
136
allowed_operators = {
137
ast.Add: operator.add,
138
ast.Sub: operator.sub,
139
ast.Mult: operator.mul,
140
ast.Div: operator.truediv,
141
ast.Pow: operator.pow,
142
ast.Mod: operator.mod,
143
ast.USub: operator.neg,
144
}
145
146
def _eval(node):
147
if isinstance(node, ast.Constant):
148
return node.value
149
elif isinstance(node, ast.BinOp):
150
left = _eval(node.left)
151
right = _eval(node.right)
152
return allowed_operators[type(node.op)](left, right)
153
elif isinstance(node, ast.UnaryOp):
154
operand = _eval(node.operand)
155
return allowed_operators[type(node.op)](operand)
156
else:
157
raise ValueError(f"Unsupported operation: {type(node)}")
158
159
try:
160
tree = ast.parse(expression, mode='eval')
161
return str(_eval(tree.body))
162
except Exception as e:
163
return f"Error: {e}"
164
165
tools = [search_database, calculate]
166
167
# Create checkpointer for memory persistence
168
checkpointer = MemorySaver()
169
170
# Create ReAct agent
171
agent = create_react_agent(
172
llm,
173
tools,
174
checkpointer=checkpointer
175
)
176
177
# Run agent with thread ID for memory
178
config = {"configurable": {"thread_id": "user-123"}}
179
result = await agent.ainvoke(
180
{"messages": [("user", "Search for Python tutorials and calculate 25 * 4")]},
181
config=config
182
)
183
```
184
185
## Detailed patterns and worked examples
186
187
Detailed pattern documentation lives in `references/details.md`. Read that file when the navigation tier above is insufficient.
188
189
## Testing Strategies
190
191
```python
192
import pytest
193
from unittest.mock import AsyncMock, patch
194
195
@pytest.mark.asyncio
196
async def test_agent_tool_selection():
197
"""Test agent selects correct tool."""
198
with patch.object(llm, 'ainvoke') as mock_llm:
199
mock_llm.return_value = AsyncMock(content="Using search_database")
200
201
result = await agent.ainvoke({
202
"messages": [("user", "search for documents")]
203
})
204
205
# Verify tool was called
206
assert "search_database" in str(result)
207
208
@pytest.mark.asyncio
209
async def test_memory_persistence():
210
"""Test memory persists across invocations."""
211
config = {"configurable": {"thread_id": "test-thread"}}
212
213
# First message
214
await agent.ainvoke(
215
{"messages": [("user", "Remember: the code is 12345")]},
216
config
217
)
218
219
# Second message should remember
220
result = await agent.ainvoke(
221
{"messages": [("user", "What was the code?")]},
222
config
223
)
224
225
assert "12345" in result["messages"][-1].content
226
```
227
228
## Performance Optimization
229
230
### 1. Caching with Redis
231
232
```python
233
from langchain_community.cache import RedisCache
234
from langchain_core.globals import set_llm_cache
235
import redis
236
237
redis_client = redis.Redis.from_url("redis://localhost:6379")
238
set_llm_cache(RedisCache(redis_client))
239
```
240
241
### 2. Async Batch Processing
242
243
```python
244
import asyncio
245
from langchain_core.documents import Document
246
247
async def process_documents(documents: list[Document]) -> list:
248
"""Process documents in parallel."""
249
tasks = [process_single(doc) for doc in documents]
250
return await asyncio.gather(*tasks)
251
252
async def process_single(doc: Document) -> dict:
253
"""Process a single document."""
254
chunks = text_splitter.split_documents([doc])
255
embeddings = await embeddings_model.aembed_documents(
256
[c.page_content for c in chunks]
257
)
258
return {"doc_id": doc.metadata.get("id"), "embeddings": embeddings}
259
```
260
261
### 3. Connection Pooling
262
263
```python
264
from langchain_pinecone import PineconeVectorStore
265
from pinecone import Pinecone
266
267
# Reuse Pinecone client
268
pc = Pinecone(api_key=os.environ["PINECONE_API_KEY"])
269
index = pc.Index("my-index")
270
271
# Create vector store with existing index
272
vectorstore = PineconeVectorStore(index=index, embedding=embeddings)
273
```
274