langchain(3):链
llm chain:它会在后台格式化提示词,然后将格式化后的提示词传给llm
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)
简单顺序链 simple sequent chain:将一系列链一个一个的执行

# 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
)
overall_simple_chain.run(product)
顺序链sequent chain:当存在多个输入输出时,使用不同的变量名标记,切忌变量名错误,通过改变LLMChain方法中的{}的输入和output_key来确定变量名

# 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
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
)
路由链route chain:如果你有多条子链,每条子链专门负责处理某种特定类型的输入,这种情况可以使用

# 设置不同的prompt模板作为不同route方向
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
}
]
# 创建目标链
llm = ChatOpenAI(temperature=0, model=llm_model)
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] = chain
# 创建默认链,其他链调用不到时备用
destinations = [f"{p['name']}: {p['description']}" for p in prompt_infos]
destinations_str = "\n".join(destinations)
# 创建提示词模板,完成任务的说明,输出内容格式
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 >>
<< INPUT >>
<< OUTPUT (remember to include the ```json)>>"""
```python
# 创建路由链
# 1.使用之前定义的prompt模板创建完整路由模板
router_template = MULTI_PROMPT_ROUTER_TEMPLATE.format(
destinations=destinations_str
)
# 2.为模板创建提示词模板
# RouterOutputParser方法帮助route chain在哪条子链中路由
router_prompt = PromptTemplate(
template=router_template,
input_variables=["input"],
output_parser=RouterOutputParser(),
)
# 3.传入llm和整个route提示词,创建route chain
router_chain = LLMRouterChain.from_llm(llm, router_prompt)
# 组建路由链route chain
# 路由链->目标链->默认链(没有目标)
chain = MultiPromptChain(router_chain=router_chain,
destination_chains=destination_chains,
default_chain=default_chain, verbose=True
)
langchain(3):链的更多相关文章
- JS核心系列:浅谈原型对象和原型链
在Javascript中,万物皆对象,但对象也有区别,大致可以分为两类,即:普通对象(Object)和函数对象(Function). 一般而言,通过new Function产生的对象是函数对象,其他对 ...
- 简单粗暴地理解js原型链--js面向对象编程
原型链理解起来有点绕了,网上资料也是很多,每次晚上睡不着的时候总喜欢在网上找点原型链和闭包的文章看,效果极好. 不要纠结于那一堆术语了,那除了让你脑筋拧成麻花,真的不能帮你什么.简单粗暴点看原型链吧, ...
- Js 原型和原型链
Js中通过原型和原型链实现了继承 Js对象属性的访问,首先会查找自身是否拥有这个属性 如果查到,则返回属性值,如果找不到,就会遍历原型链,一层一层的查找,如果找到就会返回属性值 直到遍历完Object ...
- 23种设计模式--责任链模式-Chain of Responsibility Pattern
一.责任链模式的介绍 责任链模式用简单点的话来说,将责任一步一步传下去,这就是责任,想到这个我们可以相当击鼓传花,这个是为了方便记忆,另外就是我们在项目中经常用到的审批流程等这一类的场景时我们就可以考 ...
- JavaScript之职责链模式
一.概述 职责链模式(Chain of responsibility),就是使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系.将这个对象连成一条链,并沿着这条链传递该请求,直到有 ...
- Discuz论坛黑链清理教程
本人亲测有效,原创文章哦~~~ 论坛黑链非常的麻烦,如果你的论坛有黑链,那么对不起,百度收录了你的黑链,不会自动删除,需要你手动去清理. 什么是黑链 黑链,顾名思义,就是一些赌博网站的外链,这些黑链相 ...
- 深入浅出JavaScript之原型链&继承
Javascript语言的继承机制,它没有"子类"和"父类"的概念,也没有"类"(class)和"实例"(instanc ...
- 代码的坏味道(20)——过度耦合的消息链(Message Chains)
坏味道--过度耦合的消息链(Message Chains) 特征 消息链的形式类似于:obj.getA().getB().getC(). 问题原因 如果你看到用户向一个对象请求另一个对象,然后再向后者 ...
- ResponsibleChain(责任链模式)
/** * 责任链模式 * @author TMAC-J * 老板讲任务交给CTO,CTO自然不会亲自去做,又把人物分配给项目经理,项目经理再把任务分配给组长,组长再分配给个人 * 如果中途哪个环节出 ...
- BZOJ 3083: 遥远的国度 [树链剖分 DFS序 LCA]
3083: 遥远的国度 Time Limit: 10 Sec Memory Limit: 1280 MBSubmit: 3127 Solved: 795[Submit][Status][Discu ...
随机推荐
- 野兽先辈带您学Opencv:介绍直方图,直方图均衡化,直方图计算,实战利用直方图计算蛋的面积
欧,又是坑爹的opencv实验,它又来了额 实验要求: 1.输入三通道RGB直方图 2.直方图均衡化后输出图片及直方图 3.计算鸡蛋的面积(像素数) 首先什么是直方图? 横坐标是灰度,纵坐标是每一个灰 ...
- 指标+AI+BI:构建数据分析新范式丨2024袋鼠云秋季发布会回顾
10月30日,袋鼠云成功举办了以"AI驱动,数智未来"为主题的2024年秋季发布会.大会深度探讨了如何凭借 AI 实现新的飞跃,重塑企业的经营管理方式,加速数智化进程. 作为大会的 ...
- 只需一行命令,Win11秒变Linux开发主机!
大家好,我是六哥,今天为大家分享,只需一行命令,就能拥有原生的Linux系统体验! 本文以真实操作为例,带你一步步解决常见问题,轻松搞定WSL+Docker环境. 一.只需一行命令,开启WSL 在Po ...
- ETLCloud中如何使用Kettle组件
ETLCloud中如何使用Kettle组件在当今数据驱动的时代,数据处理和分析已成为企业决策的关键.为了更高效地处理海量数据,ETL(Extract, Transform, Load)工具变得至关重要 ...
- ETL中双流合并和多流合并的区别
一.ETL工具 ETLCloud数据集成平台集实时数据集成和离线数据集成以及API发布为一体的数据集成平台.与其他开源数据集成工具相比,采用轻量化架构.具有更快的部署速度.更快的数据传输速度.更低的运 ...
- 进阶篇:3.1.6)DFM塑胶-模压件(橡胶件)设计
本章目的:设计出适合模压工艺的零件,特别是橡胶件. 1.模压Compression Molding工艺概念介绍 模压成型又称压制成型或压缩成型,是先将粉状,粒状或纤维状的塑料放入成型温度下的模具型腔中 ...
- win10电脑大写按键失灵不能用的处理方法
相信深度技术的用户都知道在电脑键盘左侧有个caps lock键,只要按一下就可以使用大写字母,但是有深度技术系统win10纯净版用户反映,电脑开机之后大写按键无法使用失灵的问题,今天就为大家分享win ...
- 可以记录IP的网络协议笔记
目录 背景: 解决方案1--HTTP头记录 解决方案2--proxy protocol协议 解决方案3--加密 TCP Option 总结 背景: 需求1--审计日志需要真实IP: 安全审计要求记录访 ...
- 为大模型 MCP Code Interpreter 而生:C# Runner 开源发布
在7月初,我立下了一个 Flag:要做一个专门为大语言模型(LLM)设计的 C# 运行器 MCP (Model-Protocol-Context).我的小小执念,是希望 C# 能够像 Python 一 ...
- IDEA的安装与卸载
IDEA安装 什么是IDE IDE是集成开发环境,用于提供程序开发环境的应用程序,一般包括代码编辑器,编译器,调试器图形用户界面等工具. 常见的Java的IDE工具有Eclipse,IntelliJ ...