【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 >>
- 注意:此处在原教程的基础上添加了一个示例,主要是因为"gpt-3.5-turbo"模型不能很好适应理解模板的意思,使用 “text-davinci-003” 或者"gpt-4-0613"可以很好的工作,因此在这里多加了示例提示让其更好的学习。
{{{{"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/
相关文章:
【LLM】Langchain使用[二](模型链)
文章目录 1. SimpleSequentialChain2. SequentialChain3. 路由链 Router Chain Reference 1. SimpleSequentialChain 场景:一个输入和一个输出 from langchain.chat_models import ChatOpenAI #导入OpenAI模型 from langchain.prompts import ChatPromptTempla…...
简单机器学习工程化过程
1、确认需求(构建问题) 我们需要做什么? 比如根据一些输入数据,预测某个值? 比如输入一些特征,判断这个是个什么动物? 这里我们要可以尝试分析一下,我们要处理的是个什么问题&…...

【MongoDB】SpringBoot整合MongoDB
【MongoDB】SpringBoot整合MongoDB 文章目录 【MongoDB】SpringBoot整合MongoDB0. 准备工作1. 集合操作1.1 创建集合1.2 删除集合 2. 相关注解3. 文档操作3.1 添加文档3.2 批量添加文档3.3 查询文档3.3.1 查询所有文档3.3.2 根据id查询3.3.3 等值查询3.3.4 范围查询3.3.5 and查…...
关于游戏引擎(godot)对齐音乐bpm的技术
引擎默认底层 1. _process(): 每秒钟调用60次(无限的) 数学 1. bpm1分钟节拍数量60s节拍数量 bpm120 60s120拍 2. 每拍子时间 60/bpm 3. 每个拍子触发周期所需要的帧数 每拍子时间*60(帧率) 这个是从帧数级别上对齐拍子的时间&#x…...

【Go】实现一个代理Kerberos环境部分组件控制台的Web服务
实现一个代理Kerberos环境部分组件控制台的Web服务 背景安全措施引入的问题SSO单点登录 过程整体设计路由反向代理登录会话组件代理YarnHbase 结果 背景 首先要说明下我们目前有部分集群的环境使用的是HDP-3.1.5.0的大数据集群,除了集成了一些自定义的服务以外&…...
Spring Security 6.x 系列【63】扩展篇之匿名认证
有道无术,术尚可求,有术无道,止于术。 本系列Spring Boot 版本 3.1.0 本系列Spring Security 版本 6.1.0 本系列Spring Authorization Server 版本 1.1.0 源码地址:https://gitee.com/pearl-organization/study-spring-security-demo 文章目录 1. 概述2. 配置3. Anonymo…...

供应链管理系统有哪些?
1万字干货分享,国内外 20款 供应链管理软件都给你讲的明明白白。如果你还不知道怎么选择,一定要翻到第三大段,这里我将会通过8年的软件产品选型经验告诉你,怎么样才能快速选到适合自己的软件工具。 (为防后续找不到&a…...

如何在PADS Logic中查找器件
PADS Logic提供类似于Windows的查找功能,可以进行器件的查找。 (1)在Logic设计界面中,将菜单显示中的“选择工具栏”进行打开,如图1所示,会弹出对应的“选择工具栏”的分栏菜单选项,如图2所示。…...

Android 生成pdf文件
Android 生成pdf文件 1.使用官方的方式 使用官方的方式也就是PdfDocument类的使用 1.1 基本使用 /**** 将tv内容写入到pdf文件*/RequiresApi(api Build.VERSION_CODES.KITKAT)private void newPdf() {// 创建一个PDF文本对象PdfDocument document new PdfDocument();//创建…...

Kafka 入门到起飞 - 生产者发送消息流程解析
生产者通过send()方法发送消息消息会经过拦截器->序列化器->分区器 进行加工然后将消息存在缓冲区当缓冲区中消息达到条件会按批次发送到broker对应分区上broker将接收到的消息进行刷盘持久化消息处理broker会返回给producer响应落盘成功返回元数据…...

基于单片机智能台灯坐姿矫正器视力保护器的设计与实现
功能介绍 以51单片机作为主控系统;LCD1602液晶显示当前当前光线强度、台灯灯光强度、当前时间、坐姿距离等;按键设置当前时间,闹钟、提醒时间、坐姿最小距离;通过超声波检测坐姿,当坐姿不正容易对眼睛和身体腰部等造成…...

欧姆龙以太网模块如何设置ip连接 Kepware opc步骤
在数字化和自动化的今天,PLC在工业控制领域的作用日益重要。然而,PLC通讯口的有限资源成为了困扰工程师们的问题。为了解决这一问题,捷米特推出了JM-ETH-CP转以太网模块,让即插即用的以太网通讯成为可能,不仅有效利用了…...

PLEX如何搭建个人局域网的视频网站
Plex是一款功能非常强大的影音媒体管理系统,最大的优势是多平台支持和界面优美,几乎可以在所有的平台上安装plex服务器和客户端,让你可以随时随地享受存储在家中的电影、照片、音乐,并且可以实现观看记录无缝衔接,手机…...

java学习02
一、基本数据类型 Java有两大数据类型,内置数据类型和引用数据类型。 内置数据类型 Java语言提供了八种基本类型。六种数字类型(四个整数型,两个浮点型),一种字符类型,还有一种布尔型。 byte࿱…...
libcurl库使用实例
libcurl libcurl是一个功能强大的跨平台网络传输库,支持多种协议,包括HTTP、FTP、SMTP等,同时提供了易于使用的API。 安装 ubuntu18.04平台安装 sudo apt-get install libcurl4-openssl-dev实例 这个示例使用libcurl库发送一个简单的HTTP …...

大数据存储架构详解:数据仓库、数据集市、数据湖、数据网格、湖仓一体
前言 本文隶属于专栏《大数据理论体系》,该专栏为笔者原创,引用请注明来源,不足和错误之处请在评论区帮忙指出,谢谢! 本专栏目录结构和参考文献请见大数据理论体系 思维导图 数据仓库 数据仓库是一个面向主题的&…...
ESP32(MicroPython) 网页控制五自由度机械臂
ESP32(MicroPython) 网页控制五自由度机械臂 本程序通过网页控制五自由度机械臂,驱动方案改用PCA9685。 代码如下 #导入Pin模块 from machine import Pin import time from machine import SoftI2C from servo import Servos import networ…...

前端笔记_OAuth规则机制下实现个人站点接入qq三方登录
文章目录 ⭐前言⭐qq三方登录流程💖qq互联中心创建网页应用💖配置回调地址redirect_uri💖流程分析 ⭐思路分解⭐技术选型实现💖技术选型:💖实现 ⭐结束 ⭐前言 大家好,我是yma16,本…...

huggingface新作品:快速和简便的训练模型
AutoTrain Advanced是一个用于训练和部署最先进的机器学习模型的工具。它旨在提供更快速、更简便的方式来进行模型训练和部署。 安装 您可以通过PIP安装AutoTrain-Advanced的Python包。请注意,为了使AutoTrain Advanced正常工作,您将需要python > 3.…...

利用鸿鹄优化共享储能的SCADA 系统功能,赋能用户数据自助分析
摘要 本文主要介绍了共享储能的 SCADA 系统大数据架构,以及如何利用鸿鹄来更好的优化 SCADA 系统功能,如何为用户进行数据自助分析赋能。 1、共享储能介绍 说到共享储能,可能不少朋友比较陌生,下面我们简单介绍一下共享储能的价值…...
vscode里如何用git
打开vs终端执行如下: 1 初始化 Git 仓库(如果尚未初始化) git init 2 添加文件到 Git 仓库 git add . 3 使用 git commit 命令来提交你的更改。确保在提交时加上一个有用的消息。 git commit -m "备注信息" 4 …...

深入剖析AI大模型:大模型时代的 Prompt 工程全解析
今天聊的内容,我认为是AI开发里面非常重要的内容。它在AI开发里无处不在,当你对 AI 助手说 "用李白的风格写一首关于人工智能的诗",或者让翻译模型 "将这段合同翻译成商务日语" 时,输入的这句话就是 Prompt。…...
MVC 数据库
MVC 数据库 引言 在软件开发领域,Model-View-Controller(MVC)是一种流行的软件架构模式,它将应用程序分为三个核心组件:模型(Model)、视图(View)和控制器(Controller)。这种模式有助于提高代码的可维护性和可扩展性。本文将深入探讨MVC架构与数据库之间的关系,以…...

ETLCloud可能遇到的问题有哪些?常见坑位解析
数据集成平台ETLCloud,主要用于支持数据的抽取(Extract)、转换(Transform)和加载(Load)过程。提供了一个简洁直观的界面,以便用户可以在不同的数据源之间轻松地进行数据迁移和转换。…...

现代密码学 | 椭圆曲线密码学—附py代码
Elliptic Curve Cryptography 椭圆曲线密码学(ECC)是一种基于有限域上椭圆曲线数学特性的公钥加密技术。其核心原理涉及椭圆曲线的代数性质、离散对数问题以及有限域上的运算。 椭圆曲线密码学是多种数字签名算法的基础,例如椭圆曲线数字签…...

【从零开始学习JVM | 第四篇】类加载器和双亲委派机制(高频面试题)
前言: 双亲委派机制对于面试这块来说非常重要,在实际开发中也是经常遇见需要打破双亲委派的需求,今天我们一起来探索一下什么是双亲委派机制,在此之前我们先介绍一下类的加载器。 目录 编辑 前言: 类加载器 1. …...
从面试角度回答Android中ContentProvider启动原理
Android中ContentProvider原理的面试角度解析,分为已启动和未启动两种场景: 一、ContentProvider已启动的情况 1. 核心流程 触发条件:当其他组件(如Activity、Service)通过ContentR…...
多元隐函数 偏导公式
我们来推导隐函数 z z ( x , y ) z z(x, y) zz(x,y) 的偏导公式,给定一个隐函数关系: F ( x , y , z ( x , y ) ) 0 F(x, y, z(x, y)) 0 F(x,y,z(x,y))0 🧠 目标: 求 ∂ z ∂ x \frac{\partial z}{\partial x} ∂x∂z、 …...

【iOS】 Block再学习
iOS Block再学习 文章目录 iOS Block再学习前言Block的三种类型__ NSGlobalBlock____ NSMallocBlock____ NSStackBlock__小结 Block底层分析Block的结构捕获自由变量捕获全局(静态)变量捕获静态变量__block修饰符forwarding指针 Block的copy时机block作为函数返回值将block赋给…...

路由基础-路由表
本篇将会向读者介绍路由的基本概念。 前言 在一个典型的数据通信网络中,往往存在多个不同的IP网段,数据在不同的IP网段之间交互是需要借助三层设备的,这些设备具备路由能力,能够实现数据的跨网段转发。 路由是数据通信网络中最基…...