【Langchain大语言模型开发教程】链

🔗 LangChain for LLM Application Development - DeepLearning.AI

学习目标

1、LLMChain

2、Sequential Chains

3、Router Chain

 LLMChain

import warnings
warnings.filterwarnings('ignore')
import os
import pandas as pdfrom dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file
df = pd.read_csv('Data.csv')df.head()

引入一些langchain的package 

from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.chains import LLMChain

初始化一个语言模型 

llm = ChatOpenAI(api_key=os.environ.get('ZHIPUAI_API_KEY'),base_url=os.environ.get('ZHIPUAI_API_URL'),model="glm-4",temperature=0.98)

 定义一个prompt template

prompt = ChatPromptTemplate.from_template("What is the best name to describe \a company that makes {product}?"
)

 我们组合成一个chain。然后执行(新版本的方法)

chain = prompt | llmchain.invoke(input="Queen Size Sheet Set")

 这里我们的GLM4的输出和GPT就不太一样了,这里给出了很多的选择

'''
Naming a company that specializes in manufacturing Queen Size Sheet Sets can be creative and reflective of the products' quality, comfort, or the brand's identity. Here are a few suggestions that might resonate well with customers:1. Queen's Retreat Textiles
2. Linen Luxe Haven
3. Pillowtop Elegance Co.
4. Comfort Queendom
5. Sheet Splendor Studios
6. Royal Slumber Collections
7. Dreamy Queen Sheets
8. Luxe Linen Queens
9. Cozy Castle Sheets
10. Queen Quilted ComfortsWhen choosing the best name, consider factors such as the target market, brand positioning, and the image you want to convey. It's also essential to ensure that the name is unique, memorable, and not already trademarked by another company in the same industry.
'''

 Sequential Chains

from langchain.chains import SimpleSequentialChainllm = ChatOpenAI(api_key=os.environ.get('ZHIPUAI_API_KEY'),base_url=os.environ.get('ZHIPUAI_API_URL'),model="glm-4",temperature=0.9)

这里我们定义两条链,他们是一个顺序执行的关系 

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

我们实例这个单一顺序链 ,执行以下,这里的效果和gpt差的还是有一些

overall_simple_chain = SimpleSequentialChain(chains=[chain_one, chain_two],verbose=True)overall_simple_chain.run("Queen Size Sheet Set")'''
The best name for a company that specializes in making Queen Size Sheet Sets could be something that reflects the quality, comfort, and size of the product. Here are a few suggestions:
1. Queen's Linen Luxe
2. Regal Sheet Haven
3. Comfort Queen Sheets
4. Royal Slumber Company
5. Queenly Quilted Sheets
6. Opulent Bedding Emporium
7. Serene Sleep Solutions
8. Queen Comfort Collection
9. Luxe Linens for Her Majesty
10. Dreamy Queen Sheets & MoreWhen choosing a name, consider factors such as the target market, the brand image you want to convey, and the uniqueness of the name for branding purposes. It's also important to ensure that the name isn't already trademarked or heavily associated with another brand in the bedding industry.
"Crafting regal comfort: Queen-sized sheets from Royal Slumber Company."> Finished chain.
'''

 如果要是有多个输入,我们可以使用LangChain的这个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 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="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","language","message"],verbose=True
)

这是我们使用GLM4的一个输出 

review = df.Review[5]
overall_chain(review)'''
{'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 does not hold, it's strange. I buy the same ones in stores and the taste is much better...\nOld batch or counterfeit!?",'summary': "The reviewer finds the product's taste mediocre, the foam disappointing, and suspects it might be an old batch or counterfeit compared to the better-tasting ones from stores. \n\n(Note: This summary is a combination of the reviewer's comments and does not reflect my own opinion.)",'language': 'The review is in French. The translation is:\n\n"I find the taste mediocre. The foam does not hold, it\'s strange. I buy the same ones in stores and the taste is much better... Old batch or counterfeit!?"','message': 'Suite à votre résumé en français\xa0: "Je trouve que le goût est médiocre. La mousse ne tient pas, c\'est étrange. J\'achète les mêmes produits dans les magasins et le goût est bien meilleur... Peut-être une vieille loterie ou un produit contrefait!?"\n\nFollow-up response en français :\n\n"Cher client, nous vous remercions pour votre feedback honnête. Votre satisfaction est très importante pour nous. Nous sommes désolés d\'entendre que la qualité du produit que vous avez reçu ne corresponds pas à ce que vous attendiez. Nous prenons vos commentaires très au sérieux et allons enquêter sur les batchs en question pour déterminer si cela pourrait être dû à un lot vieux ou à un problème de contrefaçon. Votre expérience avec notre marque est une priorité et nous ferons de notre mieux pour résoudre cela. Si vous le souhaitez, nous vous proposons également de vous remplacer le produit gratuitement ou de vous offrir un remboursement. Veuillez nous contacter pour discuter de ces options."'}
'''

Router Chain

 当我们的任务可能更加复杂的时候,我们可能就需要一个路由链,来帮我们路由到一个特定的子链上。

这里,我们定义了物理,数学,历史,计算机科学的prompt template。

from langchain.chains.router import MultiPromptChain
from langchain.chains.router.llm_router import LLMRouterChain,RouterOutputParser
from langchain.prompts import PromptTemplatellm = ChatOpenAI(api_key=os.environ.get('ZHIPUAI_API_KEY'),base_url=os.environ.get('ZHIPUAI_API_URL'),model="glm-4",temperature=0)
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}
]

接下来我们定义一个目标链 和默认链

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)default_prompt = ChatPromptTemplate.from_template("{input}")
default_chain = LLMChain(llm=llm, prompt=default_prompt)

 定义一个路由的prompt remplate

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

  实例化出这个模板,然后将其装配到LLM 路由链上。

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)

 我们可以输入不同的question,然后追踪一下我们选择了那个prompt。

chain.run("What is black body radiation?")chain.run("what is 2 + 2")chain.run("Why does every cell in our body contain DNA?")

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

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

相关文章

德国汉堡大学、清华大学联合英国布里斯托机器人实验室的研究工作分享:基于视觉遥操作的多指机械手灵巧操作

德国汉堡大学&#xff08;张建伟院士团队&#xff09;、清华大学&#xff08;孙富春教授和方斌&#xff09;联合英国布里斯托机器人实验室等单位在基于视觉信息遥操作的多指机械手灵巧操作研究方面取得进展。该工作得到了德国科学基金会&#xff08;DFG&#xff09;与中国国家自…

Git分支管理基本原理

原文全文详见个人博客&#xff1a; Git分支管理基本原理上文已讨论过svn分支管理的基本原理&#xff0c;本文将继续探讨Git分支管理的基本原理&#xff0c;以便后续进行进一步的理解和对比&#xff1a;https://www.coderli.com/git-branch-method/【Java学习交流(982860385)】…

Linux journalctl日志太长,如何倒序查看journalctl --reverse,journalctl -xeu

文章目录 需求实验方法一方法二 需求 Linux journalctl日志太长&#xff0c;如何倒序查看 我们通常关心的是最近的日志&#xff0c;但是每次打开日志都是按时间先后顺序显示的&#xff0c;如何倒序查看&#xff0c;请看下面&#xff1a; 实验 方法一 journalctl 命令默认按…

关于限定视频码率的问题

这几天有人对码率提出要求。其实这本来不是问题。码率是设给编码器的&#xff0c;编码器根据复杂度编码&#xff0c;有时高有时低。 他希望设定码率之后&#xff0c;码率不超过这个值。 你说他无理取闹&#xff1f;强词夺理&#xff1f;其实他的想法也有道理。我现在带宽就这…

Linux工具相关介绍

目录 1.linux安装软件 2.Linux软件生态问题 3.linux软件包管理器yum 4.linux里面好玩的小命令 4.1安装源 4.2小火车 4.3人物说话情景 5.vim简单介绍 5.1简单认识 5.2代码编写 5.3命令模式 1.linux安装软件 1.1源代码安装&#xff1a;这个里面可能根据代码bug需要修改…

AI模型大比拼:Claude 3系列 vs GPT-4系列最新模型综合评测

AI模型大比拼&#xff1a;Claude 3系列 vs GPT-4系列最新模型综合评测 引言 人工智能技术的迅猛发展带来了多款强大的语言模型。本文将对六款领先的AI模型进行全面比较&#xff1a;Claude 3.5 Sonnet、Claude 3 Opus、Claude 3 Haiku、GPT-4、GPT-4o和GPT-4o Mini。我们将从性能…

huawei USG6001v1学习---防火墙高可靠性(双机热备)

1.什么是双机热备 如图&#xff1a;当左图的防火墙发生故障时&#xff0c;整个系统都会收到影响&#xff0c;而右图即使有防火墙发生故障&#xff0c;但是还有一台防火墙做备份&#xff0c;相对于只有一台防火墙&#xff0c;要可靠些。 由于防火墙上不仅需要同步配置信息&…

C# 中的委托

委托的概念 在C#中&#xff0c;委托是一种引用类型&#xff0c;它表示对方法的引用&#xff0c;即委托就是一种用来指向一个方法的引用类型变量。委托的声明类似于方法签名&#xff0c;但是关键字是delegate。下面是一个委托的声明和使用的例子&#xff1a; // 声明一个委托 p…

【数据分享】2013-2022年我国省市县三级的逐月SO2数据(excel\shp格式\免费获取)

空气质量数据是在我们日常研究中经常使用的数据&#xff01;之前我们给大家分享了2000——2022年的省市县三级的逐月PM2.5数据和2013-2022年的省市县三级的逐月CO数据&#xff08;均可查看之前的文章获悉详情&#xff09;&#xff01; 本次我们分享的是我国2013——2022年的省…

【开源库学习】libodb库学习(一)

Hello World Example 在本章中&#xff0c;我们将使用传统的“Hello World”示例展示如何创建一个依赖于ODB进行对象持久化的简单C应用程序。特别是&#xff0c;我们将讨论如何声明持久类、生成数据库支持代码以及编译和运行我们的应用程序。我们还将学习如何使对象持久化&…

DAY05 CSS

文章目录 1 CSS选择器(Selectors)8. 后代(包含)选择器9. 直接子代选择器10. 兄弟选择器11. 相邻兄弟选择器12. 属性选择器 2 伪元素3 CSS样式优先级1. 相同选择器不同样式2. 相同选择器相同样式3. 继承现象4. 选择器不同权值的计算 4 CSS中的值和单位1. 颜色表示法2. 尺寸表示法…

WEB渗透信息收集篇--域名信息

一、CDN是否存在 Ping、多地ping、国外ping 在线 Website uptime monitoring service, check is site down - Host-tracker https://www.webpagetest.org/ 多个地点Ping服务器,网站测速 - 站长工具 Website Speed Test | Pingdom Tools 本地 CDNcheck https://github.…

java中多态的用法

思维导图&#xff1a; 1. 多态的概念 多态通俗的讲就是多种形态&#xff0c;同一个动作&#xff0c;作用在不同对象上&#xff0c;所产生不同的形态。 例如下图&#xff1a; 2. 多态的实现条件 Java中&#xff0c;多态的实现必须满足以下几个条件&#xff1a; 1. 必须在继承…

Spring Boot 单元测试什么时候需要添加 @RunWith

建立 Spring Boot 单元测试方法一般依赖于 JUnit4 或 JUnit5 框架。 在高版本的 Spring Boot 中&#xff0c;一般默认用的是 JUnit5。此时通过添加 SpringBootTest 注解&#xff0c;即可成功注入相关的 bean 对象&#xff0c;并进行测试。 import org.junit.jupiter.api.Test…

chrome浏览器快捷键

chrome快捷键 Ctrl Shift B 书签栏显示或隐藏&#xff08;注意&#xff1a;浏览器插件有的会拦截这个快捷键&#xff0c;暂未排查&#xff09;DevTools Keyboard shortcuts

将mars3D导入自己的项目中

文章目录 一、打开自己的vite项目二、创建场景配置文件1.json文件路径 public\config\config.json2.创建组件定义文件路径 src\components\mars-work\mars-map.vue三、demo中引入四、必要样式 依赖文件 总结 一、打开自己的vite项目 我创建了一个新的 结构如下 二、创建场景…

Netty技术全解析:EventLoopGroup类详解

❃博主首页 &#xff1a; 「码到三十五」 &#xff0c;同名公众号 :「码到三十五」&#xff0c;wx号 : 「liwu0213」 ☠博主专栏 &#xff1a; <mysql高手> <elasticsearch高手> <源码解读> <java核心> <面试攻关> ♝博主的话 &#xff1a…

java学校--Object类方法--toString

第一点解析&#xff1a; 全类名就是包名加类名 getClass&#xff08;&#xff09;.getName()是得到其包名和类名如图&#xff0c;包名是com.hspedu.object_类名是Monster。 Integer.toHexString&#xff08;hashCode&#xff08;&#xff09;&#xff09;&#xff1b;是得到其…

Spring中@PostConstruct注解的使用

1.描述 1.1 背景 最近在做一个系统交互日志模块&#xff0c;要监控一个http请求&#xff0c;并记录请求与响应日志。项目中使用RestTemplate来发送http请求&#xff0c;所以打算给RestTemplate设置拦截器&#xff0c;来进行自定义操作。但是&#xff0c;只对当前类生效&#x…

2024 暑假友谊赛 2

2024 暑假友谊赛 2 2024.7.20 9:00————12:00 过题数3/9 补题数4/9 CodeForces 1150B CodeForces 1332D CodeForces 1503B AtCoder arc134_b AtCoder abc278_d AtCoder abc216_f CodeForces 1012B CodeForces 1328E AtCoder abc344_f A - Tiling Challenge 题解&#xff…