1. LangChain 简介与核心概念

LangChain 是一个用于构建基于大语言模型(LLM)应用程序的开源框架。它通过提供模块化组件和链式调用机制,简化了 LLM 应用开发的复杂性,让开发者能够更高效地构建智能代理、问答系统、文档分析等应用。

核心概念:

  • 模型(Models):与各种 LLM(如 OpenAI GPT、Claude、本地模型)交互的抽象层。
  • 提示词(Prompts):管理、优化和模板化输入给模型的指令。
  • 链(Chains):将多个组件(模型、提示词、工具等)组合成可执行的工作流。
  • 记忆(Memory):在链或代理的多次调用之间保持状态和上下文。
  • 索引(Indexes):结合外部数据(如文档、数据库)与 LLM,实现检索增强生成(RAG)。
  • 代理(Agents):让 LLM 自主决定调用哪些工具(如搜索、计算、API)来完成复杂任务。

2. 环境搭建与快速开始

首先,确保你的 Python 环境版本在 3.8 或以上。

# 使用 pip 安装 LangChain 核心包
pip install langchain
根据需求安装社区集成包,例如 OpenAI
pip install langchain-openai
安装常用的工具包,如用于文档加载的包
pip install langchain-community

安装完成后,你可以通过一个简单的示例来验证环境:

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
初始化模型(此处需要设置你的 OPENAI_API_KEY)
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
创建提示词模板
prompt = ChatPromptTemplate.from_messages([
("system", "你是一个乐于助人的助手。"),
("user", "{input}")
])
创建链
chain = prompt | llm
调用链
response = chain.invoke({"input": "用一句话介绍 LangChain。"})
print(response.content)

3. 核心组件深度解析

3.1 模型 I/O:与 LLM 对话的基础

LangChain 提供了统一的接口来调用不同的 LLM。除了 OpenAI,还支持 Anthropic、Cohere、本地模型(如通过 Ollama)等。

from langchain_anthropic import ChatAnthropic
from langchain_community.llms import Ollama
使用 Claude 模型
claude_llm = ChatAnthropic(model="claude-3-5-sonnet-20241022")
使用本地 Ollama 模型
local_llm = Ollama(model="llama3.2")

3.2 提示词工程:从简单到复杂

好的提示词是获得高质量回答的关键。LangChain 提供了 PromptTemplateChatPromptTemplateFewShotPromptTemplate 等工具来构建动态提示。

from langchain_core.prompts import ChatPromptTemplate, FewShotPromptTemplate
from langchain_core.prompts.example_selector import SemanticSimilarityExampleSelector
构建一个包含上下文和问题的复杂提示词
template = """你是一个专业的{role}。请根据以下背景信息回答问题。
背景:{context}
问题:{question}
请给出详细、准确的回答。"""
prompt = ChatPromptTemplate.from_template(template)
使用示例
formatted_prompt = prompt.format(role="软件架构师", context="系统采用微服务架构...", question="如何设计服务间的通信?")
print(formatted_prompt)

3.3 链:构建复杂工作流

链(Chain)是 LangChain 的核心抽象,允许你将多个步骤串联起来。最简单的链是 LLMChain,更复杂的可以使用 SequentialChain 或 LCEL(LangChain Expression Language)。

from langchain.chains import LLMChain, SimpleSequentialChain
from langchain_core.prompts import PromptTemplate
定义第一个链:生成博客标题
title_template = PromptTemplate(input_variables=["topic"], template="为{topic}写一个吸引人的博客标题。")
title_chain = LLMChain(llm=llm, prompt=title_template)
定义第二个链:根据标题生成大纲
outline_template = PromptTemplate(input_variables=["title"], template="为标题《{title}》生成详细的博客大纲。")
outline_chain = LLMChain(llm=llm, prompt=outline_template)
组合成顺序链
overall_chain = SimpleSequentialChain(chains=[title_chain, outline_chain], verbose=True)
执行
result = overall_chain.run("人工智能在医疗诊断中的应用")
print(result)

3.4 记忆:让对话拥有上下文

记忆组件使 LLM 能够记住之前的交互。常用的有 ConversationBufferMemory(保存所有历史)、ConversationSummaryMemory(保存摘要)等。

from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
memory = ConversationBufferMemory()
conversation = ConversationChain(llm=llm, memory=memory, verbose=True)
conversation.predict(input="你好,我叫小明。")
conversation.predict(input="你还记得我的名字吗?")
输出会包含之前的对话历史

3.5 检索增强生成(RAG)实战

RAG 通过检索外部知识库来增强 LLM 的回答,使其能够提供更准确、更有时效性的信息。

from langchain_community.document_loaders import TextLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import Chroma
from langchain.chains import RetrievalQA
1. 加载文档
loader = TextLoader("knowledge_base.txt")
documents = loader.load()
2. 分割文本
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
texts = text_splitter.split_documents(documents)
3. 创建向量存储
embeddings = OpenAIEmbeddings()
vectorstore = Chroma.from_documents(texts, embeddings)
4. 创建检索器
retriever = vectorstore.as_retriever()
5. 创建问答链
qa_chain = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=retriever)
6. 提问
answer = qa_chain.run("LangChain 的主要优势是什么?")
print(answer)

3.6 代理:让 LLM 使用工具

代理(Agent)赋予 LLM 使用外部工具(如搜索、计算、执行代码)的能力,以完成更复杂的任务。

from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
from langchain_community.utilities import SerpAPIWrapper
from langchain.chains import LLMMathChain
定义工具
search = SerpAPIWrapper()
llm_math = LLMMathChain(llm=llm)
tools = [
Tool(
name="Search",
func=search.run,
description="当需要回答关于当前事件或具体事实的问题时使用。"
),
Tool(
name="Calculator",
func=llm_math.run,
description="当需要解决数学问题时使用。"
),
]
初始化代理
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
运行代理
agent.run("截至2026年7月,OpenAI GPT-5 的最新消息是什么?另外,计算 125 的平方根。")

4. 2026 年最佳实践与进阶技巧

4.1 性能优化与成本控制

  • 缓存:使用 langchain.cache(如 InMemoryCacheSQLiteCache)缓存重复的模型调用结果。
  • 流式输出:使用 chain.stream() 实现逐词输出,提升用户体验。
  • 异步调用:使用 chain.ainvoke()chain.abatch() 提升高并发场景下的吞吐量。
  • 模型选择:根据任务复杂度在“大模型高精度”和“小模型低成本”之间权衡。

4.2 可观测性与调试

  • 启用 verbose=True 查看链的详细执行步骤。
  • 使用 langchain.callbacks 记录日志、跟踪 token 使用量。
  • 利用 LangSmith 平台(如可用)进行全链路追踪、测试和评估。

4.3 生产环境部署考量

  • 安全性:对用户输入进行严格的清理和审查,防止提示词注入攻击。
  • 稳定性:为模型调用和工具调用添加重试和回退机制。
  • 可扩展性:考虑使用消息队列(如 Celery)处理异步任务,将向量数据库部署为独立服务。
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐