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
相关推荐
Lois_Luo2 小时前
Obsidian + Picgo + Aliyun OSS 实现笔记图片自动上传图床
笔记·oss·图床
(❁´◡`❁)Jimmy(❁´◡`❁)2 小时前
Exgcd 学习笔记
笔记·学习·算法
傻小胖2 小时前
21.ETH-权益证明-北大肖臻老师客堂笔记
笔记·区块链
云小逸3 小时前
【nmap源码学习】 Nmap网络扫描工具深度解析:从基础参数到核心扫描逻辑
网络·数据库·学习
一只小小的芙厨5 小时前
寒假集训笔记·树上背包
c++·笔记·算法·动态规划
盐焗西兰花6 小时前
鸿蒙学习实战之路-Reader Kit构建阅读器最佳实践
学习·华为·harmonyos
深蓝海拓6 小时前
PySide6从0开始学习的笔记(二十七) 日志管理
笔记·python·学习·pyqt
xqqxqxxq6 小时前
Java Thread 类核心技术笔记
java·笔记
慎独4136 小时前
科学赋能,让孩子专注高效爱上学习
学习