链(上):写一篇完美鲜花推文?用SequentialChain链接不同的组件 | 豆包MarsCode AI刷题

109 阅读5分钟

什么是 Chain

开发更复杂的应用,需要通过"Chain"链接LangChain的各个组件和功能——模型之间彼此链接,或模型与其他组件链接。目的:简化复杂应用程序的实现,并使之更加模块化,能够创建出单一的、连贯的应用程序,使调试、维护和改进应用程序变得更容易。

链的实现和使用

  • 首先LangChain通过设计好的接口,实现一个具体的链的功能。例如,LLM链(LLMChain)能够接受用户输入,使用 PromptTemplate 对其进行格式化,然后将格式化的响应传递给 LLM。这就相当于把整个Model I/O的流程封装到链里面。
  • 实现了链的具体功能之后,我们可以通过将多个链组合在一起,或者将链与其他组件组合来构建更复杂的链。

所链在内部把一系列的功能进行封装,而链的外部则又可以组合串联。链其实可以被视为LangChain中的一种基本功能单元。

LangChain中提供了很多种类型的预置链,目的是使各种各样的任务实现起来更加方便、规范。

最基础的就是LLMChain。

LLMChain:最简单的链

LLMChain围绕着语言模型推理功能又添加了一些功能,整合了PromptTemplate、语言模型(LLM或聊天模型)和 Output Parser,相当于把Model I/O放在一个链中整体操作。它使用提示模板格式化输入,将格式化的字符串传递给 LLM,并返回 LLM 输出。

不使用链

#----第一步 创建提示
# 导入LangChain中的提示模板
from langchain import PromptTemplate
# 原始字符串模板
template = "{flower}的花语是?"
# 创建LangChain模板
prompt_temp = PromptTemplate.from_template(template) 
# 根据模板创建提示
prompt = prompt_temp.format(flower='玫瑰')
# 打印提示的内容
print(prompt)

#----第二步 创建并调用模型 
# 导入LangChain中的OpenAI模型接口
from langchain import OpenAI
# 创建模型实例
model = OpenAI(temperature=0)
# 传入提示,调用模型,返回结果
result = model(prompt)
print(result)

使用链,代码结构则显得更简洁。

# 导入所需的库
from langchain_core.prompts import PromptTemplate
from langchain.chains import LLMChain
import os
from langchain_community.llms import Tongyi


# DASHSCOPE_API_KEY
os.environ["DASHSCOPE_API_KEY"] = '阿里的DASHSCOPE_API_KEY'
# 创建模型实例
llm = Tongyi(model_name="qwen-chat", api_key=os.environ["DASHSCOPE_API_KEY"])

# 原始字符串模板
template = "{flower}的花语是?"
# 创建LLMChain
llm_chain = LLMChain(
    llm=llm,
    prompt=PromptTemplate.from_template(template))
# 调用LLMChain,返回结果
result = llm_chain("玫瑰")
print(result)

链的调用方式

直接调用

上面的例子是直接调用的链对象。想函数一样调用一个对象,实际上调用该对象内部的__call__方法。

如果模板中包含多个变量,在调用链的时候,可以用字典一次性输入。

# 导入所需的库
from langchain_core.prompts import PromptTemplate
from langchain.chains import LLMChain
import os
from langchain_community.llms import Tongyi


# DASHSCOPE_API_KEY
os.environ["DASHSCOPE_API_KEY"] = '阿里的DASHSCOPE_API_KEY'
# 创建模型实例
llm = Tongyi(model_name="qwen-chat", api_key=os.environ["DASHSCOPE_API_KEY"])

# 1. 直接调用 __call__
# 设置提示模板
prompt = PromptTemplate(
    input_variables=["flower", "season"], template="{flower}在{season}的花语是?"
)

# 初始化链
llm_chain = LLMChain(llm=llm, prompt=prompt)

# 调用链
response = llm_chain({"flower": "玫瑰", "season": "夏季"})
print(response)

通过run方法

run方法实际上也是调用的__call__方法

# 2.调用 run 方法
response = llm_chain.run({"flower": "玫瑰", "season": "夏季"})
print(response)

通过predict方法

类似run,输入被指定为关键字参数而不是字典

# 3.通过predict方法
result = llm_chain.predict(flower="玫瑰", season="夏季")
print(result)

通过apply方法

允许针对输入列表运行链,一次处理多个输入

# apply方法允许您针对输入列表运行链
input_list = [
    {"flower": "玫瑰", "season": "夏季"},
    {"flower": "百合", "season": "春季"},
    {"flower": "郁金香", "season": "秋季"},
]
result = llm_chain.apply(input_list)
print(result)

通过generate方法

类似于apply方法,不过返回的是LLMResult对象,而不是字符串。LLMResult通常包含模型生成文本过程中的一些相关信息,如令牌数量、模型名称等。

# generate方法
result = llm_chain.generate(input_list)
print(result)

Sequential Chain:顺序链

把几个LLMChain串起来,形成一个顺序链。

第一步,假设大模型是一个植物学家,让他给出某种特定鲜花的知识和介绍。

第二步,假设大模型是一个鲜花评论者,让他参考上面植物学家的输出,对鲜花进行评论。

第三步,假设大模型是易速鲜花的社交媒体运营经理,参考上面植物学家和鲜花评论者的文字输出,写一篇鲜花运营文案。

import os
from langchain.chains import LLMChain, SequentialChain
from langchain.prompts import PromptTemplate
from langchain_community.llms import Tongyi


# DASHSCOPE_API_KEY
os.environ["DASHSCOPE_API_KEY"] = '阿里的DASHSCOPE_API_KEY'
# 创建模型实例
llm = Tongyi(model_name="qwen-chat", api_key=os.environ["DASHSCOPE_API_KEY"])
template = """
你是一个植物学家。给定花的名称和类型,你需要为这种花写一个200字左右的介绍。
花名: {name}
颜色: {color}
植物学家: 这是关于上述花的介绍:"""
# 第一个LLMChain:生成鲜花的介绍
prompt_template = PromptTemplate(input_variables=["name", "color"], template=template)
introduction_chain = LLMChain(
    llm=llm, prompt=prompt_template, output_key="introduction" # 输出包含introduction
)

# 第二个LLMChain:根据鲜花的介绍写出鲜花的评论
template = """
你是一位鲜花评论家。给定一种花的介绍,你需要为这种花写一篇200字左右的评论。
鲜花介绍:
{introduction}
花评人对上述花的评论:"""
prompt_template = PromptTemplate(input_variables=["introduction"], template=template)
review_chain = LLMChain(llm=llm, prompt=prompt_template, output_key="review")

# 第三个LLMChain:根据鲜花的介绍和评论写出一篇自媒体的文案
template = """
你是一家花店的社交媒体经理。给定一种花的介绍和评论,你需要为这种花写一篇社交媒体的帖子,300字左右。
鲜花介绍:
{introduction}
花评人对上述花的评论:
{review}
社交媒体帖子:
"""
prompt_template = PromptTemplate(
    input_variables=["introduction", "review"], template=template
)
social_post_chain = LLMChain(
    llm=llm, prompt=prompt_template, output_key="social_post_text"
)

# 总的链:按顺序运行三个链
overall_chain = SequentialChain(
    chains=[introduction_chain, review_chain, social_post_chain],
    input_variables=["name", "color"],
    output_variables=["introduction", "review", "social_post_text"],
    verbose=True, # 显示详细的输出
)

# 运行链并打印结果
result = overall_chain({"name": "玫瑰", "color": "黑色"})
print(result)