1、简述
LangChain 是一个用于构建 LLM(大语言模型)应用 的 Python 框架,目标是让开发者更高效地将 模型、提示词、记忆、工具、外部数据源 进行编排(Chain / Agent)。
★一句话总结:LangChain = LLM + Prompt + Memory + Tools + Data + Agent

2、LangChain 解决了什么问题?
在原生使用 LLM API 时,通常会遇到:
LangChain 通过 标准化抽象 解决这些问题。
LangChain 核心架构:
LangChain
├── Models # LLM / ChatModel
├── Prompts # PromptTemplate
├── Chains # LLMChain / SequentialChain
├── Memory # ConversationBufferMemory
├── Tools # Tool
├── Agents # ReAct / Function Calling
└── Indexes # VectorStore / Retriever
安装与基础配置:
pip install langchain langchain-community langchain-openai
import os
os.environ["OPENAI_API_KEY"] = "sk-xxx"
3、基础用法
3.1 使用 PromptTemplate
from langchain.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
from langchain.chains import LLMChain
prompt = PromptTemplate(
input_variables=["topic"],
template="请用三点总结 {topic} 的核心思想"
)
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.3)
chain = LLMChain(
llm=llm,
prompt=prompt
)
result = chain.run(topic="微服务架构")
print(result)
3.2 多步骤链路:SequentialChain
from langchain.chains import SequentialChain
chain1 = LLMChain(
llm=llm,
prompt=PromptTemplate(
input_variables=["topic"],
template="为 {topic} 生成一个技术博客大纲"
),
output_key="outline"
)
chain2 = LLMChain(
llm=llm,
prompt=PromptTemplate(
input_variables=["outline"],
template="根据以下大纲写一段总结:{outline}"
),
output_key="content"
)
full_chain = SequentialChain(
chains=[chain1, chain2],
input_variables=["topic"],
output_variables=["content"]
)
print(full_chain({"topic": "LangChain"})["content"])
3.3 对话记忆(Memory)
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
memory = ConversationBufferMemory()
conversation = ConversationChain(
llm=llm,
memory=memory
)
conversation.predict(input="什么是 LangChain?")
conversation.predict(input="它适合用在什么场景?")
4、向量数据库(RAG 实践)
4.1 文档向量化 + 检索
from langchain_community.document_loaders import TextLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import FAISS
# 加载文档
loader = TextLoader("docs.txt")
docs = loader.load()
# 切分
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
documents = splitter.split_documents(docs)
# 向量化
vectorstore = FAISS.from_documents(
documents,
OpenAIEmbeddings()
)
retriever = vectorstore.as_retriever()
4.2 RetrievalQA
from langchain.chains import RetrievalQA
qa = RetrievalQA.from_chain_type(
llm=llm,
retriever=retriever
)
qa.run("LangChain 的核心优势是什么?")
5、Tools 与 Agent 实战
5.1 自定义 Tool
from langchain.tools import Tool
defmultiply(a: int, b: int) -> int:
return a * b
tool = Tool(
name="Multiply",
func=multiply,
description="用于计算两个整数的乘积"
)
5.2 ReAct Agent
from langchain.agents import initialize_agent, AgentType
agent = initialize_agent(
tools=[tool],
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True
)
agent.run("计算 12 和 8 的乘积")
6、总结
LangChain 并不是“造模型”,而是 让 LLM 真正可编程、可工程化 的关键一环。 它非常适合: