Prompting Hands On
Introduction to Prompt Engineering¶
Below we are loading the necessary libraries, utilities, and configurations.
In [4]:
Copied!
# !pip install openai
# !pip install python-dotenv
# !pip install rich
# !pip install openai
# !pip install python-dotenv
# !pip install rich
Requirement already satisfied: rich in c:\users\adithya\appdata\roaming\python\python311\site-packages (13.8.1) Requirement already satisfied: markdown-it-py>=2.2.0 in c:\python311\lib\site-packages (from rich) (2.2.0) Requirement already satisfied: pygments<3.0.0,>=2.13.0 in c:\users\adithya\appdata\roaming\python\python311\site-packages (from rich) (2.14.0) Requirement already satisfied: mdurl~=0.1 in c:\python311\lib\site-packages (from markdown-it-py>=2.2.0->rich) (0.1.2)
for the following guide we will be using groq - llama3-70b-8192 which is open ai api compatible
In [5]:
Copied!
import os
import openai
from rich import print
from dotenv import load_dotenv
load_dotenv()
local_api_key = os.getenv("GROQ_API_KEY")
# openai.api_key = os.getenv("GROQ_API_KEY")
client = openai.OpenAI(
base_url="https://api.groq.com/openai/v1",
api_key=local_api_key
)
import os
import openai
from rich import print
from dotenv import load_dotenv
load_dotenv()
local_api_key = os.getenv("GROQ_API_KEY")
# openai.api_key = os.getenv("GROQ_API_KEY")
client = openai.OpenAI(
base_url="https://api.groq.com/openai/v1",
api_key=local_api_key
)
In [6]:
Copied!
# MODEL = "gpt-3.5-turbo"
# response = client.chat.completions.create(
# model=MODEL,
# messages=[
# {"role": "system", "content": "You are an AI research assistant. You use a tone that is technical and scientific."},
# {"role": "user", "content": "Hello, who are you?"},
# {"role": "assistant", "content": "Greeting! I am an AI research assistant. How can I help you today?"},
# {"role": "user", "content": "Can you tell me about the creation of black holes?"}
# ],
# temperature=0,
# )
MODEL = "llama3-8b-8192"
response = client.chat.completions.create(
model=MODEL,
messages=[
{"role": "system", "content": "You are an AI research assistant. You use a tone that is technical and scientific."},
{"role": "user", "content": "Hello, who are you?"},
{"role": "assistant", "content": "Greeting! I am an AI research assistant. How can I help you today?"},
{"role": "user", "content": "Can you tell me about the creation of black holes?"}
],
temperature=0,
)
print(response)
# MODEL = "gpt-3.5-turbo"
# response = client.chat.completions.create(
# model=MODEL,
# messages=[
# {"role": "system", "content": "You are an AI research assistant. You use a tone that is technical and scientific."},
# {"role": "user", "content": "Hello, who are you?"},
# {"role": "assistant", "content": "Greeting! I am an AI research assistant. How can I help you today?"},
# {"role": "user", "content": "Can you tell me about the creation of black holes?"}
# ],
# temperature=0,
# )
MODEL = "llama3-8b-8192"
response = client.chat.completions.create(
model=MODEL,
messages=[
{"role": "system", "content": "You are an AI research assistant. You use a tone that is technical and scientific."},
{"role": "user", "content": "Hello, who are you?"},
{"role": "assistant", "content": "Greeting! I am an AI research assistant. How can I help you today?"},
{"role": "user", "content": "Can you tell me about the creation of black holes?"}
],
temperature=0,
)
print(response)
ChatCompletion( id='chatcmpl-6b95d260-1414-4fbb-ba11-5a0fa9a7ab1d', choices=[ Choice( finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage( content="The creation of black holes is a fascinating topic in the realm of astrophysics. A black hole is a region in spacetime where the gravitational pull is so strong that nothing, including light, can escape. The formation of a black hole typically occurs when a massive star undergoes a catastrophic collapse, resulting in a singularity.\n\nThe process begins when a massive star, typically with a mass greater than three times that of the sun, exhausts its fuel supply and reaches the end of its life cycle. As the star's core contracts, its density increases, causing a massive amount of matter to be compressed into an incredibly small region. This compression releases an enormous amount of energy, causing a supernova explosion.\n\nIf the star is massive enough, the core will collapse into a singularity, creating a black hole. The point of singularity is characterized by infinite density and zero volume, where the laws of physics as we know them break down. The event horizon, which marks the boundary of the black hole, is the point of no return, beyond which anything that enters cannot escape.\n\nThere are several ways in which black holes can form, including:\n\n1. Stellar collapse: As mentioned earlier, the collapse of a massive star can create a black hole.\n2. Mergers: The merger of two neutron stars or black holes can also create a more massive black hole.\n3. Primordial black holes: Some theories suggest that black holes could have formed in the early universe, during the Big Bang, through the collapse of density fluctuations.\n\nThe detection of black holes is challenging due to their small size and the fact that they do not emit any radiation. However, scientists have developed various methods to detect black holes, including:\n\n1. X-ray and gamma-ray observations: Telescopes can detect X-rays and gamma-rays emitted by hot gas swirling around black holes.\n2. Radio and optical observations: Radio and optical telescopes can detect radiation emitted by matter as it spirals into a black hole.\n3. Gravitational waves: The detection of gravitational waves by LIGO and VIRGO collaboration in 2015 provided strong evidence for the existence of black holes.\n\nIn conclusion, the creation of black holes is a complex and fascinating process that involves the collapse of massive stars or the merger of compact objects. The detection of black holes is an active area of research, with scientists using a variety of methods to study these enigmatic objects.", refusal=None, role='assistant', function_call=None, tool_calls=None ) ) ], created=1729072028, model='llama3-8b-8192', object='chat.completion', service_tier=None, system_fingerprint='fp_6a6771ae9c', usage=CompletionUsage( completion_tokens=488, prompt_tokens=76, total_tokens=564, queue_time=0.015080524, prompt_time=0.009203864, completion_time=0.406666667, total_time=0.415870531 ), x_groq={'id': 'req_01jaabjpmke6gbkr1fm4rkj769'} )
In [16]:
Copied!
print(response.choices[0].message.content)
print(response.choices[0].message.content)
The creation of black holes is a fascinating topic in the realm of astrophysics. A black hole is a region in spacetime where the gravitational pull is so strong that nothing, including light, can escape. The formation of a black hole typically occurs when a massive star undergoes a catastrophic collapse, resulting in a singularity. The process begins when a massive star, typically with a mass greater than three times that of the sun, exhausts its fuel supply and reaches the end of its life cycle. As the star's core contracts, its density increases, causing a massive amount of matter to be compressed into an incredibly small region. This compression releases an enormous amount of energy, causing a supernova explosion. If the star is massive enough, the core will collapse into a singularity, creating a black hole. The point of singularity is characterized by infinite density and zero volume, where the laws of physics as we know them break down. The event horizon, which marks the boundary of the black hole, is the point of no return, beyond which anything that enters cannot escape. There are several ways in which black holes can form, including: 1. Stellar collapse: As mentioned earlier, the collapse of a massive star can create a black hole. 2. Mergers: The merger of two neutron stars or black holes can also create a more massive black hole. 3. Primordial black holes: Some theories suggest that black holes could have formed in the early universe, during the Big Bang, through the collapse of density fluctuations. The detection of black holes is challenging due to their small size and the fact that they do not emit any radiation. However, scientists have developed various methods to detect black holes, including: 1. X-ray and gamma-ray observations: Telescopes can detect X-rays and gamma-rays emitted by hot gas swirling around black holes. 2. Radio and optical observations: Radio and optical telescopes can detect radiation emitted by matter as it spirals into a black hole. 3. Gravitational waves: The detection of gravitational waves by LIGO and VIRGO collaboration in 2015 provided strong evidence for the existence of black holes. In conclusion, the creation of black holes is a complex and fascinating process that involves the collapse of massive stars or the merger of compact objects. The detection of black holes is an active area of research, with scientists using a variety of methods to study these enigmatic objects.
In [38]:
Copied!
def get_completion(messages, model="llama-3.2-90b-text-preview", temperature=0, max_tokens=4000):
response = client.chat.completions.create(
model=model,
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
)
return response.choices[0].message.content
def get_completion(messages, model="llama-3.2-90b-text-preview", temperature=0, max_tokens=4000):
response = client.chat.completions.create(
model=model,
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
)
return response.choices[0].message.content
Basic prompt example:¶
In [39]:
Copied!
prompt = "The sky is"
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message)
print(response)
prompt = "The sky is"
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message)
print(response)
blue.
In [40]:
Copied!
response = get_completion(message,temperature=0.5)
print(response)
response = get_completion(message,temperature=0.5)
print(response)
blue.
Text Summarization¶
In [20]:
Copied!
prompt = """Antibiotics are a type of medication used to treat bacterial infections. They work by either killing the bacteria or preventing them from reproducing, allowing the body's immune system to fight off the infection. Antibiotics are usually taken orally in the form of pills, capsules, or liquid solutions, or sometimes administered intravenously. They are not effective against viral infections, and using them inappropriately can lead to antibiotic resistance.
Explain the above in one sentence:"""
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message, temperature=0)
print(response)
prompt = """Antibiotics are a type of medication used to treat bacterial infections. They work by either killing the bacteria or preventing them from reproducing, allowing the body's immune system to fight off the infection. Antibiotics are usually taken orally in the form of pills, capsules, or liquid solutions, or sometimes administered intravenously. They are not effective against viral infections, and using them inappropriately can lead to antibiotic resistance.
Explain the above in one sentence:"""
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message, temperature=0)
print(response)
Antibiotics are medications that kill or prevent bacterial growth, allowing the body's immune system to fight off infections, but are ineffective against viral infections and can lead to antibiotic resistance if used inappropriately.
In [21]:
Copied!
prompt = """
Your task is to summarize an abstract into one sentence.
Abstract: Antibiotics are a type of medication used to treat bacterial infections. They work by either killing the bacteria or preventing them from reproducing, allowing the body's immune system to fight off the infection. Antibiotics are usually taken orally in the form of pills, capsules, or liquid solutions, or sometimes administered intravenously. They are not effective against viral infections, and using them inappropriately can lead to antibiotic resistance.
"""
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message, temperature=0)
print(response)
prompt = """
Your task is to summarize an abstract into one sentence.
Abstract: Antibiotics are a type of medication used to treat bacterial infections. They work by either killing the bacteria or preventing them from reproducing, allowing the body's immune system to fight off the infection. Antibiotics are usually taken orally in the form of pills, capsules, or liquid solutions, or sometimes administered intravenously. They are not effective against viral infections, and using them inappropriately can lead to antibiotic resistance.
"""
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message, temperature=0)
print(response)
Antibiotics are medications that kill or prevent bacterial growth, allowing the body's immune system to fight off infections, but are ineffective against viral infections and can lead to antibiotic resistance if used inappropriately.
In [22]:
Copied!
prompt = """
Your task is to summarize an abstract into one sentence.
Avoid technical jargon and explain it in the simplest of words.
Abstract: Antibiotics are a type of medication used to treat bacterial infections. They work by either killing the bacteria or preventing them from reproducing, allowing the body's immune system to fight off the infection. Antibiotics are usually taken orally in the form of pills, capsules, or liquid solutions, or sometimes administered intravenously. They are not effective against viral infections, and using them inappropriately can lead to antibiotic resistance.
"""
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message, temperature=0)
print(response)
prompt = """
Your task is to summarize an abstract into one sentence.
Avoid technical jargon and explain it in the simplest of words.
Abstract: Antibiotics are a type of medication used to treat bacterial infections. They work by either killing the bacteria or preventing them from reproducing, allowing the body's immune system to fight off the infection. Antibiotics are usually taken orally in the form of pills, capsules, or liquid solutions, or sometimes administered intravenously. They are not effective against viral infections, and using them inappropriately can lead to antibiotic resistance.
"""
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message, temperature=0)
print(response)
Antibiotics are medicines that help the body fight off bacterial infections by killing or stopping the growth of the bacteria, and they come in different forms such as pills, liquids, or injections.
Question Answering¶
In [23]:
Copied!
prompt = """Answer the question based on the context below. Keep the answer short and concise. Respond "Unsure about answer" if not sure about the answer.
Context: Teplizumab traces its roots to a New Jersey drug company called Ortho Pharmaceutical. There, scientists generated an early version of the antibody, dubbed OKT3. Originally sourced from mice, the molecule was able to bind to the surface of T cells and limit their cell-killing potential. In 1986, it was approved to help prevent organ rejection after kidney transplants, making it the first therapeutic antibody allowed for human use.
Question: What was OKT3 originally sourced from?
Answer:
"""
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message)
print(response)
prompt = """Answer the question based on the context below. Keep the answer short and concise. Respond "Unsure about answer" if not sure about the answer.
Context: Teplizumab traces its roots to a New Jersey drug company called Ortho Pharmaceutical. There, scientists generated an early version of the antibody, dubbed OKT3. Originally sourced from mice, the molecule was able to bind to the surface of T cells and limit their cell-killing potential. In 1986, it was approved to help prevent organ rejection after kidney transplants, making it the first therapeutic antibody allowed for human use.
Question: What was OKT3 originally sourced from?
Answer:
"""
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message)
print(response)
Mice
Text Classification¶
In [24]:
Copied!
user_input = "I think the food was okay"
prompt = """Classify the text into neutral, negative or positive. The input text will be delimited by ```
Text: ```{user_input}```
Sentiment:"""
message = [
{
"role": "user",
"content": prompt.format(user_input=user_input)
}
]
response = get_completion(message)
print(response)
user_input = "I think the food was okay"
prompt = """Classify the text into neutral, negative or positive. The input text will be delimited by ```
Text: ```{user_input}```
Sentiment:"""
message = [
{
"role": "user",
"content": prompt.format(user_input=user_input)
}
]
response = get_completion(message)
print(response)
Neutral
Information Extraction¶
In [25]:
Copied!
prompt = """Your task is to extract model names from machine learning paper abstracts. Your response is an array of the model names in the format [\"model_name\"]. If you don't find model names in the abstract or you are not sure, return [\"NA\"].
Abstract: Large Language Models (LLMs), such as ChatGPT and GPT-4, have revolutionized natural language processing research and demonstrated potential in Artificial General Intelligence (AGI). However, the expensive training and deployment of LLMs present challenges to transparent and open academic research. To address these issues, this project open-sources the Chinese LLaMA and Alpaca…
Tags:"""
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message)
print(response)
prompt = """Your task is to extract model names from machine learning paper abstracts. Your response is an array of the model names in the format [\"model_name\"]. If you don't find model names in the abstract or you are not sure, return [\"NA\"].
Abstract: Large Language Models (LLMs), such as ChatGPT and GPT-4, have revolutionized natural language processing research and demonstrated potential in Artificial General Intelligence (AGI). However, the expensive training and deployment of LLMs present challenges to transparent and open academic research. To address these issues, this project open-sources the Chinese LLaMA and Alpaca…
Tags:"""
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message)
print(response)
["LLaMA", "Alpaca"]
Machine Translation¶
In [26]:
Copied!
prompt = """Translate the following from English to Spanish:
“Glad to be here!”
"""
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message)
print(response)
prompt = """Translate the following from English to Spanish:
“Glad to be here!”
"""
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message)
print(response)
The translation of "Glad to be here!" from English to Spanish is:
¡Encantado de estar aquí!
Note: If you want to use a more informal tone, you can use:
¡Estoy encantado de estar aquí!
Or:
¡Me alegra estar aquí!
Tone Transformation¶
In [27]:
Copied!
prompt = """Translate the following from happy to super excited:
“Glad to be here!”
"""
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message)
print(response)
prompt = """Translate the following from happy to super excited:
“Glad to be here!”
"""
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message)
print(response)
Here's the translation:
"WOOHOO! Thrilled to be here and can't wait to get started!"
Role Playing¶
In [28]:
Copied!
prompt = """The following is a conversation with an AI research assistant. The assistant tone is technical and scientific.
Human: Hello, who are you?
AI: Greeting! I am an AI research assistant. How can I help you today?
Human: Can you tell me about the creation of black holes?
AI:"""
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message)
print(response)
prompt = """The following is a conversation with an AI research assistant. The assistant tone is technical and scientific.
Human: Hello, who are you?
AI: Greeting! I am an AI research assistant. How can I help you today?
Human: Can you tell me about the creation of black holes?
AI:"""
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message)
print(response)
A fascinating topic! The creation of black holes is a complex process that involves the collapse of massive stars or the merger of compact objects such as neutron stars or black holes themselves. In the case of stellar-mass black holes, they are formed when a massive star with a mass at least three times that of the sun runs out of fuel and collapses under its own gravity. If the star is massive enough, its gravity will overcome the pressure of its own nuclear reactions, causing a supernova explosion. However, if the star is not massive enough to trigger a supernova, it will collapse directly into a black hole. The collapse is a rapid process, occurring over a timescale of milliseconds. As the star collapses, its density and gravity increase, causing a singularity to form at its center. The point of singularity is characterized by infinite density and zero volume, and it is surrounded by an event horizon, which marks the boundary beyond which nothing, not even light, can escape the gravitational pull of the black hole. In the case of supermassive black holes, they are thought to have formed in the early universe through the merger of smaller black holes or the collapse of a massive cloud of gas and dust. These black holes can have masses millions or even billions of times that of the sun and are found at the centers of many galaxies, including our own Milky Way. It's worth noting that the formation of black holes is still an active area of research, and there are many open questions and uncertainties in our current understanding of the process. However, the basic principles outlined above provide a good starting point for understanding how black holes are created.
In [29]:
Copied!
system_message = """
The following is a conversation with an AI research assistant. The assistant tone is technical and scientific.
"""
prompt = """
Human: Hello, who are you?
AI: Greeting! I am an AI research assistant. How can I help you today?
Human: Can you tell me about the creation of black holes?
AI:
"""
messages = [
{
"role": "system",
"content": system_message
},
{
"role": "user",
"content": prompt
}
]
response = get_completion(messages)
print(response)
system_message = """
The following is a conversation with an AI research assistant. The assistant tone is technical and scientific.
"""
prompt = """
Human: Hello, who are you?
AI: Greeting! I am an AI research assistant. How can I help you today?
Human: Can you tell me about the creation of black holes?
AI:
"""
messages = [
{
"role": "system",
"content": system_message
},
{
"role": "user",
"content": prompt
}
]
response = get_completion(messages)
print(response)
A fascinating topic! The creation of black holes is a complex and multifaceted process that has been extensively studied in the fields of astrophysics and theoretical physics. Black holes are regions in spacetime where the gravitational pull is so strong that nothing, including light, can escape once it falls within a certain radius, known as the event horizon. The formation of a black hole typically occurs when a massive star undergoes a catastrophic collapse, resulting in a singularity at its center. There are several ways in which a massive star can collapse to form a black hole. One scenario is known as the direct collapse, where the star's core collapses under its own gravity, causing a massive amount of matter to be compressed into an incredibly small region. This compression creates an intense gravitational field, which warps the fabric of spacetime around the star, forming the event horizon. Another scenario is the indirect collapse, where the star undergoes a supernova explosion, expelling a significant amount of its mass and energy. If the star is massive enough, the remaining core can collapse into a black hole. The formation of a black hole also depends on the star's mass and metallicity. More massive stars are more likely to form black holes, as they have a greater amount of energy to be released during their collapse. Additionally, stars with lower metallicity (i.e., fewer elements heavier than hydrogen and helium) are more likely to form black holes, as they have a lower opacity and can collapse more easily. Once a black hole is formed, it can continue to grow through the accretion of surrounding matter and energy. This process can lead to the formation of an accretion disk, which is a swirling disk of hot, dense gas that surrounds the black hole. The accretion disk can emit intense radiation, including X-rays and gamma rays, which can be detected by telescopes. In summary, the creation of black holes is a complex process that involves the collapse of massive stars, the compression of matter into an incredibly small region, and the warping of spacetime around the star. The formation of black holes depends on various factors, including the star's mass, metallicity, and the presence of an accretion disk. Would you like me to elaborate on any specific aspect of black hole formation or evolution?
In [30]:
Copied!
system_message = """
The following is a conversation with an AI research assistant. The assistant tone is technical and scientific.
"""
user_message_1 = """
Hello, who are you?
"""
ai_message_1 = """
Greeting! I am an AI research assistant. How can I help you today?
"""
prompt = """
Human: Can you tell me about the creation of blackholes?
AI:
"""
messages = [
{
"role": "system",
"content": system_message
},
{
"role": "user",
"content": user_message_1
},
{
"role": "assistant",
"content": ai_message_1
},
{
"role": "user",
"content": prompt
}
]
response = get_completion(messages)
print(response)
system_message = """
The following is a conversation with an AI research assistant. The assistant tone is technical and scientific.
"""
user_message_1 = """
Hello, who are you?
"""
ai_message_1 = """
Greeting! I am an AI research assistant. How can I help you today?
"""
prompt = """
Human: Can you tell me about the creation of blackholes?
AI:
"""
messages = [
{
"role": "system",
"content": system_message
},
{
"role": "user",
"content": user_message_1
},
{
"role": "assistant",
"content": ai_message_1
},
{
"role": "user",
"content": prompt
}
]
response = get_completion(messages)
print(response)
The creation of black holes is a fascinating topic in astrophysics. A black hole is a region in space where the gravitational pull is so strong that nothing, including light, can escape. It is formed when a massive star collapses in on itself and its gravity becomes so strong that it warps the fabric of spacetime around it. The process of black hole formation typically begins with the death of a massive star. When a star with a mass at least three times that of the sun runs out of fuel, it collapses under its own gravity. If the star is massive enough, its gravity will be so strong that it will cause a massive amount of matter to be compressed into an incredibly small point, known as a singularity. At this point, the star's gravity becomes so strong that it warps the fabric of spacetime around it, creating a boundary called the event horizon. Once something crosses the event horizon, it is trapped by the black hole's gravity and cannot escape. The formation of a black hole is a complex process that involves the collapse of a massive star, the creation of a singularity, and the warping of spacetime around it. It is a fascinating area of study in astrophysics, and scientists continue to learn more about black holes and their role in the universe. Would you like to know more about black holes or is there something specific you would like to know?
Code Generation¶
In [31]:
Copied!
prompt = "\"\"\"\nTable departments, columns = [DepartmentId, DepartmentName]\nTable students, columns = [DepartmentId, StudentId, StudentName]\nCreate a MySQL query for all students in the Computer Science Department\n\"\"\""
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message)
print(response)
prompt = "\"\"\"\nTable departments, columns = [DepartmentId, DepartmentName]\nTable students, columns = [DepartmentId, StudentId, StudentName]\nCreate a MySQL query for all students in the Computer Science Department\n\"\"\""
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message)
print(response)
Here is the MySQL query to get all students in the Computer Science Department: ```sql SELECT s.* FROM students s JOIN departments d ON s.DepartmentId = d.DepartmentId WHERE d.DepartmentName = 'Computer Science'; ``` This query joins the `students` table with the `departments` table on the `DepartmentId` column. Then it filters the results to only include rows where the `DepartmentName` is 'Computer Science'. The `s.*` in the `SELECT` clause means to select all columns from the `students` table.
Reasoning¶
In [32]:
Copied!
prompt = """The odd numbers in this group add up to an even number: 15, 32, 5, 13, 82, 7, 1.
Solve by breaking the problem into steps. First, identify the odd numbers, add them, and indicate whether the result is odd or even."""
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message)
print(response)
prompt = """The odd numbers in this group add up to an even number: 15, 32, 5, 13, 82, 7, 1.
Solve by breaking the problem into steps. First, identify the odd numbers, add them, and indicate whether the result is odd or even."""
message = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(message)
print(response)
Let's break down the problem step by step: Step 1: Identify the odd numbers in the group: The odd numbers in the group are: 15, 5, 13, 7, and 1. Step 2: Add the odd numbers: 15 + 5 + 13 + 7 + 1 = 42 Step 3: Determine whether the result is odd or even: The result, 42, is an even number. Therefore, the statement "The odd numbers in this group add up to an even number" is true.
Advanced Prompting Techniques¶
Few-shot prompts¶
In [36]:
Copied!
prompt = """The odd numbers in this group add up to an even number: 4, 8, 9, 15, 12, 2, 1.
A: The answer is False.
The odd numbers in this group add up to an even number: 17, 10, 19, 4, 8, 12, 24.
A: The answer is True.
The odd numbers in this group add up to an even number: 16, 11, 14, 4, 8, 13, 24.
A: The answer is True.
The odd numbers in this group add up to an even number: 17, 9, 10, 12, 13, 4, 2.
A: The answer is False.
The odd numbers in this group add up to an even number: 15, 32, 5, 13, 82, 7, 1.
A:"""
messages = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(messages)
print(response)
prompt = """The odd numbers in this group add up to an even number: 4, 8, 9, 15, 12, 2, 1.
A: The answer is False.
The odd numbers in this group add up to an even number: 17, 10, 19, 4, 8, 12, 24.
A: The answer is True.
The odd numbers in this group add up to an even number: 16, 11, 14, 4, 8, 13, 24.
A: The answer is True.
The odd numbers in this group add up to an even number: 17, 9, 10, 12, 13, 4, 2.
A: The answer is False.
The odd numbers in this group add up to an even number: 15, 32, 5, 13, 82, 7, 1.
A:"""
messages = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(messages)
print(response)
Let's add up the odd numbers in the group: 15 + 5 + 13 + 7 + 1 = 41. Since 41 is an odd number, the statement is False. So, the correct answer is: A: The answer is False.
Chain-of-Throught (CoT) Prompting¶
In [35]:
Copied!
prompt = """The odd numbers in this group add up to an even number: 4, 8, 9, 15, 12, 2, 1.
A: Adding all the odd numbers (9, 15, 1) gives 25. The answer is False.
The odd numbers in this group add up to an even number: 15, 32, 5, 13, 82, 7, 1.
A:"""
messages = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(messages)
print(response)
prompt = """The odd numbers in this group add up to an even number: 4, 8, 9, 15, 12, 2, 1.
A: Adding all the odd numbers (9, 15, 1) gives 25. The answer is False.
The odd numbers in this group add up to an even number: 15, 32, 5, 13, 82, 7, 1.
A:"""
messages = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(messages)
print(response)
Let's add up the odd numbers: 15, 5, 13, 7, 1 = 41. The answer is False.
Zero Shot CoT¶
In [37]:
Copied!
prompt = """I went to the market and bought 10 apples. I gave 2 apples to the neighbor and 2 to the repairman. I then went and bought 5 more apples and ate 1. How many apples did I remain with?
Let's think step by step."""
messages = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(messages)
print(response)
prompt = """I went to the market and bought 10 apples. I gave 2 apples to the neighbor and 2 to the repairman. I then went and bought 5 more apples and ate 1. How many apples did I remain with?
Let's think step by step."""
messages = [
{
"role": "user",
"content": prompt
}
]
response = get_completion(messages)
print(response)
Let's break it down step by step: 1. You started with 10 apples. 2. You gave 2 apples to the neighbor, so you have 10 - 2 = 8 apples left. 3. You gave 2 apples to the repairman, so you have 8 - 2 = 6 apples left. 4. You bought 5 more apples, so you now have 6 + 5 = 11 apples. 5. You ate 1 apple, so you have 11 - 1 = 10 apples left. So, you remain with 10 apples.