【LLM】Langchain使用[二](模型链)

文章目录

    • 1. SimpleSequentialChain
    • 2. SequentialChain
    • 3. 路由链 Router Chain
  • Reference

1. SimpleSequentialChain

  • 场景:一个输入和一个输出
from langchain.chat_models import ChatOpenAI    #导入OpenAI模型
from langchain.prompts import ChatPromptTemplate   #导入聊天提示模板
from langchain.chains import LLMChain    #导入LLM链。
from langchain.chains import SimpleSequentialChainllm = ChatOpenAI(temperature=0.9, openai_api_key = api_key)# 提示模板 1 :这个提示将接受产品并返回最佳名称来描述该公司
first_prompt = ChatPromptTemplate.from_template("What is the best name to describe \a company that makes {product}?"
)
# Chain 1
chain_one = LLMChain(llm=llm, prompt=first_prompt)# 提示模板 2 :接受公司名称,然后输出该公司的长为20个单词的描述
second_prompt = ChatPromptTemplate.from_template("Write a 20 words description for the following \company:{company_name}"
)
# chain 2
chain_two = LLMChain(llm=llm, prompt=second_prompt)
# 组合两个chain,便于在一个步骤中含有该公司名字的公司描述
overall_simple_chain = SimpleSequentialChain(chains=[chain_one, chain_two],verbose=True)
product = "Queen Size Sheet Set"
overall_simple_chain.run(product)
# 结果: RegalRest Bedding
# RegalRest Bedding offers luxurious and comfortable mattresses and bedding accessories for a restful and rejuvenating sleep experience.

2. SequentialChain

  • 场景:多个输入和输出的时候
#子链1
# prompt模板 1: 翻译成英语(把下面的review翻译成英语)
first_prompt = ChatPromptTemplate.from_template("Translate the following review to english:""\n\n{Review}"
)
# chain 1: 输入:Review 输出: 英文的 Review
chain_one = LLMChain(llm=llm, prompt=first_prompt, output_key="English_Review")#子链2
# prompt模板 2: 用一句话总结下面的 review
second_prompt = ChatPromptTemplate.from_template("Can you summarize the following review in 1 sentence:""\n\n{English_Review}"
)
# chain 2: 输入:英文的Review   输出:总结
chain_two = LLMChain(llm=llm, prompt=second_prompt, output_key="summary")               #子链3
# prompt模板 3: 下面review使用的什么语言
third_prompt = ChatPromptTemplate.from_template("What language is the following review:\n\n{Review}"
)
# chain 3: 输入:Review  输出:语言
chain_three = LLMChain(llm=llm, prompt=third_prompt,output_key="language")# prompt模板 4: 使用特定的语言对下面的总结写一个后续回复
fourth_prompt = ChatPromptTemplate.from_template("Write a follow up response to the following ""summary in the specified language:""\n\nSummary: {summary}\n\nLanguage: {language}"
)
# chain 4: 输入: 总结, 语言    输出: 后续回复
chain_four = LLMChain(llm=llm, prompt=fourth_prompt,output_key="followup_message")
# 对四个子链进行组合
#输入:review    输出:英文review,总结,后续回复 
overall_chain = SequentialChain(chains=[chain_one, chain_two, chain_three, chain_four],input_variables=["Review"],output_variables=["English_Review", "summary","followup_message"],verbose=True
)
review = df.Review[5]
overall_chain(review)

结果如下,可以看到根据评论文本,子链1将文本翻译为英语,子链2将英文文本进行总结,子链3得到初始文本的语言,子链4对英文文本进行回复,并且是用初始语言。每个后面的子链可以利用前面链的outpu_key变量。

{'Review': "Je trouve le goût médiocre. La mousse ne tient pas, c'est bizarre. J'achète les mêmes dans le commerce et le goût est bien meilleur...\nVieux lot ou contrefaçon !?",'English_Review': "I find the taste mediocre. The foam doesn't hold, it's strange. I buy the same ones in stores and the taste is much better...\nOld batch or counterfeit!?",'summary': 'The reviewer is disappointed with the taste and foam quality, suspecting that the product might be either an old batch or a counterfeit 
version.','followup_message': "Après avoir examiné vos commentaires, nous sommes désolés d'apprendre que vous êtes déçu par le goût et la qualité de la mousse de notre produit. Nous comprenons vos préoccupations et nous nous excusons pour tout inconvénient que cela a pu causer. Votre avis est précieux pour nous et nous aimerions enquêter davantage sur cette situation. Nous vous assurons que notre produit est authentique et fabriqué avec les normes les plus élevées de qualité. Cependant, nous examinerons attentivement votre spéculation selon laquelle il pourrait s'agir d'un lot ancien ou d'une contrefaçon. Veuillez nous fournir plus de détails sur le produit que vous avez acheté, y compris la date d'expiration et le code de lot, afin que nous puissions résoudre ce problème de manière appropriée. Nous vous remercions de nous avoir informés de cette situation et nous nous engageons à améliorer constamment notre produit pour répondre aux attentes de nos clients."}

3. 路由链 Router Chain

一个相当常见但基本的操作是根据输入将其路由到一条链,具体取决于该输入到底是什么。如果你有多个子链,每个子链都专门用于特定类型的输入,那么可以组成一个路由链,它首先决定将它传递给哪个子链,然后将它传递给那个链。

路由器由两个组件组成:

  • 路由器链本身(负责选择要调用的下一个链)
  • destination_chains:路由器链可以路由到的链

步骤:

  • 创建目标链:目标链是由路由链调用的链,每个目标链都是一个语言模型链
  • 创建默认目标链:这是一个当路由器无法决定使用哪个子链时调用的链。在上面的示例中,当输入问题与物理、数学、历史或计算机科学无关时,可能会调用它。
  • 创建LLM用于在不同链之间进行路由的模板
    • 注意:此处在原教程的基础上添加了一个示例,主要是因为"gpt-3.5-turbo"模型不能很好适应理解模板的意思,使用 “text-davinci-003” 或者"gpt-4-0613"可以很好的工作,因此在这里多加了示例提示让其更好的学习。
      eg:
      << INPUT >>
      “What is black body radiation?”
      << OUTPUT >>
{{{{"destination": string \ name of the prompt to use or "DEFAULT""next_inputs": string \ a potentially modified version of the original input
}}}}
  • 构建路由链:首先,我们通过格式化上面定义的目标创建完整的路由器模板。这个模板可以适用许多不同类型的目标。因此,在这里,可以添加一个不同的学科,如英语或拉丁语,而不仅仅是物理、数学、历史和计算机科学。
  • 从这个模板创建提示模板。最后,通过传入llm和整个路由提示来创建路由链。需要注意的是这里有路由输出解析,这很重要,因为它将帮助这个链路决定在哪些子链路之间进行路由。
  • 创建整体链路
	from langchain.chains import SequentialChainfrom langchain.chat_models import ChatOpenAI    #导入OpenAI模型from langchain.prompts import ChatPromptTemplate   #导入聊天提示模板from langchain.chains import LLMChain    #导入LLM链。from langchain.chains.router import MultiPromptChain  #导入多提示链from langchain.chains.router.llm_router import LLMRouterChain,RouterOutputParserfrom langchain.prompts import PromptTemplate# example4#第一个提示适合回答物理问题physics_template = """You are a very smart physics professor. \You are great at answering questions about physics in a concise\and easy to understand manner. \When you don't know the answer to a question you admit\that you don't know.Here is a question:{input}"""#第二个提示适合回答数学问题math_template = """You are a very good mathematician. \You are great at answering math questions. \You are so good because you are able to break down \hard problems into their component parts, answer the component parts, and then put them together\to answer the broader question.Here is a question:{input}"""#第三个适合回答历史问题history_template = """You are a very good historian. \You have an excellent knowledge of and understanding of people,\events and contexts from a range of historical periods. \You have the ability to think, reflect, debate, discuss and \evaluate the past. You have a respect for historical evidence\and the ability to make use of it to support your explanations \and judgements.Here is a question:{input}"""#第四个适合回答计算机问题computerscience_template = """ You are a successful computer scientist.\You have a passion for creativity, collaboration,\forward-thinking, confidence, strong problem-solving capabilities,\understanding of theories and algorithms, and excellent communication \skills. You are great at answering coding questions. \You are so good because you know how to solve a problem by \describing the solution in imperative steps \that a machine can easily interpret and you know how to \choose a solution that has a good balance between \time complexity and space complexity. Here is a question:{input}"""# 拥有了这些提示模板后,可以为每个模板命名,然后提供描述。# 例如,第一个物理学的描述适合回答关于物理学的问题,这些信息将传递给路由链,然后由路由链决定何时使用此子链。prompt_infos = [{"name": "physics","description": "Good for answering questions about physics","prompt_template": physics_template},{"name": "math","description": "Good for answering math questions","prompt_template": math_template},{"name": "History","description": "Good for answering history questions","prompt_template": history_template},{"name": "computer science","description": "Good for answering computer science questions","prompt_template": computerscience_template}]api_key = "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"llm = ChatOpenAI(temperature=0, openai_api_key = api_key)destination_chains = {}for p_info in prompt_infos:name = p_info["name"]prompt_template = p_info["prompt_template"]prompt = ChatPromptTemplate.from_template(template=prompt_template)chain = LLMChain(llm=llm, prompt=prompt)destination_chains[name] = chaindestinations = [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=llm, prompt=default_prompt)# 创建LLM用于在不同链之间进行路由的模板MULTI_PROMPT_ROUTER_TEMPLATE = """Given a raw text input to a \language model select the model prompt best suited for the input. \You will be given the names of the available prompts and a \description of what the prompt is best suited for. \You may also revise the original input if you think that revising\it will ultimately lead to a better response from the language model.<< FORMATTING >>Return a markdown code snippet with a JSON object formatted to look like:```json{{{{"destination": string \ name of the prompt to use or "DEFAULT""next_inputs": string \ a potentially modified version of the original input}}}}```REMEMBER: "destination" MUST be one of the candidate prompt \names specified below OR it can be "DEFAULT" if the input is not\well suited for any of the candidate prompts.REMEMBER: "next_inputs" can just be the original input \if you don't think any modifications are needed.<< CANDIDATE PROMPTS >>{destinations}<< INPUT >>{{input}}<< OUTPUT (remember to include the ```json)>>eg:<< INPUT >>"What is black body radiation?"<< OUTPUT >>```json{{{{"destination": string \ name of the prompt to use or "DEFAULT""next_inputs": string \ a potentially modified version of the original input}}}}```"""# 构建路由链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(llm, router_prompt)# 整合多提示链chain = MultiPromptChain(router_chain=router_chain,    #l路由链路destination_chains=destination_chains,   #目标链路default_chain=default_chain,      #默认链路verbose=True)# 问题:什么是黑体辐射?response = chain.run("What is black body radiation?")print(response)

回答的结果为:

> Entering new MultiPromptChain chain...
physics: {'input': 'What is black body radiation?'}
> Finished chain.
Black body radiation refers to the electromagnetic radiation emitted by an object that absorbs all incident radiation and reflects or transmits none. It is called "black body" because it absorbs all wavelengths of light, appearing black at room temperature. According to Planck's law, black body radiation is characterized by a continuous spectrum of wavelengths and intensities, which depend on the temperature of the object. As the temperature increases, the peak intensity of the radiation shifts to shorter wavelengths, resulting in a change in color from red to orange, yellow, white, and eventually blue at very high temperatures.Black body radiation is a fundamental concept in physics and has various applications, including understanding the behavior of stars, explaining the cosmic microwave background radiation, and developing technologies like incandescent light bulbs and thermal imaging devices.

Reference

[1] https://python.langchain.com/docs/modules/chains/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/3114.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

自动化测试之数据驱动与关键字驱动

目录 1.录制/回放的神话 2.数据驱动的自动化测试框架 3.关键字驱动的自动化测试 初次接触自动化测试时&#xff0c;对数据驱动和关键字驱动不甚理解&#xff0c;觉得有点故弄玄须&#xff0c;不就是参数和函数其嘛&#xff01;其实其也体现了测试所不同与开发的一些特点&…

目标检测——R-CNN网络基础

目录 Overfeat模型RCNN模型算法流程候选区域生成CNN网络提取特征目标分类&#xff08;SVM&#xff09;目标定位预测过程 算法总结 Fast RCNN模型算法流程ROI Pooling目标分类和回归 模型训练模型总结 Overfeat模型 RCNN模型 算法流程 候选区域生成 CNN网络提取特征 目标分类&am…

机器学习1

核心梯度下降算法&#xff1a; import numpy as np from utils.features import prepare_for_trainingclass LinearRegression:def __init__(self,data,labels,polynomial_degree 0,sinusoid_degree 0,normalize_dataTrue):"""1.对数据进行预处理操作2.先得到…

Python-Web框架flask使用

目录 1.Web框架 1.1 flask 1.1.1 debug调试 1.1.2 定义参数web服务 获取字符串 ​编辑 1.1.3 html网页渲染 1.13.1 带参数传给网页文件 普通元素 列表元素 字典元素 1.Web框架 1.1 flask python的web框架&#xff0c;目录结构如下&#xff1a; 1.static存放的是css,…

Windows7中使用SRS集成音视频一对一通话

SRS早就具备了SFU的能力&#xff0c;比如一对一通话、多人通话、直播连麦等等。在沟通中&#xff0c;一对一是常用而且典型的场景&#xff0c; 让我们一起来看看如何用SRS做直播和RTC一体化的一对一通话。 一、启动windows7-docker 二、拉取SRS镜像 执行命令:docker pull oss…

BTY生态系统DNS关于DeSoc的构想

2022年5月&#xff0c;以太坊创始人Vitalik Buterin与经济学家Glen Weyl和Flashbots研究员Puja Ohlhaver联合发布了《Decentralized Society: Finding Web3’s Soul》。这篇论文的核心是围绕“Web3灵魂”创造出去中心化社会的可能性。 论文中阐述&#xff0c;当下Web3 更多是表…

程序员如何准备技术面试

程序员如何准备技术面试 &#x1f607;博主简介&#xff1a;我是一名正在攻读研究生学位的人工智能专业学生&#xff0c;我可以为计算机、人工智能相关本科生和研究生提供排忧解惑的服务。如果您有任何问题或困惑&#xff0c;欢迎随时来交流哦&#xff01;&#x1f604; ✨座右…

Nacos服务注册和配置中心(Config,Eureka,Bus)1

SCA(Spring Cloud Alibaba)核心组件 Spring Cloud是若干个框架的集合&#xff0c;包括spring-cloud-config、spring-cloud-bus等近20个子项目&#xff0c;提供了服务治理、服务网关、智能路由、负载均衡、断路器、监控跟踪、分布式消息队列、配置管理等领域的解决方案,Spring C…

python_day11_practice

将文本数据插入数据库 两文本文件为day10面向对象练习案例 将data_define.py文件复制过来&#xff08;导入失败&#xff0c;疑惑&#xff09; 新建数据库&#xff0c;建表orders -- CREATE DATABASE py_sql charset utf8;use py_sql;create table orders(order_date date,…

从0到1构建证券行业组织级项目管理体系的探索与实践︱东吴证券PMO负责人娄鹏呈

东吴证券股份有限公司信息技术总部PMO负责人娄鹏呈先生受邀为由PMO评论主办的2023第十二届中国PMO大会演讲嘉宾&#xff0c;演讲议题&#xff1a;从0到1构建证券行业组织级项目管理体系的探索与实践。大会将于8月12-13日在北京举办&#xff0c;敬请关注&#xff01; 议题简要&a…

[java安全]CommonsCollections3.1

文章目录 【java安全】CommonsCollections3.1InvokerTransformerConstantTransformerChainedTransformerTransformedMap如何触发checkSetValue()方法&#xff1f;AnnotationInvocationHandlerpoc利用链 【java安全】CommonsCollections3.1 java开发过程中经常会用到一些库。Ap…

hardMacro的后防和后端处理

目录 1.hardMacro及仿真模型 2.后防该怎么做及遇到的问题 1.hardMacro及仿真模型 在芯片设计中在使用第三方IP时 会有vonder提供hard Macro IP的情况。什么是hard Macro呢&#xff1f;就是vonder最终提供的是GDS(设计版图)文件给后端。 GDS文件包含了芯片实现的所有信息&#…

微服务系列文章之 Nginx反向代理

Nginx反向代理模块的指令是由ngx_http_proxy_module模块进行解析&#xff0c;该模块在安装Nginx的时候已经自己加装到Nginx中了&#xff0c;接下来我们把反向代理中的常用指令一一介绍下&#xff1a; proxy_pass proxy_set_header proxy_redirect1、proxy_pass 该指令用来设置…

Star History 月度开源精选|2023 年 6 月

上一期 Star History 月度精选是写给市场、运营人员的&#xff0c;而这一期回归到 DevTools 类别&#xff0c;我们六月发现了好一些开发者可以用的不错工具&#xff01; AI Getting Started 还记得 Supabase “Build in a weekend” 的广告词吗&#xff01;AI Getting Started…

【C++】C++11 -- 新功能

文章目录 C11 -- 新功能默认成员函数类成员变量初始化强制生成默认函数关键字default禁用生成默认函数的关键字deletefinal and override 关键字 C11 – 新功能 默认成员函数 在C11之前一个类有6个默认成员函数&#xff0c;在C11标准中又新增了两个默认成员函数&#xff0c;分…

23款奔驰S450 4MATIC更换原厂流星雨智能数字大灯,让智能照亮您前行的路

“流星雨”数字大灯&#xff0c;极具辨识度&#xff0c;通过260万像素的数字微镜技术&#xff0c;实现“流星雨”仪式感与高度精确的光束分布&#xff1b;在远光灯模式下&#xff0c;光束精准度更达之前84颗LED照明的100倍&#xff0c;更新增坡道照明功能&#xff0c;可根据导航…

【PCB专题】如何在Allegro中定义字体及批量修改丝印

在PCB板上丝印往往包含了很多信息,比如元件边界、元件参数、元件编号、极性、静电标识、板号等,这些信息在生产、测试及后期维护等都需要使用。一个好的设计往往都能从丝印的布局、丝印的完整性上体现出来。如下所示PCB在电解电容旁有极性丝印、电阻旁有电阻的位号信息等。 …

利用 jenkins 关联 Job 方式完善 RobotFramework 测试 Setup 以及 Teardown 后操作

目录 1.前言 2.Jekins 关联 Job 方式 1.前言 Jenkins是一个流行的持续集成和交付工具&#xff0c;它可以帮助自动化构建、测试和部署软件。与Robot Framework结合使用&#xff0c;可以实现更高效的测试工作流程。 在Robot Framework中&#xff0c;Setup和Teardown是测试用例…

SQL语句GROUP BY、HAVING、EXISTS、SQL函数(Null判断、日期相关、计算数值和字符串操作 )

目录 GROUP BY HAVING EXISTS SQL函数 Null判断函数 日期数据类型及函数 计算数值和字符串操作函数 AVG(平均值) COUNT(数据条数) FIRST/LAST(第一条数据) MAX/MIN(最大值) SUM(列总和) UCASE/ LCASE (转换大小写) MID(截取字符串) LEN(字符值的长度) ROUND(数…

什么是70v转12v芯片?

问&#xff1a;什么是70v转12v芯片&#xff1f; 答&#xff1a;70v转12v芯片是一种电子器件&#xff0c;其功能是将输入电压范围在9v至100v之间的电源转换为稳定的12v输出电压。这种芯片通常被用于充电器、车载电池充电器和电源适配器等设备中。 问&#xff1a;这种芯片的最大…