LangChain 四大核心:Chain, Agent, Memory, Tools

知识库
知识库文档
/tech-stacks/langchain/tutorial/LangChain 四大核心:Chain, Agent, Memory, Tools.md

文档

LangChain 入门教程:四大核心概念

1. Chain:可组合的流水线

Chain 是 LangChain 的核心抽象——将多个步骤串联:

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-3.5-turbo")

# LCEL(LangChain Expression Language)语法
chain = (
    ChatPromptTemplate.from_template("将以下内容翻译为{language}:{text}")
    | llm
    | StrOutputParser()
)

result = chain.invoke({"language": "法语", "text": "你好,世界"})
print(result)  # Bonjour, le monde

| 管道操作符是 LCEL 的核心语法,每个环节的输出自动成为下一个的输入。

2. Agent:LLM 自主决策

Agent 让 LLM 自己决定使用哪些工具、以什么顺序调用:

from langchain.agents import create_react_agent, AgentExecutor
from langchain_community.tools import DuckDuckGoSearchRun, PythonREPLTool

tools = [
    DuckDuckGoSearchRun(),           # 搜索
    PythonREPLTool(),                # 执行 Python 代码
]

agent = create_react_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

executor.invoke({
    "input": "2024年诺贝尔物理学奖得主是谁?把他的年龄算出来(当前年份减去出生年份)"
})

ReAct 模式:Thought → Action → Observation → ... → Final Answer

3. Memory:对话记忆

from langchain.memory import ConversationSummaryMemory

memory = ConversationSummaryMemory(llm=llm, return_messages=True)

# 第一个对话
memory.save_context({"input": "我叫小明"}, {"output": "你好小明!"})
# 第二个
memory.save_context({"input": "我喜欢 Python"}, {"output": "Python 是很好的选择!"})

print(memory.load_memory_variables({}))
# {'history': '用户叫小明,喜欢 Python 编程。'}

记忆类型对比:

类型 原理 适合
BufferMemory 存全部 短对话
BufferWindowMemory 只存最近 K 轮 长对话限流
SummaryMemory LLM 摘要压缩 长对话保留要点
VectorStoreMemory 向量检索历史 关键信息回溯

4. Tools:扩展 LLM 能力边界

from langchain_core.tools import tool

@tool
def multiply(a: int, b: int) -> int:
    """乘法计算器,输入两个整数返回乘积"""
    return a * b

@tool
def get_current_weather(city: str) -> str:
    """获取城市当前天气"""
    import random
    return f"{city}:晴天,{random.randint(18, 35)}°C"

tools = [multiply, get_current_weather]

工具定义的关键:docstring 是 LLM 理解工具的唯一途径,必须写清楚用途和参数。

5. RAG 架构全景

文档加载器 → TextSplitter → Embedding → VectorStore ←─ 检索
                                            ↓            ↑
                                       用户提问 → Embedding ─┘
                                            ↓
                                       LLM + Context
                                            ↓
                                         回答

6. LangChain vs LlamaIndex vs 原生

框架 适合 不适合
LangChain Agent、复杂编排、多 LLM 简单调用
LlamaIndex 文档 RAG、数据分析 Agent 场景
原生 SDK 简单问答、原型 多步骤链

思考题

  1. Agent 中 "Thought" 步骤的作用是什么?如果去掉会发生什么?
  2. RAG 中 chunk_size 设为 100 和 2000 对检索质量有何影响?
  3. Memory 在并发多用户场景如何隔离?应该用哪种 memory 策略?

信息

路径
/tech-stacks/langchain/tutorial/LangChain 四大核心:Chain, Agent, Memory, Tools.md
更新时间
2026/5/31