赞
踩
第一部分 langchain入门以及prompt、解析器使用
第二部分langchain学习之memory机制
是一种简化的链,用于将多个步骤串联在一起,其中每个步骤的输出直接作为下一个步骤的输入。适用于简单的线性任务序列。
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)
chain_2根据chain_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)
chain_2会根据chain_1的输出来运行,运行的结果会给到chain_4,而chain_3会根据chain_1的输出来运行,运行的结果会给到chain_4,得到最终的结果。
是一种更高级的链类型,允许根据输入动态选择不同的模型或链来处理任务。适用于需要根据输入动态路由的复杂任务。
通常结合MultiPromptChain、RouterOutputParser使用
RouterOutputParser解析模型的输出,以决定将任务传递给哪个子链。
#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('实现的英文单词是什么')
最终的chain会先按照multi_prompt_router_template来选择最合适的子链,比如‘实现的英文单词是什么’这就符合template_3英语,那么就会选择这个子链,再按照template_3的prompt进行最终的输出。如果没有合适的就会采用default子链。
可以将大模型与未训练过的文档结合起来
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))
Chain 的应用场景
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。