Design LLM applications using LangChain 1.x

LangChain & LangGraph Architecture

by wshobson · MIT license · ★ 39,857 on GitHub · updated Sep 21

LangChain & LangGraph Architecture cover

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.

---
name: langchain-architecture
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.
---

# LangChain & LangGraph Architecture

Master modern LangChain 1.x and LangGraph for building sophisticated LLM applications with agents, state management, memory, and tool integration.

## When to Use This Skill

- Building autonomous AI agents with tool access
- Implementing complex multi-step LLM workflows
- Managing conversation memory and state
- Integrating LLMs with external data sources and APIs
- Creating modular, reusable LLM application components
- Implementing document processing pipelines
- Building production-grade LLM applications

Overview

Master modern LangChain 1.x and LangGraph for building sophisticated LLM applications with agents, state management, memory, and tool integration.

Manual install (npx, ZIP)
Claude Codenpx skills add wshobson/agents --skill langchain-architecture -g -a claude-code
Claude Code (manual)mkdir -p ~/.claude/skills && curl -sL https://codeload.github.com/wshobson/agents/tar.gz/4236bb91f839 \ | tar -xz -C ~/.claude/skills --strip-components=4 agents-4236bb91f839/plugins/llm-application-dev/skills/langchain-architecture
Windows (PowerShell)New-Item -ItemType Directory -Force "$HOME\.claude\skills" | Out-Null; Invoke-WebRequest "https://m.agentalley.io/zip/8049c609700a439bea17/langchain-architecture.zip" -OutFile "$env:TEMP\langchain-architecture.zip"; Expand-Archive "$env:TEMP\langchain-architecture.zip" -DestinationPath "$HOME\.claude\skills" -Force
Claude.ai / desktopDownload the ZIP and upload it under Settings → Capabilities → Skills.
Codex, Cursor, other agentsPoint them at SKILL.md. The other files are plain text.

Connects with Agent Alley MCP · agentalley.io/mcp

Files included

  • SKILL.md7.8 KB
  • references/1 file · 10.8 KB
Read the files here
wshobson/4236bb92 files
SKILL.md
Show the full text274 lines

LangChain & LangGraph Architecture

Master modern LangChain 1.x and LangGraph for building sophisticated LLM applications with agents, state management, memory, and tool integration.

When to Use This Skill

  • Building autonomous AI agents with tool access
  • Implementing complex multi-step LLM workflows
  • Managing conversation memory and state
  • Integrating LLMs with external data sources and APIs
  • Creating modular, reusable LLM application components
  • Implementing document processing pipelines
  • Building production-grade LLM applications

Package Structure (LangChain 1.x)

langchain (1.2.x)         # High-level orchestration
langchain-core (1.2.x)    # Core abstractions (messages, prompts, tools)
langchain-community       # Third-party integrations
langgraph                 # Agent orchestration and state management
langchain-openai          # OpenAI integrations
langchain-anthropic       # Anthropic/Claude integrations
langchain-voyageai        # Voyage AI embeddings
langchain-pinecone        # Pinecone vector store

Core Concepts

1. LangGraph Agents

LangGraph is the standard for building agents in 2026. It provides:

Key Features:

  • StateGraph: Explicit state management with typed state
  • Durable Execution: Agents persist through failures
  • Human-in-the-Loop: Inspect and modify state at any point
  • Memory: Short-term and long-term memory across sessions
  • Checkpointing: Save and resume agent state

Agent Patterns:

  • ReAct: Reasoning + Acting with create_react_agent
  • Plan-and-Execute: Separate planning and execution nodes
  • Multi-Agent: Supervisor routing between specialized agents
  • Tool-Calling: Structured tool invocation with Pydantic schemas
2. State Management

LangGraph uses TypedDict for explicit state:

from typing import Annotated, TypedDict
from langgraph.graph import MessagesState

# Simple message-based state
class AgentState(MessagesState):
    """Extends MessagesState with custom fields."""
    context: Annotated[list, "retrieved documents"]

# Custom state for complex agents
class CustomState(TypedDict):
    messages: Annotated[list, "conversation history"]
    context: Annotated[dict, "retrieved context"]
    current_step: str
    results: list
3. Memory Systems

Modern memory implementations:

  • ConversationBufferMemory: Stores all messages (short conversations)
  • ConversationSummaryMemory: Summarizes older messages (long conversations)
  • ConversationTokenBufferMemory: Token-based windowing
  • VectorStoreRetrieverMemory: Semantic similarity retrieval
  • LangGraph Checkpointers: Persistent state across sessions
4. Document Processing

Loading, transforming, and storing documents:

Components:

  • Document Loaders: Load from various sources
  • Text Splitters: Chunk documents intelligently
  • Vector Stores: Store and retrieve embeddings
  • Retrievers: Fetch relevant documents
5. Callbacks & Tracing

LangSmith is the standard for observability:

  • Request/response logging
  • Token usage tracking
  • Latency monitoring
  • Error tracking
  • Trace visualization

Quick Start

Modern ReAct Agent with LangGraph
from langgraph.prebuilt import create_react_agent
from langgraph.checkpoint.memory import MemorySaver
from langchain_anthropic import ChatAnthropic
from langchain_core.tools import tool
import ast
import operator

# Initialize LLM (Claude Sonnet 5 recommended)
llm = ChatAnthropic(model="claude-sonnet-5")

# Define tools with Pydantic schemas
@tool
def search_database(query: str) -> str:
    """Search internal database for information."""
    # Your database search logic
    return f"Results for: {query}"

@tool
def calculate(expression: str) -> str:
    """Safely evaluate a mathematical expression.

    Supports: +, -, *, /, **, %, parentheses
    Example: '(2 + 3) * 4' returns '20'
    """
    # Safe math evaluation using ast
    allowed_operators = {
        ast.Add: operator.add,
        ast.Sub: operator.sub,
        ast.Mult: operator.mul,
        ast.Div: operator.truediv,
        ast.Pow: operator.pow,
        ast.Mod: operator.mod,
        ast.USub: operator.neg,
    }

    def _eval(node):
        if isinstance(node, ast.Constant):
            return node.value
        elif isinstance(node, ast.BinOp):
            left = _eval(node.left)
            right = _eval(node.right)
            return allowed_operators[type(node.op)](left, right)
        elif isinstance(node, ast.UnaryOp):
            operand = _eval(node.operand)
            return allowed_operators[type(node.op)](operand)
        else:
            raise ValueError(f"Unsupported operation: {type(node)}")

    try:
        tree = ast.parse(expression, mode='eval')
        return str(_eval(tree.body))
    except Exception as e:
        return f"Error: {e}"

tools = [search_database, calculate]

# Create checkpointer for memory persistence
checkpointer = MemorySaver()

# Create ReAct agent
agent = create_react_agent(
    llm,
    tools,
    checkpointer=checkpointer
)

# Run agent with thread ID for memory
config = {"configurable": {"thread_id": "user-123"}}
result = await agent.ainvoke(
    {"messages": [("user", "Search for Python tutorials and calculate 25 * 4")]},
    config=config
)

Detailed patterns and worked examples

Detailed pattern documentation lives in references/details.md. Read that file when the navigation tier above is insufficient.

Testing Strategies

import pytest
from unittest.mock import AsyncMock, patch

@pytest.mark.asyncio
async def test_agent_tool_selection():
    """Test agent selects correct tool."""
    with patch.object(llm, 'ainvoke') as mock_llm:
        mock_llm.return_value = AsyncMock(content="Using search_database")

        result = await agent.ainvoke({
            "messages": [("user", "search for documents")]
        })

        # Verify tool was called
        assert "search_database" in str(result)

@pytest.mark.asyncio
async def test_memory_persistence():
    """Test memory persists across invocations."""
    config = {"configurable": {"thread_id": "test-thread"}}

    # First message
    await agent.ainvoke(
        {"messages": [("user", "Remember: the code is 12345")]},
        config
    )

    # Second message should remember
    result = await agent.ainvoke(
        {"messages": [("user", "What was the code?")]},
        config
    )

    assert "12345" in result["messages"][-1].content

Performance Optimization

1. Caching with Redis
from langchain_community.cache import RedisCache
from langchain_core.globals import set_llm_cache
import redis

redis_client = redis.Redis.from_url("redis://localhost:6379")
set_llm_cache(RedisCache(redis_client))
2. Async Batch Processing
import asyncio
from langchain_core.documents import Document

async def process_documents(documents: list[Document]) -> list:
    """Process documents in parallel."""
    tasks = [process_single(doc) for doc in documents]
    return await asyncio.gather(*tasks)

async def process_single(doc: Document) -> dict:
    """Process a single document."""
    chunks = text_splitter.split_documents([doc])
    embeddings = await embeddings_model.aembed_documents(
        [c.page_content for c in chunks]
    )
    return {"doc_id": doc.metadata.get("id"), "embeddings": embeddings}
3. Connection Pooling
from langchain_pinecone import PineconeVectorStore
from pinecone import Pinecone

# Reuse Pinecone client
pc = Pinecone(api_key=os.environ["PINECONE_API_KEY"])
index = pc.Index("my-index")

# Create vector store with existing index
vectorstore = PineconeVectorStore(index=index, embedding=embeddings)
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---
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 documents
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 
View all files on GitHub →

Details

Updated
Sep 21, 2026
License
MIT
Stars on the repo
★ 39,857
Checked
Source
wshobson/agents ↗
Creator
wshobson · 179 listings
View creator

Similar skills

See all →
SkillCreate branded architecture, architecture deltaDiagram designcathrynlavery/diagram-design · by cathrynlaveryCreate branded architecture, architecture delta, IT current-state, flowchart, sequence, state machine, ER/data model, timeline, swimlane, quadrant, radar/spider, polar chart (polar/radial lollipop), loop/flywheel, nested, tree, org chart, layer stack, Venn, pyramid/funnel, treemap and marimekko, heatmap, bar and dumbbell, waterfall, line (slopegraph, ridgeline, streamgraph, bump), Gantt and scatter charts (bubble, beeswarm), high-level, process, medallion, data flow, DP integration, DP security matrix, Sankey, fishbone, Wardley map, kanban, user journey, deployment, dependency graph, UML class, story map, or database schema diagrams as HTML/SVG/PNG, with .drawio, Mermaid, and .excalidraw import, plus lifecycle phase maps, block decomposition trees, and onboarding guidance.★ 43.2k GitHub starsSkillReview a PR against the Pascal architectural rulesReview architecturepascalorg/editor · by pascalorgReview a PR against the Pascal architectural rules — package boundaries (core/viewer/editor/nodes), the registry-driven composition model (def.geometry / def.renderer / def.system), legacy-dispatch regressions, the slots + world-scale-UV convention for new nodes/geometry, hook hygiene (useEditor/useScene/useViewer), and selector performance. Use when the user asks to review a PR, audit a branch, or check that changes respect the codebase's architecture.★ 24.6k GitHub starsSkillCreate and edit draw.io/diagrams.net diagramsDraw.io Architecture StudioAgents365-ai/drawio-skill · by Agents365-aiCreate and edit draw.io/diagrams.net diagrams as editable `.drawio` files. Covers architecture, UML/ERD/sequence, BPMN, network, and swimlane views authored from a description or converted from code, IaC, SQL, and API schemas, plus sync, query, test, review, export, and publish of existing diagrams. Use when the user asks for draw.io/diagrams.net or an editable diagram; prefer Mermaid/PlantUML when diagrams-as-code is enough.★ 9.8k GitHub starsSkillCreate polished dark-themed architecture diagramsArchitecture Diagram SkillCocoon-AI/architecture-diagram-generator · by Cocoon-AICreate polished dark-themed architecture diagrams as self-contained HTML+SVG files. Use when the user asks for system, infrastructure, cloud, security, or network topology diagrams.★ 7.4k GitHub starsSkillThe foundational knowledge distillation pattern for buildingLLM Wiki — Knowledge Distillation PatternAr9av/obsidian-wiki · by Ar9avThe foundational knowledge distillation pattern for building and maintaining an AI-powered Obsidian wiki. Based on Andrej Karpathy's LLM Wiki architecture. Use this skill whenever the user wants to understand the wiki pattern, set up a new knowledge base, or needs guidance on the three-layer architecture (raw sources → wiki → schema). Also use when discussing knowledge management strategy, wiki structure decisions, or how to organize distilled knowledge. This is the "theory" skill — other skills handle specific operations (ingesting, querying, linting).★ 3.5k GitHub starsSkillManage software complexity through deep modulesA Philosophy of Software Design Frameworkwondelai/skills · by wondelaiManage software complexity through deep modules, information hiding, and strategic programming. Use when the user mentions "module design", "API too complex", "shallow class", "complexity budget", "strategic vs tactical", "deep module", "information leakage", "pass-through method", "this code is over-engineered", or "simplify this design". Also trigger when reviewing an interface for simplicity, evaluating whether an abstraction is pulling its weight, deciding whether a comment is worth writing, or choosing between general-purpose and special-purpose approaches. Covers deep vs shallow modules, red flags for complexity, and comments as design documentation. For code quality, see clean-code. For architecture boundaries, see clean-architecture.★ 2.2k GitHub stars

More from wshobson

SkillMaster C/.NET backend development patterns for buildingwshobson/agents · by wshobsonMaster C#/.NET backend development patterns for building robust APIs, MCP servers, and enterprise applications. Covers async/await, dependency injection, Entity Framework Core, Dapper, configuration, caching, and testing with xUnit. Use when developing .NET backends, reviewing C# code, or designing API architectures.★ 39.9k GitHub starsSkillImplement WCAG 2.2 compliant interfaces with mobileAccessibility compliancewshobson/agents · by wshobsonImplement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.★ 39.9k GitHub starsSkillMaster Material Design 3 and Jetpack Compose patternsAndroid Mobile Designwshobson/agents · by wshobsonMaster Material Design 3 and Jetpack Compose patterns for building native Android apps. Use when designing Android interfaces, implementing Compose UI, or following Google's Material Design guidelines.★ 39.9k GitHub starsSkillMigrate from AngularJS to Angular using hybrid modeAngular migrationwshobson/agents · by wshobsonMigrate from AngularJS to Angular using hybrid mode, incremental component rewriting, and dependency injection updates. Use when upgrading AngularJS applications, planning framework migrations, or modernizing legacy Angular code.★ 39.9k GitHub starsSkillUnderstand anti-reversing, obfuscationAnti reversing techniqueswshobson/agents · by wshobsonUnderstand anti-reversing, obfuscation, and protection techniques encountered during software analysis. Use this skill when analyzing malware evasion techniques, when implementing anti-debugging protections for CTF challenges, when reverse engineering packed binaries, or when building security research tools that need to detect virtualized environments.★ 39.9k GitHub starsSkillBuild production Apache Airflow DAGs with best practicesApache Airflow DAG Patternswshobson/agents · by wshobsonBuild production Apache Airflow DAGs with best practices for operators, sensors, testing, and deployment. Use when creating data pipelines, orchestrating workflows, or scheduling batch jobs.★ 39.9k GitHub stars