LangChain 实战指南:从入门到构建智能应用

1. 引言

大语言模型(LLM)正在重塑软件开发的方式,而 LangChain 作为最流行的 LLM 应用开发框架之一,帮助开发者将模型能力与外部工具、数据源和业务逻辑无缝连接。无论你是刚接触 AI 编程的新手,还是希望系统化构建生产级应用的工程师,本文都将为你提供一份从入门到实战的完整指南。

如果你更倾向于视频学习,可以观看我的视频课程《LangChain 实战》,视频中我会结合代码演示逐步讲解每个核心模块的用法。

2. 什么是 LangChain

LangChain 是一个用于构建基于大语言模型应用的开发框架,于 2022 年 10 月开源,迅速成为 AI 工程领域最受关注的项目之一。它提供了一套标准化的接口和丰富的组件,让开发者可以轻松地将 LLM 与外部数据源、API 工具以及记忆系统集成。

2.1 核心设计理念

LangChain 的核心设计理念可以概括为三个关键词:

  • 模块化:每个功能(模型调用、提示词管理、记忆、检索等)都是独立模块,可按需组合。
  • 可组合性:通过 Chain 机制将多个组件串联成完整的工作流。
  • 生态丰富:支持数百种模型提供商、向量数据库和工具集成。

2.2 为什么选择 LangChain

相比直接调用 OpenAI API 或其他模型接口,LangChain 提供了更高层次的抽象,解决了以下常见痛点:

  • 管理多轮对话的上下文与记忆
  • 将外部数据接入模型(RAG)
  • 调用外部工具和 API(Function Calling)
  • 构建可复用的复杂工作流

3. 环境准备与安装

在开始之前,请确保你的开发环境满足以下要求:

  • Python 3.8 及以上版本
  • pip 包管理工具
  • 一个可用的 LLM API Key(如 OpenAI、Anthropic 或国内大模型服务)

3.1 安装 LangChain

使用 pip 安装核心库:

bash 复制代码
pip install langchain

根据你使用的模型提供商,还需要安装对应的集成包:

bash 复制代码
# OpenAI
pip install langchain-openai

# Anthropic
pip install langchain-anthropic

# 国内模型(如智谱、通义等)
pip install langchain-community

3.2 配置环境变量

建议将 API Key 存放在环境变量中,避免硬编码到代码里:

bash 复制代码
export OPENAI_API_KEY="sk-xxxx"

4. 核心模块详解

LangChain 的生态由多个核心模块组成,理解它们之间的关系是掌握框架的关键。

4.1 Models(模型)

模型模块负责与大语言模型交互。LangChain 统一了不同提供商的调用接口:

python 复制代码
from langchain_openai import ChatOpenAI

# 初始化模型
llm = ChatOpenAI(
    model="gpt-4o",
    temperature=0.7,
    max_tokens=2000
)

# 直接调用
response = llm.invoke("用一句话介绍 LangChain")
print(response.content)

4.2 Prompts(提示词)

提示词模块提供了模板化管理和动态构建提示词的能力:

python 复制代码
from langchain_core.prompts import ChatPromptTemplate

# 定义提示词模板
prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一位{role}专家,请用{style}的风格回答问题。"),
    ("human", "{question}")
])

# 填充变量
formatted_prompt = prompt.format_messages(
    role="Python",
    style="简洁专业",
    question="什么是装饰器?"
)

4.3 Chains(链)

链是 LangChain 的核心抽象,用于将多个组件串联成完整流程:

python 复制代码
from langchain_core.output_parsers import StrOutputParser

# 构建链:提示词 → 模型 → 输出解析
chain = prompt | llm | StrOutputParser()

# 执行链
result = chain.invoke({
    "role": "Python",
    "style": "简洁专业",
    "question": "什么是装饰器?"
})
print(result)

4.4 Memory(记忆)

记忆模块让应用能够记住历史对话,实现多轮交互:

python 复制代码
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain

# 创建带记忆的对话链
memory = ConversationBufferMemory(return_messages=True)
conversation = ConversationChain(
    llm=llm,
    memory=memory,
    verbose=True
)

# 多轮对话
conversation.predict(input="我叫小明,今年 25 岁")
conversation.predict(input="我刚才说我叫什么名字?")

4.5 Retrievers(检索器)

检索器是 RAG(检索增强生成)的核心组件,让模型能够访问外部知识库:

python 复制代码
from langchain_community.document_loaders import TextLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import FAISS

# 1. 加载文档
loader = TextLoader("knowledge.txt")
documents = loader.load()

# 2. 文本切分
splitter = RecursiveCharacterTextSplitter(
    chunk_size=500,
    chunk_overlap=50
)
chunks = splitter.split_documents(documents)

# 3. 向量化存储
embeddings = OpenAIEmbeddings()
vectorstore = FAISS.from_documents(chunks, embeddings)

# 4. 构建检索器
retriever = vectorstore.as_retriever(search_kwargs={"k": 3})

5. 实战案例:构建 RAG 问答系统

下面我们综合运用以上模块,构建一个基于本地文档的智能问答系统。

5.1 完整代码实现

python 复制代码
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_community.document_loaders import TextLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import FAISS
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

# 1. 加载并切分文档
loader = TextLoader("company_manual.txt")
documents = loader.load()

splitter = RecursiveCharacterTextSplitter(
    chunk_size=500,
    chunk_overlap=50
)
chunks = splitter.split_documents(documents)

# 2. 构建向量库
embeddings = OpenAIEmbeddings()
vectorstore = FAISS.from_documents(chunks, embeddings)
retriever = vectorstore.as_retriever(search_kwargs={"k": 3})

# 3. 定义提示词模板
prompt = ChatPromptTemplate.from_messages([
    ("system", "请基于以下资料回答问题,如果资料中没有相关信息,请如实说明:\n\n{context}"),
    ("human", "{question}")
])

# 4. 构建 RAG 链
def format_docs(docs):
    return "\n\n".join(doc.page_content for doc in docs)

rag_chain = (
    {"context": retriever | format_docs, "question": lambda x: x["question"]}
    | prompt
    | ChatOpenAI(model="gpt-4o", temperature=0.3)
    | StrOutputParser()
)

# 5. 提问
result = rag_chain.invoke({"question": "公司的年假政策是什么?"})
print(result)

5.2 工作流程解析

#mermaid-svg-NnG48d6dHhzRy2Fp{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-NnG48d6dHhzRy2Fp .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-NnG48d6dHhzRy2Fp .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-NnG48d6dHhzRy2Fp .error-icon{fill:#552222;}#mermaid-svg-NnG48d6dHhzRy2Fp .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-NnG48d6dHhzRy2Fp .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-NnG48d6dHhzRy2Fp .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-NnG48d6dHhzRy2Fp .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-NnG48d6dHhzRy2Fp .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-NnG48d6dHhzRy2Fp .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-NnG48d6dHhzRy2Fp .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-NnG48d6dHhzRy2Fp .marker{fill:#333333;stroke:#333333;}#mermaid-svg-NnG48d6dHhzRy2Fp .marker.cross{stroke:#333333;}#mermaid-svg-NnG48d6dHhzRy2Fp svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-NnG48d6dHhzRy2Fp p{margin:0;}#mermaid-svg-NnG48d6dHhzRy2Fp .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-NnG48d6dHhzRy2Fp .cluster-label text{fill:#333;}#mermaid-svg-NnG48d6dHhzRy2Fp .cluster-label span{color:#333;}#mermaid-svg-NnG48d6dHhzRy2Fp .cluster-label span p{background-color:transparent;}#mermaid-svg-NnG48d6dHhzRy2Fp .label text,#mermaid-svg-NnG48d6dHhzRy2Fp span{fill:#333;color:#333;}#mermaid-svg-NnG48d6dHhzRy2Fp .node rect,#mermaid-svg-NnG48d6dHhzRy2Fp .node circle,#mermaid-svg-NnG48d6dHhzRy2Fp .node ellipse,#mermaid-svg-NnG48d6dHhzRy2Fp .node polygon,#mermaid-svg-NnG48d6dHhzRy2Fp .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-NnG48d6dHhzRy2Fp .rough-node .label text,#mermaid-svg-NnG48d6dHhzRy2Fp .node .label text,#mermaid-svg-NnG48d6dHhzRy2Fp .image-shape .label,#mermaid-svg-NnG48d6dHhzRy2Fp .icon-shape .label{text-anchor:middle;}#mermaid-svg-NnG48d6dHhzRy2Fp .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-NnG48d6dHhzRy2Fp .rough-node .label,#mermaid-svg-NnG48d6dHhzRy2Fp .node .label,#mermaid-svg-NnG48d6dHhzRy2Fp .image-shape .label,#mermaid-svg-NnG48d6dHhzRy2Fp .icon-shape .label{text-align:center;}#mermaid-svg-NnG48d6dHhzRy2Fp .node.clickable{cursor:pointer;}#mermaid-svg-NnG48d6dHhzRy2Fp .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-NnG48d6dHhzRy2Fp .arrowheadPath{fill:#333333;}#mermaid-svg-NnG48d6dHhzRy2Fp .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-NnG48d6dHhzRy2Fp .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-NnG48d6dHhzRy2Fp .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-NnG48d6dHhzRy2Fp .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-NnG48d6dHhzRy2Fp .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-NnG48d6dHhzRy2Fp .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-NnG48d6dHhzRy2Fp .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-NnG48d6dHhzRy2Fp .cluster text{fill:#333;}#mermaid-svg-NnG48d6dHhzRy2Fp .cluster span{color:#333;}#mermaid-svg-NnG48d6dHhzRy2Fp div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-NnG48d6dHhzRy2Fp .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-NnG48d6dHhzRy2Fp rect.text{fill:none;stroke-width:0;}#mermaid-svg-NnG48d6dHhzRy2Fp .icon-shape,#mermaid-svg-NnG48d6dHhzRy2Fp .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-NnG48d6dHhzRy2Fp .icon-shape p,#mermaid-svg-NnG48d6dHhzRy2Fp .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-NnG48d6dHhzRy2Fp .icon-shape .label rect,#mermaid-svg-NnG48d6dHhzRy2Fp .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-NnG48d6dHhzRy2Fp .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-NnG48d6dHhzRy2Fp .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-NnG48d6dHhzRy2Fp :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 用户提问
检索器检索相关文档
向量数据库 FAISS
返回 Top-K 相关片段
提示词模板组装上下文
大语言模型生成回答
输出最终答案

6. 进阶技巧与最佳实践

6.1 使用 Agent 实现工具调用

Agent 让模型能够自主决定调用哪些工具来完成任务:

python 复制代码
from langchain.agents import create_openai_functions_agent, AgentExecutor
from langchain_core.tools import Tool
from langchain_core.prompts import ChatPromptTemplate

# 定义工具
def get_weather(city: str) -> str:
    """查询城市天气"""
    return f"{city}今天晴,气温 25°C"

tools = [
    Tool(
        name="get_weather",
        func=get_weather,
        description="查询指定城市的天气"
    )
]

# 创建 Agent
agent_prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一个智能助手,可以调用工具回答问题。"),
    ("human", "{input}"),
    ("placeholder", "{agent_scratchpad}")
])

agent = create_openai_functions_agent(
    llm=ChatOpenAI(model="gpt-4o"),
    tools=tools,
    prompt=agent_prompt
)

executor = AgentExecutor(agent=agent, tools=tools)
result = executor.invoke({"input": "北京今天天气怎么样?"})
print(result["output"])

6.2 性能优化建议

  • 缓存:对重复的模型调用启用缓存,减少 API 费用
  • 流式输出 :使用 stream 方法实现打字机效果,提升用户体验
  • 异步支持 :使用 ainvoke 处理高并发场景
  • 成本控制 :合理设置 max_tokens,使用更经济的模型处理简单任务

6.3 常见问题排查

问题 可能原因 解决方案
API 调用超时 网络问题或模型负载高 增加超时时间,实现重试机制
回答不准确 检索结果相关度低 调整 chunk 大小、增加 top-k 数量
上下文超限 文档过长 优化切分策略,使用摘要压缩
费用过高 频繁调用大模型 引入缓存、使用小模型分流

7. 总结与学习资源

LangChain 为 LLM 应用开发提供了强大的基础设施,从简单的提示词管理到复杂的 RAG 和 Agent 系统,都能通过统一的抽象高效实现。掌握本文的核心模块和实战案例,你就具备了构建生产级 AI 应用的基础能力。

推荐学习路径

  1. 掌握 Python 基础与 API 调用
  2. 熟悉 LangChain 五大核心模块
  3. 动手实现 RAG 问答系统
  4. 进阶学习 Agent 与多工具编排
  5. 关注官方文档与社区最佳实践

如果你想通过视频更直观地学习这些内容,欢迎观看我的视频课程《LangChain 实战》,课程中我会用大量可运行的代码示例,带你一步步从零构建完整的 AI 应用。

相关推荐
IT_陈寒1 小时前
Vite性能优化完全指南
前端·人工智能·后端
青少儿编程课堂1 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会C/C++考级:拓扑排序课程表排课解析
c++·python·算法·bfs·信息学竞赛
const_qiu1 小时前
第三章 04:3.6 基础调用链的构建
开发语言·python
一条泥憨鱼1 小时前
AI Agent 安全实践:从 MCP 工具调用到 Java 权限校验
java·人工智能·安全
向上的车轮1 小时前
Python 大数据处理不慢:Polars + DuckDB + Arrow 实战指南
开发语言·python
东方佑1 小时前
用先验重构线性注意力:为什么它至少比普通线性注意力更接近标准注意力
人工智能·机器学习·重构
lucas_AI1 小时前
Read-Parse-Describe:文档解析终于把「图里画了什么」也写进结果了
人工智能
Nebula_g1 小时前
云禾外卖补充—项目整体后端运行逻辑-对流程的更深层次理解
java·开发语言·网络·数据库·状态模式·javase
aneasystone本尊1 小时前
学习大模型训练的目标函数:Next Token Prediction
人工智能