对于简单的应用程序,直接调用大语言模型(LLM)已经足够。因此,之前的课程中,主要使用了LangChain的提示模板、模型接口以及输出解析器,实现了一些基本功能。但当你想开发更复杂的应用时,就需要通过“Chain”来串联不同组件和功能。
什么是Chain?
Chain是LangChain的核心组件,能够将多个LLM、提示模板和其他功能模块相互链接。通过这种链式结构,可以实现复杂应用的模块化,简化调试、维护和改进过程。LangChain中提供了很多预置的链,用于实现各种任务。
LLMChain:最简单的链
LLMChain是最基础的链,整合了提示模板、LLM和输出解析器,相当于将Model I/O封装在一个链里。例如,如果想让模型解释某种花的花语,可以通过LLMChain将提示模板和模型调用整合起来,代码如下:
from langchain import PromptTemplate, OpenAI, LLMChain
# 创建模型实例和提示模板
template = "{flower}的花语是?"
llm = OpenAI(temperature=0)
# 创建LLMChain
llm_chain = LLMChain(llm=llm, prompt=PromptTemplate.from_template(template))
# 调用链获取结果
result = llm_chain("玫瑰")
print(result)
这样,通过LLMChain就能完成提示的构建和模型调用,比单独实现每一步更加简洁。
顺序链:SequentialChain
SequentialChain可以将多个链按顺序连接起来,用于更复杂的任务。例如,假设我们需要:
- 让模型以植物学家的身份为某种花生成介绍。
- 让模型根据介绍撰写花评。
- 让模型生成一篇社交媒体的文案。
我们可以通过SequentialChain将这些步骤串联起来:
from langchain.llms import OpenAI
from langchain.chains import LLMChain, SequentialChain
from langchain.prompts import PromptTemplate
# 设置模型和提示模板
llm = OpenAI(temperature=.7)
# 第一步:生成花的介绍
intro_template = """你是一个植物学家... (省略部分)"""
intro_prompt = PromptTemplate(input_variables=["name", "color"], template=intro_template)
introduction_chain = LLMChain(llm=llm, prompt=intro_prompt, output_key="introduction")
# 第二步:生成评论
review_template = """你是一位鲜花评论家... (省略部分)"""
review_prompt = PromptTemplate(input_variables=["introduction"], template=review_template)
review_chain = LLMChain(llm=llm, prompt=review_prompt, output_key="review")
# 第三步:生成社交媒体文案
social_template = """你是花店的社交媒体经理... (省略部分)"""
social_prompt = PromptTemplate(input_variables=["introduction", "review"], template=social_template)
social_post_chain = LLMChain(llm=llm, prompt=social_prompt, 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)
这样,我们就通过SequentialChain实现了从植物学描述到社交媒体文案的生成过程。
链的调用方式
链的调用有多种方式,可以直接调用链对象,也可以使用run方法、predict方法、apply方法或generate方法。例如:
run方法适用于单一输入。apply方法可以处理输入列表,一次生成多个结果。generate方法返回一个LLMResult对象,包含生成文本的详细信息。
总结
链(Chain)是LangChain的关键组件,能够将多个LLM、提示模板和其他功能模块链接在一起,实现复杂应用的模块化和高效开发。LLMChain是最基础的链,可以整合提示和模型调用;SequentialChain则可以将多个链按顺序连接,用于实现多步骤的任务。下一节课,我们将继续介绍RouterChain等更强大的链类型。
思考题
- 请你使用LLMChain重构第4课中用提示模板生成鲜花描述的代码,并尝试将output_parser也整合到LLMChain中。
- 选择一个LangChain中的链类型,尝试使用它解决一个问题并分享你的代码。