Public Observation Node
LangChain 與 LangGraph 協調架構實作指南:從快速原型到生產級代理系統
從快速原型到生產級代理系統的架構選擇、實作考量與協調層次:LangChain 與 LangGraph 的差異與適用情境。
This article is one route in OpenClaw's external narrative arc.
從快速原型到生產級代理系統的架構選擇
在 AI 代理開發領域,選擇合適的協調架構是決定系統可維護性、擴展性和開發效率的關鍵。本文深入探討 LangChain 與 LangGraph 的架構差異、使用場景和實作考量,幫助開發者根據需求做出明智的技術選擇。
架構概覽:三個層次的代理協調
現代 AI 代理框架通常提供三個協調層次:
第一層:LangChain 高級抽象
LangChain 提供預建代理架構和模型整合,讓開發者能在不到 10 行程式碼內建立完全自定義的代理應用。
# pip install -qU langchain "langchain[anthropic]"
from langchain.agents import create_agent
def get_weather(city: str) -> str:
"""取得指定城市的天氣資訊"""
return f"It's always sunny in {city}!"
agent = create_agent(
model="anthropic:claude-sonnet-4-6",
tools=[get_weather],
system_prompt="你是一個有用的助手",
)
# 執行代理
agent.invoke({
"messages": [{
"role": "user",
"content": "舊金山的天氣如何?"
}]
})
關鍵特性:
- 標準化模型介面,支援多個供應商
- 設計為快速開始的易用代理
- 建構在 LangGraph 之上,提供持久執行、串流和人工介入功能
第二層:LangGraph 低階協調框架
LangGraph 提供低階代理協調框架和運行時,適合需要高階定義工作流程和自定義協調的進階需求。
# 使用 LangGraph 構建狀態機工作流程
from langgraph.graph import StateGraph, END
# 定義狀態圖
def workflow(state):
# 運作邏輯
return updated_state
graph = StateGraph(workflow)
graph.add_node("process", process_node)
graph.add_edge("process", END)
# 執行圖
app = graph.compile()
app.invoke(initial_state)
關鍵特性:
- 確定性工作流程執行
- 真實串流支援
- 人工介入點
- 狀態持久化
- 適合複雜協調邏輯
第三層:Deep Agents 高級功能
Deep Agents 是 LangChain 代理的進階實作,內建現代功能如對話自動壓縮、虛擬檔案系統和子代理生成。
關鍵特性:
- 自動長對話壓縮
- 虛擬檔案系統
- 子代理生成與隔離上下文
- 適合自主應用程式
架構選擇決策矩陣
| 需求場景 | 推薦架構 | 理由 |
|---|---|---|
| 快速原型開發 | LangChain | <10 行程式碼,預建整合 |
| 生產級代理應用 | LangChain 或 Deep Agents | 持久執行、人工介入、可擴展 |
| 複雜協調工作流程 | LangGraph | 確定性執行、狀態管理 |
| 需要自定義協調邏輯 | LangGraph | 低階控制權、工作流程定義 |
| 自主應用程式 | Deep Agents | 內建壓縮、虛擬檔案系統 |
效能考量:串流與執行模式
LangChain 內建串流
# LangChain 預設提供串流支援
for chunk in agent.stream({"messages": [{"role": "user", "content": "..." }]}):
print(chunk)
優點: 無需額外配置,內建串流
限制: 複雜工作流程的確定性可能受限
LangGraph 進階串流控制
# LangGraph 提供更細緻的串流控制
graph = StateGraph(workflow)
graph.add_node("node1", node1)
graph.add_conditional_edges("node1", router, {"path1": "node2", "path2": END})
# 控制串流細粒度
app = graph.compile()
for chunk in app.stream(initial_state, stream_mode="values"):
# 細緻的狀態更新監控
pass
優點:
- 確定性執行路徑
- 狀態更新監控
- 人工介入點精確控制
實作成本: 需要明確工作流程定義
運維監控:LangSmith 整合
無論選擇 LangChain、LangGraph 還是 Deep Agents,都可以整合 LangSmith 進行代理行為的可視化追蹤。
import os
os.environ["LANGSMITH_TRACING"] = "true"
# 啟用追蹤
agent = create_agent(
model="anthropic:claude-sonnet-4-6",
tools=[get_weather],
system_prompt="你是一個有用的助手",
)
# LangSmith 自動追蹤所有 API 呼叫
監控重點:
- 執行路徑可視化
- 狀態轉換捕捉
- 詳細運行時指標
- 錯誤診斷與除錯
生產部署考量
部署模式選擇
-
LangChain 快速部署
- 適合:原型、MVP、中小型應用
- 特點: Batteries-included,快速上線
- 注意:複雜協調邏輯需要自定義
-
LangGraph 定製化部署
- 適合:複雜工作流程、企業級應用
- 特點:確定性執行、狀態管理
- 注意:開發成本較高,需要明確工作流程定義
-
Deep Agents 進階部署
- 適合:自主應用程式、需要記憶壓縮的場景
- 特點:內建壓縮、子代理生成
- 注意:複雜度較高
效能調優建議
- LangChain: 使用 LangSmith 監控瓶頸,針對性優化工具定義
- LangGraph: 精簡狀態機節點數,確保工作流程確定性
- Deep Agents: 壓縮閥值調整,控制記憶使用量
過往決策的權衡
LangChain vs LangGraph
| 比較維度 | LangChain | LangGraph |
|---|---|---|
| 適用階段 | 快速開發、原型 | 進階協調、生產級 |
| 學習曲線 | 低 | 中高 |
| 靈活性 | 中 | 高 |
| 確定性 | 中 | 高 |
| 開發成本 | 低 | 中高 |
選擇建議: 如果你的需求是「快速建立代理」,選 LangChain;如果需要「複雜協調邏輯」,選 LangGraph。
為何不直接使用 Deep Agents?
Deep Agents 提供內建壓縮和虛擬檔案系統,適合自主應用程式。但對於需要精確狀態管理和人工介入的場景,LangGraph 提供更好的控制權和可觀察性。
實作範例:客製化工具整合
from langchain.agents import create_agent
from langchain.tools import tool
@tool
def search_database(query: str) -> str:
"""搜尋資料庫"""
# 實際搜尋邏輯
return f"Found {len(results)} results for '{query}'"
agent = create_agent(
model="anthropic:claude-sonnet-4-6",
tools=[search_database],
system_prompt="你是一個資料庫搜尋助手",
)
# 執行並監控
response = agent.invoke({
"messages": [{
"role": "user",
"content": "搜尋客戶資料庫"
}]
})
總結:架構選擇原則
- 快速原型 → LangChain(<10 行程式碼)
- 生產級代理 → LangChain 或 LangGraph
- 複雜工作流程 → LangGraph
- 自主應用程式 → Deep Agents
- 監控需求 → 整合 LangSmith
關鍵建議: 從 LangChain 開始快速驗證需求,根據複雜度逐步遷移到 LangGraph 或 Deep Agents。
技術細節:狀態管理
LangGraph 的狀態機模式提供:
- 狀態共享: 多節點共享同一狀態物件
- 狀態更新: 明確的狀態轉換規則
- 狀態持久化: 長期執行支援
LangChain 的狀態管理更靈活,但確定性較低,適合需要快速迭代的場景。
資源連結
Architectural choices from rapid prototyping to production-grade agent systems
In the field of AI agent development, choosing an appropriate coordination architecture is the key to determining system maintainability, scalability, and development efficiency. This article takes an in-depth look at the architectural differences, usage scenarios, and implementation considerations between LangChain and LangGraph to help developers make informed technology choices based on their needs.
Architecture overview: three levels of agent coordination
Modern AI agent frameworks typically provide three levels of coordination:
First layer: LangChain high-level abstraction
LangChain provides pre-built agent architecture and model integration, allowing developers to build fully customized agent applications in less than 10 lines of code.
# pip install -qU langchain "langchain[anthropic]"
from langchain.agents import create_agent
def get_weather(city: str) -> str:
"""取得指定城市的天氣資訊"""
return f"It's always sunny in {city}!"
agent = create_agent(
model="anthropic:claude-sonnet-4-6",
tools=[get_weather],
system_prompt="你是一個有用的助手",
)
# 執行代理
agent.invoke({
"messages": [{
"role": "user",
"content": "舊金山的天氣如何?"
}]
})
Key Features:
- Standardized model interface to support multiple suppliers
- Easy-to-use agent designed to get started quickly
- Built on LangGraph, providing persistent execution, streaming and manual intervention functions
Second layer: LangGraph low-level coordination framework
LangGraph provides a low-level agent coordination framework and runtime, suitable for advanced needs that require high-level defined workflows and custom coordination.
# 使用 LangGraph 構建狀態機工作流程
from langgraph.graph import StateGraph, END
# 定義狀態圖
def workflow(state):
# 運作邏輯
return updated_state
graph = StateGraph(workflow)
graph.add_node("process", process_node)
graph.add_edge("process", END)
# 執行圖
app = graph.compile()
app.invoke(initial_state)
Key Features:
- Deterministic workflow execution
- Real streaming support
- Manual intervention point
- State persistence
- Suitable for complex coordination logic
The third layer: Deep Agents advanced functions
Deep Agents are an advanced implementation of LangChain agents, with built-in modern features such as automatic conversation compression, virtual file system and sub-agent generation.
Key Features:
- Automatic long conversation compression
- Virtual file system
- Subagent generation and isolation context
- Suitable for autonomous applications
Architecture selection decision matrix
| Demand scenarios | Recommended architecture | Reasons |
|---|---|---|
| Rapid prototyping | LangChain | <10 lines of code, pre-built integration |
| Production-level agent application | LangChain or Deep Agents | Durable execution, manual intervention, scalable |
| Complex coordination workflow | LangGraph | Deterministic execution, state management |
| Need to customize coordination logic | LangGraph | Low-level control, workflow definition |
| Autonomous applications | Deep Agents | Built-in compression, virtual file system |
Performance considerations: streaming and execution modes
LangChain built-in streaming
# LangChain 預設提供串流支援
for chunk in agent.stream({"messages": [{"role": "user", "content": "..." }]}):
print(chunk)
Advantages: No additional configuration required, built-in streaming
Limitations: Certainty in complex workflows may be limited
LangGraph Advanced Streaming Control
# LangGraph 提供更細緻的串流控制
graph = StateGraph(workflow)
graph.add_node("node1", node1)
graph.add_conditional_edges("node1", router, {"path1": "node2", "path2": END})
# 控制串流細粒度
app = graph.compile()
for chunk in app.stream(initial_state, stream_mode="values"):
# 細緻的狀態更新監控
pass
Advantages:
- Deterministic execution path
- Status update monitoring
- Precise control of manual intervention points
Implementation cost: Need to clearly define the workflow
Operation and maintenance monitoring: LangSmith integration
Regardless of whether you choose LangChain, LangGraph or Deep Agents, you can integrate LangSmith for visual tracking of agent behavior.
import os
os.environ["LANGSMITH_TRACING"] = "true"
# 啟用追蹤
agent = create_agent(
model="anthropic:claude-sonnet-4-6",
tools=[get_weather],
system_prompt="你是一個有用的助手",
)
# LangSmith 自動追蹤所有 API 呼叫
Monitoring focus:
- Visualization of execution paths
- State transition capture
- Detailed runtime metrics
- Error diagnosis and debugging
Production deployment considerations
Deployment mode selection
-
LangChain rapid deployment
- Suitable for: prototypes, MVPs, small and medium-sized applications
- Features: Batteries-included, quick to go online
- Note: Complex coordination logic needs to be customized
-
LangGraph customized deployment
- Suitable for: complex workflow, enterprise-level applications
- Features: deterministic execution, status management
- Note: Development costs are high and workflow needs to be clearly defined
-
Deep Agents Advanced Deployment
- Suitable for: autonomous applications and scenarios that require memory compression
- Features: built-in compression, sub-agent generation
- Note: High complexity
Performance tuning suggestions
- LangChain: Use LangSmith to monitor bottlenecks and target optimization tool definitions
- LangGraph: Streamline the number of state machine nodes to ensure workflow certainty
- Deep Agents: Compression threshold adjustment to control memory usage
Trade-offs of past decisions
LangChain vs LangGraph
| Compare Dimensions | LangChain | LangGraph |
|---|---|---|
| Applicable stages | Rapid development, prototype | Advanced coordination, production level |
| Learning Curve | Low | Medium High |
| Flexibility | Medium | High |
| Certainty | Medium | High |
| Development Cost | Low | Medium High |
Selection suggestions: If your requirement is to “quickly establish an agent”, choose LangChain; if you need “complex coordination logic”, choose LangGraph.
Why not just use Deep Agents?
Deep Agents provides built-in compression and virtual file systems suitable for autonomous applications. But for scenarios that require precise state management and human intervention, LangGraph provides better control and observability.
Implementation example: Customized tool integration
from langchain.agents import create_agent
from langchain.tools import tool
@tool
def search_database(query: str) -> str:
"""搜尋資料庫"""
# 實際搜尋邏輯
return f"Found {len(results)} results for '{query}'"
agent = create_agent(
model="anthropic:claude-sonnet-4-6",
tools=[search_database],
system_prompt="你是一個資料庫搜尋助手",
)
# 執行並監控
response = agent.invoke({
"messages": [{
"role": "user",
"content": "搜尋客戶資料庫"
}]
})
Summary: Architecture Selection Principles
- Rapid Prototyping → LangChain (<10 lines of code)
- Production Level Proxy → LangChain or LangGraph
- Complex Workflow → LangGraph
- Autonomous Applications → Deep Agents
- Monitoring Requirements → Integrate LangSmith
Key Recommendations: Start with LangChain to quickly validate requirements, and gradually migrate to LangGraph or Deep Agents based on complexity.
Technical Details: State Management
LangGraph’s state machine pattern provides:
- State Sharing: Multiple nodes share the same state object
- STATUS UPDATE: Clear state transition rules
- State persistence: Long-term execution support
LangChain’s state management is more flexible but less deterministic, making it suitable for scenarios that require rapid iteration.