Langchain:22年的老古董,现在都不知道是什么?一千字带你通关
·
LangChain 技术全栈速览
最小篇幅,最大信息密度。一文覆盖 LangChain 全知识体系。
一、知识图谱
┌─────────────────────────────┐ │ LangChain 应用层 │ │ ┌──────┐ ┌──────┐ ┌──────┐ │ │ │ RAG │ │Agent │ │Workflow│ │ │ └──┬───┘ └──┬───┘ └──┬───┘ │ │ │ │ │ │ │ └────────┼────────┘ │ │ ▼ │ │ ┌──────────────────────┐ │ │ │ Chain / LCEL │ │ │ └──────────┬───────────┘ │ │ ▼ │ │ ┌─────┐ ┌──────┐ ┌───────┐ │ │ │Model│ │Prompt│ │Parser │ │ │ └─────┘ └──────┘ └───────┘ │ └─────────────────────────────┘
二、环境底线
pip install langchain langchain-openai langchain-community pip install faiss-cpu chromadb pypdf streamlit
| 组件 | 推荐方案 | 替代方案 |
|---|---|---|
| LLM | DeepSeek(便宜中文化) | OpenAI / 通义 / Ollama本地 |
| 向量库 | FAISS(入门) | Chroma(生产) |
| Embedding | OpenAI text-embedding-3-small | BGE-small-zh(本地免费) |
| 搜索 | Tavily | Cohere Rerank |
三、核心三板斧:Model → Prompt → Chain
3.1 Model:统一调用接口
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(base_url="https://api.deepseek.com", api_key="sk-xxx", model="deepseek-chat")
# 三种调用方式
llm.invoke("问题") # 单次
llm.batch(["q1","q2"]) # 并发批量
for chunk in llm.stream("..."): # 流式
3.2 PromptTemplate:告别字符串拼接
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
("system", "你是{role}"),
("human", "{question}"),
])
# 填入变量 → 消息列表 → 喂给 LLM
prompt.invoke({"role":"老师","question":"..."}).to_messages()
3.3 LCEL:管道符串联一切
chain = prompt | llm | StrOutputParser() # | 是核心语法
chain.invoke({"topic":"LangChain"}) # 输入 dict → 输出 str
RunnablePassthrough:原样传递数据 RunnableParallel:并行执行多个子链(翻译 + 总结同时跑)
四、Memory:让对话有记忆
from langchain_core.prompts import MessagesPlaceholder
from langchain_core.runnables import RunnableWithMessageHistory
from langchain_community.chat_message_histories import ChatMessageHistory
# Prompt 中预留历史槽位
prompt = ChatPromptTemplate.from_messages([
("system", "你是一个助手"),
MessagesPlaceholder(variable_name="chat_history"), # ← 关键
("human", "{input}"),
])
# 包装成有记忆的链
chain_with_history = RunnableWithMessageHistory(
prompt | llm,
lambda session_id: ChatMessageHistory(), # 按 session_id 取历史
input_messages_key="input",
history_messages_key="chat_history",
)
| 要点 | 说明 |
|---|---|
| 持久化 | SQLChatMessageHistory 替换内存存储,重启不丢失 |
| 裁剪 | trim_messages(max_tokens=2000) 防上下文溢出 |
| session_id | 区分多用户,生产环境每条链对应一个 session |
五、RAG:检索增强生成
5.1 五步流水线
加载文档 → 分块 → 向量化 → 存向量库 → 检索+生成
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import FAISS
# 1. 加载
docs = PyPDFLoader("doc.pdf").load()
# 2. 分块
chunks = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50).split_documents(docs)
# 3+4. 向量化 + 存储
vectorstore = FAISS.from_documents(chunks, embeddings)
# 5. 检索 + 生成
retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
# 完整 RAG Chain
rag_chain = (
{"context": retriever | format_docs, "question": RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)
5.2 分块黄金参数
| 参数 | 推荐值 | 原理 |
|---|---|---|
| chunk_size | 500-1000 | 太小缺上下文,太大不精准 |
| chunk_overlap | 10% | 防关键信息被截断在两块之间 |
| separators | \n\n → \n → 。 → |
优先在自然边界切割 |
六、RAG 进阶优化
优化四象限
| 方向 | 技术 | 原理 |
|---|---|---|
| 查询优化 | Query Rewrite | 口语→精确查询 |
| HyDE | 用 LLM 先生成假设答案,再拿答案向量去搜 | |
| Multi-Query | 生成 3-5 个查询变体,合并去重检索 | |
| 检索优化 | MMR | 最大边际相关,减少重复 chunk |
| Rerank | Cross-Encoder 重排序(Cohere/LLM Rerank) | |
| 混合检索 | 向量 + BM25 关键词 | |
| 生成优化 | 引用来源 | 回答中标注页码 |
| 拒答机制 | 检索不到 → "我不知道" | |
| 压缩上下文 | 去除无关片段 | |
| 评估 | RAGAS | 忠实度 + 相关性 + 上下文精确度 + 召回率 |
一句话:查询改写让搜得到 → MMR/Rerank 让搜得准 → 引用来源让答得可信。
七、Agent:LLM 自主调用工具
7.1 Chain vs Agent
| Chain | Agent | |
|---|---|---|
| 流程 | 固定,开发者定义 | 动态,LLM 自主决策 |
| 适用 | 翻译→总结等确定性任务 | "帮我查天气再算个平均值" |
| 核心 | LCEL 管道 | ReAct 推理循环 |
7.2 定义工具
from langchain_core.tools import tool
@tool
def calculator(expression: str) -> str:
"""计算数学表达式,如 '3+5*2'"""
return str(eval(expression))
@tool
def get_weather(city: str) -> str:
"""查询城市天气"""
return f"{city}:晴 25°C"
7.3 创建 Agent
from langchain.agents import create_tool_calling_agent, AgentExecutor
agent = create_tool_calling_agent(llm, [calculator, get_weather], prompt)
executor = AgentExecutor(
agent=agent, tools=tools,
max_iterations=5, # 防死循环
handle_parsing_errors=True, # 容错
)
executor.invoke({"input": "北京天气几度?"})
7.4 ReAct 模式
Thought → Action → Observation → Thought → ... → Answer "需要天气" | 调工具 | 拿到结果 | "够了" | 最终回复
八、LangGraph:复杂工作流
8.1 解决什么问题
LangChain Agent 流程不可控。LangGraph 用状态图精确控制每一步。
8.2 核心四要素
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
question: str
answer: str
category: str
# 节点 → 函数,输入 State 返回部分 State
def classify(state): ...
def answer_math(state): ...
graph = StateGraph(State)
graph.add_node("classify", classify)
graph.add_node("math", answer_math)
graph.add_edge(START, "classify") # 普通边
graph.add_conditional_edges("classify", route_func, { # 条件分支
"math": "math", "code": "code", "general": "general"
})
graph.add_edge("math", END)
app = graph.compile()
app.invoke({"question": "1+1=?"})
8.3 三种经典模式
| 模式 | 场景 | Graph 形态 |
|---|---|---|
| 条件分支 | 问题分类→不同回答路径 | classify → {math/code/general} |
| 循环优化 | 生成→审核→不满意重写(最多N次) | draft → review ⇄ revise |
| 并行处理 | 同时分析优点+缺点→汇总评分 | summarize → {strengths, weaknesses} → score |
九、三个入门项目
| 项目 | 技术栈 | 一行卖点 |
|---|---|---|
| PDF 智能问答 | LangChain + FAISS + Streamlit | MMR检索 + 来源引用 + 流式输出 |
| 多工具 Agent | LangChain Agent + FastAPI | 搜索/计算/天气/数据库 + 容错恢复 |
| 文档审核工作流 | LangGraph + FastAPI | 摘要→审核→决策→循环修改 |
十、极速质检
Q1: LangChain 核心模块?
Model(LLM封装)、Prompt(模板管理)、Chain(LCEL管道)、Memory(对话历史)、Retriever(RAG检索)、Agent(工具调用)、LangGraph(工作流)。
Q2: RAG 检索不准怎么办?
查询改写 → Multi-Query → HyDE → MMR → Rerank → 混合检索。依次叠加,观察效果。
Q3: Agent 和 Chain 区别?
Chain 流程固定(确定性),Agent 动态决策(开放性)。复杂条件/循环用 LangGraph。
Q4: 如何处理幻觉?
RAG绑定事实来源 + temperature=0 + 拒答机制 + 标注引用出处。三重保障最有效。
Q5: Memory 怎么持久化?
SQLChatMessageHistory存 SQLite,按session_id区分用户。长对话加trim_messages裁剪。
十一、技能优先级
必须掌握 强烈推荐 了解即可 ───────────────── ──────────────── ────────────── Python + LangChain LangGraph LLM 训练 RAG 全流程 Docker/Cloud 部署 分布式系统 Agent + Tool 向量库进阶(Milvus) 算法细节 LCEL 链式语法 RAGAS 评估 GPU编程 FastAPI 技术博客/开源贡献
十二、一条龙速通路线
第1天 → 跑通 LLM 调用 + LCEL 链 + Memory 对话 第2天 → RAG 全流程(PDF→向量库→问答) 第3天 → RAG 优化(Rewrite + MMR + Rerank + 评估) 第4天 → Agent 多工具 + ReAct 第5天 → LangGraph 条件分支 + 循环优化 第6天 → 3 个项目 + Streamlit/Docker 部署第7-8周 → 简历 + 面试 + 投递
🦞 最小篇幅,最大信息密度。收藏即掌握。
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐
所有评论(0)