LangChain 中的链(Chains)类型及示例
LangChain 提供了多种类型的链(Chains),用于将多个组件组合起来完成复杂任务。以下是主要的链类型及示例:
1. LLMChain(基础链)
最基本的链类型,将提示模板、LLM和输出解析器组合在一起。
1 2 3 4 5 6 7 8 9 10 11 12 from langchain.chains import LLMChainfrom langchain.prompts import PromptTemplatefrom langchain.llms import OpenAIprompt = PromptTemplate( input_variables=["product" ], template="为{product}写一个创意广告文案:" ) llm = OpenAI(temperature=0.9 ) chain = LLMChain(llm=llm, prompt=prompt) print (chain.run("环保水杯" ))
2. SequentialChain(顺序链)
按顺序执行多个链,前一个链的输出作为下一个链的输入。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 from langchain.chains import SequentialChain, LLMChainprompt1 = PromptTemplate( input_variables=["product" ], template="为{product}写一个创意广告文案:" ) chain1 = LLMChain(llm=llm, prompt=prompt1, output_key="ad_copy" ) prompt2 = PromptTemplate( input_variables=["ad_copy" ], template="评估以下广告的效果:\n{ad_copy}\n\n评估结果:" ) chain2 = LLMChain(llm=llm, prompt=prompt2, output_key="review" ) overall_chain = SequentialChain( chains=[chain1, chain2], input_variables=["product" ], output_variables=["ad_copy" , "review" ] ) result = overall_chain({"product" : "智能手表" }) print (result)
对输入进行转换而不调用LLM。
1 2 3 4 5 6 7 8 9 10 11 12 13 from langchain.chains import TransformChaindef transform_func (inputs: dict ) -> dict : text = inputs["text" ] return {"output_text" : text.upper()} transform_chain = TransformChain( input_variables=["text" ], output_variables=["output_text" ], transform=transform_func ) transform_chain.run({"text" : "hello world" })
4. RouterChain(路由链)
根据输入决定使用哪个子链。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 from langchain.chains.router import MultiPromptChainfrom langchain.chains.router.llm_router import LLMRouterChain, RouterOutputParserphysics_template = """你是一位物理专家。回答物理问题: 问题: {input}""" math_template = """你是一位数学专家。回答数学问题: 问题: {input}""" prompt_infos = [ { "name" : "physics" , "description" : "适合回答物理问题" , "prompt_template" : physics_template }, { "name" : "math" , "description" : "适合回答数学问题" , "prompt_template" : math_template } ] router_chain = MultiPromptChain.from_prompts( llm, prompt_infos, verbose=True ) print (router_chain.run("什么是相对论?" ))print (router_chain.run("2+2等于几?" ))
5. APIChain(API链)
与外部API交互的链。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 from langchain.chains import APIChainfrom langchain.llms import OpenAIapi_docs = """ API文档: BASE URL: https://api.example.com 端点: GET /weather?location={location} 参数: - location: 城市名称 响应: { "temp": 温度, "condition": 天气状况 } """ chain = APIChain.from_llm_and_api_docs(llm, api_docs, verbose=True ) chain.run("上海现在的天气如何?" )
6. SQLDatabaseChain(数据库链)
与SQL数据库交互的链。
1 2 3 4 5 6 7 from langchain import SQLDatabase, SQLDatabaseChaindb = SQLDatabase.from_uri("sqlite:///chinook.db" ) llm = OpenAI(temperature=0 ) db_chain = SQLDatabaseChain(llm=llm, database=db, verbose=True ) db_chain.run("有多少位顾客?" )
7. RetrievalQAChain(检索问答链)
结合检索器和LLM的问答链。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 from langchain.chains import RetrievalQAfrom langchain.document_loaders import TextLoaderfrom langchain.embeddings import OpenAIEmbeddingsfrom langchain.vectorstores import FAISSloader = TextLoader("state_of_the_union.txt" ) documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000 , chunk_overlap=0 ) texts = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() docsearch = FAISS.from_documents(texts, embeddings) qa = RetrievalQA.from_chain_type( llm=OpenAI(), chain_type="stuff" , retriever=docsearch.as_retriever() ) query = "总统提到了什么重要政策?" qa.run(query)
8. ConversationChain(对话链)
维护对话上下文的链。
1 2 3 4 5 6 7 8 9 10 11 from langchain.chains import ConversationChainfrom langchain.memory import ConversationBufferMemoryconversation = ConversationChain( llm=OpenAI(), memory=ConversationBufferMemory(), verbose=True ) conversation.predict(input ="你好!" ) conversation.predict(input ="我很好,谢谢!你呢?" )
9. MapReduceChain(映射归约链)
处理长文档的链,先映射处理各部分,再归约总结。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 from langchain.chains import MapReduceChainmap_prompt = PromptTemplate( input_variables=["page" ], template="总结以下文本:\n{page}" ) reduce_prompt = PromptTemplate( input_variables=["summaries" ], template="结合以下总结写出最终总结:\n{summaries}" ) chain = MapReduceChain.from_params( llm=llm, map_prompt=map_prompt, reduce_prompt=reduce_prompt ) with open ("long_document.txt" ) as f: long_text = f.read() result = chain.run({"input_text" : long_text})
这些链可以单独使用,也可以组合起来构建更复杂的应用。LangChain还允许创建自定义链以满足特定需求。