LangChain

Python 生态最流行的 LLM 应用开发框架,提供 Agent、Tool、Memory、VectorStore 等完整工具链

简介

LangChain 是 Python 生态中最广泛使用的 LLM 应用开发框架,用于构建由大语言模型驱动的应用程序。它提供了从简单的链式调用到复杂的自主 Agent 的完整抽象层,让开发者可以专注于业务逻辑而非底层 LLM 交互细节。

LangChain 的核心设计理念是”组合”:通过将 LLM、工具、记忆、检索器等组件以声明式方式组合,构建出从简单问答到复杂多步骤 Agent 的各种应用。

核心组件

1. Agent(智能体)

  • create_openai_functions_agent:基于 OpenAI Function Calling 的 Agent 创建函数
  • AgentExecutor:封装完整的推理-执行循环(LLM 调用→解析工具调用→执行工具→结果回传→继续推理)
  • 支持多种 Agent 类型:ReAct、OpenAI Functions、Plan-and-Execute 等

2. Tool(工具)

  • @tool 装饰器:将普通 Python 函数自动转换为 LLM 可调用的工具
  • 自动提取函数签名、参数类型、文档字符串,生成 Function Calling schema
  • 支持工具组合和工具路由

3. Memory(记忆)

  • ConversationBufferMemory:完整对话历史缓存
  • ConversationSummaryMemory:对话摘要压缩
  • ConversationBufferWindowMemory:滑动窗口记忆
  • 通过 MessagesPlaceholder 注入 prompt

4. Prompt 模板

  • ChatPromptTemplate:结构化聊天 prompt 构建
  • MessagesPlaceholder:动态插入消息占位符(如聊天历史、agent_scratchpad)
  • 支持系统消息、用户消息、AI 消息的声明式组合

5. VectorStore(向量存储)

  • Chroma:本地向量数据库集成
  • OpenAIEmbeddings:文本向量化
  • similarity_search:语义相似度检索
  • 支持持久化存储(persist_directory

关键信息

  • 类型:开发框架
  • 语言:Python(另有 LangChain4j 为 Java 版本、LangChain.js 为 JavaScript 版本)
  • 核心范式:Chain(链式调用)→ Agent(自主推理)→ Graph(图编排)
  • 官方文档https://python.langchain.com
  • 竞争框架:LlamaIndex(侧重检索)、Haystack(侧重 NLP 管道)、Semantic Kernel(微软生态)

不同素材中的观点

来自 2026-06-13-langchain-openai-agent-tutorial

  • LangChain + OpenAI 是从零搭建 AI Agent 的最直接路径:pip install langchain openai 即可开始
  • @tool 装饰器将 Python 函数自动转换为 Function Calling 格式,开发者无需手动编写 JSON schema
  • AgentExecutor 封装了完整的推理-执行循环,开发者只需定义工具和 prompt
  • ConversationBufferMemory + MessagesPlaceholder 实现多轮对话记忆,Agent 能理解指代(如”第一封邮件”)
  • ChromaDB 向量存储扩展了 Agent 的知识检索能力,可用于 RAG 场景
  • 系统提示词是 Agent 行为的”操作系统”,比工具定义更能影响 Agent 的行为质量

来自 2026-06-13-deep-agents-framework-guide

  • LangChain 在 LangChain 生态金字塔中是”方向盘和仪表盘”层——提供丰富组件(PromptTemplate / Tools / RAG),Deep Agents 在其之上构建
  • Deep Agents 的中间件架构(TodoListMiddleware、FilesystemMiddleware、SubAgentMiddleware)通过 LangChain 的 create_agent 函数注入
  • LangChain 的 @tool 装饰器是 Deep Agents 自定义工具的底层机制

实用信息

安装方式

pip install langchain openai chromadb python-dotenv

基本用法

from langchain.agents import AgentExecutor, create_openai_functions_agent
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.memory import ConversationBufferMemory
from langchain_openai import ChatOpenAI
 
# 创建 LLM
llm = ChatOpenAI(model="gpt-4")
 
# 定义 prompt
prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一个智能助手..."),
    MessagesPlaceholder(variable_name="chat_history"),
    MessagesPlaceholder(variable_name="agent_scratchpad")
])
 
# 创建 Agent
agent = create_openai_functions_agent(llm=llm, tools=tools, prompt=prompt)
executor = AgentExecutor(agent=agent, tools=tools, memory=memory, verbose=True)

适用场景

  • 需要 LLM 调用外部工具的应用
  • 多轮对话机器人
  • RAG 知识库问答
  • 多步骤任务自动化
  • 多 Agent 协作系统

相关页面