第四章 模型链¶
链(Chains)通常将大语言模型(LLM)与提示(Prompt)结合在一起,基于此,我们可以对文本或数据进行一系列操作。
链(Chains)可以一次性接受多个输入
例如,我们可以创建一个链,该链接受用户输入,使用提示模板对其进行格式化,然后将格式化的响应传递给LLM。我们可以通过将多个链组合在一起,或者通过将链与其他组件组合在一起来构建更复杂的链。
一、设置OpenAI API Key¶
import os
import openai
from dotenv import load_dotenv, find_dotenv
# 读取本地/项目的环境变量。
# find_dotenv()寻找并定位.env文件的路径
# load_dotenv()读取该.env文件,并将其中的环境变量加载到当前的运行环境中
# 如果你设置的是全局的环境变量,这行代码则没有任何作用。
_ = load_dotenv(find_dotenv())
# 获取环境变量 OPENAI_API_KEY
openai.api_key = os.environ['OPENAI_API_KEY']
二、大语言模型链¶
大语言模型链(LLMChain)是一个简单但非常强大的链,也是后面我们将要介绍的许多链的基础。
2.1 导入数据¶
import pandas as pd
df = pd.read_csv('data/Data.csv')
df.head()
| Product | Review | |
|---|---|---|
| 0 | Queen Size Sheet Set | I ordered a king size set. My only criticism w... |
| 1 | Waterproof Phone Pouch | I loved the waterproof sac, although the openi... |
| 2 | Luxury Air Mattress | This mattress had a small hole in the top of i... |
| 3 | Pillows Insert | This is the best throw pillow fillers on Amazo... |
| 4 | Milk Frother Handheld\n | I loved this product. But they only seem to l... |
2.2 初始化语言模型¶
from langchain_community.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.chains.llm import LLMChain
# 这里我们将参数temperature设置为0.0,从而减少生成答案的随机性。
# 如果你想要每次得到不一样的有新意的答案,可以尝试调整该参数。
llm = ChatOpenAI(temperature=0.0)
/Users/lta/anaconda3/envs/cookbook/lib/python3.10/site-packages/langchain_core/_api/deprecation.py:119: LangChainDeprecationWarning: The class `ChatOpenAI` was deprecated in LangChain 0.0.10 and will be removed in 0.3.0. An updated version of the class exists in the langchain-openai package and should be used instead. To use it run `pip install -U langchain-openai` and import as `from langchain_openai import ChatOpenAI`. warn_deprecated(
2.3 初始化提示模版¶
初始化提示,这个提示将接受一个名为product的变量。该prompt将要求LLM生成一个描述制造该产品的公司的最佳名称
prompt = ChatPromptTemplate.from_template(
"What is the best name to describe \
a company that makes {product}?"
)
2.4 构建大语言模型链¶
将大语言模型(LLM)和提示(Prompt)组合成链。这个大语言模型链非常简单,可以让我们以一种顺序的方式去通过运行提示并且结合到大语言模型中。
chain = LLMChain(llm=llm, prompt=prompt)
/Users/lta/anaconda3/envs/cookbook/lib/python3.10/site-packages/langchain_core/_api/deprecation.py:119: LangChainDeprecationWarning: The class `LLMChain` was deprecated in LangChain 0.1.17 and will be removed in 0.3.0. Use RunnableSequence, e.g., `prompt | llm` instead. warn_deprecated(
2.5 运行大语言模型链¶
因此,如果我们有一个名为"Queen Size Sheet Set"的产品,我们可以通过使用chain.run将其通过这个链运行
product = "Queen Size Sheet Set"
chain.run(product)
/Users/lta/anaconda3/envs/cookbook/lib/python3.10/site-packages/langchain_core/_api/deprecation.py:119: LangChainDeprecationWarning: The method `Chain.run` was deprecated in langchain 0.1.0 and will be removed in 0.3.0. Use invoke instead. warn_deprecated(
'"Royal Comfort Linens"'
您可以输入任何产品描述,然后查看链将输出什么结果
2.6 中文提示¶
prompt = ChatPromptTemplate.from_template(
"描述制造{product}的一个公司的最佳名称是什么?"
)
chain = LLMChain(llm=llm, prompt=prompt)
product = "大号床单套装"
chain.run(product)
'“豪华床品集团”'
三、顺序链¶
3.1 简单顺序链¶
顺序链(SequentialChains)是按预定义顺序执行其链接的链。具体来说,我们将使用简单顺序链(SimpleSequentialChain),这是顺序链的最简单类型,其中每个步骤都有一个输入/输出,一个步骤的输出是下一个步骤的输入。
from langchain.chains.sequential import SimpleSequentialChain
llm = ChatOpenAI(temperature=0.9)
3.1.1 创建两个子链¶
# 提示模板 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)
3.1.2 构建简单顺序链¶
现在我们可以组合两个LLMChain,以便我们可以在一个步骤中创建公司名称和描述
overall_simple_chain = SimpleSequentialChain(chains=[chain_one, chain_two], verbose=True)
给一个输入,然后运行上面的链
3.1.3 运行简单顺序链¶
product = "Queen Size Sheet Set"
overall_simple_chain.run(product)
> Entering new SimpleSequentialChain chain... "Regal Linens" "Regal Linens offers luxurious bedding and home textiles that elevate your living space with elegance, comfort, and style. Shop now!" > Finished chain.
'"Regal Linens offers luxurious bedding and home textiles that elevate your living space with elegance, comfort, and style. Shop now!"'
3.1.4 中文提示¶
# 中文
first_prompt = ChatPromptTemplate.from_template(
"描述制造{product}的一个公司的最好的名称是什么"
)
chain_one = LLMChain(llm=llm, prompt=first_prompt)
second_prompt = ChatPromptTemplate.from_template(
"写一个20字的描述对于下面这个\
公司:{company_name}的"
)
chain_two = LLMChain(llm=llm, prompt=second_prompt)
overall_simple_chain = SimpleSequentialChain(chains=[chain_one, chain_two],verbose=True)
product = "大号床单套装"
overall_simple_chain.run(product)
> Entering new SimpleSequentialChain chain... “豪华阁” "豪华阁是一家提供高端奢华服务的公司,以优质的产品和服务赢得客户的信任和青睐。" > Finished chain.
'"豪华阁是一家提供高端奢华服务的公司,以优质的产品和服务赢得客户的信任和青睐。"'
3.2 顺序链¶
当只有一个输入和一个输出时,简单顺序链(SimpleSequentialChain)即可实现。当有多个输入或多个输出时,我们则需要使用顺序链(SequentialChain)来实现。
from langchain.chains.sequential import SequentialChain
from langchain_community.chat_models import ChatOpenAI #导入OpenAI模型
from langchain.prompts import ChatPromptTemplate #导入聊天提示模板
from langchain.chains.llm import LLMChain #导入LLM链。
llm = ChatOpenAI(temperature=0.9)
接下来我们将创建一系列的链,然后一个接一个使用他们
3.2.1 创建四个子链¶
#子链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")
#子链4
# 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")
3.2.2 对四个子链进行组合¶
#输入: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是法语,可以把英文review看做是一种翻译,接下来是根据英文review得到的总结,最后输出的是用法语原文进行的续写信息。
review = df.Review[5]
overall_chain(review)
> Entering new SequentialChain chain...
/Users/lta/anaconda3/envs/cookbook/lib/python3.10/site-packages/langchain_core/_api/deprecation.py:119: LangChainDeprecationWarning: The method `Chain.__call__` was deprecated in langchain 0.1.0 and will be removed in 0.3.0. Use invoke instead. warn_deprecated(
> 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 last, it's strange. I buy the same ones in stores and the taste is much better... Old batch or counterfeit!?",
'summary': 'The reviewer is not satisfied with the taste and quality of the product, suspecting it may be an old batch or counterfeit.',
'followup_message': "Cher client,\n\nNous sommes désolés d'apprendre que vous n'êtes pas satisfait du goût et de la qualité de notre produit. Nous prenons très au sérieux les retours de nos clients et nous vous assurons que la fraîcheur et l'authenticité de nos produits sont nos priorités absolues.\n\nAfin de résoudre ce problème, pourriez-vous nous fournir plus de détails sur le produit que vous avez acheté et nous informer de l'endroit et de la date d'achat ? Cela nous aidera à enquêter sur la situation et à garantir que nos produits répondent à nos normes de qualité élevées.\n\nNous vous remercions de nous avoir partagé vos préoccupations et nous vous prions de nous excuser pour le désagrément causé. Nous sommes impatients de résoudre ce problème et de restaurer votre confiance en notre marque.\n\nCordialement,\nL'équipe de service client."}
3.2.3 中文提示¶
# 中文
#子链1
# prompt模板 1: 翻译成英语(把下面的review翻译成英语)
first_prompt = ChatPromptTemplate.from_template(
"把下面的评论review翻译成英文:"
"\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(
"请你用一句话来总结下面的评论review:"
"\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(
"下面的评论review使用的什么语言:\n\n{Review}"
)
# chain 3: 输入:Review 输出:语言
chain_three = LLMChain(llm=llm, prompt=third_prompt, output_key="language")
#子链4
# prompt模板 4: 使用特定的语言对下面的总结写一个后续回复
fourth_prompt = ChatPromptTemplate.from_template(
"使用特定的语言对下面的总结写一个后续回复:"
"\n\n总结: {summary}\n\n语言: {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)
> 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 weird. I buy the same ones in stores and the taste is much better... Old batch or counterfeit!?",
'summary': 'The taste is disappointing and the quality seems suspicious, possibly indicating an old batch or counterfeit product.',
'followup_message': "Merci pour votre retour. Nous sommes désolés d'apprendre que vous avez été déçu par le goût et la qualité de notre produit. Nous allons enquêter sur cette question et prendre les mesures nécessaires pour nous assurer que nos clients reçoivent toujours des produits authentiques et de la plus haute qualité. Merci de nous avoir informés de cette situation."}
四、 路由链¶
到目前为止,我们已经学习了大语言模型链和顺序链。但是,如果我们想做一些更复杂的事情怎么办?
一个相当常见但基本的操作是根据输入将其路由到一条链,具体取决于该输入到底是什么。如果你有多个子链,每个子链都专门用于特定类型的输入,那么可以组成一个路由链,它首先决定将它传递给哪个子链,然后将它传递给那个链。
路由器由两个组件组成:
- 路由链(Router Chain):路由器链本身,负责选择要调用的下一个链
- destination_chains:路由器链可以路由到的链
举一个具体的例子,让我们看一下我们在不同类型的链之间路由的地方,我们在这里有不同的prompt:
from langchain.chains.router import MultiPromptChain #导入多提示链
from langchain.chains.router.llm_router import LLMRouterChain,RouterOutputParser
from langchain.prompts import PromptTemplate
llm = ChatOpenAI(model='gpt-4o', temperature=0)
4.1 定义提示模板¶
首先,我们定义提示适用于不同场景下的提示模板。
#第一个提示适合回答物理问题
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}"""
4.2 对提示模版进行命名和描述¶
在定义了这些提示模板后,我们可以为每个模板命名,并给出具体描述。例如,第一个物理学的描述适合回答关于物理学的问题,这些信息将传递给路由链,然后由路由链决定何时使用此子链。
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
}
]
LLMRouterChain(此链使用 LLM 来确定如何路由事物)
在这里,我们需要一个多提示链。这是一种特定类型的链,用于在多个不同的提示模板之间进行路由。 但是这只是路由的一种类型,我们也可以在任何类型的链之间进行路由。
这里我们要实现的几个类是大模型路由器链。这个类本身使用语言模型来在不同的子链之间进行路由。这就是上面提供的描述和名称将被使用的地方。
4.3 基于提示模版信息创建相应目标链¶
目标链是由路由链调用的链,每个目标链都是一个语言模型链
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)
4.4 创建默认目标链¶
除了目标链之外,我们还需要一个默认目标链。这是一个当路由器无法决定使用哪个子链时调用的链。在上面的示例中,当输入问题与物理、数学、历史或计算机科学无关时,可能会调用它。
default_prompt = ChatPromptTemplate.from_template("{input}")
default_chain = LLMChain(llm=llm, prompt=default_prompt)
4.5 定义不同链之间的路由模板¶
这包括要完成的任务的说明以及输出应该采用的特定格式。
注意:此处在原教程的基础上添加了一个示例,主要是因为"gpt-3.5-turbo"模型不能很好适应理解模板的意思,使用 "text-davinci-003" 或者"gpt-4o"可以很好的工作,因此在这里多加了示例提示让其更好的学习。 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
}}}}
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
}}}}
```
"""
4.6 构建路由链¶
首先,我们通过格式化上面定义的目标创建完整的路由器模板。这个模板可以适用许多不同类型的目标。 因此,在这里,您可以添加一个不同的学科,如英语或拉丁语,而不仅仅是物理、数学、历史和计算机科学。
接下来,我们从这个模板创建提示模板
最后,通过传入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)
4.7 创建整体链路¶
#多提示链
chain = MultiPromptChain(router_chain=router_chain, #l路由链路
destination_chains=destination_chains, #目标链路
default_chain=default_chain, #默认链路
verbose=True
)
4.8 进行提问¶
如果我们问一个物理问题,我们希望看到他被路由到物理链路
# 问题:什么是黑体辐射?
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 an idealized object called a "black body," which absorbs all incident radiation, regardless of frequency or angle of incidence. A black body in thermal equilibrium emits radiation with a characteristic spectrum that depends only on its temperature, not on its material or surface properties.\n\nThe spectrum of black body radiation is described by Planck\'s law, which shows that the intensity of radiation emitted at different wavelengths peaks at a wavelength inversely proportional to the temperature. This means that as the temperature of the black body increases, the peak wavelength of the emitted radiation shifts to shorter wavelengths (higher frequencies).\n\nKey characteristics of black body radiation include:\n\n1. **Planck\'s Law**: Describes the spectral density of the radiation.\n2. **Wien\'s Displacement Law**: States that the wavelength at which the emission is strongest is inversely proportional to the temperature.\n3. **Stefan-Boltzmann Law**: States that the total energy emitted per unit surface area of a black body is proportional to the fourth power of its temperature.\n\nBlack body radiation is a fundamental concept in physics and has important implications in fields such as thermodynamics, quantum mechanics, and astrophysics.'
如果我们问一个数学问题,我们希望看到他被路由到数学链路
# 问题:2+2等于多少?
chain.run("what is 2 + 2")
> Entering new MultiPromptChain chain... math: {'input': 'what is 2 + 2'} > Finished chain.
"Thank you for the kind words! Let's break down the problem of finding the sum of \\(2 + 2\\).\n\n1. **Identify the numbers involved**: The numbers we are adding are 2 and 2.\n2. **Understand the operation**: The operation we are performing is addition.\n\nNow, let's perform the addition step-by-step:\n\n- Start with the first number: 2\n- Add the second number: 2\n\nSo, \\(2 + 2\\) can be visualized as:\n\\[ 2 + 2 = 4 \\]\n\nTherefore, the sum of \\(2 + 2\\) is \\(4\\)."
如果我们传递一个与任何子链路都无关的问题时,会发生什么呢?
这里,我们问了一个关于生物学的问题,我们可以看到它选择的链路是无。这意味着它将被传递到默认链路,它本身只是对语言模型的通用调用。语言模型幸运地对生物学知道很多,所以它可以帮助我们。
# 问题:为什么我们身体里的每个细胞都包含DNA?
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 serves as the fundamental blueprint for all cellular functions and activities. Here are some key reasons why DNA is present in every cell:\n\n1. **Genetic Information**: DNA carries the genetic instructions necessary for the development, functioning, growth, and reproduction of all living organisms. These instructions are encoded in the sequence of nucleotides within the DNA molecule.\n\n2. **Protein Synthesis**: DNA contains the codes for making proteins, which are essential molecules that perform a wide variety of functions within the cell. Proteins are involved in virtually every cellular process, including structural support, catalyzing metabolic reactions (enzymes), and regulating gene expression.\n\n3. **Cellular Identity and Function**: Different types of cells in the body have different functions, and the DNA in each cell contains the information needed to produce the specific proteins that allow the cell to perform its unique role. For example, muscle cells produce proteins that enable contraction, while nerve cells produce proteins involved in transmitting signals.\n\n4. **Replication and Inheritance**: DNA must be present in every cell to ensure that genetic information can be accurately copied and passed on during cell division. This is crucial for growth, development, and tissue repair. When cells divide, they replicate their DNA so that each new cell receives a complete set of genetic instructions.\n\n5. **Regulation of Cellular Activities**: DNA contains regulatory elements that control when and how genes are expressed. This regulation ensures that genes are turned on or off as needed, allowing cells to respond to changes in their environment and maintain homeostasis.\n\n6. **Consistency and Continuity**: Having DNA in every cell ensures consistency and continuity of genetic information throughout the organism. This uniformity is essential for the coordinated functioning of the body's systems and for maintaining the organism's overall integrity.\n\nIn summary, DNA is present in every cell because it provides the essential instructions for cellular function, growth, and reproduction, ensuring that each cell can perform its specific role and contribute to the organism's overall health and survival."
4.9 中文提示¶
# 中文
#第一个提示适合回答物理问题
physics_template = """你是一个非常聪明的物理专家。 \
你擅长用一种简洁并且易于理解的方式去回答问题。\
当你不知道问题的答案时,你承认\
你不知道.
这是一个问题:
{input}"""
#第二个提示适合回答数学问题
math_template = """你是一个非常优秀的数学家。 \
你擅长回答数学问题。 \
你之所以如此优秀, \
是因为你能够将棘手的问题分解为组成部分,\
回答组成部分,然后将它们组合在一起,回答更广泛的问题。
这是一个问题:
{input}"""
#第三个适合回答历史问题
history_template = """你是以为非常优秀的历史学家。 \
你对一系列历史时期的人物、事件和背景有着极好的学识和理解\
你有能力思考、反思、辩证、讨论和评估过去。\
你尊重历史证据,并有能力利用它来支持你的解释和判断。
这是一个问题:
{input}"""
#第四个适合回答计算机问题
computerscience_template = """ 你是一个成功的计算机科学专家。\
你有创造力、协作精神、\
前瞻性思维、自信、解决问题的能力、\
对理论和算法的理解以及出色的沟通技巧。\
你非常擅长回答编程问题。\
你之所以如此优秀,是因为你知道 \
如何通过以机器可以轻松解释的命令式步骤描述解决方案来解决问题,\
并且你知道如何选择在时间复杂性和空间复杂性之间取得良好平衡的解决方案。
这还是一个输入:
{input}"""
# 中文
prompt_infos = [
{
"名字": "物理学",
"描述": "擅长回答关于物理学的问题",
"提示模板": physics_template
},
{
"名字": "数学",
"描述": "擅长回答数学问题",
"提示模板": math_template
},
{
"名字": "历史",
"描述": "擅长回答历史问题",
"提示模板": history_template
},
{
"名字": "计算机科学",
"描述": "擅长回答计算机科学问题",
"提示模板": computerscience_template
}
]
# 中文
destination_chains = {}
for p_info in prompt_infos:
name = p_info["名字"]
prompt_template = p_info["提示模板"]
prompt = ChatPromptTemplate.from_template(template=prompt_template)
chain = LLMChain(llm=llm, prompt=prompt)
destination_chains[name] = chain
destinations = [f"{p['名字']}: {p['描述']}" for p in prompt_infos]
destinations_str = "\n".join(destinations)
default_prompt = ChatPromptTemplate.from_template("{input}")
default_chain = LLMChain(llm=llm, prompt=default_prompt)
# 中文
# 多提示路由模板
MULTI_PROMPT_ROUTER_TEMPLATE = """给语言模型一个原始文本输入,\
让其选择最适合输入的模型提示。\
系统将为您提供可用提示的名称以及最适合改提示的描述。\
如果你认为修改原始输入最终会导致语言模型做出更好的响应,\
你也可以修改原始输入。
<< 格式 >>
返回一个带有JSON对象的markdown代码片段,该JSON对象的格式如下:
```json
{{{{
"destination": 字符串 \ 使用的提示名字或者使用 "DEFAULT"
"next_inputs": 字符串 \ 原始输入的改进版本
}}}}
```
记住:“destination”必须是下面指定的候选提示名称之一,\
或者如果输入不太适合任何候选提示,\
则可以是 “DEFAULT” 。
记住:如果您认为不需要任何修改,\
则 “next_inputs” 可以只是原始输入。
<< 候选提示 >>
{destinations}
<< 输入 >>
{{input}}
<< 输出 (记得要包含 ```json)>>
样例:
<< 输入 >>
"什么是黑体辐射?"
<< 输出 >>
```json
{{{{
"destination": 字符串 \ 使用的提示名字或者使用 "DEFAULT"
"next_inputs": 字符串 \ 原始输入的改进版本
}}}}
```
"""
# 中文
# 创建路由链
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
)
#中文
chain.run("什么是黑体辐射?")
> Entering new MultiPromptChain chain... 物理学: {'input': '什么是黑体辐射?'} > Finished chain.
'黑体辐射是指一种理想化物体(称为黑体)在热平衡状态下发出的电磁辐射。黑体是一个完全吸收所有入射辐射的物体,不反射或透射任何光。它的辐射只依赖于其温度,而与材料和表面特性无关。\n\n黑体辐射的特点可以通过普朗克辐射定律来描述,该定律给出了不同温度下黑体在各个波长上辐射的能量分布。随着温度升高,黑体辐射的峰值波长会向更短的波长移动,这就是所谓的维恩位移定律。\n\n简单来说,黑体辐射是一个理想化概念,用来描述物体在不同温度下如何发出电磁辐射。'
# 中文
chain.run("你知道李白是谁嘛?")
> Entering new MultiPromptChain chain... None: {'input': '你知道李白是谁嘛?'} > Finished chain.
'当然知道,李白是中国唐代著名的诗人,被誉为“诗仙”。他生于701年,卒于762年,字太白,号青莲居士。李白以其豪放不羁的个性和卓越的诗才著称,他的诗歌风格豪放飘逸,充满浪漫主义色彩。李白的作品数量众多,流传至今的有上千首,其中许多作品被认为是中国古典诗歌的经典之作。\n\n李白的诗歌题材广泛,包括山水田园、边塞征战、友情离别、人生哲理等。他的代表作有《将进酒》、《静夜思》、《早发白帝城》、《行路难》等。李白的诗歌不仅在中国文学史上占有重要地位,也对后世产生了深远的影响。'
# 中文
chain.run("2 + 2 等于多少")
> Entering new MultiPromptChain chain... 数学: {'input': '2 + 2 等于多少'} > Finished chain.
'2 + 2 等于 4。\n\n我们可以将这个问题分解为以下几个步骤来验证:\n\n1. **理解加法的定义**:加法是将两个或多个数值组合在一起得到一个总和的过程。\n2. **识别操作数**:在这个问题中,我们有两个操作数,都是2。\n3. **执行加法操作**:将这两个操作数相加,即 2 + 2。\n4. **得到结果**:2 + 2 = 4。\n\n因此,2 + 2 的结果是 4。'
# 中文
chain.run("为什么我们身体里的每个细胞都包含DNA?")
> Entering new MultiPromptChain chain... None: {'input': '为什么我们身体里的每个细胞都包含DNA?'} > Finished chain.
'我们身体里的每个细胞都包含DNA,这是因为DNA是遗传信息的载体,负责指导细胞的生长、发育、功能和繁殖。以下是一些关键原因:\n\n1. **遗传信息的传递**:DNA包含了所有遗传信息,这些信息决定了生物体的特征和功能。每个细胞都需要这些信息来执行其特定的功能。\n\n2. **细胞分裂和生长**:在细胞分裂过程中,DNA必须被复制并传递给新生成的细胞。这样,每个新细胞都能获得完整的遗传信息,确保其正常功能和生长。\n\n3. **蛋白质合成**:DNA包含了编码蛋白质的基因。蛋白质是细胞功能的执行者,参与了几乎所有的细胞过程。每个细胞需要DNA来指导蛋白质的合成,以维持其正常功能。\n\n4. **细胞特化**:尽管每个细胞都包含相同的DNA,但不同类型的细胞会表达不同的基因。这种基因表达的差异使得细胞能够特化,执行特定的功能。例如,肌肉细胞、神经细胞和皮肤细胞虽然都包含相同的DNA,但它们的功能和形态各不相同。\n\n5. **修复和维护**:细胞在其生命周期中可能会受到损伤。DNA包含了修复和维护细胞功能的指令,帮助细胞修复自身并维持正常运作。\n\n总之,DNA在每个细胞中扮演着至关重要的角色,确保生物体的正常发育、功能和生存。'