ChatGPT Prompt Engineering For Developers

Srimathi Jagadeesan
hackgenius
Published in
9 min readJun 12, 2023

I’ll walk you through about ChatGPT Prompt Engineering for Developers.

ChatGPT Prompts

We’ll be discussing about writing clear prompts for Large Language Models (LLMS). Okay then, let’s dive into the content.

What is Prompt Engineering?

Prompt engineering is the process of creating prompts that help large language models (LLMs) generate text, content, translate languages, write different kinds of creative content, and answer your questions in an informative way. Prompts are essentially instructions that tell the LLM what to do.

First You’ll learn some of prompting best practices & use cases like summarizing, inferring, transforming, expanding.

LLMs….

There have been broadly two types of LLMs,

1.Base LLMs
2.Instruction Tuned LLMs

Base LLMs:

Base LLM has been trained to predict the next word based on text training data, often trained on a large amount of data from the internet and other sources to figure out what’s the next most likely word to follow.

Example Prompt,

What is the Capital Of Tamil Nadu?

The result might be...,

1.What is the Tamil Nadu's population?

2.What are some popular tourist attractions in Tamil Nadu?

3.What are some famous festivals celebrated in Tamil Nadu?

Instruction Tuned LLMs:

Tries to follow instructions, Fine-tune on instructions & good attempts at following those instructions.

What is the Capital Of Tamil Nadu?

The result might be ...,

The Capital of Tamil Nadu is Chennai.

Guidelines For Prompting

In this section, we’ll practice two prompting principles and their related tactics in order to write clear & effective prompts for large language models.

Firstly , Load API Keys & Python Libraries. Here you can use Jupyter Notebook Environment for writing Prompts.

We will use Open AI’s GPT 3.5 turbo model,

First run this code,

import openai
import os

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())

openai.api_key = os.getenv('OPENAI_API_KEY')
def get_completion(prompt, model="gpt-3.5-turbo"):
messages = [{"role": "user", "content": prompt}]
response = openai.ChatCompletion.create(
model=model,
messages=messages,
temperature=0, # this is the degree of randomness of the model's output
)
return response.choices[0].message["content"]

Prompting Principles….

P1: Write clear and specific instructions
P2: Give the model time to “think”

P1-Write Clear & Specific Instructions:

=> Use delimiters ,

Delimiters can be anything like: ```, “””, < >, <tag> </tag>, :

Let’s get into the code,

text = f"""
NASA, the National Aeronautics and Space Administration,\
stands as a beacon of human ingenuity and exploration.\
For over six decades, this renowned agency has spearheaded groundbreaking \
research and pushed the boundaries of scientific knowledge. \
With a mission to understand and unravel the mysteries of the universe, \
NASA has become synonymous with innovation, technological\ advancement, and
space exploration. Through its diverse array of missions, both manned and
unmanned, NASA has revolutionized our understanding of space, brought us
closer to other celestial bodies, and expanded the horizons of human
possibility. From the iconic Apollo moon landings to the launch of the\
Hubble Space Telescope and the ongoing pursuit of Mars exploration,\
NASA's contributions have shaped our understanding of the cosmos and \
inspired generations to reach for the stars. With each mission,\
NASA reaffirms its commitment to pushing the frontiers of scientific \
discovery and fostering a sense of wonder and awe in all those who gaze \
skyward.
"""
prompt = f"""
Summarize the text delimited by triple backticks \
into a single sentence.

```{text}```

"""
response = get_completion(prompt)
print(response)
Response :

NASA is a renowned agency that has spearheaded groundbreaking research and pushed the boundaries of scientific knowledge through its diverse array of missions,
both manned and unmanned, revolutionizing our understanding of space, bringing us closer to other celestial bodies,
and expanding the horizons of human possibility.

=> Ask for a structured output,

JSON, HTML

prompt = f"""
Generate a list of freedom fighters along \
with their book names and genres.
Provide them in JSON format with the following keys:
freedom fighter name, title, author, genre.
"""
response = get_completion(prompt)
print(response)
Response :

[
{
"freedom fighter name": "Nelson Mandela",
"title": "Long Walk to Freedom",
"author": "Nelson Mandela",
"genre": "Autobiography"
},
{
"freedom fighter name": "Mahatma Gandhi",
"title": "The Story of My Experiments with Truth",
"author": "Mahatma Gandhi",
"genre": "Autobiography"
},
{
"freedom fighter name": "Martin Luther King Jr.",
"title": "Stride Toward Freedom: The Montgomery Story",
"author": "Martin Luther King Jr.",
"genre": "Memoir"
},
{
"freedom fighter name": "Rosa Parks",
"title": "Quiet Strength: The Faith, the Hope, and the Heart of a Woman Who Changed a Nation",
"author": "Rosa Parks",
"genre": "Memoir"
},
{
"freedom fighter name": "Malcolm X",
"title": "The Autobiography of Malcolm X",
"author": "Malcolm X and Alex Haley",
"genre": "Autobiography"
}
]

P2-Give the model time to “think”:

=> Specify the steps required to complete a task,

text = f"""
NASA, the National Aeronautics and Space Administration,\
stands as a beacon of human ingenuity and exploration.\
For over six decades, this renowned agency has spearheaded groundbreaking \
research and pushed the boundaries of scientific knowledge. \
With a mission to understand and unravel the mysteries of the universe, \
NASA has become synonymous with innovation, technological\ advancement, and
space exploration. Through its diverse array of missions, both manned and
unmanned, NASA has revolutionized our understanding of space, brought us
closer to other celestial bodies, and expanded the horizons of human
possibility. From the iconic Apollo moon landings to the launch of the\
Hubble Space Telescope and the ongoing pursuit of Mars exploration,\
NASA's contributions have shaped our understanding of the cosmos and \
inspired generations to reach for the stars. With each mission,\
NASA reaffirms its commitment to pushing the frontiers of scientific \
discovery and fostering a sense of wonder and awe in all those who gaze \
skyward.
"""
# example 1
prompt_1 = f"""
Perform the following actions:
1 - Summarize the following text delimited by triple \
backticks with 2 sentence.
2 - Translate the summary into Tamil.


Separate your answers with line breaks.

Text:
```{text}```
"""
response = get_completion(prompt_1)
print("Completion for prompt 1:")
print(response)
Response :

Completion for prompt 1:
NASA has been at the forefront of space exploration for over six decades, pushing the boundaries of scientific knowledge and inspiring generations to reach for the stars. Through its diverse array of missions, both manned and unmanned, NASA has revolutionized our understanding of space and expanded the horizons of human possibility.

NASA, பிரபலமான நிறுவனமாக நிலையான பூமியின் பிரகாசமான மர்மங்களை புரிந்து கொள்ள மிரட்டுகிற ஒரு மதிப்புரையாளர் மற்றும் பயணத் தொடர்பான பல முறைகளில் நடத்தப்பட்ட மிகப் பெரிய பயணங்களின் மூலம் பூமியின் பிரகாசமான மர்மங்களை புரிந்து கொள்ள முயற்சிக்கின்றன.

=> Ask for a output in a Specified Format,

prompt_2 = f"""
Your task is to perform the following actions:
1 - Summarize the following text delimited by
<> with 1 sentence.
2 - Translate the summary into French.
3 - List each name in the French summary.
4 - Output a json object that contains the
following keys: french_summary, num_names.

Use the following format:
Text: <text to summarize>
Summary: <summary>
Translation: <summary translation>
Names: <list of names in Italian summary>
Output JSON: <json with summary and num_names>

Text: <{text}>
"""
response = get_completion(prompt_2)
print("\nCompletion for prompt 2:")
print(response)
Response :

Completion for prompt 2:
Summary: NASA has been at the forefront of space exploration for over six decades, revolutionizing our understanding of the cosmos and inspiring generations to reach for the stars.
Translation: La NASA est à l'avant-garde de l'exploration spatiale depuis plus de six décennies, révolutionnant notre compréhension de l'univers et inspirant des générations à atteindre les étoiles.
Names: NASA
Output JSON: {"french_summary": "La NASA est à l'avant-garde de l'exploration spatiale depuis plus de six décennies, révolutionnant notre compréhension de l'univers et inspirant des générations à atteindre les étoiles.", "num_names": 1}

Summarizing 📝

In this section , We will summarize text with a focus on specific topics.

Let’s dive into the sample one,

Laptop_review = """
I recently purchased the Lenovo IdeaPad 5 laptop, and I have been thoroughly impressed with its performance and features. This laptop offers a perfect balance of power, portability, and affordability, making it a fantastic choice for both work and entertainment.\
The first thing that stood out to me is the sleek and modern design of the IdeaPad 5. The slim profile and lightweight construction make it highly portable, ideal for users who are constantly on the go. The build quality is excellent, with a sturdy chassis that feels durable and capable of withstanding daily use.\
The display on this laptop is simply stunning. The 15.6-inch Full HD IPS panel offers vibrant colors, sharp details, and wide viewing angles. Whether I'm working on spreadsheets, watching movies, or editing photos, the display delivers a fantastic visual experience.\
Performance-wise, the IdeaPad 5 doesn't disappoint. Equipped with an Intel Core i5 processor and 8GB of RAM, it handles multitasking with ease. I experienced smooth and responsive performance, even when running demanding applications or working on multiple browser tabs simultaneously. The integrated Intel graphics are suitable for casual gaming and video streaming\.
Another standout feature of the IdeaPad 5 is its battery life. With moderate usage, I was able to get around 8-10 hours of battery life, which is impressive for a laptop in this price range. It allows me to work or enjoy entertainment for extended periods without constantly worrying about finding a power outlet.\
The keyboard on this laptop is comfortable and well-spaced, providing a satisfying typing experience. The keys are backlit, making it convenient to work in low-light environments. The touchpad is responsive and accurate, supporting multi-touch gestures for smooth navigation.\
In terms of connectivity, the IdeaPad 5 offers a good range of ports, including USB-C, USB-A, HDMI, and an SD card reader. It also has built-in Wi-Fi and Bluetooth for seamless wireless connectivity.\
Overall, the Lenovo IdeaPad 5 is an excellent laptop that offers a compelling combination of performance, portability, and affordability. Whether you're a student, a professional, or a casual user, this laptop delivers reliable performance and a great user experience. It's a solid investment that provides excellent value for the price.\
Please note that this review is fictional and not based on an actual Lenovo IdeaPad 5 model.
"""
prompt = f"""
Your task is to generate a short summary of a product \
review from an ecommerce site.

Summarize the review below, delimited by triple
backticks, in at most 30 words.

Review: ```{Laptop_review}```
"""

response = get_completion(prompt)
print(response)
Response :

The Lenovo IdeaPad 5 laptop offers a perfect balance of power, portability,
and affordability, with a sleek design, stunning display, smooth performance, long battery life, and
comfortable keyboard. It's an excellent investment that provides excellent
value for the price.

Inferring….

So , In this part we will infer sentiment and topics from product reviews and articles.

The sample code,

product_review = """
I recently purchased the Algebraic Wireless Bluetooth Speaker, and\
I must say it has exceeded my expectations in every way.\
This portable speaker has quickly become my go-to audio companion,\
and here's why I absolutely love it.First and foremost, \
the sound quality of the speaker is exceptional. \
Despite its compact size, it delivers powerful and immersive audio.\
The bass is deep and punchy, while the midrange and treble frequencies \
are well-balanced, resulting in a rich and full-bodied sound.\
Whether I'm listening to my favorite music genres or enjoying a podcast, \
the speaker reproduces every nuance with incredible clarity.\
The wireless connectivity of this speaker is a breeze\.
Pairing my smartphone or tablet with the speaker is quick and \
hassle-free. Once connected, I experience a stable and reliable \
Bluetooth connection, allowing me to move around freely without\
any audio interruptions or dropouts. Additionally, \
the speaker has an impressive wireless range, ensuring I \
can keep my device at a distance without losing connection quality.\
"""
prompt = f"""
What is the sentiment of the following product review,
which is delimited with triple backticks?

Review text: '''{product_review}'''
"""
response = get_completion(prompt)
print(response)
Response:
The sentiment of the product review is positive.

Transforming

In this section, We will explore how to use Large Language Models for text transformation tasks such as language translation, spelling and grammar checking.

Example 1

prompt = f"""
Translate the following English text to Bengali: \
```Hi, Can you explain me about generative AI?```
"""
response = get_completion(prompt)
print(response)
Response :
হাই, আপনি কি জেনারেটিভ এআই সম্পর্কে আমাকে ব্যাখ্যা করতে পারেন?
Example 2

prompt = f"""
Find out the language:
```வணக்கம் என் பெயர் ஜான்```
"""
response = get_completion(prompt)
print(response)
Response :

The language is Tamil.
Example 3

prompt = f"""
Translate the following text to Tamil and Sanskrit
and English pirate: \
```I want to buy a new Laptop```
"""
response = get_completion(prompt)
print(response)
Response :

Tamil: நான் புதிய லேப்டாப் வாங்க வேண்டும் (Nāṉ puṭiya lēpṭāp vāṅga vēṇṭum)

Sanskrit: अहं नवं लैपटॉपं खरीदितुं इच्छामि (Ahaṃ navaṃ laipṭaṭōpaṃ kharīdituṃ icchāmi)

English: I want to buy a new Laptop.

Finally , I’ll make a blog on Expanding and the Chat Format soon. Thank you for taking the time to read this blog, and I hope it provided you with the information you were seeking.

HAPPY LEARNING!

--

--

Srimathi Jagadeesan
hackgenius

Conversational AI || Mentored 500+ Students || Bot Builder|| Tech blogger|| Technical Trainer || Self learner.