Skills · Data & AI

LangChain & LangGraph Architecture

Unverified28/40

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.

Originally by wshobson · MIT

Claude CodePartialHas SKILL.md but declares no allowed-tools — Claude Code will ask for permission each time
CursorPartialPlain prose you can paste in — but no Cursor rules file
CodexPartialPlain prose you can paste in — but no AGENTS.md
Gemini CLIPartialPlain prose you can paste in
CopilotPartialPlain prose you can paste in — but no Copilot instructions file
npx agentalley add langchain-architecture

This command does not work yet — the CLI is still being built. Until then, use Raw in the reader below to take the file.

Who is stuck, and on what

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.

The whole source

No sign-in, no blur, nothing truncated
langchain-architecture/SKILL.md274 lines7.8 KBRawView on GitHub
Frontmatter — 2 properties
namelangchain-architecture
descriptionDesign 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.
1---
2name: langchain-architecture
3description: 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---A5No allowed-tools declared — no way to tell what this skill may touch
5 
6# LangChain & LangGraph Architecture
7 
8Master 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```
23langchain (1.2.x) # High-level orchestration
24langchain-core (1.2.x) # Core abstractions (messages, prompts, tools)
25langchain-community # Third-party integrations
26langgraph # Agent orchestration and state management
27langchain-openai # OpenAI integrations
28langchain-anthropic # Anthropic/Claude integrations
29langchain-voyageai # Voyage AI embeddings
30langchain-pinecone # Pinecone vector store
31```
32 
33## Core Concepts
34 
35### 1. LangGraph Agents
36 
37LangGraph 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 
56LangGraph uses TypedDict for explicit state:
57 
58```python
59from typing import Annotated, TypedDict
60from langgraph.graph import MessagesState
61 
62# Simple message-based state
63class AgentState(MessagesState):
64 """Extends MessagesState with custom fields."""
65 context: Annotated[list, "retrieved documents"]
66 
67# Custom state for complex agents
68class 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 
77Modern 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 
87Loading, 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 documentsA4This skill pulls in web or user content but never says to treat that content as data. A signal, not proof.
95 
96### 5. Callbacks & Tracing
97 
98LangSmith 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
111from langgraph.prebuilt import create_react_agent
112from langgraph.checkpoint.memory import MemorySaver
113from langchain_anthropic import ChatAnthropic
114from langchain_core.tools import tool
115import ast
116import operator
117 
118# Initialize LLM (Claude Sonnet 5 recommended)
119llm = ChatAnthropic(model="claude-sonnet-5")
120 
121# Define tools with Pydantic schemas
122@tool
123def 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
129def 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 
165tools = [search_database, calculate]
166 
167# Create checkpointer for memory persistence
168checkpointer = MemorySaver()
169 
170# Create ReAct agent
171agent = create_react_agent(
172 llm,
173 tools,
174 checkpointer=checkpointer
175)
176 
177# Run agent with thread ID for memory
178config = {"configurable": {"thread_id": "user-123"}}
179result = 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 
187Detailed pattern documentation lives in `references/details.md`. Read that file when the navigation tier above is insufficient.
188 
189## Testing Strategies
190 
191```python
192import pytest
193from unittest.mock import AsyncMock, patch
194 
195@pytest.mark.asyncio
196async 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
209async 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
233from langchain_community.cache import RedisCache
234from langchain_core.globals import set_llm_cache
235import redis
236 
237redis_client = redis.Redis.from_url("redis://localhost:6379")
238set_llm_cache(RedisCache(redis_client))
239```
240 
241### 2. Async Batch Processing
242 
243```python
244import asyncio
245from langchain_core.documents import Document
246 
247async 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 
252async 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
264from langchain_pinecone import PineconeVectorStore
265from pinecone import Pinecone
266 
267# Reuse Pinecone client
268pc = Pinecone(api_key=os.environ["PINECONE_API_KEY"])
269index = pc.Index("my-index")
270 
271# Create vector store with existing index
272vectorstore = PineconeVectorStore(index=index, embedding=embeddings)
273```
274 

Reviews

Installed this one?Write the first review and take the Trailblazer badge.

Reviews only open after a real install, so this is empty — and we leave it empty rather than invent one.

Alternatives

Also in Data & AI