LangChain学习之Chains的执行过程

1. 学习背景

在LangChain for LLM应用程序开发中课程中,学习了LangChain框架扩展应用程序开发中语言模型的用例和功能的基本技能,遂做整理为后面的应用做准备。视频地址:基于LangChain的大语言模型应用开发+构建和评估。

2.前期准备

本实验基于jupyternotebook进行。

2.1LLM Chain运行过程

import warnings
warnings.filterwarnings('ignore')
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.chains import LLMChainllm = ChatOpenAI(api_key = "XXXX",base_url = "XXXX",temperature=0.9
)prompt = ChatPromptTemplate.from_template("What is the best name to describe \a company that makes {product}?"
)chain = LLMChain(llm= llm, prompt= prompt)
product = "Queen Size Sheet Set"
chain.run(product)

输出如下:

'"Royal Linens"'

2.2使用SimpleSequentialChain按序执行

最简单的顺序链形式,每个步骤都有一个单一的输入/输出,一个步骤的输出是下一个步骤的输入。

from langchain.chains import SimpleSequentialChain# prompt template 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)# prompt template 2
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)overall_simple_chain = SimpleSequentialChain(chains=[chain_one, chain_two], verbose=True)
product = "Queen Size Sheet Set"
overall_simple_chain.run(product)

输出如下:

> Entering new SimpleSequentialChain chain...
Royal Comfort Linens
Royal Comfort Linens provides luxury bedding and bath products that are designed to bring elegance and comfort to your home.> Finished chain.
'Royal Comfort Linens provides luxury bedding and bath products that are designed to bring elegance and comfort to your home.'

可以看到,先执行了chain_one,输出得到了company_name,接着将其作为参数,送入chain_two执行,得到了最终的描述。

2.3使用SequentialChain执行

更一般的顺序链形式,允许多个输入/输出,特别重要的是如何命名输入/输出变量名。

from langchain.chains import SequentialChain# prompt template 1: translate to english
first_prompt = ChatPromptTemplate.from_template("Translate the following review to english:""\n\n{Review}"
)
# chain 1: input= Review and output= English_Review
chain_one = LLMChain(llm=llm, prompt=first_prompt, output_key="English_Review")# prompt template 2: summarize the english review
second_prompt = ChatPromptTemplate.from_template("Can you summarize the following review in 1 sentence:""\n\n{English_Review}"
)
# chain 2: input= English_Review and output= summary
chain_two = LLMChain(llm=llm, prompt=second_prompt, output_key="summary")# prompt template 3: translate to english
third_prompt = ChatPromptTemplate.from_template("What language is the following review:\n\n{Review}"
)
# chain 3: input= Review and output= language
chain_three = LLMChain(llm=llm, prompt=third_prompt, output_key="language")# prompt template 4: follow up message
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: input= summary, language and output= followup_message
chain_four = LLMChain(llm=llm, prompt=fourth_prompt, output_key="followup_message")# overall_chain: input= Review 
# and output= English_Review,summary, followup_message
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 = "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... Vieux lot ou contrefaçon !?"
overall_chain(review)

输出如下:

> Entering new SequentialChain chain...> Finished chain.
{'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... Old batch or counterfeit!?",'summary': 'The reviewer is disappointed with the mediocre taste and lack of foam in the product, suggesting that it may be an old batch or counterfeit.','followup_message': "Bonjour,\n\nNous sommes désolés d'apprendre que vous n'avez pas eu une expérience satisfaisante avec notre produit. Nous vous assurons que nous prenons la qualité de nos produits très au sérieux et nous aimerions en savoir plus sur votre expérience. Avez-vous vérifié la date de péremption du produit ? Il est possible qu'il s'agisse d'un lot ancien. De plus, pourriez-vous nous fournir plus de détails sur le produit que vous avez acheté afin que nous puissions enquêter sur la possibilité d'une contrefaçon ?\n\nMerci de nous avoir fait part de vos préoccupations. Nous espérons avoir l'occasion de rectifier cette situation et de vous offrir une meilleure expérience avec nos produits à l'avenir.\n\nCordialement, [Votre nom]"}

2.4使用Router Chain执行

本案例定义了几个模板类,分别是擅长物理、数学、历史、计算机的模型助手。首先定义prompt模板,并构造提示词信息的数组。

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}
]

先构造基本prompt

from langchain.chains.router import MultiPromptChain
from langchain.chains.router.llm_router import LLMRouterChain,RouterOutputParser
from langchain.prompts import PromptTemplatedestination_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] = 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=llm, prompt=default_prompt)

再写prompt,定义可自由路由的方式或条件。


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)>>"""

接着定义路由,尝试运行代码

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, destination_chains=destination_chains, default_chain=default_chain, verbose=True)
chain.run("What is black body radiation?")

输出如下:

> Entering new MultiPromptChain chain...
physics: {'input': 'What is black body radiation?'}
> Finished chain.
"Black body radiation refers to the electromagnetic radiation emitted by a perfect black body, which is an idealized physical body that absorbs all incident electromagnetic radiation and re-emits it in a characteristic manner. The radiation is emitted at all wavelengths and its intensity and distribution depend only on the body's temperature. This concept is important in understanding the behavior of objects at high temperatures and for developing theories of quantum mechanics and thermodynamics."

再次尝试

chain.run("what is 2 + 2")

输出如下:

> Entering new MultiPromptChain chain...
math: {'input': 'what is 2 + 2'}
> Finished chain.
'The answer to the question "what is 2 + 2" is 4.'

再次尝试

chain.run("Why does every cell in our body contain DNA?")

输出如下:

> Entering new MultiPromptChain chain...
None: {'input': 'Why does every cell in our body contain DNA?'}
> Finished chain.
'Every cell in our body contains DNA because DNA carries the genetic information that determines the characteristics and functions of the cell. This genetic information is crucial for the cell to carry out its specific functions and to replicate and divide to produce new cells. DNA also serves as a blueprint for the production of proteins, which are essential for the structure and function of cells. Therefore, DNA is essential for the survival and functioning of every cell in our body.'

3.总结

chain这个例子还有些模糊,需要自己动手实践,特别是RouterChain,看的还有些头大,再接再厉。

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

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

相关文章

缨帽变换(TCT)增强特征(亮度、绿度、湿度)

目录 缨帽变换(TCT)简介TCT与主成分分析(PCA)区别使用函数.matrixMultiply().arrayProject()缨帽变换(TCT)简介 缨帽变换(Tasseled Cap Transformation),也称为缨帽特征空间或缨帽系数,是一种用于遥感图像分析的线性变换方法。它最初由美国农业部的研究人员E. K…

SwiftUI三处理用户输入

代码下载 在Landmark应用中&#xff0c;标记喜爱的地方&#xff0c;过滤地标列表&#xff0c;只显示喜欢的地标。要增加这些特性&#xff0c;首先要在列表上添加一个开关&#xff0c;用来过滤用户喜欢的地标。在地标上添加一个星标按钮&#xff0c;用户可以点击它来标记这个地…

jdk的组成和跨平台原理

为什么 1.笔试会用到 2. 方便理解程序的运行 java跨平台的原因&#xff1a; sun公司提供了各种平台可以使用的jvm,所以java将程序一次编译成字节码之后可以给各种平台运行。这也是java这么多年深受欢迎的原因

c++ lambda学习

一. 书写形式 [ capture clause ] (parameters) -> return-type { definition of method } [ 捕获 ] ( 参数列表 ) -> 返回类型 { 函数定义 } return-type返回值一般可以推导出来, 可以不用写, 所以可以简化为 [ capture clause ] (parameters) { definition of meth…

循环购模式!增加用户复购的不二之选!

大家好&#xff0c;我是吴军&#xff0c;来自一家专注于软件开发与商业模式设计的公司。我们主要业务是构建商城系统&#xff0c;并为各类企业提供全面的商业模式解决方案。目前&#xff0c;我们已经成功开发了超过200种独特的商业模式&#xff0c;帮助许多企业实现了他们的商业…

TCP协议的核心机制

TCP协议的核心机制 一:确认应答机制1.2:超时重传接收缓冲区 超时重传时间重置连接 一:确认应答机制 对于TCP协议来说,要解决的一个很重要的问题,就是可靠传输 可靠传输,不是指发送方能够100%的把数据发送给接收方,而是尽可能. 尤其是让发送方知道,接收方是否收到. 举个例子: …

MySQL 数据库实验

前言 数据库实验是抽的&#xff0c;所以仅供大家参考哦&#xff01; 查看方式 上传到云盘里面了&#xff0c;大家可以下载( •̀ ω •́ )y https://www.alipan.com/s/WE9G9bGHdnV 提取码&#xff1a;7g6c

详解:重庆耶非凡的选品师项目有哪些优势?

在竞争激烈的电商市场中&#xff0c;重庆耶非凡科技有限公司凭借其独特的选品师项目&#xff0c;成功地在众多企业中脱颖而出。这一项目不仅体现了公司对市场趋势的敏锐洞察力&#xff0c;更彰显了其专业的选品能力和对消费者需求的深刻理解。 首先&#xff0c;耶非凡的选品师项…

大模型时代的具身智能系列专题(七)

北大王鹤团队 王鹤&#xff0c;北京大学前沿计算研究中心助理教授&#xff0c;本科毕业于清华大学&#xff0c;博士毕业于斯坦福大学&#xff0c;师从美国三院院士Leonidas. J Guibas教授。他创立并领导了具身感知与交互实验室(EPIC Lab)&#xff0c;实验室立足三维视觉感知与…

MyBatis的各种查询功能

1、查询&#xff1a; 查询的标签select必须设置属性resultType或resultMap&#xff0c;用于设置实体类和数据库表的映射关系 resultType&#xff1a;自动映射&#xff0c;用于属性名和表中字段名一致的情况 resultMap&#xff1a;自定义映射&#xff0c;用于一对多或多对一或…

mysql 索引和null值的关系

在MySQL中&#xff0c;索引与NULL值的处理涉及一些特殊规则和注意事项&#xff0c;这些规则影响着索引的使用效率和查询优化器的决策&#xff1a; 索引中NULL值的包容性 允许NULL值&#xff1a;MySQL允许在唯一索引&#xff08;Unique Index&#xff09;和普通索引&#xff0…

Github生成SSH密钥,使用SSH进行连接

目录 一、生成新的SSH密钥 二、添加新的SSH密钥 三、测试SSH连接 四、SSH密钥密码 五、创建新仓库并推送到github 说明 使用 SSH URL 将 git clone、git fetch、git pull 或 git push 执行到远程存储库时&#xff0c; 须在计算机上生成 SSH 密钥对&#xff0c;并将公钥添加到…

1. 数据结构

文章目录 数据结构一、线性结构和非线性结构1. 线性结构2. 非线性结构 二、数组&#xff08;Array&#xff09;1. 定义2. 初始化数组 2. 链表&#xff08;Linked List&#xff09;3. 栈&#xff08;Stack&#xff09;4. 队列&#xff08;Queue&#xff09;5. 树&#xff08;Tre…

(CVPRW,2024)可学习的提示:遥感领域小样本语义分割

文章目录 相关资料摘要引言方法训练基础类别新类别推理 相关资料 论文&#xff1a;Learnable Prompt for Few-Shot Semantic Segmentation in Remote Sensing Domain 代码&#xff1a;https://github.com/SteveImmanuel/OEM-Few-Shot-Learnable-Prompt 摘要 小样本分割是一项…

STP----生成树协议

目的&#xff1a;解决二层环路问题 跨层封装 广播风暴---广播帧在二层环路中形成逆时针和顺时针转动环路&#xff0c;并且无限循环&#xff0c;最终造成设备宕机&#xff0c;网络瘫痪。 MAC地址表的翻摆&#xff08;漂移&#xff09;---同一个数据帧&#xff0c;顺时针接收后记…

GUN compiler collection源代码编译过程

第一部分&#xff1a; 学习kernel需要了解编译的一些过程&#xff0c;为了详细理解GCC编译过程的原理&#xff0c;动手做了个sy&#xff0c;记录如下&#xff0c;有需要的童鞋可以参考。 1.环境&#xff1a;&#xff08;均可&#xff0c;二次环境并非是WSL版本&#xff09; r…

大模型应用框架-LangChain

LangChain的介绍和入门 &#x1f4a5; 什么是LangChain LangChain由 Harrison Chase 创建于2022年10月&#xff0c;它是围绕LLMs&#xff08;大语言模型&#xff09;建立的一个框架&#xff0c;LLMs使用机器学习算法和海量数据来分析和理解自然语言&#xff0c;GPT3.5、GPT4是…

[LitCTF 2024 公开赛道] Crypto/PWN/Rev

DAS是打不动了&#xff0c;只能玩玩新生赛了。 Crypto small_e e3对密文直接开3次方 m [iroot(i,3)[0] for i in c_list] bytes(m) #bLitCTF{you_know_m_equ4l_cub3_root_0f_n}common_primes n1,n2有公共因子&#xff0c;用gcd求&#xff0c;再解RSA >>> p gc…

Android handler 一次通关

前言 Android 的 Handler 是一个用于管理线程间通信的工具,主要用于在不同的线程之间发送和处理消息。它是 Android 应用程序中处理异步任务的重要组成部分,尤其是在需要在后台线程进行操作,而操作结果需要在主线程(UI 线程)中更新界面时。 Handler 的基本概念 消息(Me…

一维时间序列信号的奇异小波时频分析方法(Python)

最初的时频分析技术就是短时窗傅里叶变换STFT&#xff0c;由于时窗变短&#xff0c;可供分析的信号量减少&#xff0c;采用经典的谱估算方法引起的误差所占比重会增加。且该短时窗一旦选定&#xff0e;则在整个变换过程中其时窗长度是固定的。变换后的时频分辨率也即固定&#…