面向开发者的LLM入门课程-模型链英文版提示: 英文版提示 1.大语言模型链 from langchain.chat_models import ChatOpenAI from langchain.prompts import ChatPromptTem……
哈喽!伙伴们,我是小智,你们的AI向导。欢迎来到每日的AI学习时间。今天,我们将一起深入AI的奇妙世界,探索“面向开发者的LLM入门课程-模型链英文版提示”,并学会本篇文章中所讲的全部知识点。还是那句话“不必远征未知,只需唤醒你的潜能!”跟着小智的步伐,我们终将学有所成,学以致用,并发现自身的更多可能性。话不多说,现在就让我们开始这场激发潜能的AI学习之旅吧。
面向开发者的LLM入门课程-模型链英文版提示:
英文版提示
1.大语言模型链
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.chains import LLMChainllm = ChatOpenAI(temperature=0.0)
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 Comfort Linens’
2.简单顺序链
from langchain.chains import SimpleSequentialChain
llm = ChatOpenAI(temperature=0.9)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)
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 Beddings”
Royal Comfort Beddings is a reputable company that offers luxurious and
comfortable bedding options fit for royalty.
> Finished chain.
‘Royal Comfort Beddings is a reputable company that offers luxurious and
comfortable bedding options fit for royalty.’
3.顺序链
from langchain.chains import SequentialChain
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.chains import LLMChainllm = ChatOpenAI(temperature=0.9)
first_prompt = ChatPromptTemplate.from_template(
“Translate the following review to english:”
“nn{Review}”
)chain_one = LLMChain(llm=llm, prompt=first_prompt, output_key=”English_Review”)
second_prompt = ChatPromptTemplate.from_template(
“Can you summarize the following review in 1 sentence:”
“nn{English_Review}”
)chain_two = LLMChain(llm=llm, prompt=second_prompt, output_key=”summary”)
third_prompt = ChatPromptTemplate.from_template(
“What language is the following review:nn{Review}”
)chain_three = LLMChain(llm=llm, prompt=third_prompt, output_key=”language”)
fourth_prompt = ChatPromptTemplate.from_template(
“Write a follow up response to the following ”
“summary in the specified language:”
“nnSummary: {summary}nnLanguage: {language}”
)chain_four = LLMChain(llm=llm, prompt=fourth_prompt,
output_key=”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 = 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 poor. The foam doesn’t hold, it’s weird. I
buy the same ones from the store and the taste is much better…nOld batch or
counterfeit!?”,
‘summary’: ‘The reviewer is disappointed with the poor taste and lack of foam in
the product, suspecting it to be either an old batch or a counterfeit.’,
‘followup_message’: “Réponse de suivi:nnCher(e) critique,nnNous sommes
vraiment désolés d’apprendre que vous avez été déçu(e) par le mauvais goût et
l’absence de mousse de notre produit. Nous comprenons votre frustration et
souhaitons rectifier cette situation.nnTout d’abord, nous tenons à vous assurer
que nous ne vendons que des produits authentiques et de haute qualité. Chaque lot
de notre produit est soigneusement contrôlé avant d’être mis sur le
marché.nnCependant, il est possible qu’un incident se soit produit dans votre
cas. Nous vous invitons donc à nous contacter directement afin que nous puissions
mieux comprendre la situation et résoudre ce problème. Nous accorderons une
attention particulière à la fraîcheur et à la mousse de notre produit pour
garantir votre satisfaction.nnNous tenons à vous remercier pour vos
commentaires, car ils nous aident à améliorer continuellement notre produit.
Votre satisfaction est notre priorité absolue et nous ferons tout notre possible
pour rectifier cette situation.nnNous espérons avoir l’opportunité de vous
fournir une expérience agréable avec notre produit à
l’avenir.nnCordialement,nL’équipe du service client”}
4.路由链
from langchain.chains import LLMChain
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.chains.router import MultiPromptChain
from langchain.chains.router.llm_router import LLMRouterChain,RouterOutputParser
from langchain.prompts import PromptTemplate
llm = ChatOpenAI(temperature=0.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] = 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)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
)print(chain.run(“What is black body radiation?”))
print(chain.run(“what is 2 + 2”))
print(chain.run(“Why does every cell in our body contain DNA?”))
> 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 significant
applications in various fields, including astrophysics, thermodynamics, and
quantum mechanics. It played a crucial role in the development of quantum theory
and understanding the behavior of light and matter.> Entering new MultiPromptChain chain…
math: {‘input’: ‘what is 2 + 2’}
> Finished chain.
Thank you for your kind words! As a mathematician, I am happy to help with
any math questions, no matter how simple or complex they may be.The question you’ve asked is a basic addition problem: “What is 2 + 2?” To
solve this, we can simply add the two numbers together:2 + 2 = 4
Therefore, the answer to the question “What is 2 + 2?” is 4.
> 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 is the genetic material that
carries the instructions for the development, functioning, and reproduction of
all living organisms. DNA contains the information necessary for the synthesis of
proteins, which are essential for the structure and function of cells. It serves
as a blueprint for the production of specific proteins that determine the
characteristics and traits of an organism. Additionally, DNA is responsible for
the transmission of genetic information from one generation to the next during
reproduction. Therefore, every cell in our body contains DNA to ensure the proper
functioning and continuity of life.
嘿,伙伴们,今天我们的AI探索之旅已经圆满结束。关于“面向开发者的LLM入门课程-模型链英文版提示”的内容已经分享给大家了。感谢你们的陪伴,希望这次旅程让你对AI能够更了解、更喜欢。谨记,精准提问是解锁AI潜能的钥匙哦!如果有小伙伴想要了解学习更多的AI知识,请关注我们的官网“AI智研社”,保证让你收获满满呦!
还没有评论呢,快来抢沙发~