当前位置:   article > 正文

轻松上手 LangChain 6大模块之 Chains

langchain 六大组件如何使用

▼最近直播超级多,预约保你有收获

6f91edbb796bd53dc1d28f791ff7ed3a.png

 1

LangChain 6大模块是什么?

LangChain 是 AI 大模型应用开发框架,由6个模块组成,分别为:Model IO、Retrieval、Chains、Memory、Agents 和 Callbacks。

Model IO:AI 应用的核心部分,其中包括输入、Model和输出。

Retrieval:该功能与向量数据库密切相关,是在向量数据库中搜索与问题相关的文档内容。

Memory:为对话形式的模型存储历史对话记录,在长对话过程中随时将这些历史对话记录重新加载,以保证对话的准确度。

Chains:虽然通过 Model IO、Retrieval 和 Memory 这三大模块可以初步完成应用搭建,但是若想实现一个强大且复杂的应用,还是需要将各模块组合起来,这时就可以利用 Chains 将其连接起来,从而丰富功能。

Agents:它可以通过用户的输入,理解用户的意图,返回一个特定的动作类型和参数,从而自主调用相关的工具来满足用户的需求,将应用更加智能化。

Callbacks: 回调机制可以调用链路追踪、记录日志,帮助开发者更好的调试大模型。

 2

Chains 深度剖析

如果把用 LangChain 构建 AI 大模型应用的过程比作“积木模型”的搭建与拼接,那么 Chain 就是是该模型搭建过程中的骨骼部分,通过它将各模块快速组合在一起就可以快速搭建一个应用。Chain 的使用方式也是通过接口的直接调用,在本文中将 Chain 分为三种类型,从简单到复杂依次介绍。

第一、LLMChains:

这种类型的 Chain 应用起来很简单也可以说是后续要介绍  Chain 的基础,但其功能是足够强大的。通过 LLMChain 可以直接将数据、Prompt、以及想要应用的大模型串到一起,以下是 LLMChain 的例子。

  1. from langchain import PromptTemplate, OpenAI, LLMChain
  2. prompt_template = "What is a good name for a company that makes {product}?"
  3. llm = OpenAI(temperature=0)
  4. chain = LLMChain(
  5.     llm=llm,
  6.     prompt=PromptTemplate.from_template(prompt_template)
  7. )
  8. print(chain("colorful socks")) 
  9. # 输出结果'Socktastic!'

在这个例子中,我们首先初始化了一个 Prompt 字符串模版,并初始化大模型,然后利用 Chain 将模型运行起来。在「Chain 将模型运行起来」这个过程中:Chain 将会格式化 Prompt,然后将它传递给 LLM。

第二、Sequential Chains:

不同于基本的 LLMChain,Sequential Chain(序列链)是由一系列的链组合而成的,序列链有两种类型,一种是单个输入输出,另一个则是多个输入输出。先来看第一种单个输入输出的示例代码:

1、单个输入输出

在这个示例中,创建了两条 Chain,并且让第一条 Chain 接收一个虚构剧本的标题,输出该剧本的概要,作为第二条 Chain 的输入,然后生成一个虚构评论。通过 Sequential Chains 可以简单实现这一需求。

第一条 Chain:

  1. # This is an LLMChain to write a synopsis given a title of a play.
  2. from langchain import PromptTemplate, OpenAI, LLMChain
  3. llm = OpenAI(temperature=.7)
  4. template = """You are a playwright. Given the title of play, it is your job to write a synopsis for that title.
  5. Title: {title}
  6. Playwright: This is a synopsis for the above play:"""
  7. prompt_template = PromptTemplate(input_variables=["title"], template=template)
  8. synopsis_chain = LLMChain(llm=llm, prompt=prompt_template)

第二条 Chain:

  1. # This is an LLMChain to write a review of a play given a synopsis.
  2. from langchain import PromptTemplate, OpenAI, LLMChain
  3. llm = OpenAI(temperature=.7)
  4. 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.
  5. Play Synopsis:
  6. {synopsis}
  7. Review from a New York Times play critic of the above play:"""
  8. prompt_template = PromptTemplate(input_variables=["synopsis"], template=template)
  9. review_chain = LLMChain(llm=llm, prompt=prompt_template)

最后利用 SimpleSequentialChain 即可将两个 Chains 直接串联起来:

  1. from langchain.chains import SimpleSequentialChain
  2. overall_chain = SimpleSequentialChain(chains=[synopsis_chain, review_chain], verbose=True)
  3. print(review = overall_chain.run("Tragedy at sunset on the beach"))

可以看到对于单个输入输出的顺序链,就是将两个 Chain 作为参数传给 SimpleSequentialChain 即可,无需复杂的声明。

2、多个输入输出

除了单个输入输出的模式,序列链还支持更为复杂的多个输入输出,对于多输入输出模式来说,最应该需要关注的就是输入关键字和输出关键字,它们需要十分的精准,才能够保证 Chain 的识别与应用,以一个 Demo 为例:

  1. from langchain import PromptTemplate, OpenAI, LLMChain
  2. llm = OpenAI(temperature=.7)
  3. 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.
  4. Title: {title}
  5. Era: {era}
  6. Playwright: This is a synopsis for the above play:"""
  7. prompt_template = PromptTemplate(input_variables=["title"'era'], template=template)
  8. synopsis_chain = LLMChain(llm=llm, prompt=prompt_template, output_key="synopsis")
  9. #第一条chain
  1. from langchain import PromptTemplate, OpenAI, LLMChain
  2. llm = OpenAI(temperature=.7)
  3. 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.
  4. Play Synopsis:
  5. {synopsis}
  6. Review from a New York Times play critic of the above play:"""
  7. prompt_template = PromptTemplate(input_variables=["synopsis"], template=template)
  8. review_chain = LLMChain(llm=llm, prompt=prompt_template, output_key="review")
  9. #第二条chain
  1. from langchain.chains import SequentialChain
  2. overall_chain = SequentialChain(
  3.     chains=[synopsis_chain, review_chain],
  4.     input_variables=["era""title"],
  5.     # Here we return multiple variables
  6.     output_variables=["synopsis""review"],
  7.     verbose=True)
  8. #第三条chain
overall_chain({"title""Tragedy at sunset on the beach""era""Victorian England"})

对于每一个Chain在定义的时候,都需要关注其output_key 和input_variables,按照顺序将其指定清楚。最终在运行 Chain 时我们只需要指定第一个 Chain 中需要声明的变量。

第三、RouterChains:

再介绍一个经常会用到的场景,比如:我们目前有三类 Chain,分别对应三种学科的问题解答。我们的输入内容也是与这三种学科对应,但是随机的,比如:第一次输入数学问题,第二次有可能是历史问题......这时候期待的效果是:可以根据输入的内容是什么,自动将其应用到对应的子链中。RouterChain 就为我们提供了这样一种能力,它会首先决定将要传递下去的子链,然后把输入传递给那个链。并且在设置的时候需要为其设置默认 Chain,以兼容输入内容不满足任意一项时的情况。

  1. physics_template = """You are a very smart physics professor. \
  2. You are great at answering questions about physics in a concise and easy to understand manner. \
  3. When you don't know the answer to a question you admit that you don't know.
  4. Here is a question:
  5. {input}"""
  6. math_template = """You are a very good mathematician. You are great at answering math questions. \
  7. You are so good because you are able to break down hard problems into their component parts, \
  8. answer the component parts, and then put them together to answer the broader question.
  9. Here is a question:
  10. {input}"""

如上述有一个物理学和数学的 Prompt:

  1. prompt_infos = [
  2.     {
  3.         "name""physics",
  4.         "description""Good for answering questions about physics",
  5.         "prompt_template": physics_template
  6.     },
  7.     {
  8.         "name""math",
  9.         "description""Good for answering math questions",
  10.         "prompt_template": math_template
  11.     }
  12. ]

然后需要声明这两个 Prompt 的基本信息。

  1. from langchain import ConversationChain, LLMChain, PromptTemplate, OpenAI
  2. llm = OpenAI()
  3. destination_chains = {}
  4. for p_info in prompt_infos:
  5.     name = p_info["name"]
  6.     prompt_template = p_info["prompt_template"]
  7.     prompt = PromptTemplate(template=prompt_template, input_variables=["input"])
  8.     chain = LLMChain(llm=llm, prompt=prompt)
  9.     destination_chains[name] = chain
  10. default_chain = ConversationChain(llm=llm, output_key="text")

最后将其运行到 RouterChain 中即可,我们此时在输入的时候 Chain 就会根据 input 的内容进行相应的选择最为合适的 Prompt。

  1. from langchain.chains.router.llm_router import LLMRouterChain, RouterOutputParser
  2. from langchain.chains.router.multi_prompt_prompt import MULTI_PROMPT_ROUTER_TEMPLATE
  3. # Create a list of destinations
  4. destinations = [f"{p['name']}: {p['description']}" for p in prompt_infos]
  5. destinations_str = "\n".join(destinations)
  6. # Create a router template
  7. router_template = MULTI_PROMPT_ROUTER_TEMPLATE.format(destinations=destinations_str)
  8. router_prompt = PromptTemplate(
  9.     template=router_template,
  10.     input_variables=["input"],
  11.     output_parser=RouterOutputParser(),
  12. )
  13. router_chain = LLMRouterChain.from_llm(llm, router_prompt)
  14. chain = MultiPromptChain(
  15.     router_chain=router_chain,
  16.     destination_chains=destination_chains,
  17.     default_chain=default_chain,
  18.     verbose=True,
  19. )
  20. print(chain.run('什么是黑体辐射'))

为了帮助同学们彻底掌握 LangChain 的应用开发,今晚20点我会开一场直播和同学们深度剖析,请同学们点击以下预约按钮免费预约

 3

AI大模型开发技能直播课程

大模型的技术体系非常复杂,即使有了知识图谱和学习路线后,快速掌握并不容易,我们打造了大模型应用技术的系列直播课程,包括:通用大模型技术架构原理、大模型 Agent 应用开发、企业私有大模型开发、向量数据库、大模型应用治理、大模型应用行业落地案例等6项核心技能,帮助同学们快速掌握 AI 大模型的技能。

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/621590
推荐阅读
相关标签