【LangChain】顺序(Sequential)

LangChain学习文档

  • 基础
    • 【LangChain】LLM
    • 【LangChain】路由(Router)
    • 【LangChain】顺序(Sequential)

概述

我们调用语言模型后的下一步,一般都是对语言模型进行一系列调用。也就是我们想要获取一个调用的输出并将其用作另一个调用的输入。

在本笔记本中,我们将通过一些示例来说明如何使用顺序链来执行此操作。顺序链允许您连接多个链并将它们组成执行某些特定场景的管道。顺序链有两种类型:

  • SimpleSequentialChain:顺序链最简单的形式,其中每个步骤都有一个单一的输入/输出,一个步骤的输出是下一步的输入。
  • SequentialChain:顺序链的更通用形式,允许多个输入/输出。

内容

SimpleSequentialChain

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

# This is an LLMChain to write a synopsis given a title of a play.
llm = OpenAI(temperature=.7)
# 一个输入变量 title
template = """You are a playwright. Given the title of play, it is your job to write a synopsis for that title.

Title: {title}
Playwright: This is a synopsis for the above play:"""
prompt_template = PromptTemplate(input_variables=["title"], template=template)
# 得到一个chain
synopsis_chain = LLMChain(llm=llm, prompt=prompt_template)

# This is an LLMChain to write a review of a play given a synopsis.
llm = OpenAI(temperature=.7)
# 一个输入变量synopsis
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.

Play Synopsis:
{synopsis}
Review from a New York Times play critic of the above play:"""
prompt_template = PromptTemplate(input_variables=["synopsis"], template=template)
# 得到一个Chain
review_chain = LLMChain(llm=llm, prompt=prompt_template)

上面定义了两个Chain,现在我们把它按照顺序,连起来。

# This is the overall chain where we run these two chains in sequence.
from langchain.chains import SimpleSequentialChain
overall_chain = SimpleSequentialChain(chains=[synopsis_chain, review_chain], verbose=True)

执行:

review = overall_chain.run("海滩日落时的悲剧")

结果:

    
    
    > Entering new SimpleSequentialChain chain...
    
    # 概要
    《海滩日落悲剧》讲述了一对年轻夫妇杰克和莎拉的故事,他们相爱并期待着共同的未来。在结婚纪念日的那天晚上,他们决定在日落时分在海滩上散步。当他们行走时,他们遇到了一个神秘人物,这个人物告诉他们,他们的爱情将在不久的将来受到考验。
    
	然后,这个人物告诉这对夫妇,太阳很快就会落山,随之而来的是一场悲剧。如果杰克和莎拉能够在一起并通过考验,他们将获得永恒的爱情。然而,如果他们失败了,他们的爱情就会永远消失。
	
	该剧讲述了这对夫妇努力维持在一起并与威胁分裂他们的力量作斗争的故事。尽管悲剧正在等待着他们,他们仍然彼此忠诚,并为维持爱情而奋斗。最后,这对夫妇必须决定是共同冒险,还是屈服于日落的悲剧。
	# 评论
	《海滩日落悲剧》讲述了一个关于爱、希望和牺牲的扣人心弦的故事。通过杰克和莎拉的故事,观众踏上了自我发现之旅,并了解爱的力量可以克服最大的障碍。
	
	该剧才华横溢的演员阵容让角色栩栩如生,让我们感受到他们情感的深度和挣扎的激烈程度。凭借引人入胜的故事情节和引人入胜的表演,这部剧一定会吸引观众的眼球。

	该剧以日落海滩为背景,为故事增添了一丝凄美和浪漫,而神秘的人物则让观众着迷。总的来说,《海滩日落的悲剧》是一部引人入胜、发人深省的戏剧,一定会让观众感到鼓舞和希望。
    
    > Finished chain.

Sequential Chain

当然,并非所有顺序链都像传递单个字符串作为参数并获取单个字符串作为链中所有步骤的输出一样简单。

在下一个示例中,我们将尝试更复杂的链,其中涉及多个输入,并且还有多个最终输出。

特别重要的是: 我们如何命名输入/输出变量名称。在上面的示例中,我们不必考虑这一点,因为我们只是将一个链的输出直接作为输入传递给下一个链,但在这里我们确实需要担心这一点,因为我们有多个输入。

第一个LLMChain:

# This is an LLMChain to write a synopsis given a title of a play and the era it is set in.
llm = OpenAI(temperature=.7)
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.
# 这里定义了两个输入变量title和era,并定义一个输出变量:synopsis
Title: {title}
Era: {era}
Playwright: This is a synopsis for the above play:"""
prompt_template = PromptTemplate(input_variables=["title", "era"], template=template)
synopsis_chain = LLMChain(llm=llm, prompt=prompt_template, output_key="synopsis")

第二个LLMChain:

# This is an LLMChain to write a review of a play given a synopsis.
llm = OpenAI(temperature=.7)
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.
# 定义了一个输入变量:synopsis,输出变量:review
Play Synopsis:
{synopsis}
Review from a New York Times play critic of the above play:"""
prompt_template = PromptTemplate(input_variables=["synopsis"], template=template)
review_chain = LLMChain(llm=llm, prompt=prompt_template, output_key="review")

执行:

overall_chain({"title":"Tragedy at sunset on the beach", "era": "Victorian England"})

结果:

    > Entering new SequentialChain chain...
    
    > Finished chain.

    {'title': 'Tragedy at sunset on the beach',
     'era': 'Victorian England',
     'synopsis': "xxxxxx",
     'review': "xxxxxxx"}

顺序链中使用Memory

有时,我们希望传递一些上下文在链的每个步骤或链的后续部分中使用,但是维护输入/输出变量并将其链接在一起可能很快就会变得混乱。使用 SimpleMemory 是管理此问题并清理内存链的便捷方法。

例如,使用之前的剧作家 SequentialChain,假设您想要包含一些有关戏剧的日期、时间和地点的上下文,并使用生成的概要和评论创建一些社交媒体帖子文本。您可以将这些新的上下文变量添加为 input_variables,或者我们可以将 SimpleMemory 添加到链中来管理此上下文:

from langchain.chains import SequentialChain
from langchain.memory import SimpleMemory

llm = OpenAI(temperature=.7)
template = """You are a social media manager for a theater company.  Given the title of play, the era it is set in, the date,time and location, the synopsis of the play, and the review of the play, it is your job to write a social media post for that play.

Here is some context about the time and location of the play:
Date and Time: {time}
Location: {location}

Play Synopsis:
{synopsis}
Review from a New York Times play critic of the above play:
{review}

Social Media Post:
"""
# 这里使用多变量的方式
prompt_template = PromptTemplate(input_variables=["synopsis", "review", "time", "location"], template=template)
# 这个Chain使用的是多变量的方式
social_chain = LLMChain(llm=llm, prompt=prompt_template, output_key="social_post_text")

# 这个Chain使用的是SimpleMemory的方式
overall_chain = SequentialChain(
    memory=SimpleMemory(memories={"time": "December 25th, 8pm PST", "location": "Theater in the Park"}),
    chains=[synopsis_chain, review_chain, social_chain],
    input_variables=["era", "title"],
    # Here we return multiple variables
    output_variables=["social_post_text"],
    verbose=True)

overall_chain({"title":"Tragedy at sunset on the beach", "era": "Victorian England"})

结果如下:

    > Entering new SequentialChain chain...
    
    > Finished chain.

    {'title': 'Tragedy at sunset on the beach',
     'era': 'Victorian England',
     'time': 'December 25th, 8pm PST',
     'location': 'Theater in the Park',
     'social_post_text': "\nSpend your Christmas night with us at Theater in the Park and experience the heartbreaking story of love and loss that is 'A Walk on the Beach'. Set in Victorian England, this romantic tragedy follows the story of Frances and Edward, a young couple whose love is tragically cut short. Don't miss this emotional and thought-provoking production that is sure to leave you in tears. #AWalkOnTheBeach #LoveAndLoss #TheaterInThePark #VictorianEngland"}

总结

本文主要讲,。

  1. 多个Chain,如何按顺序串起来:
  • SimpleSequentialChain:这种方式,输入、输出变量都只能是一个,也正因如此,所以上下游的Chain的输入输出变量名可以不一样。
  • SequentialChain:这种方式,允许有多个输入、输出变量。上下游的Chain的输入输出变量,要对应,不然传不下去。
  1. 顺序链中使用Memory,因为变量变多后,会在使用上造成混乱,故提供了Memory的方式,来避免这种混乱。

参考地址:

https://python.langchain.com/docs/modules/chains/foundational/sequential_chains

你可能感兴趣的:(LangChain,AI,langchain)