当前位置: 首页 > news >正文

【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/

相关文章:

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

文章目录 1. SimpleSequentialChain2. SequentialChain3. 路由链 Router Chain Reference 1. SimpleSequentialChain 场景&#xff1a;一个输入和一个输出 from langchain.chat_models import ChatOpenAI #导入OpenAI模型 from langchain.prompts import ChatPromptTempla…...

简单机器学习工程化过程

1、确认需求&#xff08;构建问题&#xff09; 我们需要做什么&#xff1f; 比如根据一些输入数据&#xff0c;预测某个值&#xff1f; 比如输入一些特征&#xff0c;判断这个是个什么动物&#xff1f; 这里我们要可以尝试分析一下&#xff0c;我们要处理的是个什么问题&…...

【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次&#xff08;无限的&#xff09; 数学 1. bpm1分钟节拍数量60s节拍数量 bpm120 60s120拍 2. 每拍子时间 60/bpm 3. 每个拍子触发周期所需要的帧数 每拍子时间*60(帧率&#xff09; 这个是从帧数级别上对齐拍子的时间&#x…...

【Go】实现一个代理Kerberos环境部分组件控制台的Web服务

实现一个代理Kerberos环境部分组件控制台的Web服务 背景安全措施引入的问题SSO单点登录 过程整体设计路由反向代理登录会话组件代理YarnHbase 结果 背景 首先要说明下我们目前有部分集群的环境使用的是HDP-3.1.5.0的大数据集群&#xff0c;除了集成了一些自定义的服务以外&…...

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万字干货分享&#xff0c;国内外 20款 供应链管理软件都给你讲的明明白白。如果你还不知道怎么选择&#xff0c;一定要翻到第三大段&#xff0c;这里我将会通过8年的软件产品选型经验告诉你&#xff0c;怎么样才能快速选到适合自己的软件工具。 &#xff08;为防后续找不到&a…...

如何在PADS Logic中查找器件

PADS Logic提供类似于Windows的查找功能&#xff0c;可以进行器件的查找。 &#xff08;1&#xff09;在Logic设计界面中&#xff0c;将菜单显示中的“选择工具栏”进行打开&#xff0c;如图1所示&#xff0c;会弹出对应的“选择工具栏”的分栏菜单选项&#xff0c;如图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&#xff08;&#xff09;方法发送消息消息会经过拦截器->序列化器->分区器 进行加工然后将消息存在缓冲区当缓冲区中消息达到条件会按批次发送到broker对应分区上broker将接收到的消息进行刷盘持久化消息处理broker会返回给producer响应落盘成功返回元数据…...

基于单片机智能台灯坐姿矫正器视力保护器的设计与实现

功能介绍 以51单片机作为主控系统&#xff1b;LCD1602液晶显示当前当前光线强度、台灯灯光强度、当前时间、坐姿距离等&#xff1b;按键设置当前时间&#xff0c;闹钟、提醒时间、坐姿最小距离&#xff1b;通过超声波检测坐姿&#xff0c;当坐姿不正容易对眼睛和身体腰部等造成…...

欧姆龙以太网模块如何设置ip连接 Kepware opc步骤

在数字化和自动化的今天&#xff0c;PLC在工业控制领域的作用日益重要。然而&#xff0c;PLC通讯口的有限资源成为了困扰工程师们的问题。为了解决这一问题&#xff0c;捷米特推出了JM-ETH-CP转以太网模块&#xff0c;让即插即用的以太网通讯成为可能&#xff0c;不仅有效利用了…...

PLEX如何搭建个人局域网的视频网站

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

java学习02

一、基本数据类型 Java有两大数据类型&#xff0c;内置数据类型和引用数据类型。 内置数据类型 Java语言提供了八种基本类型。六种数字类型&#xff08;四个整数型&#xff0c;两个浮点型&#xff09;&#xff0c;一种字符类型&#xff0c;还有一种布尔型。 byte&#xff1…...

libcurl库使用实例

libcurl libcurl是一个功能强大的跨平台网络传输库&#xff0c;支持多种协议&#xff0c;包括HTTP、FTP、SMTP等&#xff0c;同时提供了易于使用的API。 安装 ubuntu18.04平台安装 sudo apt-get install libcurl4-openssl-dev实例 这个示例使用libcurl库发送一个简单的HTTP …...

大数据存储架构详解:数据仓库、数据集市、数据湖、数据网格、湖仓一体

前言 本文隶属于专栏《大数据理论体系》&#xff0c;该专栏为笔者原创&#xff0c;引用请注明来源&#xff0c;不足和错误之处请在评论区帮忙指出&#xff0c;谢谢&#xff01; 本专栏目录结构和参考文献请见大数据理论体系 思维导图 数据仓库 数据仓库是一个面向主题的&…...

ESP32(MicroPython) 网页控制五自由度机械臂

ESP32&#xff08;MicroPython&#xff09; 网页控制五自由度机械臂 本程序通过网页控制五自由度机械臂&#xff0c;驱动方案改用PCA9685。 代码如下 #导入Pin模块 from machine import Pin import time from machine import SoftI2C from servo import Servos import networ…...

前端笔记_OAuth规则机制下实现个人站点接入qq三方登录

文章目录 ⭐前言⭐qq三方登录流程&#x1f496;qq互联中心创建网页应用&#x1f496;配置回调地址redirect_uri&#x1f496;流程分析 ⭐思路分解⭐技术选型实现&#x1f496;技术选型&#xff1a;&#x1f496;实现 ⭐结束 ⭐前言 大家好&#xff0c;我是yma16&#xff0c;本…...

huggingface新作品:快速和简便的训练模型

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

利用鸿鹄优化共享储能的SCADA 系统功能,赋能用户数据自助分析

摘要 本文主要介绍了共享储能的 SCADA 系统大数据架构&#xff0c;以及如何利用鸿鹄来更好的优化 SCADA 系统功能&#xff0c;如何为用户进行数据自助分析赋能。 1、共享储能介绍 说到共享储能&#xff0c;可能不少朋友比较陌生&#xff0c;下面我们简单介绍一下共享储能的价值…...

国产pcie switch 8748+飞腾/龙芯/昇腾高速存储方案设计

方案概述 本设计以国微PCIe Switch 8748为核心交换芯片&#xff0c;通过多端口PCIe 4.0/5.0通道连接飞腾ARM架构处理器、龙芯LoongArch处理器及昇腾AI加速卡&#xff0c;构建支持NVMe协议的高速存储集群&#xff0c;目标实现6.5GB/s以上的可持续带宽。 硬件架构 处理器选型 飞…...

第二十八章 RTC——实时时钟

第二十八章 RTC——实时时钟​​​​​​​ 目录 第二十八章 RTC——实时时钟 1 RTC实时时钟简介 2 RTC外设框图剖析 3 UNIX时间戳 4 与RTC控制相关的库函数 4.1 等待时钟同步和操作完成 4.2 使能备份域涉及RTC配置 4.3 设置RTC时钟分频 4.4 设置、获取RTC计数器及闹钟 5 实时时…...

字符串加密(华为OD)

题目描述 给你一串未加密的字符串str,通过对字符串的每一个字母进行改变来实现加密,加密方式是在每一个字母str[i]偏移特定数组元素a[i]的量,数组a前三位已经赋值:a[0]=1,a[1]=2,a[2]=4。当i>=3时,数组元素a[i]=a[i-1]+a[i-2]+a[i-3]。例如:原文 abcde 加密后 bdgkr,…...

学习日记-day23-6.6

完成目标&#xff1a; 知识点&#xff1a; 1.IO流_转换流使用 ## 转换流_InputStreamReader1.字节流读取中文在编码一致的情况,也不要边读边看,因为如果字节读不准,读不全,输出的内容有可能会出现乱码 2.所以,我们学了字符流,字符流读取文本文档中的内容如果编码一致,就不会出…...

5.2 HarmonyOS NEXT应用性能诊断与优化:工具链、启动速度与功耗管理实战

HarmonyOS NEXT应用性能诊断与优化&#xff1a;工具链、启动速度与功耗管理实战 在HarmonyOS NEXT的全场景生态中&#xff0c;应用性能直接影响用户体验。通过专业的性能分析工具链、针对性的启动速度优化&#xff0c;以及精细化的功耗管理&#xff0c;开发者能够构建"秒…...

机器学习-ROC曲线​​ 和 ​​AUC指标

1. 什么是ROC曲线&#xff1f;​​ ROC&#xff08;Receiver Operating Characteristic&#xff0c;受试者工作特征曲线&#xff09;是用来评估​​分类模型性能​​的一种方法&#xff0c;特别是针对​​二分类问题​​&#xff08;比如“患病”或“健康”&#xff09;。 ​…...

dvwa10——XSS(DOM)

XSS攻击&#xff1a; DOM型XSS 只在浏览器前端攻击触发&#xff1a;修改url片段代码不存储 反射型XSS 经过服务器攻击触发&#xff1a;可能通过提交恶意表单&#xff0c;连接触发代码不存储 存储型XSS 经由服务器攻击触发&#xff1a;可能通过提交恶意表单&#xff0c;连…...

jdbcTemplate.query备忘录

jdbcTemplate.query中使用全部字符串和参数注入&#xff0c; 查询速度为什么差距这么大 如何正确使用JdbcTemplate参数化查询 1、使用?占位符 String sql "SELECT * FROM users WHERE name LIKE ?"; List<User> users jdbcTemplate.query(sql,new Object[…...

深度探索:如何用DeepSeek重构你的工作流

前言:AI时代的工作革命 在人工智能浪潮席卷的今天,DeepSeek作为国产大模型的代表之一,正以其强大的自然语言处理能力、代码生成能力和多模态交互特性,重新定义着人类的工作方式。根据IDC报告显示,2024年企业级AI应用市场规模已突破800亿美元,其中智能办公场景占比达32%,…...

使用SSH tunnel访问内网的MySQL

文章目录 环境背景方法参考 注&#xff1a;本文是使用SSH tunnel做端口转发的一个示例。有关SSH端口转发&#xff0c;可参考我的几篇文档 https://blog.csdn.net/duke_ding2/article/details/106878081https://blog.csdn.net/duke_ding2/article/details/135627263https://blo…...