Chapter 5: Prompt Engineering and System Instructions
Practical Exercises β Chapter 5
Exercise 1: Crafting an Effective Prompt
Task:
Write a prompt that asks the model to explain the concept of object-oriented programming (OOP) in Python. Your prompt should be clear and specific, and it should include a system message that sets the tone as a friendly tutor.
Instructions:
- Use a system message to instruct the model to adopt a friendly and instructive tone.
- Your user prompt should request a clear explanation of OOP with an emphasis on key concepts.
Solution:
import openai
import os
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
# Construct the conversation
messages = [
{"role": "system", "content": "You are a friendly and knowledgeable programming tutor."},
{"role": "user", "content": "Can you explain what object-oriented programming (OOP) is in Python, and describe the concepts of classes and objects?"}
]
# Call the API with a moderate token limit
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=messages,
max_tokens=150,
temperature=0.5
)
print("Exercise 1 Output:")
print(response["choices"][0]["message"]["content"])
Exercise 2: Using Prompt Templates for a Specific Task
Task:
Develop a prompt template for generating a professional customer support response that explains how to reset a password. Include an example of the expected email format.
Instructions:
- Use a system message to set the tone as an empathetic and efficient customer support agent.
- In the user message, provide an example scenario and ask the AI to generate a response following a similar structure.
Solution:
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a courteous and efficient customer support assistant."},
{"role": "user", "content": (
"Example email format:\n"
"Subject: Password Reset Assistance\n"
"Dear [Customer],\n"
"Thank you for reaching out. To reset your password, please click on the following link...\n"
"If you have any issues, let us know.\n"
"Best regards,\n"
"Support Team\n\n"
"Now, please generate a similar email response for a customer who has forgotten their password."
)}
],
max_tokens=180,
temperature=0.5
)
print("Exercise 2 Output:")
print(response["choices"][0]["message"]["content"])
Exercise 3: Zero-shot Versus Few-shot Prompting
Task:
Compare zero-shot and few-shot prompting for generating a brief summary of the benefits of remote work. First, try zero-shot, then provide two examples of effective summaries as part of a few-shot prompt.
Instructions:
- For zero-shot, simply provide the prompt.
- For few-shot, include two example summaries before asking for a new one.
Solution:
# Zero-shot Prompting
response_zero_shot = openai.ChatCompletion.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Summarize three benefits of remote work."}],
max_tokens=100,
temperature=0.6
)
print("Zero-shot Response:")
print(response_zero_shot["choices"][0]["message"]["content"])
# Few-shot Prompting
response_few_shot = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are an efficient content generator."},
{"role": "user", "content": (
"Example 1: Remote work enhances flexibility by reducing commute time, allows for a better work-life balance, and can lead to increased productivity due to a personalized work environment.\n\n"
"Example 2: The benefits of remote work include the ability to work from anywhere, lower operating costs for businesses, and the opportunity for employees to create a better personal schedule.\n\n"
"Now, please provide a new summary of three benefits of remote work."
)}
],
max_tokens=120,
temperature=0.6
)
print("\nFew-shot Response:")
print(response_few_shot["choices"][0]["message"]["content"])
Exercise 4: Applying Chain-of-Thought Prompting
Task:
Ask the model to solve a logical problem by reasoning through steps. For example: "Explain step-by-step how you would determine if a number is prime."
Instructions:
- Use a system message to prompt the assistant to think in a chain-of-thought.
- Formulate the user prompt to request a detailed, step-by-step explanation.
Solution:
response_chain = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a logical problem-solving assistant who explains every step in detail."},
{"role": "user", "content": "Explain step-by-step how you would determine if the number 29 is prime."}
],
max_tokens=200,
temperature=0.5
)
print("Chain-of-thought Response:")
print(response_chain["choices"][0]["message"]["content"])
Exercise 5: Iterative Prompt Refinement
Task:
Start with a basic prompt asking for a summary of the latest trends in artificial intelligence. Then refine it iteratively to include details such as key technologies and potential impacts. Submit both the basic and refined prompts.
Instructions:
- First, send a basic prompt and capture the response.
- Then, update the prompt by adding additional context and constraints.
- Compare the outputs.
Solution:
# Basic prompt for AI trends
basic_prompt = "Summarize the latest trends in artificial intelligence."
response_basic = openai.ChatCompletion.create(
model="gpt-4o",
messages=[{"role": "user", "content": basic_prompt}],
max_tokens=150,
temperature=0.6
)
print("Basic Prompt Response:")
print(response_basic["choices"][0]["message"]["content"])
# Refined prompt with more context
refined_prompt = (
"Summarize the latest trends in artificial intelligence, including key technologies such as natural language processing, "
"computer vision, and reinforcement learning. Also, discuss potential impacts on industries like healthcare and finance."
)
response_refined = openai.ChatCompletion.create(
model="gpt-4o",
messages=[{"role": "user", "content": refined_prompt}],
max_tokens=200,
temperature=0.6
)
print("\nRefined Prompt Response:")
print(response_refined["choices"][0]["message"]["content"])
If you have successfully completed these exercises, congratulations! You’ve now practiced a range of prompt engineering techniques—from crafting effective prompts and utilizing system messages, to experimenting with zero-shot, few-shot, and chain-of-thought prompting. These exercises empower you to create refined interactions tailored to your application’s needs.
Armed with these skills, you're ready to move forward and further enhance your AI applications. Keep experimenting, refining your prompts, and building engaging, efficient interactions with the Chat Completions API.
Practical Exercises β Chapter 5
Exercise 1: Crafting an Effective Prompt
Task:
Write a prompt that asks the model to explain the concept of object-oriented programming (OOP) in Python. Your prompt should be clear and specific, and it should include a system message that sets the tone as a friendly tutor.
Instructions:
- Use a system message to instruct the model to adopt a friendly and instructive tone.
- Your user prompt should request a clear explanation of OOP with an emphasis on key concepts.
Solution:
import openai
import os
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
# Construct the conversation
messages = [
{"role": "system", "content": "You are a friendly and knowledgeable programming tutor."},
{"role": "user", "content": "Can you explain what object-oriented programming (OOP) is in Python, and describe the concepts of classes and objects?"}
]
# Call the API with a moderate token limit
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=messages,
max_tokens=150,
temperature=0.5
)
print("Exercise 1 Output:")
print(response["choices"][0]["message"]["content"])
Exercise 2: Using Prompt Templates for a Specific Task
Task:
Develop a prompt template for generating a professional customer support response that explains how to reset a password. Include an example of the expected email format.
Instructions:
- Use a system message to set the tone as an empathetic and efficient customer support agent.
- In the user message, provide an example scenario and ask the AI to generate a response following a similar structure.
Solution:
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a courteous and efficient customer support assistant."},
{"role": "user", "content": (
"Example email format:\n"
"Subject: Password Reset Assistance\n"
"Dear [Customer],\n"
"Thank you for reaching out. To reset your password, please click on the following link...\n"
"If you have any issues, let us know.\n"
"Best regards,\n"
"Support Team\n\n"
"Now, please generate a similar email response for a customer who has forgotten their password."
)}
],
max_tokens=180,
temperature=0.5
)
print("Exercise 2 Output:")
print(response["choices"][0]["message"]["content"])
Exercise 3: Zero-shot Versus Few-shot Prompting
Task:
Compare zero-shot and few-shot prompting for generating a brief summary of the benefits of remote work. First, try zero-shot, then provide two examples of effective summaries as part of a few-shot prompt.
Instructions:
- For zero-shot, simply provide the prompt.
- For few-shot, include two example summaries before asking for a new one.
Solution:
# Zero-shot Prompting
response_zero_shot = openai.ChatCompletion.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Summarize three benefits of remote work."}],
max_tokens=100,
temperature=0.6
)
print("Zero-shot Response:")
print(response_zero_shot["choices"][0]["message"]["content"])
# Few-shot Prompting
response_few_shot = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are an efficient content generator."},
{"role": "user", "content": (
"Example 1: Remote work enhances flexibility by reducing commute time, allows for a better work-life balance, and can lead to increased productivity due to a personalized work environment.\n\n"
"Example 2: The benefits of remote work include the ability to work from anywhere, lower operating costs for businesses, and the opportunity for employees to create a better personal schedule.\n\n"
"Now, please provide a new summary of three benefits of remote work."
)}
],
max_tokens=120,
temperature=0.6
)
print("\nFew-shot Response:")
print(response_few_shot["choices"][0]["message"]["content"])
Exercise 4: Applying Chain-of-Thought Prompting
Task:
Ask the model to solve a logical problem by reasoning through steps. For example: "Explain step-by-step how you would determine if a number is prime."
Instructions:
- Use a system message to prompt the assistant to think in a chain-of-thought.
- Formulate the user prompt to request a detailed, step-by-step explanation.
Solution:
response_chain = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a logical problem-solving assistant who explains every step in detail."},
{"role": "user", "content": "Explain step-by-step how you would determine if the number 29 is prime."}
],
max_tokens=200,
temperature=0.5
)
print("Chain-of-thought Response:")
print(response_chain["choices"][0]["message"]["content"])
Exercise 5: Iterative Prompt Refinement
Task:
Start with a basic prompt asking for a summary of the latest trends in artificial intelligence. Then refine it iteratively to include details such as key technologies and potential impacts. Submit both the basic and refined prompts.
Instructions:
- First, send a basic prompt and capture the response.
- Then, update the prompt by adding additional context and constraints.
- Compare the outputs.
Solution:
# Basic prompt for AI trends
basic_prompt = "Summarize the latest trends in artificial intelligence."
response_basic = openai.ChatCompletion.create(
model="gpt-4o",
messages=[{"role": "user", "content": basic_prompt}],
max_tokens=150,
temperature=0.6
)
print("Basic Prompt Response:")
print(response_basic["choices"][0]["message"]["content"])
# Refined prompt with more context
refined_prompt = (
"Summarize the latest trends in artificial intelligence, including key technologies such as natural language processing, "
"computer vision, and reinforcement learning. Also, discuss potential impacts on industries like healthcare and finance."
)
response_refined = openai.ChatCompletion.create(
model="gpt-4o",
messages=[{"role": "user", "content": refined_prompt}],
max_tokens=200,
temperature=0.6
)
print("\nRefined Prompt Response:")
print(response_refined["choices"][0]["message"]["content"])
If you have successfully completed these exercises, congratulations! You’ve now practiced a range of prompt engineering techniques—from crafting effective prompts and utilizing system messages, to experimenting with zero-shot, few-shot, and chain-of-thought prompting. These exercises empower you to create refined interactions tailored to your application’s needs.
Armed with these skills, you're ready to move forward and further enhance your AI applications. Keep experimenting, refining your prompts, and building engaging, efficient interactions with the Chat Completions API.
Practical Exercises β Chapter 5
Exercise 1: Crafting an Effective Prompt
Task:
Write a prompt that asks the model to explain the concept of object-oriented programming (OOP) in Python. Your prompt should be clear and specific, and it should include a system message that sets the tone as a friendly tutor.
Instructions:
- Use a system message to instruct the model to adopt a friendly and instructive tone.
- Your user prompt should request a clear explanation of OOP with an emphasis on key concepts.
Solution:
import openai
import os
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
# Construct the conversation
messages = [
{"role": "system", "content": "You are a friendly and knowledgeable programming tutor."},
{"role": "user", "content": "Can you explain what object-oriented programming (OOP) is in Python, and describe the concepts of classes and objects?"}
]
# Call the API with a moderate token limit
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=messages,
max_tokens=150,
temperature=0.5
)
print("Exercise 1 Output:")
print(response["choices"][0]["message"]["content"])
Exercise 2: Using Prompt Templates for a Specific Task
Task:
Develop a prompt template for generating a professional customer support response that explains how to reset a password. Include an example of the expected email format.
Instructions:
- Use a system message to set the tone as an empathetic and efficient customer support agent.
- In the user message, provide an example scenario and ask the AI to generate a response following a similar structure.
Solution:
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a courteous and efficient customer support assistant."},
{"role": "user", "content": (
"Example email format:\n"
"Subject: Password Reset Assistance\n"
"Dear [Customer],\n"
"Thank you for reaching out. To reset your password, please click on the following link...\n"
"If you have any issues, let us know.\n"
"Best regards,\n"
"Support Team\n\n"
"Now, please generate a similar email response for a customer who has forgotten their password."
)}
],
max_tokens=180,
temperature=0.5
)
print("Exercise 2 Output:")
print(response["choices"][0]["message"]["content"])
Exercise 3: Zero-shot Versus Few-shot Prompting
Task:
Compare zero-shot and few-shot prompting for generating a brief summary of the benefits of remote work. First, try zero-shot, then provide two examples of effective summaries as part of a few-shot prompt.
Instructions:
- For zero-shot, simply provide the prompt.
- For few-shot, include two example summaries before asking for a new one.
Solution:
# Zero-shot Prompting
response_zero_shot = openai.ChatCompletion.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Summarize three benefits of remote work."}],
max_tokens=100,
temperature=0.6
)
print("Zero-shot Response:")
print(response_zero_shot["choices"][0]["message"]["content"])
# Few-shot Prompting
response_few_shot = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are an efficient content generator."},
{"role": "user", "content": (
"Example 1: Remote work enhances flexibility by reducing commute time, allows for a better work-life balance, and can lead to increased productivity due to a personalized work environment.\n\n"
"Example 2: The benefits of remote work include the ability to work from anywhere, lower operating costs for businesses, and the opportunity for employees to create a better personal schedule.\n\n"
"Now, please provide a new summary of three benefits of remote work."
)}
],
max_tokens=120,
temperature=0.6
)
print("\nFew-shot Response:")
print(response_few_shot["choices"][0]["message"]["content"])
Exercise 4: Applying Chain-of-Thought Prompting
Task:
Ask the model to solve a logical problem by reasoning through steps. For example: "Explain step-by-step how you would determine if a number is prime."
Instructions:
- Use a system message to prompt the assistant to think in a chain-of-thought.
- Formulate the user prompt to request a detailed, step-by-step explanation.
Solution:
response_chain = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a logical problem-solving assistant who explains every step in detail."},
{"role": "user", "content": "Explain step-by-step how you would determine if the number 29 is prime."}
],
max_tokens=200,
temperature=0.5
)
print("Chain-of-thought Response:")
print(response_chain["choices"][0]["message"]["content"])
Exercise 5: Iterative Prompt Refinement
Task:
Start with a basic prompt asking for a summary of the latest trends in artificial intelligence. Then refine it iteratively to include details such as key technologies and potential impacts. Submit both the basic and refined prompts.
Instructions:
- First, send a basic prompt and capture the response.
- Then, update the prompt by adding additional context and constraints.
- Compare the outputs.
Solution:
# Basic prompt for AI trends
basic_prompt = "Summarize the latest trends in artificial intelligence."
response_basic = openai.ChatCompletion.create(
model="gpt-4o",
messages=[{"role": "user", "content": basic_prompt}],
max_tokens=150,
temperature=0.6
)
print("Basic Prompt Response:")
print(response_basic["choices"][0]["message"]["content"])
# Refined prompt with more context
refined_prompt = (
"Summarize the latest trends in artificial intelligence, including key technologies such as natural language processing, "
"computer vision, and reinforcement learning. Also, discuss potential impacts on industries like healthcare and finance."
)
response_refined = openai.ChatCompletion.create(
model="gpt-4o",
messages=[{"role": "user", "content": refined_prompt}],
max_tokens=200,
temperature=0.6
)
print("\nRefined Prompt Response:")
print(response_refined["choices"][0]["message"]["content"])
If you have successfully completed these exercises, congratulations! You’ve now practiced a range of prompt engineering techniques—from crafting effective prompts and utilizing system messages, to experimenting with zero-shot, few-shot, and chain-of-thought prompting. These exercises empower you to create refined interactions tailored to your application’s needs.
Armed with these skills, you're ready to move forward and further enhance your AI applications. Keep experimenting, refining your prompts, and building engaging, efficient interactions with the Chat Completions API.
Practical Exercises β Chapter 5
Exercise 1: Crafting an Effective Prompt
Task:
Write a prompt that asks the model to explain the concept of object-oriented programming (OOP) in Python. Your prompt should be clear and specific, and it should include a system message that sets the tone as a friendly tutor.
Instructions:
- Use a system message to instruct the model to adopt a friendly and instructive tone.
- Your user prompt should request a clear explanation of OOP with an emphasis on key concepts.
Solution:
import openai
import os
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
# Construct the conversation
messages = [
{"role": "system", "content": "You are a friendly and knowledgeable programming tutor."},
{"role": "user", "content": "Can you explain what object-oriented programming (OOP) is in Python, and describe the concepts of classes and objects?"}
]
# Call the API with a moderate token limit
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=messages,
max_tokens=150,
temperature=0.5
)
print("Exercise 1 Output:")
print(response["choices"][0]["message"]["content"])
Exercise 2: Using Prompt Templates for a Specific Task
Task:
Develop a prompt template for generating a professional customer support response that explains how to reset a password. Include an example of the expected email format.
Instructions:
- Use a system message to set the tone as an empathetic and efficient customer support agent.
- In the user message, provide an example scenario and ask the AI to generate a response following a similar structure.
Solution:
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a courteous and efficient customer support assistant."},
{"role": "user", "content": (
"Example email format:\n"
"Subject: Password Reset Assistance\n"
"Dear [Customer],\n"
"Thank you for reaching out. To reset your password, please click on the following link...\n"
"If you have any issues, let us know.\n"
"Best regards,\n"
"Support Team\n\n"
"Now, please generate a similar email response for a customer who has forgotten their password."
)}
],
max_tokens=180,
temperature=0.5
)
print("Exercise 2 Output:")
print(response["choices"][0]["message"]["content"])
Exercise 3: Zero-shot Versus Few-shot Prompting
Task:
Compare zero-shot and few-shot prompting for generating a brief summary of the benefits of remote work. First, try zero-shot, then provide two examples of effective summaries as part of a few-shot prompt.
Instructions:
- For zero-shot, simply provide the prompt.
- For few-shot, include two example summaries before asking for a new one.
Solution:
# Zero-shot Prompting
response_zero_shot = openai.ChatCompletion.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Summarize three benefits of remote work."}],
max_tokens=100,
temperature=0.6
)
print("Zero-shot Response:")
print(response_zero_shot["choices"][0]["message"]["content"])
# Few-shot Prompting
response_few_shot = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are an efficient content generator."},
{"role": "user", "content": (
"Example 1: Remote work enhances flexibility by reducing commute time, allows for a better work-life balance, and can lead to increased productivity due to a personalized work environment.\n\n"
"Example 2: The benefits of remote work include the ability to work from anywhere, lower operating costs for businesses, and the opportunity for employees to create a better personal schedule.\n\n"
"Now, please provide a new summary of three benefits of remote work."
)}
],
max_tokens=120,
temperature=0.6
)
print("\nFew-shot Response:")
print(response_few_shot["choices"][0]["message"]["content"])
Exercise 4: Applying Chain-of-Thought Prompting
Task:
Ask the model to solve a logical problem by reasoning through steps. For example: "Explain step-by-step how you would determine if a number is prime."
Instructions:
- Use a system message to prompt the assistant to think in a chain-of-thought.
- Formulate the user prompt to request a detailed, step-by-step explanation.
Solution:
response_chain = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a logical problem-solving assistant who explains every step in detail."},
{"role": "user", "content": "Explain step-by-step how you would determine if the number 29 is prime."}
],
max_tokens=200,
temperature=0.5
)
print("Chain-of-thought Response:")
print(response_chain["choices"][0]["message"]["content"])
Exercise 5: Iterative Prompt Refinement
Task:
Start with a basic prompt asking for a summary of the latest trends in artificial intelligence. Then refine it iteratively to include details such as key technologies and potential impacts. Submit both the basic and refined prompts.
Instructions:
- First, send a basic prompt and capture the response.
- Then, update the prompt by adding additional context and constraints.
- Compare the outputs.
Solution:
# Basic prompt for AI trends
basic_prompt = "Summarize the latest trends in artificial intelligence."
response_basic = openai.ChatCompletion.create(
model="gpt-4o",
messages=[{"role": "user", "content": basic_prompt}],
max_tokens=150,
temperature=0.6
)
print("Basic Prompt Response:")
print(response_basic["choices"][0]["message"]["content"])
# Refined prompt with more context
refined_prompt = (
"Summarize the latest trends in artificial intelligence, including key technologies such as natural language processing, "
"computer vision, and reinforcement learning. Also, discuss potential impacts on industries like healthcare and finance."
)
response_refined = openai.ChatCompletion.create(
model="gpt-4o",
messages=[{"role": "user", "content": refined_prompt}],
max_tokens=200,
temperature=0.6
)
print("\nRefined Prompt Response:")
print(response_refined["choices"][0]["message"]["content"])
If you have successfully completed these exercises, congratulations! You’ve now practiced a range of prompt engineering techniques—from crafting effective prompts and utilizing system messages, to experimenting with zero-shot, few-shot, and chain-of-thought prompting. These exercises empower you to create refined interactions tailored to your application’s needs.
Armed with these skills, you're ready to move forward and further enhance your AI applications. Keep experimenting, refining your prompts, and building engaging, efficient interactions with the Chat Completions API.