软件测试/人工智能|一文告诉你LangChain核心模块chains原理

发布时间 2023-11-29 17:03:11作者: 霍格沃兹测试开发学社

简介

Chain是LangChain的核心模块之一,它将每个零散的逻辑串联成一整个业务流程,相当于是所有复杂逻辑的基础,由此可见chain的重要性非比寻常。本文就来给大家介绍一下Chain模块的原理。

下面是chain的各种类型

设计思路

LangChain 能火爆的主要原因之一就是Chain 的设计非常巧妙,它的设计思路如下图:

如图所示,Chain可以根据需求,将各种能力拼接整合,因此,Chain可以包含多个模块;当然,我们也可以定制只使用 Prompt 和 LLM 模块的LLMChain。

运用实践

Chains主要包含以下几个模块,在我们的实践演练中,将会演示这几个模块的使用。

LLMChain

LLMChain是一个整合语言模型和提示模板的最简单链,如下图:

代码如下:


# LangChain相关模块的导入
from langchain import LLMChain
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate

# 加载个人的OpenAI Token
key = 'open_ai_key'
# 创建OpenAI调用实例
# 本示例中为了让结果更具有创造性,temperature设置为0.9
llm = ChatOpenAI(temperature=0.9, openai_api_key=key)
# 根据prompt模板生成prompt实例
prompt = ChatPromptTemplate.from_template(
    "请给生产: {product} 的工厂起一个恰当的厂名,并给出一句广告语。"
)
# 组合大模型实例和prompt实例,生成LLMChain实例,将结构固定,方便复用
chain = LLMChain(
    # 大模型实例
    llm=llm,
    # prompt实例
    prompt=prompt,
    # 开启详细模式,会将大模型调用细节输出到控制台
    verbose=True
)
# 通过run方法,传入模版中需要的参数,调用大模型获取结果
product = "Huawei Mate60 Pro"
res = chain.run(product)
print(res)

--------------
输出结果如下:
厂名:华夏技术有限公司
广告语:轻舟已过万重山

SimpleSequentialChain

串联式调用语言模型链的一种,简单的串联每个步骤(Chain 实例),每个步骤都有单一的输入/输出,并且一个步骤的输入是下一个步骤的输出。


# LangChain相关模块的导入
from langchain import LLMChain
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.chains import SimpleSequentialChain
# 加载个人的OpenAI Token
key = 'open_ai_key'


# 创建OpenAI调用实例
# temperature用来设置大模型返回数据的随机性和创造性,较低的数值返回的数据就更贴近现实。
llm = ChatOpenAI(temperature=0.9, openai_api_key=key)
# 第一个LLM请求的prompt模板
first_prompt = ChatPromptTemplate.from_template(
    "请给生产 {product} 的工厂起一个恰当的厂名"
)
# 第一个Chain,接收外部输入,根据模版请求大模型获取输出,作为第二个Chain的输入
chain_one = LLMChain(llm=llm, prompt=first_prompt, verbose=True)
# 第二个大模型请求的prompt模版
second_prompt = ChatPromptTemplate.from_template(
    "为厂名写一段广告语: {company_name}"
)
# 第二个Chain,接收第一个Chain的输出,根据模版请求大模型获取输出
chain_two = LLMChain(llm=llm, prompt=second_prompt, verbose=True)
# 将请求拆分成两个Chain,可以针对每段请求细化相应的prompt内容,得到更准确更合理的结果,并且也可以复用其中的每个Chain实例
# 使用SimpleSequentialChain将两个Chain串联起来,其中每个Chain都只支持一个输入和一个输出,根据chains列表中的顺序,将前一个Chain的输出作为下一个Chain的输入
overall_simple_chain = SimpleSequentialChain(
    chains=[chain_one, chain_two],
    verbose=True
)
# 第一个Chain需要的输入
product = "比亚迪 秦plus dmi"
# 通过run方法,传入参数,逐个运行整个Chain后,获取最终的结果
res = overall_simple_chain.run(product)
print(res)

-----------
输出结果如下:
比亚迪汽车有限公司

比亚迪,传统汽车颠覆者

SequentialChain

串联式调用语言模型链的一种,序列中的每个 Chain 实例都支持多个输入和输出,最终 SequentialChain 运行时根据 Chains 参数和每个 Chain 示例中设定的参数,分析每个实例所需的参数并按需传递。代码示例:


import langchain
# LangChain相关模块的导入
from langchain import LLMChain
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.chains import SequentialChain

# 在全局范围开启详细模式,能将调用大模型时发送的数据打印到控制台,绿色文本
langchain.verbose = True

key = 'open_ai_key'

# 本示例中为了让结果更具有创造性,temperature设置为0.9
llm = ChatOpenAI(temperature=0.9, openai_api_key=key)

# Chain1 语言转换,产生英文产品名
prompt1 = ChatPromptTemplate.from_template(
    "将以下文本翻译成英文: {product_name}"
)
chain1 = LLMChain(
    # 使用的大模型实例
    llm=llm,
    # prompt模板
    prompt=prompt1,
    # 输出数据变量名
    output_key="english_product_name",
)
# Chain2 根据英文产品名,生成一段英文介绍文本
prompt2 = ChatPromptTemplate.from_template(
    "Based on the following product, give an introduction text about 100 words: {english_product_name}"
)
chain2 = LLMChain(
    llm=llm,
    prompt=prompt2,
    output_key="english_introduce"
)
# Chain3 找到产品名所属的语言
prompt3 = ChatPromptTemplate.from_template(
    "下列文本使用的语言是什么?: {product_name}"
)
chain3 = LLMChain(
    llm=llm,
    prompt=prompt3,
    output_key="language"
)
# Chain4 根据Chain2生成的英文介绍,使用产品名称原本的语言生成一段概述
prompt4 = ChatPromptTemplate.from_template(
    "使用语言类型为: {language} ,为下列文本写一段不多于50字的概述: {english_introduce}"
)
chain4 = LLMChain(
    llm=llm,
    prompt=prompt4,
    output_key="summary"
)
# 标准版的序列Chain,SequentialChain,其中每个chain都支持多个输入和输出,
# 根据chains中每个独立chain对象,和chains中的顺序,决定参数的传递,获取最终的输出结果
overall_chain = SequentialChain(
    chains=[chain1, chain2, chain3, chain4],
    input_variables=["product_name"],
    output_variables=["english_product_name", "english_introduce", "language", "summary"],
    verbose=True
)
product_name = "黄油啤酒"
res = overall_chain(product_name)
print(res)

LLMRouteChain

以下是一段非常简单的 Python 代码。实现的主要是分支判断的作用。


if a == 1:
    print("我爱踢足球")
elif b == 1:
    print("我爱打篮球")
else:
    print("我爱打游戏")

而 LLMRouteChain 的主要作用是能根据提示词的不同而选择不同的Chain进行执行。而实现这一需求,需要以下3个模块结合完成,也是MultiPromptChain的三个参数,以下内容是摘取的部分源码:
class MultiPromptChain(MultiRouteChain):
"""A multi-route chain that uses an LLM router chain to choose amongst prompts."""

    router_chain: RouterChain
"""Chain for deciding a destination chain and the input to it."""
    destination_chains: Mapping[str, LLMChain]
"""Map of name to candidate chains that inputs can be routed to."""
    default_chain: LLMChain
"""Default chain to use when router doesn't map input to one of the destinations."""

总结

本文主要介绍了LangChain核心模块Chain的原理以及一些基础的应用,希望本文能够帮助到大家。

获取更多技术资料,请点击!

在这里插入图片描述