AI创想

标题: 【LangChain系列4】【Chain模块详解】 [打印本页]

作者: 我是奥利奥丶    时间: 2025-9-7 23:36
标题: 【LangChain系列4】【Chain模块详解】
目录



前言

LangChain给自身的定位是:用于开发由大语言模型支持的应用程序的框架。它的做法是:通过提供标准化且丰富的模块抽象,构建大语言模型的输入输出规范,利用其核心概念chains,灵活地连接整个应用开发流程。 这里是LangChain系列的第四篇,主要介绍LangChain的Chain模块。

一、LangChain

1-1、介绍

LangChain是一个框架,用于开发由大型语言模型(LLM)驱动的应用程序。
LangChain 简化了 LLM 应用程序生命周期的每个阶段:
总结:LangChain是一个用于开发由LLM支持的应用程序的框架,通过提供标准化且丰富的模块抽象,构建LLM的输入输出规范,主要是利用其核心概念chains,可以灵活地链接整个应用开发流程。(即,其中的每个模块抽象,都是源于对大模型的深入理解和实践经验,由许多开发者提供出来的标准化流程和解决方案的抽象,再通过灵活的模块化组合,才得到了langchain)


1-2、LangChain抽象出来的核心模块

想象一下,如果要组织一个AI应用,开发者一般需要?
由上边的内容,引出LangChain抽象的一些核心模块:
LangChain通过模块化的方式去高级抽象LLM在不同场景下的能力,其中LangChain抽象出的最重要的核心模块如下:
1-3、特点

LangChain的特点如下:


1-4、langchain解决的一些行业痛点

在使用大模型的过程中,一些行业痛点:
1-5、安装
  1. pip install langchain
复制代码
二、Chain模块

2-1、介绍

LangChain的chain模块是其框架中用于构建智能对话和任务式应用的核心组件之一,主要负责流程控制和数据传递。以下是chain模块的一些详细介绍:

链的创建与组合:
核心链类型:
通过这些链的组合和嵌套,LangChain框架能够实现复杂的自然语言处理应用程序,提供高度的扩展性和可维护性
2-2、LLMChain

LLMChain 是 LangChain 中最简单的链,作为其他复杂 Chains 和 Agents 的内部调用,被广泛应用。一个LLMChain由PromptTemplate和语言模型(LLM or Chat Model)组成。它使用直接传入(或 memory 提供)的 key-value 来规范化生成 Prompt Template(提示模板),并将生成的 prompt (格式化后的字符串)传递给大模型,并返回大模型输出。
案例如下:
  1. from langchain_community.chat_models import ChatZhipuAI
  2. from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
  3. from langchain.chains import LLMChain
  4. from langchain.prompts import PromptTemplate
  5. import os
  6. os.environ["ZHIPUAI_API_KEY"]=""
  7. chat = ChatZhipuAI(
  8.     model="glm-4",
  9.     temperature=0.5,)
  10. prompt = PromptTemplate(
  11.     input_variables=["product"],
  12.     template="给制造{product}的有限公司取10个好名字,并给出完整的公司名称",)
  13. chain = LLMChain(llm=chat, prompt=prompt)print(chain.invoke({'product':"性能卓越的GPU"}))
复制代码
输出:



设置chain.verbose =True可以给出中间推理过程。



2-3、Sequential Chain(顺序链)

SequentialChain是一种链(Chain)类型,用于定义一系列步骤或组件,这些步骤或组件将按顺序执行。SequentialChain的核心功能是将多个处理步骤串联起来,使得每一步的输出成为下一步的输入,从而形成一个有序的执行流程。顺序链(Sequential Chain )允许用户连接多个链并将它们组合成执行特定场景的流水线(Pipeline)。有两种类型的顺序链:

SimpleSequentialChain-Demo: 包含参数chains以及参数verbose
  1. from langchain.llms import OpenAI
  2. from langchain.chains import LLMChain
  3. from langchain.prompts import PromptTemplate
  4. os.environ["ZHIPUAI_API_KEY"]=""
  5. llm = ChatZhipuAI(
  6.     model="glm-4",
  7.     temperature=0.5,)
  8. template ="""You are a playwright. Given the title of play, it is your job to write a synopsis for that title.
  9. Title: {title}
  10. Playwright: This is a synopsis for the above play:"""
  11. prompt_template = PromptTemplate(input_variables=["title"], template=template)
  12. synopsis_chain = LLMChain(llm=llm, prompt=prompt_template)
  13. template ="""You are a play critic from the New York Times. Given the synopsis of play, it is your job to write a review for that play.
  14. Play Synopsis:
  15. {synopsis}
  16. Review from a New York Times play critic of the above play:"""
  17. prompt_template = PromptTemplate(input_variables=["synopsis"], template=template)
  18. review_chain = LLMChain(llm=llm, prompt=prompt_template)from langchain.chains import SimpleSequentialChain
  19. overall_chain = SimpleSequentialChain(chains=[synopsis_chain, review_chain], verbose=True)
  20. review = overall_chain.run("Tragedy at sunset on the beach")
复制代码
输出:





SequentialChain-Demo: 通用顺序链,包含多个输入以及输出。参数包括:chains、input_variables、output_variables、verbose
  1. from langchain.llms import OpenAI
  2. from langchain.chains import LLMChain
  3. from langchain.prompts import PromptTemplate
  4. os.environ["ZHIPUAI_API_KEY"]=""
  5. llm = ChatZhipuAI(
  6.     model="glm-4",
  7.     temperature=0.5,)
  8. template ="""You are a playwright. Given the title of play and the era it is set in, it is your job to write a synopsis for that title.
  9. Title: {title}
  10. Era: {era}
  11. Playwright: This is a synopsis for the above play:"""
  12. prompt_template = PromptTemplate(input_variables=["title",'era'], template=template)
  13. synopsis_chain = LLMChain(llm=llm, prompt=prompt_template, output_key="synopsis")
  14. template ="""You are a play critic from the New York Times. Given the synopsis of play, it is your job to write a review for that play.
  15. Play Synopsis:
  16. {synopsis}
  17. Review from a New York Times play critic of the above play:"""
  18. prompt_template = PromptTemplate(input_variables=["synopsis"], template=template)
  19. review_chain = LLMChain(llm=llm, prompt=prompt_template, output_key="review")from langchain.chains import SequentialChain
  20. overall_chain = SequentialChain(
  21.     chains=[synopsis_chain, review_chain],
  22.     input_variables=["era","title"],# Here we return multiple variables
  23.     output_variables=["synopsis","review"],
  24.     verbose=True)
  25. overall_chain({"title":"Tragedy at sunset on the beach","era":"Victorian England"})
复制代码
输出:





SequentialChain与SimpleSequentialChain相比,重要的是定义好中间的输入变量以及输出变量(input_variables、output_variables),方便后续输出
2-4、Router Chain

RouterChain: 是LangChain框架中的一个组件,用于构建可以根据输入动态选择下一个执行链条的系统。它主要包含两个部分:RouterChain本身和destination_chains(目标链)。RouterChain负责选择下一个要调用的链条,而destination_chains是RouterChain可以路由到的链条集合
以下是RouterChain的一些关键特点和用途:
1、构建目标链 destination_chains: 即RouterChain可以路由到的链条集合。这里创建了一个默认的对话链ConversationChain ,在没有合适chain的情况下,会选择使用默认对话链。
  1. from langchain.chains.router import MultiPromptChain
  2. from langchain.llms import OpenAI
  3. from langchain.chains import ConversationChain
  4. from langchain.chains.llm import LLMChain
  5. from langchain.prompts import PromptTemplate
  6. from langchain_community.chat_models import ChatZhipuAI
  7. physics_template ="""You are a very smart physics professor.
  8. You are great at answering questions about physics in a concise and easy to understand manner.
  9. When you don't know the answer to a question you admit that you don't know.
  10. Here is a question:
  11. {input}"""
  12. math_template ="""You are a very good mathematician. You are great at answering math questions.
  13. You are so good because you are able to break down hard problems into their component parts,
  14. answer the component parts, and then put them together to answer the broader question.
  15. Here is a question:
  16. {input}"""# 主要构建物理、数学两条链,所以这里先构建了相关信息,用于下边构建目标链。
  17. prompt_infos =[{"name":"physics","description":"Good for answering questions about physics","prompt_template": physics_template,},{"name":"math","description":"Good for answering math questions","prompt_template": math_template,},]
  18. os.environ["ZHIPUAI_API_KEY"]=""
  19. llm = ChatZhipuAI(
  20.     model="glm-4",
  21.     temperature=0.5,)# 创建一个空的目标链字典,用于存放根据prompt_infos生成的LLMChain。
  22. destination_chains ={}# 遍历prompt_infos列表,为每个信息创建一个LLMChain。for p_info in prompt_infos:
  23.     name = p_info["name"]# 提取名称
  24.     prompt_template = p_info["prompt_template"]# 提取模板# 创建PromptTemplate对象
  25.     prompt = PromptTemplate(template=prompt_template, input_variables=["input"])# 使用上述模板和llm对象创建LLMChain对象
  26.     chain = LLMChain(llm=llm, prompt=prompt)# 将新创建的chain对象添加到destination_chains字典中
  27.     destination_chains[name]= chain
  28. # 创建一个默认的ConversationChain
  29. default_chain = ConversationChain(llm=llm, output_key="text")
复制代码
输出:



2、使用LLMRouterChain实现条件判断:
  1. from langchain.chains.router.llm_router import LLMRouterChain, RouterOutputParser
  2. from langchain.chains.router.multi_prompt_prompt import MULTI_PROMPT_ROUTER_TEMPLATE
  3. destinations =[f"{p['name']}: {p['description']}"for p in prompt_infos]
  4. destinations_str ="\n".join(destinations)
  5. router_template = MULTI_PROMPT_ROUTER_TEMPLATE.format(destinations=destinations_str)
  6. router_prompt = PromptTemplate(
  7.     template=router_template,
  8.     input_variables=["input"],
  9.     output_parser=RouterOutputParser(),)
  10. router_chain = LLMRouterChain.from_llm(llm, router_prompt)
  11. chain = MultiPromptChain(
  12.     router_chain=router_chain,
  13.     destination_chains=destination_chains,
  14.     default_chain=default_chain,
  15.     verbose=True,)print(chain.run("What is black body radiation?"))
复制代码
输出:



总结:
1、 用户输入一个问题。
2、 router_chain使用router_prompt处理用户的输入,并根据输出决定将问题路由到哪个destination_chain。
3、 根据router_chain的路由结果,MultiPromptChain将问题发送到相应的destination_chain进行处理。
4、 destination_chain处理问题并生成答案。
5、 如果router_chain无法确定合适的destination_chain,问题将被发送到default_chain进行处理。
这个系统允许根据用户的输入动态选择最合适的处理链,提高了系统的灵活性和准确性。同时,verbose参数可以帮助开发者调试和监控系统的执行过程。
2-4、Transform Chain

Transform Chain: 主要用于对数据进行转换处理,然后再将转换后的结果输出给后续的处理链。
参考文章:
langchain_community.utilities.sql_database.SQLDatabase
[url=https://python.langchain.com.cn/docs/modules/agents/toolkits/json]LangChain




欢迎光临 AI创想 (http://llms-ai.com/) Powered by Discuz! X3.4