Skip to content
🔗 分享本题
查看我的学习进度 →

LangChain 将 Prompt、LLM、解析器、检索、记忆和工具组件编排为可复用 Chain

🧠 图解记忆: LangChain 把模型、提示词、检索与工具组件化,Chain 把它们串成可复用流程。

💡 答案要点

LangChain 核心组件:

组件作用示例
LLM模型抽象层ChatOpenAI、ChatAnthropic
Prompt提示词模板ChatPromptTemplate
Chain任务编排LLMChain、SequentialChain
Agent自主决策AgentExecutor
Memory对话记忆ConversationBufferMemory
Retriever文档检索VectorStoreRetriever
VectorStore向量存储Chroma、Milvus、FAISS

Chain 使用示例:

python
from langchain.chains import LLMChain
from langchain.prompts import ChatPromptTemplate
from langchain.chat_models import ChatOpenAI

# 1. 定义 Prompt 模板
prompt = ChatPromptTemplate.from_template(
    "你是一个{role}。请回答以下问题:{question}"
)

# 2. 创建 LLMChain
chain = LLMChain(
    llm=ChatOpenAI(model="gpt-4o"),
    prompt=prompt
)

# 3. 执行
result = chain.run(role="客服助手", question="如何退款?")
print(result)

面试话术:

"LangChain 的核心价值是抽象和编排。我用 LLMChain 封装了 Prompt + LLM,用 SequentialChain 编排多步任务,用 AgentExecutor 实现自主决策。这样代码更模块化,容易测试和维护。"

📚 参考:LangChain 官方文档(核心组件与 Chain)