当前位置:   article > 正文

langchain学习之chain机制_langchain的chain

langchain的chain

系列文章目录

第一部分 langchain入门以及prompt、解析器使用
第二部分langchain学习之memory机制



前言

Chain 代表一个处理步骤的序列,每个步骤可以是一个调用语言模型、调用外部工具(如搜索引擎或数据库)、执行自定义逻辑,或者其他任何操作。Chain 的设计使得你可以灵活地将多个步骤组合在一起,以处理复杂的任务。下面来介绍各个类型的chain。有关导库内容可以看前面2个部分。

一、SimpleSequentialChain

	是一种简化的链,用于将多个步骤串联在一起,其中每个步骤的输出直接作为下一个步骤的输入。适用于简单的线性任务序列。
  • 1
from langchain.chains import SimpleSequentialChain
prompt_1 = ChatPromptTemplate.from_template('根据{product}名称,创造一个公司名,只要一个')
chain_1 = LLMChain(llm=model,prompt=prompt_1)
prompt_2 = ChatPromptTemplate.from_template('根据{company}名称,输出20字以内的描述')
chain_2 = LLMChain(llm=model,prompt=prompt_2)
product = '笔记本电脑'
simple_chain = SimpleSequentialChain(chains=[chain_1,chain_2],verbose=True)
simple_chain.run(product)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

chain_2根据chain_1的结果来运行。

二、SequentialChain

	是一种更灵活和复杂的链,它允许每个步骤有不同的输入和输出,可以处理更多样化的任务序列。
  • 1
from langchain.chains import SequentialChain
prompt_1 = ChatPromptTemplate.from_template('根据{product}名称,创造一个公司名,只要一个')
chain_1 = LLMChain(llm=model,prompt=prompt_1,output_key='company')
prompt_2 = ChatPromptTemplate.from_template('根据{company}名称,输出20字以内的描述')
chain_2 = LLMChain(llm=model,prompt=prompt_2,output_key='company_describe')
prompt_3 = ChatPromptTemplate.from_template('根据{product}名称,写一个20字以内的描述')
chain_3 = LLMChain(llm=model,prompt=prompt_3,output_key='product_describe')
prompt_4 = ChatPromptTemplate.from_template('根据{company_describe}和{product_describe},写一个20字以内的总结')
chain_4 = LLMChain(llm=model,prompt=prompt_4,output_key='summary')
product = '笔记本电脑'
product = df.product[]
seq_chain = SequentialChain(chains=[chain_1,chain_2,chain_3,chain_4],input_variables=['product'],
                               output_variables=['company','company_describe','product_describe','summary'],verbose=True)
seq_chain(product)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

chain_2会根据chain_1的输出来运行,运行的结果会给到chain_4,而chain_3会根据chain_1的输出来运行,运行的结果会给到chain_4,得到最终的结果。

三、LLMRouterChain

	是一种更高级的链类型,允许根据输入动态选择不同的模型或链来处理任务。适用于需要根据输入动态路由的复杂任务。
	通常结合MultiPromptChain、RouterOutputParser使用
	RouterOutputParser解析模型的输出,以决定将任务传递给哪个子链。
  • 1
  • 2
  • 3

#RouteChain
from langchain.chains.router import MultiPromptChain#在多个不同提示词模版之间路由
from langchain.chains.router.llm_router import LLMRouterChain, RouterOutputParser#解析器
from langchain.prompts import PromptTemplate
template_1 = '''你是一个物理老师,根据下面的一个问题,来回答,并解释为什么,来帮助学生作答
                问题:{input}
                '''
template_2 = '''你是一个数学老师,根据下面的一个问题,来回答,并解释为什么,来帮助学生作答
                问题:{input}
                '''
template_3 = '''你是一个英语老师,根据下面的一个问题,来回答,并解释为什么,来帮助学生作答
                问题:{input}
                '''
prompt_infos = [
    {
        'name':'物理',
        'description':'回答物理问题',
        'prompt_template':template_1
    },
    {
        'name':'数学',
        'description':'回答数学问题',
        'prompt_template':template_2
    },
    {
        'name':'英语',
        'description':'回答英语问题',
        'prompt_template':template_3
    }
]
destination_chains={}
for info in prompt_infos:
    name = info['name']
    prompt_template = info['prompt_template']
    prompt = ChatPromptTemplate.from_template(template=prompt_template)
    chain = LLMChain(llm=model,prompt=prompt)
    destination_chains[name] = chain
    
destinations = [f"{p['name']}: {p['description']}" for p in prompt_infos]
destinations_str = '\n'.join(destinations)
default_prompt = ChatPromptTemplate.from_template('{input}')  #默认链,没有找到合适的就采取默认
default_chain = LLMChain(llm=model,prompt=default_prompt)
multi_prompt_router_template='''给定一个原始文本输入到一个语言模型并且选择最适合输入的模型提示语。你会获得可用的提示语的名称以及该提示语最合适的描述。
                                记住:任何情况下都要使用原始文本输入。
                                << FORMATTING >>
                                返回一个 Markdown 代码片段,其中 JSON 对象的格式如下:
                                ```json
                                {{{{
                                "destination": string
                                "next_inputs": string
                                }}}}
                                ```
                                记住: "destination"的值需要从下面"CANDIDATE PROMPTS"里挑选一个和原始文本输入内容最匹配的值。如果没有匹配的则把值设为"default"
                                记住: "next_inputs"的值就是给定的原始文本输入
                                << CANDIDATE PROMPTS >>
                                {destinations}
                                << INPUT >>
                                {{input}}
                                << OUTPUT (must include ```json at the start of the response) >>
                                << OUTPUT (must end with ```) >>
'''
router_template = multi_prompt_router_template.format(
    destinations=destinations_str
)
router_prompt = PromptTemplate(
    template=router_template,
    input_variables=["input"],
    output_parser=RouterOutputParser(),
)

router_chain = LLMRouterChain.from_llm(model, router_prompt, verbose=True)
chain = MultiPromptChain(router_chain=router_chain, 
                         destination_chains=destination_chains, 
                         default_chain=default_chain, verbose=True)
chain.run('实现的英文单词是什么')  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75

最终的chain会先按照multi_prompt_router_template来选择最合适的子链,比如‘实现的英文单词是什么’这就符合template_3英语,那么就会选择这个子链,再按照template_3的prompt进行最终的输出。如果没有合适的就会采用default子链。

四、文档链

可以将大模型与未训练过的文档结合起来
  • 1
from langchain.chains import RetrievalQA  #帮助检索文档
from langchain_wenxin.chat_models import ChatWenxin
from langchain.document_loaders import CSVLoader #文档加载器  在这里加载csv文件
from langchain.vectorstores import DocArrayInMemorySearch  #向量存储
from IPython.display import display,Markdown
from langchain.indexes import VectorstoreIndexCreator  #很方便创建向量存储
file = 'xxx.csv'   #加载一个csv文件,里面有文本信息
loader = CSVLoader(file_path=file)
docs = loader.load()
!pip install -q sentence-transformers
from langchain_community.embeddings import HuggingFaceEmbeddings
embeddings = HuggingFaceEmbeddings(model_name='shibing624/text2vec-base-chinese')#加载embeddings   国内的
!pip install -q docarray
db = DocArrayInMemorySearch.from_documents(docs,embeddings) #构建向量存储
#方式一
query='xxx'
docs = db.similarity_search(query=query,k=2)#查询与query相关的k个内容
print(list(docs))
print(len(docs))  #结果就是k=2
#方式二
gdocs = ''.join([docs[i].page_content for i in range(len(docs))]) #所有文档放在一起
res = model.call_as_llm(f'{gdocs} 问题:请用markdown表格列出所有与xxx相关的内容,并总结')
display(Markdown(res))
#方式三
#开始使用RetrievalQA链
retriever = db.as_retriever()#检索器   定义了一个接受查询内容并返回相似文档的方法
qa_stuff = RetrievalQA.from_chain_type(llm=model,chain_type='stuff',#stuff 最简单的,将所有文档内容都一起放在上下文中
                                      retriever=retriever,verbose=True)
query='请用markdown表格列出所有与xx相关的内容,并总结'
res = qa_stuff.run(query)
display(Markdown(res))
#方式四
index = VectorstoreIndexCreator(
        vectorstore_cls = DocArrayInMemorySearch,
        embedding = embeddings
).from_loaders([loader])
query='请用markdown表格列出所有与xx相关的内容,并总结'
res = index.query(query,llm=model)
display(Markdown(res))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

总结

Chain 的应用场景

  • 问答系统: 将用户的问题传递给语言模型,并从知识库中检索答案。
  • 信息抽取: 从文本中提取特定信息,并进一步处理。
  • 数据增强: 将文本传递给多个工具或模型,以生成更多数据或增强现有数据。
  • 对话代理: 构建复杂的对话系统,处理多轮对话和上下文管理。
  • 通过使用 Chain,你可以将不同的步骤组合在一起,创建灵活且强大的自然语言处理工作流。
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/904683
推荐阅读
相关标签
  

闽ICP备14008679号