Langchain学习笔记一 -基础模块以及架构概览

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
相关推荐
武子康3 小时前
调查研究-186 LangChain 和 LangGraph 的区别:从快速构建 Agent 到生产级工作流编排
人工智能·langchain·llm
葫芦和十三3 天前
渐进发现|代码库不是文档库
langchain·agent·ai编程
柒和远方3 天前
LangGraph 深度解析:从增强型 LLM 到生产级 Agent
langchain·llm·agent
通信小呆呆4 天前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人
H__Rick4 天前
自动对焦学习-3
人工智能·学习·计算机视觉
Daisy Lee4 天前
量化学习-第1章-什么是量化金融
学习·金融·datawhale
Alsn864 天前
等待学习-学习目录:Docker 容器安全攻防
学习·安全·docker
YM52e4 天前
买菜计算器小应用 - HarmonyOS ArkUI 开发实战-PC版本
学习·华为·harmonyos·鸿蒙·鸿蒙系统
小雨下雨的雨4 天前
HarmonyOS ArkUI训练营入门-组件掌握系列-Animation 动画效果实现-PC版本
学习·华为·harmonyos·鸿蒙
闪闪发亮的小星星4 天前
高斯光以及高斯光公式解释
笔记