【LangChain】传统 Chain(langchain.chains 模块)列举 和 解释说明
在 LangChain 中,传统 Chain 指的是 langchain.chains 模块中定义的基于类的链,广泛用于 LangChain 0.1.x 及之前的版本。这些 Chain 提供了预定义的工作流,封装了提示模板、语言模型(LLM)、检索器、解析器等组件,用于处理特定任务,如问答、文档处理、API 调用等。然而,随着 LangChain 0.2.x 和 0.3.x 的发展,传统 Chain 逐渐被 LangChain Expression Language(LCEL) 取代,部分 Chain 已废弃或不推荐使用。
基于 LangChain 0.3.x(截至 2025 年 5 月 3 日)梳理 langchain.chains 模块中的所有传统 Chain 类型,包括已废弃和仍可用的 Chain,并说明其功能、适用场景和迁移建议。提供代码示例,展示传统 Chain 的用法和 LCEL 迁移方式,参考 LangChain 文档和源码,确保列出所有相关 Chain。
传统 Chain 概述
传统 Chain 位于 langchain.chains 模块,基于类(如 LLMChain、RetrievalQA)实现,特点是:
- 封装性:每个 Chain 针对特定任务,提供开箱即用的功能。
- 局限性:灵活性较低,难以自定义,且部分 Chain 已废弃。
- 状态:部分 Chain 在 LangChain 0.2.x 中触发
LangChainDeprecationWarning,将在 1.0 中移除。 - 迁移建议:推荐使用 LCEL(如
RunnableSequence、RunnableParallel)替代,参考 LangChain 迁移指南。
以下是 langchain.chains 模块中的所有传统 Chain 类型,穷举基于 LangChain 0.3.x 的源码和文档(langchain.chains 包),按功能分类,涵盖核心 Chain、文档处理 Chain、API 交互 Chain 和其他专用 Chain。
传统 Chain 完整列表
1. 核心 Chain
这些是 LangChain 中最基础的 Chain,用于通用任务。
-
LLMChain
- 功能:结合提示模板和 LLM,生成文本输出。
- 适用场景:简单问答、文本生成、提示驱动任务。
- 状态:已废弃(LangChain 0.2.x),触发
LangChainDeprecationWarning。 - 示例:
from langchain.chains import LLMChainfrom langchain_openai import ChatOpenAIfrom langchain.prompts import PromptTemplatellm = ChatOpenAI(temperature=0)prompt = PromptTemplate.from_template(\"什么是{topic}?\")chain = LLMChain(llm=llm, prompt=prompt)result = chain.run(topic=\"人工智能\")print(result) - LCEL 迁移:
from langchain_core.prompts import ChatPromptTemplatefrom langchain_core.output_parsers import StrOutputParserprompt = ChatPromptTemplate.from_template(\"什么是{topic}?\")chain = prompt | llm | StrOutputParser()result = chain.invoke({\"topic\": \"人工智能\"})
-
SimpleSequentialChain
- 功能:按顺序执行多个 Chain,前一个输出作为后一个输入。
- 适用场景:多步骤任务,如生成+翻译、摘要+分析。
- 状态:已废弃(LangChain 0.2.x)。
- 示例:
chain1 = LLMChain(llm=llm, prompt=PromptTemplate.from_template(\"总结:{text}\"))chain2 = LLMChain(llm=llm, prompt=PromptTemplate.from_template(\"翻译为中文:{summary}\"))chain = SimpleSequentialChain(chains=[chain1, chain2])result = chain.run(\"AI is a field of computer science.\") - LCEL 迁移:
chain = (prompt1 | llm | StrOutputParser() | {\"summary\": RunnablePassthrough()} | prompt2 | llm | StrOutputParser())
-
SequentialChain
- 功能:类似
SimpleSequentialChain,但支持多个输入输出,允许更复杂的步骤依赖。 - 适用场景:需要传递多个变量的多步骤任务。
- 状态:已废弃(LangChain 0.2.x)。
- 示例:
from langchain.chains import SequentialChainchain = SequentialChain( chains=[chain1, chain2], input_variables=[\"text\"], output_variables=[\"summary\", \"translation\"]) - LCEL 迁移:
chain = RunnableSequence( {\"summary\": prompt1 | llm | StrOutputParser(), \"text\": RunnablePassthrough()}, prompt2 | llm | StrOutputParser())
- 功能:类似
2. 检索与问答 Chain
这些 Chain 结合向量存储或检索器,用于检索增强生成(RAG)和文档问答。
-
ConversationalRetrievalChain
- 功能:结合对话历史和向量存储检索器,实现 RAG,支持多轮对话。
- 适用场景:聊天机器人、上下文相关的知识库问答。
- 状态:已废弃(LangChain 0.2.x)。
- 示例:见前文迁移示例(
ConversationBufferMemory和ConversationalRetrievalChain)。 - LCEL 迁移:
使用RunnableWithMessageHistory和ChatMessageHistory,结合检索器和 LCEL 链(见下文完整示例)。
-
RetrievalQA
- 功能:结合向量存储检索器和 LLM,基于检索到的文档回答问题。
- 适用场景:文档问答、知识库查询。
- 状态:部分可用,推荐迁移到 LCEL。
- 示例:
from langchain.chains import RetrievalQAfrom langchain_openai import ChatOpenAI, OpenAIEmbeddingsfrom langchain_community.vectorstores import Chromaembeddings = OpenAIEmbeddings()vectorstore = Chroma.from_texts([\"人工智能是...\"], embeddings)llm = ChatOpenAI(temperature=0)chain = RetrievalQA.from_chain_type(llm=llm, chain_type=\"stuff\", retriever=vectorstore.as_retriever())result = chain.run(\"人工智能是什么?\") - LCEL 迁移:
from langchain_core.prompts import ChatPromptTemplatefrom langchain_core.runnables import RunnablePassthroughprompt = ChatPromptTemplate.from_messages([(\"system\", \"根据上下文回答:\\n{context}\"), (\"human\", \"{question}\")])chain = {\"context\": vectorstore.as_retriever(), \"question\": RunnablePassthrough()} | prompt | llm | StrOutputParser()
-
RetrievalQAWithSourcesChain
- 功能:类似
RetrievalQA,但返回答案和来源文档。 - 适用场景:需要溯源的问答,如学术查询。
- 状态:部分可用,推荐 LCEL。
- 示例:
from langchain.chains import RetrievalQAWithSourcesChainchain = RetrievalQAWithSourcesChain.from_chain_type(llm=llm, chain_type=\"stuff\", retriever=vectorstore.as_retriever())result = chain({\"question\": \"人工智能是什么?\"}) - LCEL 迁移:
chain = {\"context\": vectorstore.as_retriever(), \"question\": RunnablePassthrough()} | prompt | llm | StrOutputParser()# 自定义解析器返回来源
- 功能:类似
3. 文档处理 Chain
这些 Chain 用于处理和分析文档,常与 RetrievalQA 结合。
-
StuffDocumentsChain
- 功能:将多个文档“塞入”(stuff)提示模板,生成回答或摘要。
- 适用场景:短文档处理、简单 RAG。
- 状态:部分可用,推荐 LCEL。
- 示例:
from langchain.chains import StuffDocumentsChainfrom langchain.chains.llm import LLMChaindocument_prompt = PromptTemplate(input_variables=[\"page_content\"], template=\"{page_content}\")llm_chain = LLMChain(llm=llm, prompt=PromptTemplate.from_template(\"总结:{text}\"))chain = StuffDocumentsChain(llm_chain=llm_chain, document_variable_name=\"text\") - LCEL 迁移:
chain = {\"text\": RunnableLambda(lambda docs: \"\\n\".join(doc.page_content for doc in docs))} | prompt | llm | StrOutputParser()
-
MapReduceDocumentsChain
- 功能:对文档分片进行映射(Map)处理,再归约(Reduce)生成最终输出。
- 适用场景:长文档摘要、大规模文档分析。
- 状态:部分可用,推荐 LCEL。
- 示例:
from langchain.chains import MapReduceDocumentsChainmap_chain = LLMChain(llm=llm, prompt=PromptTemplate.from_template(\"总结每段:{text}\"))reduce_chain = LLMChain(llm=llm, prompt=PromptTemplate.from_template(\"综合总结:{summaries}\"))chain = MapReduceDocumentsChain(llm_chain=map_chain, reduce_documents_chain=reduce_chain) - LCEL 迁移:
map_runnable = RunnableLambda(lambda docs: [map_prompt | llm | StrOutputParser().invoke({\"text\": doc.page_content}) for doc in docs])reduce_runnable = {\"summaries\": map_runnable} | reduce_prompt | llm | StrOutputParser()
-
RefineDocumentsChain
- 功能:迭代优化文档内容,逐步生成更精确的回答。
- 适用场景:高质量回答的长文档处理。
- 状态:部分可用,推荐 LCEL。
- 示例:
from langchain.chains import RefineDocumentsChaininitial_chain = LLMChain(llm=llm, prompt=PromptTemplate.from_template(\"初步回答:{text}\"))refine_chain = LLMChain(llm=llm, prompt=PromptTemplate.from_template(\"优化回答:{existing_answer}\\n新信息:{text}\"))chain = RefineDocumentsChain(initial_llm_chain=initial_chain, refine_llm_chain=refine_chain) - LCEL 迁移:
chain = RunnableLambda(lambda docs: reduce(lambda acc, doc: refine_prompt | llm | StrOutputParser().invoke({\"existing_answer\": acc, \"text\": doc.page_content}), docs, initial_prompt | llm | StrOutputParser().invoke({\"text\": docs[0].page_content})))
-
MapRerankDocumentsChain
- 功能:对文档分片进行映射并评分(Rerank),选择最佳文档生成回答。
- 适用场景:需要高精度的文档选择。
- 状态:部分可用,推荐 LCEL。
- 示例:
from langchain.chains import MapRerankDocumentsChainrank_chain = LLMChain(llm=llm, prompt=PromptTemplate.from_template(\"评分并回答:{text}\"))chain = MapRerankDocumentsChain(llm_chain=rank_chain) - LCEL 迁移:
chain = RunnableLambda(lambda docs: max([(rank_prompt | llm | StrOutputParser().invoke({\"text\": doc.page_content}), doc) for doc in docs], key=lambda x: x[0])[1]) | answer_prompt | llm | StrOutputParser()
4. API 交互 Chain
这些 Chain 用于与外部 API 或服务交互。
-
APIChain
- 功能:基于 LLM 生成 API 请求,调用外部 API 并解析响应。
- 适用场景:与 REST API 交互,如天气查询、数据服务。
- 状态:部分可用,推荐使用工具调用或 LCEL。
- 示例:
from langchain.chains import APIChainapi_docs = \"GET /weather?city={city} returns weather data\"chain = APIChain.from_llm_and_api_docs(llm=llm, api_docs=api_docs)result = chain.run(\"北京的天气\") - LCEL 迁移:
chain = prompt | llm.bind_tools([weather_tool]) | tool_parser | RunnableLambda(lambda x: call_api(x))
-
OpenAPIChain
- 功能:基于 OpenAPI 规范生成 API 请求。
- 适用场景:复杂的 API 交互,需解析 OpenAPI 文档。
- 状态:部分可用,推荐工具调用。
- 示例:
from langchain.chains import OpenAPIChainchain = OpenAPIChain.from_openapi_spec(spec, llm=llm) - LCEL 迁移:
chain = prompt | llm.bind_tools(openapi_tools) | tool_parser
5. 数据库与结构化数据 Chain
这些 Chain 用于处理数据库查询或结构化数据。
-
SQLDatabaseChain
- 功能:将自然语言查询转换为 SQL 查询,执行并返回结果。
- 适用场景:数据库查询,如 SQLite、PostgreSQL。
- 状态:部分可用,推荐 LCEL。
- 示例:
from langchain.chains import SQLDatabaseChainfrom langchain_community.utilities import SQLDatabasedb = SQLDatabase.from_uri(\"sqlite:///db.sqlite\")chain = SQLDatabaseChain.from_llm(llm=llm, db=db)result = chain.run(\"有多少用户?\") - LCEL migration:
prompt = ChatPromptTemplate.from_template(\"生成 SQL 查询:{question}\")chain = prompt | llm | StrOutputParser() | RunnableLambda(lambda sql: db.run(sql))
-
VectorDBQA
- 功能:类似
RetrievalQA,但专为向量数据库问答设计。 - 适用场景:向量存储问答(早期版本)。
- 状态:已废弃,推荐
RetrievalQA或 LCEL。 - LCEL 迁移:
参考RetrievalQA迁移。
- 功能:类似
6. 数学与计算 Chain
这些 Chain 用于处理数学或逻辑计算。
- LLMMathChain
- 功能:将自然语言数学问题转换为代码或表达式,计算结果。
- 适用场景:数学计算,如“2+3*4”。
- 状态:部分可用,推荐 LCEL 或工具调用。
- 示例:
from langchain.chains import LLMMathChainchain = LLMMathChain.from_llm(llm=llm)result = chain.run(\"2 + 3 * 4\") - LCEL 迁移:
prompt = ChatPromptTemplate.from_template(\"将问题转换为 Python 表达式:{question}\")chain = prompt | llm | StrOutputParser() | RunnableLambda(lambda x: eval(x))
7. 对话与记忆 Chain
这些 Chain 管理对话历史。
- ConversationChain
- 功能:结合 LLM 和内存(如
ConversationBufferMemory),支持多轮对话。 - 适用场景:简单聊天机器人。
- 状态:已废弃(LangChain 0.2.x)。
- 示例:
from langchain.chains import ConversationChainfrom langchain.memory import ConversationBufferMemorymemory = ConversationBufferMemory()chain = ConversationChain(llm=llm, memory=memory)result = chain.run(\"你好,我叫鲍勃\") - LCEL 迁移:
from langchain_core.runnables import RunnableWithMessageHistoryprompt = ChatPromptTemplate.from_messages([(\"system\", \"你是一个助手\"), MessagesPlaceholder(variable_name=\"history\"), (\"human\", \"{input}\")])chain = RunnableWithMessageHistory(prompt | llm | StrOutputParser(), get_session_history)
- 功能:结合 LLM 和内存(如
8. 其他专用 Chain
这些 Chain 针对特定任务或实验性功能。
-
GraphQAChain
- 功能:基于知识图谱(如 Neo4j)回答问题。
- 适用场景:图数据库查询。
- 状态:实验性,推荐 LangGraph。
- 示例:
from langchain.chains import GraphQAChainfrom langchain_community.graphs import Neo4jGraphgraph = Neo4jGraph(url=\"neo4j://localhost\")chain = GraphQAChain.from_llm(llm=llm, graph=graph) - LCEL 迁移:
使用 LangGraph 构建图工作流。
-
ConstitutionalChain
- 功能:基于“宪法”原则(如道德、安全)检查和修改 LLM 输出。
- 适用场景:内容审查、输出过滤。
- 状态:部分可用,推荐 LCEL。
- 示例:
from langchain.chains import ConstitutionalChainprinciples = [...] # 定义原则chain = ConstitutionalChain.from_llm(llm=llm, principles=principles) - LCEL 迁移:
chain = prompt | llm | StrOutputParser() | RunnableLambda(lambda x: check_principles(x))
-
LLMRouterChain
- 功能:根据输入动态选择子链执行。
- 适用场景:多任务路由,如问题分类。
- 状态:已废弃,推荐
RunnableBranch。 - 示例:
from langchain.chains.router import LLMRouterChaindestinations = [...] # 定义子链chain = LLMRouterChain.from_llm(llm=llm, destinations=destinations) - LCEL 迁移:
chain = RunnableBranch((lambda x: condition(x), chain1), (lambda x: condition2(x), chain2), default_chain)
-
MultiPromptChain
- 功能:根据输入选择不同提示模板执行。
- 适用场景:多提示任务,如问题类型分类。
- 状态:已废弃,推荐
RunnableBranch。 - LCEL 迁移:
类似LLMRouterChain。
-
MultiRetrievalQAChain
- 功能:从多个检索器中选择最合适的执行问答。
- 适用场景:多知识库查询。
- 状态:已废弃,推荐 LCEL。
- LCEL 迁移:
chain = RunnableBranch((lambda x: retriever_condition(x), retriever1), (lambda x: retriever_condition2(x), retriever2)) | prompt | llm
-
TransformChain
- 功能:对输入执行自定义转换(如清洗、格式化)。
- 适用场景:数据预处理。
- 状态:已废弃,推荐
RunnableLambda。 - 示例:
from langchain.chains import TransformChainchain = TransformChain(transform=lambda x: {\"text\": x[\"text\"].upper()}) - LCEL 迁移:
chain = RunnableLambda(lambda x: {\"text\": x[\"text\"].upper()})
-
AnalyzeDocumentChain
- 功能:分析单个文档,执行摘要、提取等任务。
- 适用场景:文档处理。
- 状态:部分可用,推荐 LCEL。
- 示例:
from langchain.chains import AnalyzeDocumentChainchain = AnalyzeDocumentChain(combine_docs_chain=StuffDocumentsChain(...)) - LCEL 迁移:
chain = RunnableLambda(lambda doc: process_doc(doc)) | prompt | llm
-
CombineDocumentsChain
- 功能:基类,用于组合文档的通用逻辑(由
StuffDocumentsChain等继承)。 - 适用场景:文档处理的基础框架。
- 状态:部分可用,推荐 LCEL。
- LCEL 迁移:
参考子类(如StuffDocumentsChain)。
- 功能:基类,用于组合文档的通用逻辑(由
列举说明
以上列出了 langchain.chains 模块中的所有传统 Chain 类型(截至 LangChain 0.3.x),共 24 种,基于:
- LangChain 官方文档(chains 模块)。
- 源码分析(
langchain/chains目录)。 - 社区和迁移指南(v0.2 迁移)。
分类总结:
- 核心 Chain(3):
LLMChain,SimpleSequentialChain,SequentialChain。 - 检索与问答(3):
ConversationalRetrievalChain,RetrievalQA,RetrievalQAWithSourcesChain。 - 文档处理(4):
StuffDocumentsChain,MapReduceDocumentsChain,RefineDocumentsChain,MapRerankDocumentsChain。 - API 交互(2):
APIChain,OpenAPIChain。 - 数据库(2):
SQLDatabaseChain,VectorDBQA。 - 数学(1):
LLMMathChain。 - 对话(1):
ConversationChain。 - 其他专用(8):
GraphQAChain,ConstitutionalChain,LLMRouterChain,MultiPromptChain,MultiRetrievalQAChain,TransformChain,AnalyzeDocumentChain,CombineDocumentsChain。
注意:
- 部分 Chain(如
CombineDocumentsChain)是基类,主要由子类(如StuffDocumentsChain)使用。 - 实验性 Chain(如
GraphQAChain)功能不稳定,推荐 LangGraph。 - 已废弃 Chain(如
LLMChain、ConversationalRetrievalChain)触发警告,需尽快迁移。
完整代码示例
以下展示一个传统 ConversationalRetrievalChain 示例及其 LCEL 迁移版本,代表 RAG 场景的典型用法:
import osos.environ[\"OPENAI_API_KEY\"] = \"Your OpenAI API Key\"# 传统 Chain 示例from langchain.chains import ConversationalRetrievalChainfrom langchain.memory import ConversationBufferMemoryfrom langchain_openai import ChatOpenAI, OpenAIEmbeddingsfrom langchain_community.vectorstores import Chromaembeddings = OpenAIEmbeddings(model=\"text-embedding-3-small\")vectorstore = Chroma.from_texts( [\"人工智能(AI)是计算机科学的一个分支,专注于创建智能系统。\", \"机器学习是 AI 的子领域,涉及从数据中学习模型。\"], embeddings)llm = ChatOpenAI(temperature=0, model=\"gpt-4o-mini\")memory = ConversationBufferMemory(memory_key=\"chat_history\", return_messages=True)chain = ConversationalRetrievalChain.from_llm( llm=llm, retriever=vectorstore.as_retriever(search_kwargs={\"k\": 2}), memory=memory, verbose=True)result = chain({\"question\": \"什么是人工智能?\"})print(result[\"answer\"])result = chain({\"question\": \"它包含哪些子领域?\"})print(result[\"answer\"])# LCEL 迁移示例from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholderfrom langchain_core.output_parsers import StrOutputParserfrom langchain_core.runnables import RunnablePassthrough, RunnableWithMessageHistoryfrom langchain_community.chat_message_histories import ChatMessageHistoryfrom operator import itemgetterprompt = ChatPromptTemplate.from_messages([ (\"system\", \"你是一个助手,根据以下上下文和对话历史回答问题:\\n上下文:{context}\"), MessagesPlaceholder(variable_name=\"history\"), (\"human\", \"{question}\")])runnable = ( { \"context\": itemgetter(\"question\") | vectorstore.as_retriever(search_kwargs={\"k\": 2}), # 提取 question 并传递给 retriever \"question\": itemgetter(\"question\"), # 提取 question 传递给 prompt \"history\": itemgetter(\"history\") | RunnablePassthrough() # 传递 history } | prompt | llm | StrOutputParser())store = {}def get_session_history(session_id: str) -> ChatMessageHistory: if session_id not in store: store[session_id] = ChatMessageHistory() return store[session_id]qa = RunnableWithMessageHistory( runnable, get_session_history, input_messages_key=\"question\", history_messages_key=\"history\")session_id = \"user1\"response = qa.invoke({\"question\": \"什么是人工智能?\"}, config={\"configurable\": {\"session_id\": session_id}})print(response)response = qa.invoke({\"question\": \"它包含哪些子领域?\"}, config={\"configurable\": {\"session_id\": session_id}})print(response)
输出示例:
# 传统 Chain人工智能(AI)是计算机科学的一个分支,专注于创建能够执行需要人类智能的任务的系统,例如学习、推理和决策。人工智能包含子领域,如机器学习,涉及从数据中学习模型。# LCEL 链人工智能(AI)是计算机科学的一个分支,专注于创建能够执行需要人类智能的任务的系统,例如学习、推理和决策。人工智能包含子领域,如机器学习,涉及从数据中学习模型。
说明:
- 传统
ConversationalRetrievalChain使用ConversationBufferMemory管理历史,LCEL 使用RunnableWithMessageHistory。 - LCEL 链更灵活,支持流式、异步等功能。
注意事项
- API 密钥安全:
- 使用
.env文件:from dotenv import load_dotenvload_dotenv() - 确保密钥支持嵌入模型和 LLM。
- 使用
- 迁移优先级:
- 优先迁移已废弃 Chain(如
LLMChain、ConversationalRetrievalChain)。 - 使用 LangChain CLI 自动迁移:
pip install langchain-clilangchain migrate
- 优先迁移已废弃 Chain(如
- 性能:
- LCEL 链支持
stream和ainvoke,优于传统 Chain。 - 优化检索器(如
k参数)提高 RAG 效率。
- LCEL 链支持
- Ollama 替代:
- 使用
langchain_ollama避免 OpenAI 费用:from langchain_ollama import ChatOllama, OllamaEmbeddingsllm = ChatOllama(model=\"qwen3:1.7b\")embeddings = OllamaEmbeddings(model=\"nomic-embed-text\")
- 使用
常见问题
Q1:如何确认某个 Chain 是否废弃?
A:运行代码检查是否触发 LangChainDeprecationWarning,或参考 LangChain 文档。
Q2:所有传统 Chain 都需要迁移吗?
A:已废弃 Chain(如 LLMChain)必须迁移,部分可用 Chain(如 RetrievalQA)可暂时使用,但 LCEL 是未来标准。
Q3:LCEL 能否完全替代传统 Chain?
A:是的,LCEL 通过 Runnable 组合可实现所有传统 Chain 功能,且更灵活。
Q4:如何调试传统 Chain?
A:设置 verbose=True 查看日志,或迁移到 LCEL 使用 langchain.debug = True。
总结
LangChain 中的传统 Chain(langchain.chains)共 24 种,包括:
- 核心:
LLMChain,SimpleSequentialChain,SequentialChain。 - 检索与问答:
ConversationalRetrievalChain,RetrievalQA,RetrievalQAWithSourcesChain。 - 文档处理:
StuffDocumentsChain,MapReduceDocumentsChain,RefineDocumentsChain,MapRerankDocumentsChain。 - API 交互:
APIChain,OpenAPIChain。 - 数据库:
SQLDatabaseChain,VectorDBQA。 - 数学:
LLMMathChain。 - 对话:
ConversationChain。 - 其他:
GraphQAChain,ConstitutionalChain,LLMRouterChain,MultiPromptChain,MultiRetrievalQAChain,TransformChain,AnalyzeDocumentChain,CombineDocumentsChain。


