Skip to content

2.0 本章介绍: LangGraph 核心架构模式

开篇寄语

在 Module 1 中,你已经掌握了 LangGraph 的基础概念——图、状态、节点、边。现在,是时候进入更深层次的学习了。作为一位在软件架构领域耕耘多年的研究者,我深知架构模式的重要性:它们不仅仅是代码模板,更是经过实战检验的思维框架。本章将带你系统学习五种核心架构模式,它们是构建生产级 Agent 系统的基石。


📖 本章在课程中的定位

Module 0: 基础准备 (Python + 工程 + 工具链)

Module 1: LangGraph 框架基础 (图、状态、节点、边)

Module 2: 核心架构模式 ← 你在这里

Module 3-7: 高级特性与生产部署

🎯 本章核心目标

完成本章学习后,你将能够:

  1. 掌握五种经典架构模式 - Simple Graph、Chain、Router、Agent、Agent with Memory
  2. 理解模式背后的设计思想 - 为什么需要这个模式?它解决什么问题?
  3. 实现生产级部署 - 从开发到部署的完整流程
  4. 建立架构思维 - 面对需求,如何选择合适的架构模式

🤔 为什么 Module 2 是关键转折点?

这一章标志着从学习工具构建系统的转变:

Module 1: 学会"怎么用"
    会用 StateGraph
    会写 Node 函数
    会添加 Edge

Module 2: 理解"为什么用"
    为什么 Router 比 Simple Graph 更智能?
    为什么 Agent 需要工具?
    为什么需要 Memory?

这是质的飞跃!

关键洞察

架构模式不是"高级技巧",而是问题的自然解决方案。当你理解了问题的本质,架构模式就会自然浮现。


📚 本章内容结构与学习路径

本章采用从简单到复杂、从静态到动态的渐进式架构:

📍 2.1 Simple Graph: 最简图

核心问题: 如何构建一个最基础的 LangGraph 应用?

这是 LangGraph 的"Hello World",但它揭示了所有后续模式的基础。

你将学到

1. 图的最小组成

python
graph = StateGraph(State)
graph.add_node("node_1", node_1_func)
graph.add_edge(START, "node_1")
graph.add_edge("node_1", END)
app = graph.compile()

2. 状态流转机制

初始状态 → Node → 更新状态 → 下一个 Node → ... → 最终状态

3. 实战案例:情绪生成器

  • 接收用户输入
  • 添加"I am"
  • 随机选择"happy"或"sad"
  • 输出完整句子

架构图示

START → [add_i_am] → [decide_mood] → [happy/sad] → END

为什么从这里开始?

Simple Graph 是理解 LangGraph 执行引擎的最佳入口。它没有复杂的逻辑,但展示了所有核心机制。

学习重点

  • 理解编译-执行两阶段
  • 掌握状态的读取和更新
  • 实现第一个条件边

时间投入: 2-3 小时(含深度理解)

难度: ⭐☆☆☆☆


📍 2.2 Chain: 链式架构

核心问题: 如何构建一个多步骤的处理流水线?

Chain 是最经典的架构模式,适用于线性处理流程

链式架构的本质

输入 → 步骤1 → 步骤2 → 步骤3 → 输出

每个步骤:
- 接收上一步的输出
- 执行特定操作
- 传递给下一步

实战案例:智能文章生成器

需求

  1. 根据主题生成大纲
  2. 根据大纲生成文章
  3. 对文章进行润色

架构设计

python
graph.add_edge(START, "generate_outline")
graph.add_edge("generate_outline", "generate_article")
graph.add_edge("generate_article", "polish")
graph.add_edge("polish", END)

为什么需要 Chain?

场景Simple GraphChain
步骤数量1-2步3+步
步骤依赖强(每步依赖前一步)
可读性更高(清晰的流程)
可维护性高(模块化)

深入理解:Chain vs Pipeline

传统 Pipeline(如 Unix 管道):

bash
cat file.txt | grep "error" | sort | uniq

LangGraph Chain

python
# 不是简单的数据传递,而是状态演进
State_0 → Node_1 → State_1 → Node_2 → State_2 → ...

关键差异

  1. 状态累积:每个节点可以访问完整历史
  2. 丰富上下文:不仅传递输出,还保留所有中间状态
  3. 可观测性:每一步的状态都可检查

最佳实践

1. 模块化设计

python
def step_1(state): ...  # 只做一件事
def step_2(state): ...  # 只做一件事
def step_3(state): ...  # 只做一件事

2. 错误传播

python
class State(TypedDict):
    data: str
    error: Optional[str]  # 错误信息

def step_with_error_handling(state):
    if state.get("error"):
        return {}  # 跳过执行
    try:
        result = process(state["data"])
        return {"data": result}
    except Exception as e:
        return {"error": str(e)}

3. 进度追踪

python
class State(TypedDict):
    data: str
    progress: list[str]  # 记录每一步

def step_1(state):
    result = process(state["data"])
    return {
        "data": result,
        "progress": ["step_1_completed"]
    }

学习重点

  • 设计清晰的步骤划分
  • 实现状态的有序传递
  • 处理步骤间的依赖关系

时间投入: 3-4 小时

难度: ⭐⭐☆☆☆


📍 2.3 Router: 路由架构

核心问题: 如何根据输入或状态动态选择执行路径?

Router 引入了智能决策,这是从"自动化"到"智能化"的关键一步。

路由架构的本质

         输入

      [分类器]

    ┌─────┼─────┐
    ↓     ↓     ↓
  路径A  路径B  路径C
    ↓     ↓     ↓
    └─────┴─────┘

        输出

实战案例:智能客服路由

需求

  • FAQ问题 → 直接回答
  • 技术问题 → 知识库查询
  • 投诉 → 转人工

架构设计

python
def classify_intent(state) -> Literal["faq", "technical", "complaint"]:
    user_message = state["messages"][-1].content
    intent = llm_classify(user_message)
    return intent

graph.add_conditional_edges(
    "classifier",
    classify_intent,
    {
        "faq": "faq_handler",
        "technical": "knowledge_base",
        "complaint": "human_handoff"
    }
)

Router vs Chain 的本质区别

Chain(固定流程)

python
# 所有输入走相同路径
A → B → C → D

# 类比:高速公路(单行道)

Router(动态路由)

python
# 根据条件选择路径
        A

    [决策]
    ↙  ↓  ↘
   B   C   D
    ↓  ↓  ↓
      [汇聚]

# 类比:智能导航(多条路线)

路由策略设计

策略 1: 基于规则(Rule-based)

python
def rule_based_router(state):
    if "urgent" in state["message"].lower():
        return "high_priority"
    elif state["user_tier"] == "vip":
        return "vip_service"
    else:
        return "normal_service"

策略 2: 基于 LLM(AI-powered)

python
def llm_router(state):
    prompt = """
    Classify this request:
    - "sales" for sales inquiries
    - "support" for technical support
    - "other" for everything else

    Request: {message}
    """
    classification = llm.invoke(prompt.format(message=state["message"]))
    return classification.content.strip().lower()

策略 3: 混合(Hybrid)

python
def hybrid_router(state):
    # 1. 先用规则快速过滤
    if state["user_tier"] == "vip":
        return "vip_fast_track"

    # 2. 规则无法决策,用 LLM
    return llm_router(state)

多级路由架构

python
# 一级路由:意图分类
def intent_router(state):
    return classify_intent(state["message"])

# 二级路由:细分处理
def technical_router(state):
    if state["severity"] == "critical":
        return "urgent_tech"
    return "normal_tech"

graph.add_conditional_edges("intent", intent_router, {
    "technical": "tech_router",
    "sales": "sales_handler"
})

graph.add_conditional_edges("tech_router", technical_router, {
    "urgent_tech": "emergency_team",
    "normal_tech": "support_team"
})

关键洞察

Router 的智能程度决定了 Agent 的智能程度。一个好的 Router 能让简单的系统表现出复杂的行为。

学习重点

  • 设计清晰的分类维度
  • 实现多级路由
  • 平衡规则和 AI 的使用

时间投入: 4-5 小时

难度: ⭐⭐⭐☆☆


📍 2.4 Agent: 工具调用架构

核心问题: 如何让 AI 不仅能"说话",还能"做事"?

Agent 是本章的核心重点,它实现了推理-行动循环(ReAct)

Agent 的本质

思考 (Reasoning)

决定调用什么工具

行动 (Acting)

观察结果

继续思考...

这是一个循环,直到找到答案。

ReAct 循环详解

第1轮

用户: "北京今天天气怎么样?明天呢?"

LLM 思考: "我需要查询天气"

决策: tool_call = get_weather("北京", "今天")

工具执行: {"temp": 22, "condition": "晴"}

LLM 继续思考: "还需要查明天的"

第2轮

LLM 思考: "已知今天,还需明天"

决策: tool_call = get_weather("北京", "明天")

工具执行: {"temp": 25, "condition": "多云"}

LLM 继续思考: "信息齐全,可以回答了"

第3轮

LLM 思考: "总结信息"

决策: 不调用工具,给出最终答案

输出: "北京今天晴天22度,明天多云25度"

结束

完整 Agent 架构

python
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langgraph.prebuilt import ToolNode

# 1. 定义工具
@tool
def get_weather(city: str, date: str) -> str:
    """获取天气信息"""
    return f"{city}{date}的天气是晴天"

@tool
def search_web(query: str) -> str:
    """搜索网络信息"""
    return f"搜索结果: {query}"

tools = [get_weather, search_web]

# 2. 创建带工具的 LLM
llm = ChatOpenAI(model="gpt-4")
llm_with_tools = llm.bind_tools(tools)

# 3. 定义状态
class AgentState(TypedDict):
    messages: Annotated[list[BaseMessage], add]

# 4. Agent 节点
def agent_node(state):
    response = llm_with_tools.invoke(state["messages"])
    return {"messages": [response]}

# 5. 路由函数
def should_continue(state) -> Literal["tools", "end"]:
    last_message = state["messages"][-1]
    if hasattr(last_message, "tool_calls") and last_message.tool_calls:
        return "tools"
    return "end"

# 6. 构建图
graph = StateGraph(AgentState)
graph.add_node("agent", agent_node)
graph.add_node("tools", ToolNode(tools))

graph.add_edge(START, "agent")
graph.add_conditional_edges("agent", should_continue, {
    "tools": "tools",
    "end": END
})
graph.add_edge("tools", "agent")  # 关键:形成循环

app = graph.compile()

Agent vs Router 的本质区别

维度RouterAgent
决策次数一次多次(循环)
决策依据输入输入 + 工具结果
执行模式路径选择思考-行动循环
复杂度
智能程度中等

可视化对比

Router(一次决策)

输入 → [分类] → 路径A/B/C → 输出
       单次决策

Agent(多次决策)

输入 → [思考] → 工具1 → [思考] → 工具2 → [思考] → 输出
       决策1     执行     决策2     执行     决策3

工具设计的艺术

好的工具设计

python
@tool
def search_database(
    table: str,
    filters: dict,
    limit: int = 10
) -> str:
    """在数据库中搜索记录

    Args:
        table: 表名("users", "orders", "products")
        filters: 过滤条件,如 {"status": "active", "age__gt": 18}
        limit: 返回结果数量

    Returns:
        JSON格式的搜索结果
    """
    # 清晰的参数
    # 详细的文档
    # 结构化的返回

工具组合策略

策略 1: 最小工具集(Minimal)

python
tools = [
    search,      # 通用搜索
    calculate,   # 数学计算
    execute_code # 代码执行
]
# 优点:LLM 容易选择
# 缺点:每个工具功能复杂

策略 2: 细粒度工具(Granular)

python
tools = [
    search_web,
    search_database,
    search_documents,
    add, subtract, multiply, divide,
    get_user_info,
    update_user_info,
    ...
]
# 优点:每个工具职责单一
# 缺点:工具太多,LLM 容易混淆

策略 3: 分层工具(Hierarchical)

python
# 一级工具:粗粒度
@tool
def data_operations(operation: Literal["search", "create", "update"], **kwargs):
    """数据操作的入口"""
    if operation == "search":
        return search_tool(**kwargs)
    elif operation == "create":
        return create_tool(**kwargs)
    ...

# 二级工具:细粒度(内部调用)
def search_tool(...): ...
def create_tool(...): ...

工具调用的错误处理

python
@tool
def safe_api_call(endpoint: str, params: dict) -> str:
    """安全的 API 调用"""
    try:
        response = requests.get(endpoint, params=params, timeout=5)
        response.raise_for_status()
        return json.dumps(response.json())
    except requests.Timeout:
        return "ERROR: API 超时,请稍后重试"
    except requests.HTTPError as e:
        return f"ERROR: API 返回错误 {e.response.status_code}"
    except Exception as e:
        return f"ERROR: 未知错误 {str(e)}"

# LLM 看到错误信息,可以决定:
# 1. 重试
# 2. 换用其他工具
# 3. 告诉用户失败原因

关键洞察

Agent 不是"调用工具的程序",而是"会使用工具的智能体"。工具是 Agent 的"手",LLM 是 Agent 的"大脑"。

学习重点

  • 实现完整的 ReAct 循环
  • 设计高质量的工具
  • 处理工具调用的错误

时间投入: 6-8 小时(本章最重要)

难度: ⭐⭐⭐⭐☆


📍 2.5 Agent with Memory: 记忆管理

核心问题: 如何让 Agent 记住对话历史和用户信息?

Memory 让 Agent 从"无状态服务"变为"有记忆的助手"。

记忆的层次

层次1: 对话记忆 (Conversation Memory)
    └─ 记住当前会话的所有消息

层次2: 工作记忆 (Working Memory)
    └─ 记住任务执行过程中的中间结果

层次3: 长期记忆 (Long-term Memory)
    └─ 跨会话记住用户信息、偏好等

对话记忆实现

python
class ConversationState(TypedDict):
    messages: Annotated[list[BaseMessage], add]  # 关键:使用 add

def chat_node(state):
    # 所有历史消息都在 state["messages"]
    response = llm.invoke(state["messages"])
    return {"messages": [response]}  # 自动追加

# 执行过程:
# 第1轮: messages = [HumanMessage("你好")]
# 第2轮: messages = [HumanMessage("你好"), AIMessage("你好!"), HumanMessage("我叫Alice")]
# 第3轮: messages = [..., AIMessage("很高兴认识你,Alice")]

记忆修剪策略

问题:无限增长的消息列表会导致:

  1. Token 超限
  2. 成本增加
  3. 响应变慢

解决方案 1: 固定窗口

python
def trim_messages_node(state):
    messages = state["messages"]
    if len(messages) > 20:
        # 保留 system message + 最后15条
        system_msgs = [m for m in messages if m.type == "system"]
        recent_msgs = messages[-15:]
        return {"messages": system_msgs + recent_msgs}
    return {}

解决方案 2: 智能总结

python
def summarize_history_node(state):
    messages = state["messages"]
    if len(messages) > 20:
        # 总结旧消息
        old_messages = messages[:-10]
        summary = llm.invoke([
            SystemMessage("总结以下对话历史"),
            *old_messages
        ])

        # 保留:总结 + 最近10条
        return {"messages": [summary] + messages[-10:]}
    return {}

解决方案 3: 语义过滤

python
def filter_by_relevance_node(state):
    current_query = state["messages"][-1].content
    history = state["messages"][:-1]

    # 计算相关性
    relevant_messages = []
    for msg in history:
        similarity = compute_similarity(current_query, msg.content)
        if similarity > 0.7:
            relevant_messages.append(msg)

    return {"messages": relevant_messages + [state["messages"][-1]]}

长期记忆架构

需求:记住用户的:

  • 个人信息(姓名、偏好)
  • 历史交互
  • 任务状态

实现方式 1: 扩展状态

python
class StatefulAgentState(TypedDict):
    messages: Annotated[list[BaseMessage], add]
    user_profile: dict  # 用户画像
    preferences: dict   # 偏好设置
    task_history: list  # 任务历史

def update_profile_node(state):
    last_message = state["messages"][-1].content
    if "我叫" in last_message:
        name = extract_name(last_message)
        profile = state.get("user_profile", {})
        profile["name"] = name
        return {"user_profile": profile}
    return {}

实现方式 2: 外部存储(生产环境)

python
from langgraph.checkpoint import MemorySaver

# 内存存储(开发环境)
memory = MemorySaver()

app = graph.compile(checkpointer=memory)

# 使用线程 ID 区分不同用户
config = {"configurable": {"thread_id": "user_123"}}

# 第一次对话
app.invoke({"messages": [HumanMessage("我叫Alice")]}, config)

# 稍后的对话(同一用户)
app.invoke({"messages": [HumanMessage("我叫什么?")]}, config)
# Agent 能记住: "你叫 Alice"

Memory + Agent 的完整示例

python
class MemoryAgentState(TypedDict):
    messages: Annotated[list[BaseMessage], add]
    user_info: dict
    conversation_summary: str

def agent_with_memory_node(state):
    # 1. 构建系统提示(包含记忆)
    system_message = f"""你是一个有记忆的助手。

用户信息:
{json.dumps(state.get('user_info', {}), ensure_ascii=False)}

对话总结:
{state.get('conversation_summary', '无')}
"""

    # 2. 调用 LLM(带上下文)
    messages = [SystemMessage(content=system_message)] + state["messages"]
    response = llm_with_tools.invoke(messages)

    # 3. 更新用户信息(从对话中提取)
    new_user_info = extract_user_info(response.content)

    return {
        "messages": [response],
        "user_info": {**state.get("user_info", {}), **new_user_info}
    }

关键洞察

记忆不是"存储历史消息"那么简单,而是"智能管理上下文"——知道记住什么、忘记什么、何时总结。

学习重点

  • 实现对话历史管理
  • 设计记忆修剪策略
  • 集成持久化存储

时间投入: 5-6 小时

难度: ⭐⭐⭐⭐☆


📍 2.6 Deployment: 生产环境部署

核心问题: 如何将开发环境的 Agent 部署到生产环境?

这是从"能跑的代码"到"可靠的服务"的关键一步。

开发 vs 生产的差异

维度开发环境生产环境
存储InMemoryStorePostgreSQL/Redis
并发单线程多进程/多线程
监控print()结构化日志 + 监控系统
容错崩溃即停止自动重启 + 降级策略
配置硬编码环境变量 + 配置中心
访问localhost公网 + 负载均衡

部署架构设计

架构 1: 单体部署(Simple)

┌─────────────────────────┐
│  LangGraph Application  │
│  ├─ StateGraph          │
│  ├─ LLM Client          │
│  └─ Tools               │
├─────────────────────────┤
│  MemorySaver (SQLite)   │
└─────────────────────────┘

   HTTP/WebSocket

   Client Apps

适用:个人项目、原型验证

架构 2: 微服务部署(Production)

┌─────────────┐     ┌─────────────┐
│  Load       │     │  API        │
│  Balancer   │────▶│  Gateway    │
└─────────────┘     └──────┬──────┘

        ┌──────────────────┼──────────────────┐
        ↓                  ↓                  ↓
┌───────────────┐  ┌───────────────┐  ┌───────────────┐
│ LangGraph     │  │ LangGraph     │  │ LangGraph     │
│ Server 1      │  │ Server 2      │  │ Server 3      │
└───────┬───────┘  └───────┬───────┘  └───────┬───────┘
        │                  │                  │
        └──────────────────┼──────────────────┘

              ┌────────────────────────┐
              │  Shared Resources      │
              ├────────────────────────┤
              │  PostgreSQL (状态)     │
              │  Redis (缓存)          │
              │  S3 (文件存储)         │
              │  Monitoring (监控)     │
              └────────────────────────┘

适用:企业级应用、高并发场景

LangGraph Platform 部署

核心组件

  1. LangGraph Server

    • HTTP API 服务器
    • WebSocket 支持(流式输出)
    • 多线程执行引擎
  2. Checkpointer

    • PostgreSQL: 状态持久化
    • Redis: 实时缓存
  3. Docker 容器化

    dockerfile
    FROM python:3.11-slim
    WORKDIR /app
    COPY requirements.txt .
    RUN pip install -r requirements.txt
    COPY . .
    CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
  4. 配置管理

    python
    # config.py
    import os
    
    class Config:
        OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
        DATABASE_URL = os.getenv("DATABASE_URL")
        REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379")
        MAX_CONCURRENT_REQUESTS = int(os.getenv("MAX_CONCURRENT", "10"))

部署清单

1. 文件结构

my-agent/
├── langgraph.json          # LangGraph 配置
├── agent.py                # 图定义
├── requirements.txt        # 依赖
├── .env.example            # 环境变量模板
├── Dockerfile              # Docker 配置
├── docker-compose.yml      # 多容器编排
└── tests/                  # 测试

2. langgraph.json

json
{
  "dependencies": ["langchain", "langgraph", "openai"],
  "graphs": {
    "agent": "./agent.py:graph"
  },
  "env": ".env"
}

3. 部署命令

bash
# 构建 Docker 镜像
langgraph build

# 本地测试
langgraph dev

# 启动服务
langgraph up

# 生产部署
docker-compose up -d

监控与可观测性

1. 结构化日志

python
import structlog

logger = structlog.get_logger()

def agent_node(state):
    logger.info(
        "agent_execution",
        user_id=state.get("user_id"),
        message_count=len(state["messages"]),
        execution_time=timer.elapsed()
    )
    ...

2. 性能指标

python
from prometheus_client import Counter, Histogram

request_count = Counter('agent_requests_total', 'Total requests')
request_duration = Histogram('agent_request_duration_seconds', 'Request duration')

@request_duration.time()
def process_request(state):
    request_count.inc()
    ...

3. 健康检查

python
from fastapi import FastAPI

app = FastAPI()

@app.get("/health")
async def health_check():
    return {
        "status": "healthy",
        "components": {
            "database": check_database(),
            "redis": check_redis(),
            "llm_api": check_llm_api()
        }
    }

关键洞察

部署不是"把代码放到服务器",而是构建一个可靠、可扩展、可观测的生产系统。

学习重点

  • 理解开发-生产环境差异
  • 掌握 Docker 容器化
  • 实现监控和日志

时间投入: 6-8 小时

难度: ⭐⭐⭐⭐⭐


🎯 本章学习方法论

推荐学习路径(3周计划)

Week 1: 基础模式

Day 1-2: Simple Graph (理解基础)
Day 3-4: Chain (理解流水线)
Day 5-6: Router (理解路由)
Day 7: 综合练习 + 回顾

Week 2: 核心模式

Day 8-10: Agent (理解 ReAct)
Day 11-13: Agent with Memory (理解记忆)
Day 14: 综合练习 + 回顾

Week 3: 生产部署

Day 15-17: Deployment (理解部署)
Day 18-19: 构建完整项目
Day 20-21: 优化和调试

学习策略

1. 渐进式理解

第1遍: 运行示例代码,看到效果
第2遍: 修改参数,观察变化
第3遍: 从零实现,理解原理
第4遍: 优化设计,形成模式

2. 对比学习

学 Chain → 思考: Router 解决了 Chain 的什么问题?
学 Router → 思考: Agent 比 Router 强在哪里?
学 Agent → 思考: Memory 给 Agent 带来什么?

3. 项目驱动

不是: 学完所有模式 → 开始做项目
而是: 每学一个模式 → 立即用到项目中

实践建议

项目 1: 智能文档助手

  • Week 1: 实现基础的 Chain(上传→解析→总结)
  • Week 2: 添加 Router(根据文档类型路由)
  • Week 3: 升级为 Agent(可以回答文档相关问题)

项目 2: 客服系统

  • Week 1: 实现 Router(意图分类路由)
  • Week 2: 添加 Agent(可以查询知识库)
  • Week 3: 添加 Memory(记住用户信息)

📊 本章知识图谱

Module 2: 核心架构模式

├─ Simple Graph
│  ├─ 基础构建
│  ├─ 状态流转
│  └─ 条件边入门

├─ Chain
│  ├─ 线性流程设计
│  ├─ 模块化分解
│  └─ 错误处理

├─ Router
│  ├─ 意图分类
│  ├─ 动态路由
│  ├─ 多级路由
│  └─ 规则 vs AI

├─ Agent
│  ├─ ReAct 循环
│  ├─ 工具设计
│  ├─ 工具调用
│  └─ 错误恢复

├─ Memory
│  ├─ 对话记忆
│  ├─ 工作记忆
│  ├─ 长期记忆
│  └─ 记忆修剪

└─ Deployment
   ├─ 容器化
   ├─ 持久化
   ├─ 监控
   └─ 扩展

💡 给不同背景学习者的建议

🎓 如果你是后端开发者

你的优势

  • 熟悉 API 设计
  • 理解微服务架构
  • 掌握部署和运维

学习重点

  • Week 1: 快速过(已有架构思维)
  • Week 2: 深入学习(AI 特有模式)
  • Week 3: 重点关注(利用已有经验)

建议项目:构建一个 API 服务,集成 Agent

预计时间: 2周,每天 2-3小时


👨‍💻 如果你是前端开发者

你的优势

  • 熟悉异步编程
  • 理解状态管理
  • 关注用户体验

学习重点

  • 理解后端 Agent 的工作原理
  • 学习如何与 Agent API 交互
  • 实现流式输出的 UI

建议项目:构建一个聊天界面,连接 Agent 后端

预计时间: 3周,每天 2-3小时


🧑‍🔬 如果你是 AI/ML 研究者

你的优势

  • 理解 LLM 原理
  • 熟悉提示工程
  • 掌握模型调优

学习重点

  • Week 1: 快速过(概念简单)
  • Week 2: 重点学习(AI 应用核心)
  • Week 3: 思考如何优化

建议项目:设计创新的工具调用策略

预计时间: 1-2周,每天 3-4小时


🏢 如果你是产品经理/架构师

你的优势

  • 理解业务需求
  • 掌握系统设计
  • 关注用户价值

学习重点

  • 理解每种模式的应用场景
  • 评估技术可行性
  • 设计系统架构

建议学习方式

  • 运行所有示例,建立感性认知
  • 重点理解架构图和决策树
  • 参与技术方案评审

预计时间: 1周,每天 2-3小时


📖 推荐资源

官方资源

实战案例

  • 客服系统: Router + Agent + Memory
  • 文档助手: Chain + RAG
  • 代码 Agent: Agent + Code Execution Tools

社区资源

  • Discord: LangChain 官方社区
  • GitHub: LangGraph Issues 和 Discussions

⚠️ 常见误区与避坑指南

❌ 误区 1: "我应该总是用最复杂的模式"

正解: 用最简单的能解决问题的模式。

简单问题 → Simple Graph / Chain
中等问题 → Router
复杂问题 → Agent
需要记忆 → Agent + Memory

❌ 误区 2: "Agent 能自动解决所有问题"

正解: Agent 需要好的工具和好的提示。

❌ 误区 3: "部署很简单,复制代码就行"

正解: 生产部署需要考虑监控、日志、容错、扩展等。

❌ 误区 4: "记忆越多越好"

正解: 需要平衡记忆深度和成本、性能。

❌ 误区 5: "跳过前面的模式,直接学 Agent"

正解: Simple Graph 和 Chain 是基础,必须掌握。


🎯 学习成果检验

完成本章后,你应该能够:

理论检验

  • [ ] 能够说出五种模式的核心差异
  • [ ] 能够根据需求选择合适的模式
  • [ ] 能够解释 ReAct 循环的工作原理
  • [ ] 能够设计记忆管理策略

实践检验

  • [ ] 能够实现一个完整的 Chain
  • [ ] 能够实现一个多路由的 Router
  • [ ] 能够实现一个带工具的 Agent
  • [ ] 能够添加记忆管理
  • [ ] 能够部署到生产环境

综合检验

挑战任务: 构建一个"智能旅行助手"

需求:

  1. 根据用户输入识别意图(Router)
  2. 可以查询天气、航班、酒店(Agent + Tools)
  3. 记住用户的旅行偏好(Memory)
  4. 部署为可访问的服务(Deployment)

评分标准:

  • 基础(60分): 实现所有功能
  • 良好(80分): 代码清晰,有错误处理
  • 优秀(100分): 生产级质量,有监控和日志

🚀 本章结语

Module 2 是本课程的核心章节。这五种架构模式是:

  1. Simple Graph: 基石
  2. Chain: 流水线
  3. Router: 智能路由
  4. Agent: 行动力
  5. Memory: 持久性
  6. Deployment: 生产力

掌握它们,你就掌握了构建任意 Agent 系统的能力。

记住

架构模式不是教条,而是思维工具。面对实际问题,灵活组合这些模式,创造出最适合的解决方案。


准备好了吗?让我们开始 Module 2 的学习之旅!

➡️ [2.1 Simple Graph: 最简图](./2.1 Simple graph.md)


Module 2 撰写者一位相信"架构决定系统上限"的研究者2024年10月

基于 MIT 许可证发布。内容版权归作者所有。