学习笔记8《链(上):写一篇完美鲜花推文?用SequencialChain链接不同的组件》

179 阅读3分钟

什么是Chain

在LangChain中,Chain是一种将多个组件相互链接,组合成一个链的机制。这种机制简化了复杂应用程序的实现,并使之更加模块化。Chain可以被视为LangChain中的一种基本功能单元,它将一系列的功能进行封装,同时也可以与其他链或组件组合串联。

LLMChain:最简单的链

LLMChain是LangChain中最基本的链,它整合了PromptTemplate、语言模型(LLM或聊天模型)和Output Parser,相当于把Model I/O放在一个链中整体操作。

使用LLMChain重构代码

不使用链的代码:

from langchain import PromptTemplate
template = "{flower}的花语是?"
prompt_temp = PromptTemplate.from_template(template) 
prompt = prompt_temp.format(flower='玫瑰')
print(prompt)

from langchain import OpenAI
model = OpenAI(temperature=0)
result = model(prompt)
print(result)

使用LLMChain的代码:

from langchain import PromptTemplate, OpenAI, LLMChain

template = "{flower}的花语是?"
llm = OpenAI(temperature=0)
llm_chain = LLMChain(
    llm=llm,
    prompt=PromptTemplate.from_template(template))
result = llm_chain("玫瑰")
print(result)

链的调用方式

  • 直接调用:直接调用链对象,会触发内部的__call__方法。
  • 通过run方法llm_chain.run("玫瑰")等价于直接调用llm_chain("玫瑰")
  • 通过predict方法llm_chain.predict(flower="玫瑰")
  • 通过apply方法llm_chain.apply([{"flower": "玫瑰"}, {"flower": "百合"}])
  • 通过generate方法llm_chain.generate([{"flower": "玫瑰"}, {"flower": "百合"}])

Sequential Chain:顺序链

Sequential Chain可以将多个LLMChain串起来,形成一个顺序链,按顺序运行这些链。

示例:生成鲜花的介绍、评论和社交媒体帖子

import os
from langchain.llms import OpenAI
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.chains import SequentialChain

os.environ["OPENAI_API_KEY"] = '你的OpenAI API Key'

llm = OpenAI(temperature=.7)
template = """
你是一个植物学家。给定花的名称和类型,你需要为这种花写一个200字左右的介绍。

花名: {name}
颜色: {color}
植物学家: 这是关于上述花的介绍:"""
prompt_template = PromptTemplate(input_variables=["name", "color"], template=template)
introduction_chain = LLMChain(llm=llm, prompt=prompt_template, output_key="introduction")

template = """
你是一位鲜花评论家。给定一种花的介绍,你需要为这种花写一篇200字左右的评论。

鲜花介绍:
{introduction}
花评人对上述花的评论:"""
prompt_template = PromptTemplate(input_variables=["introduction"], template=template)
review_chain = LLMChain(llm=llm, prompt=prompt_template, output_key="review")

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)

总结

LangChain提供的“链”功能可以帮助我们将多个组件连接起来,简化复杂应用程序的实现。LLMChain和SequentialChain是最基本的链类型,它们可以被用来构建更复杂的应用程序。

思考题

  1. 使用LLMChain重构第4课中的鲜花描述生成代码。
  2. 将output_parser整合到LLMChain中,进一步简化程序结构。
  3. 选择一个LangChain中的链(未使用过的类型),尝试使用它解决一个问题,并分享你的用例和代码。