OVERVIEW
一 LangChain 总体架构(5 层)
以 LangChain 为核心,当前主流结构可以抽象为:
text
输入 → Prompt → Model → Chain/Agent → Tool/Memory → Output
拆成 5 层:
| 层级 | 作用 | 核心模块 |
|---|---|---|
| L1 | 模型层 | Models |
| L2 | 提示层 | Prompts |
| L3 | 运行层 | Chains / Runnables |
| L4 | 智能层 | Agents / Tools |
| L5 | 记忆层 | Memory / Retriever |
整体架构示意图:
text
```
📥 输入 (Input)
↓
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ L5 记忆层 (Memory / Retriever) ┃
┃ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┃
┃ │Conversation│ │ VectorStore│ │ Retriever │ ... ┃ ← 选其一或组合
┃ │ Memory │ │ │ │ │ ┃
┃ └────────────┘ └────────────┘ └────────────┘ ┃
┃ 💾 长期记忆、向量检索、上下文管理 ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
↓
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ L4 智能层 (Agents / Tools) ┃
┃ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┃
┃ │ Agent │ │ Tools │ │ReAct/Tool │ ... ┃ ← 选其一或组合
┃ │ Executor │ │ │ │ Calling │ ┃
┃ └────────────┘ └────────────┘ └────────────┘ ┃
┃ 🤖 自主决策、工具调用、多步推理 ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
↓
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ L3 运行层 (Chains / Runnables) ┃
┃ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┃
┃ │ LCEL │ │ LLMChain │ │ Runnable │ ... ┃ ← 选其一
┃ │ │ │ │ │ Sequence │ ┃
┃ └────────────┘ └────────────┘ └────────────┘ ┃
┃ ⚙️ 流程编排、数据流转、LCEL 表达式 ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
↓
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ L2 提示层 (Prompts) ┃
┃ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┃
┃ │ Prompt │ │ Chat │ │ FewShot │ ... ┃ ← 选其一
┃ │ Template │ │ Prompt │ │ Prompt │ ┃
┃ └────────────┘ └────────────┘ └────────────┘ ┃
┃ 📝 模板管理、变量注入、Few-shot 示例 ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
↓
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ L1 模型层 (Models) ┃
┃ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┃
┃ │ OpenAI │ │ Claude │ │HuggingFace │ ... ┃ ← 选其一
┃ │ │ │ │ │ │ ┃
┃ └────────────┘ └────────────┘ └────────────┘ ┃
┃ 🧠 LLM / Chat / Embedding ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
↓
📤 输出 (Output)
二 模块说明
L1 Models层
Chat Models(主流)
python
from langchain.chat_models import ChatOpenAI
或新写法:
python
from langchain_openai import ChatOpenAI
Embeddings(向量)
python
from langchain.embeddings import OpenAIEmbeddings
L2 提示层
负责:Prompt 模板化
1️⃣ PromptTemplate(文本)
python
from langchain.prompts import PromptTemplate
本质:
python
str.format
2️⃣ ChatPromptTemplate(核心)
python
from langchain.prompts import ChatPromptTemplate
3️⃣ MessagesPlaceholder(历史占位)
python
from langchain.prompts import MessagesPlaceholder
用于插入 memory:
python
MessagesPlaceholder("chat_history")
Prompt 层总结
| 模块 | 用途 |
|---|---|
| PromptTemplate | 简单脚本 |
| ChatPromptTemplate | 主流 |
| MessagesPlaceholder | 多轮 |
L3:Chains / Runnables(执行层)
这是 LangChain 最重要的一层。
现在已经统一成:👉 Runnable 体系
1 Runnable(核心抽象)
任何可执行对象都是 Runnable:
Prompt → LLM → Parser
都实现:
python
.invoke()
.stream()
.batch()
2 管道写法
chain = prompt | llm | parser
本质是:RunnableSequence
3 OutputParser(解析器)
from langchain.output_parsers import JsonOutputParser
作用:👉 把模型输出 → 结构化
L4:Agents & Tools(智能层)
负责:让模型"会用工具",这是 Agent 系统的核心。
1 Tools(工具)
from langchain.tools import tool
定义函数:
@tool
def search(q: str):
...
让模型调用。
2 AgentExecutor(运行器)
负责跑 Agent( 负责循环、工具调用、返回结果、verbose/tracing 等)
from langchain.agents import AgentExecutor
3 Tool Calling Agent(推荐)
create_openai_tools_agent()
基于 function calling,更稳。
**「现代标准写法」示例 **
python
from langchain_openai import ChatOpenAI
from langchain.tools import tool
from langchain.agents import (
create_tool_calling_agent,
AgentExecutor
)
from langchain.prompts import ChatPromptTemplate
llm = ChatOpenAI(model="gpt-4o-mini")
@tool
def search(q: str) -> str:
return f"Result for: {q}"
tools = [search]
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant."),
("human", "{input}"),
("placeholder", "{agent_scratchpad}"),
])
# 1️⃣ 造 agent(只负责"想怎么用工具")
agent = create_tool_calling_agent(
llm=llm,
tools=tools,
prompt=prompt
)
# 2️⃣ Executor(负责跑循环)
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
verbose=True
)
# 3️⃣ 调用
res = agent_executor.invoke({
"input": "Search PPO and summarize"
})
print(res["output"])**。
L5:Memory / Retriever(记忆与知识)
负责:上下文 & 知识增强
1️⃣ Memory(对话记忆)
from langchain.memory import ConversationBufferMemory
常见:
| 类型 | 作用 |
|---|---|
| Buffer | 全存 |
| Window | 最近 N 条 |
| Summary | 自动总结 |
2️⃣ VectorStore(向量库)
from langchain.vectorstores import FAISS
或:Chroma/Milvus/Weaviate
3️⃣ Retriever(检索器)
统一接口:
retriever = db.as_retriever()
用于 RAG。
4️⃣ RAG Chain
典型结构:
Retriever → Prompt → LLM
✅ 记忆层总结
| 模块 | 用途 |
|---|---|
| Memory | 多轮 |
| VectorStore | 知识库 |
| Retriever | RAG |