본문 바로가기
데이터과학/GPT 활용

효율적인 프롬프트 엔지니어링을 위한 가이드라인

by 경성현 2023. 5. 3.

거대 언어 모델(Large Language Model, LLM)이 잘 이해할 수 있는 형태로 질문(a.k.a 프롬프트 작성)을 하기 위한 두가지 원칙이 있습니다. 두가지 원칙을 다루기 전에, 가장 기본이 되는 원칙은 ‘프롬프트를 영어로 작성하라’ 입니다. 네이버에서 출시한 하이버 클로바에게 질의 한다면, 한글로 질의하고 응답을 받는게 자연스럽겠지만, ChatGPT는 영어로 질의해야 더 잘 알아듣고, 더 잘 대답해줍니다. 이제 좋은 프롬프트 작성을 위한 첫번째 원칙에 대해서 이야기 해 보겠습니다.

1. 명료하면서 구체적으로 질문하라

💡 좋은 프롬프트 작성을 위한 첫번째 원칙은 “명료하면서 구체적으로 질문하라”입니다. 그런데 여기서 명료하게(clear) 질문하는 것은 질문이 짧은 것을 의미하지는 않습니다.

1-1: 구분자를 사용하여 정보영역을 표기하라

명료하고 구체적인 질문을 위해 프롬프트 엔지니어링을 위한 전략이 몇가지 있습니다.

구분자는 어떤 것이든지 사용 가능하며, 다음과 같은 기호들이 있습니다. trible backticks (```), triple quotes ("""), braket (< >), <tag> </tag>, :

ChatGPT 프롬프트에 최근 뉴스를 요약해달라는 요청을 아래와 같이 해봤습니다.

🗣 Summarize the text delimited by triple backticks into a single sentence.

‘’’
Federal Reserve Chairman Jerome Powell will likely maintain the door open to different scenarios. Inflation has been easing at a slower-than-anticipated pace, so it is possible that Powell & co decide to condition additional tightening to data. But caution should prevail. Another American bank collapsed between the March meeting and this one, and the Fed could not ignore the fact that the problem is far from over.
Chances of a 25 bps rate hike stand above 85%, which means such action will hardly affect the US Dollar, as it has already been priced in. Should the central bank decide differently, hell could break loose across the FX board. It could sound crazy even to consider it, but the Reserve Bank of Australia (RBA) did so on Tuesday, surprising financial markets with a 50 bps hike. Indeed, Australian and American conditions are quite different, but well, the Australian central bank showed market players that every option is on the table in a central bank meeting.
Anyway, with the expected hike, the focus will shift to whatever Chairman Powell has to say on the future of monetary policy and how concerned policymakers are about the financial situation. It will be quite difficult to calm down markets, but if someone can do it, it is Powell.
‘’’
♻️ The Federal Reserve is likely to keep options open and proceed cautiously with any further tightening of monetary policy, with a predicted 85% chance of a 25 bps rate hike, and attention turning to Chairman Jerome Powell's statements on the future of monetary policy and concerns about the financial situation, as the Fed cannot ignore the fact that another American bank has collapsed between the March and present meetings.

프롬프트에서 따옴표(```)로 표기되어 있는 뉴스 내용을 짧게 요약해 주었습니다. 요약된 내용을 한글로 번역해보니 아래와 같은 내용이네요.

♻️ 연방준비제도이사회(FRB)는 옵션을 열어두고 추가 통화정책 긴축을 조심스럽게 진행할 가능성이 높아 25bp의 금리인상 가능성이 85%로 점쳐지고 있으며, 제롬 파월 의장의 통화정책의 미래와 금융상황에 대한 우려에 관심이 쏠리고 있다, 연준이 3월과 현재 회의 사이에 또 다른 미국 은행이 무너졌다는 사실을 무시할 수 없기 때문이다.

1-2: 가능하다면 구조화된 형태의 결과를 요청하라

ChatGPT에게 책 제목 3개를 생성하도록 지시할 수 있습니다. 이때, 생성한 책 제목의 장르와 줄거리도 함께 작성하도록 요청할 수 있는데요. 그 결과는 JSON 형태의 구조화된 양식으로 도출하는 것이 가능합니다. 이런 경우 아래와 같이 요청 내용의 맨 마지막에 “Provide them in JSON format with the following keys: key1_nm, key2_nm, key3_nm”과 같이 프롬프트를 작성해 주면 됩니다.

🗣 Generate a list of three made-up book titles along \
with their genre and 100-word summary.
Provide them in JSON format with the following keys:
book_id, title, genre, summary.
♻️ Here are three made-up book titles with their respective genres and summaries in JSON format:
{
"book_id": 1,
"title": "The Shadow Conspiracy",
"genre": "Thriller",
"summary": "When a young journalist uncovers a plot to control the world's most powerful governments, she must go on the run to expose the truth before it's too late. With danger lurking around every corner, she teams up with a mysterious underground group to unravel the conspiracy and prevent global catastrophe."
}

{
"book_id": 2,
"title": "Echoes in the Mist",
"genre": "Romance",
"summary": "After a tragic accident claims the life of her fiancé, a young woman moves to a remote town to start over. There, she meets a ruggedly handsome man who helps her heal and learn to love again. But as they grow closer, they discover dark secrets lurking in the misty woods, threatening to tear them apart."
}

{
"book_id": 3,
"title": "Quantum Dreams",
"genre": "Science Fiction",
"summary": "In the near future, a breakthrough in quantum computing allows humans to enter a virtual reality world where anything is possible. But when a hacker gains control of the system, the world turns into a nightmare where people's deepest fears come to life. A small group of rebels must fight their way through the virtual reality landscape to stop the hacker before it's too late."
}

 

1-3: 주어진 조건을 만족하는지 물어볼 수 있습니다

줄글로 구성되어 있는 문장을 주고, 해당 문장이 어떤 절차를 설명하는 것이라면 단계별로 절차를 식별할 수 있도록 문장을 재작성 해달라고 프롬프트를 작성할 수도 있습니다. 이때, 줄글로 되어 있는 문장이 어떤 절차를 설명하는 글이 아니라면, 해당 글에는 절차를 포함하고 있습니다” 라고 간단하게 대답하도록 프롬프트를 작성할 수 있습니다.

🗣 You will be provided with text delimited by triple quotes.
If it contains a sequence of instructions, \
re-write those instructions in the following format:
Step 1 - ...
Step 2 - …

Step N - …
If the text does not contain a sequence of instructions, \
then simply write "No steps provided."

"""
Making a cup of tea is easy! First, you need to get some \
water boiling. While that's happening, \
grab a cup and put a tea bag in it. Once the water is \
hot enough, just pour it over the tea bag. \
Let it sit for a bit so the tea can steep. After a \
few minutes, take out the tea bag. If you \
like, you can add some sugar or milk to taste. \
And that's it! You've got yourself a delicious \
cup of tea to enjoy.
"""
 ♻️ Here are the rewritten instructions in step format:
Step 1 - Get some water boiling.
Step 2 - Grab a cup and put a tea bag in it.
Step 3 - Once the water is hot enough, pour it over the tea bag.
Step 4 - Let it sit for a bit so the tea can steep.
Step 5 - After a few minutes, take out the tea bag.
Step 6 - If you like, add some sugar or milk to taste.
Step 7 - Enjoy your delicious cup of tea!
Note: The instructions are sequential and involve a series of actions that need to be taken in a particular order to make a cup of tea.

위의 프롬프트 예시에서 요약한 뉴스글을 입력으로 줬더니, 해당 글에는 절차가 포함되어 있지 않다고 알려줍니다.

🗣 You will be provided with text delimited by triple quotes. If it contains a sequence of instructions, \ re-write those instructions in the following format:
Step 1 - ...
Step 2 - …

Step N - …
If the text does not contain a sequence of instructions, \
then simply write "No steps provided."

"""
The Federal Reserve is likely to keep options open and proceed cautiously with any further tightening of monetary policy, with a predicted 85% chance of a 25 bps rate hike, and attention turning to Chairman Jerome Powell's statements on the future of monetary policy and concerns about the financial situation, as the Fed cannot ignore the fact that another American bank has collapsed between the March and present meetings.
"""
♻️ No steps provided.
Note: The text contains information and analysis about the Federal Reserve's monetary policy and the potential impacts of a predicted rate hike, but it does not provide a sequence of instructions to follow.

2. 모델이 스스로 생각할 시간을 줘라

💡 좋은 프롬프트 작성을 위한 두번째 원칙은 “모델이 스스로 생각할 수 있도록 시간을 줘라”입니다.

2-1. 과제를 완료하기 위한 단계를 구체화 하라

프롬프트를 통해 ChatGPT에게 어떤 여러가지 질문을 할때는, 단계를 구체화하여 하나씩 답을 만들어 갈 수 있도록 가이드를 주면 좋습니다. 가령 여러 문장으로 되어 있는 영문 텍스트로부터, 해당글을 요약하고, 요약된 내용을 한글로 번역하고, 해당 글에서 등장하는 이름을 추출하는 테스크를 요청하고, 결과는 JSON 형태로 전달받고 싶다면, 아래와 같이 프롬프트를 작성 하면 됩니다.

🗣 Perform the following actions:
1 - Summarize the following text delimited by triple \
backticks into 1 sentence.
2 - Translate the 1 sentence summary into Korean.
3 - List each name in the Korean summary.
4 - Output a json object that contains the following \
keys: korean_summary, num_names.
Separate your answers with line breaks.

Text:
"""
In a charming village, siblings Jack and Jill set out on \
a quest to fetch water from a hilltop \
well. As they climbed, singing joyfully, misfortune \
struck—Jack tripped on a stone and tumbled \
down the hill, with Jill following suit. \
Though slightly battered, the pair returned home to \
comforting embraces. Despite the mishap, \
their adventurous spirits remained undimmed, and they \
continued exploring with delight.
"""
♻️ 1 sentence summary: Siblings Jack and Jill journey to fetch water from a hilltop well, but suffer a misfortune before returning home and continuing their explorations undaunted.
1문장 요약: 형제 자크와 질은 언덕 꼭대기 우물에서 물을 길어오려고 여행을 떠나지만, 불운이 잇따르며 집으로 돌아와서도 모험적인 정신을 잃지 않고 즐겁게 탐험을 이어간다.

Names in Korean summary: 자크(Jack), 질(Jill)

JSON object: { "korean_summary": "형제 자크와 질은 언덕 꼭대기 우물에서 물을 길어오려고 여행을 떠나지만, 불운이 잇따르며 집으로 돌아와서도 모험적인 정신을 잃지 않고 즐겁게 탐험을 이어간다.", "num_names": 2 }

위의 예시에서는 챗GPT가 단계별로 결과를 도출해 줍니다. 이제 결과를 내가 원하는 형식(format)으로 출력해 주도록 프롬프트를 조금 변경해 보겠습니다.

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

Use the following format: 

Text: <text to summarize> 
Summary: <summary> 
Translation: <summary translation> 
Names: <list of names in Korean summary> 
Output JSON: <json with summary and num_names>

Text: < In a charming village, siblings Jack and Jill set out on \
a quest to fetch water from a hilltop \
well. As they climbed, singing joyfully, misfortune \
struck—Jack tripped on a stone and tumbled \
down the hill, with Jill following suit. \
Though slightly battered, the pair returned home to \
comforting embraces. Despite the mishap, \
their adventurous spirits remained undimmed, and they \
continued exploring with delight.>
♻️ Summary: Siblings Jack and Jill journey to fetch water from a hilltop well, but suffer a misfortune before returning home and continuing their explorations undaunted.

Translation: 형제 자크와 질은 언덕 꼭대기 우물에서 물을 길어오려고 여행을 떠나지만, 불운이 잇따르며 집으로 돌아와서도 모험적인 정신을 잃지 않고 즐겁게 탐험을 이어간다.

Names: 자크(Jack), 질(Jill)

Output JSON: { "korean_summary": "형제 자크와 질은 언덕 꼭대기 우물에서 물을 길어오려고 여행을 떠나지만, 불운이 잇따르며 집으로 돌아와서도 모험적인 정신을 잃지 않고 즐겁게 탐험을 이어간다.", "num_names": 2 }

2-2. 제출 답안을 채점하기 전에 챗GPT 자체적으로 정답을 계산해 보도록 지시하기

챗GPT에게 문제를 내주고, 이 문제에 대해 학 생이작한성 답안이 맞는지 채점하도록 요청하는 프롬프트를 작성해 보겠습니다.

🗣 Determine if the student's solution is correct or not.

Question: I'm building a solar power installation and I need \
help working out the financials.
- Land costs $100 / square foot
- I can buy solar panels for $250 / square foot
- I negotiated a contract for maintenance that will cost \
me a flat $100k per year, and an additional $10 / square foot \

What is the total cost for the first year of operations as a function of the number of square feet.

Student's Solution:
Let x be the size of the installation in square feet.
Costs:
1. Land cost: 100x
2. Solar panel cost: 250x
3. Maintenance cost: 100,000 + 100x
Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000 
♻️ The student's solution is correct.

챗GPT는 학생이 제출한 솔루션의 맨 마지막 문장만을 점검했는지 정답이라고 판단했습니다. 하지만, 실제로 계산을해보면 답안이 틀린것을 알 수 있습니다. 이번에는 챗GPT에게 문제를 스스로 풀어 볼 수 있도록 가이드를 주고, 스스로 풀이한 결과와 학생의 솔루션을 비교해서 정답을 판단하도록 요청하는 프롬프트를 작성해 보겠습니다.

🗣 Your task is to determine if the student's solution \
is correct or not. To solve the problem do the following:

First, work out your own solution to the problem.
Then compare your solution to the student's solution \
and evaluate if the student's solution is correct or not.
Don't decide if the student's solution is correct until you have done the problem yourself.

Use the following format:
Question:
<question here>

Student’s solution:
<student’s solution here>

Actual solution:
<steps to work out the solution and your solution here>

In the student’s solution the same as actual solution \
just calculated:
<yes or no>

Student grade:
<correct or incorrect>

Question: <I'm building a solar power installation and I need help \\
working out the financials.
- Land costs $100 / square foot
- I can buy solar panels for $250 / square foot
- I negotiated a contract for maintenance that will cost \\
me a flat $100k per year, and an additional $10 / square \\
foot What is the total cost for the first year of operations \\
as a function of the number of square feet.>

Student's solution:
<Let x be the size of the installation in square feet. Costs:
1. Land cost: 100x
2. Solar panel cost: 250x
3. Maintenance cost: 100,000 + 100x
Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000>

Actual solution:
♻️ Let the size of the installation be x in square feet.
The total cost for the first year of operations can be calculated as follows:
1. Land cost: $100 per square foot, so the total land cost will be 100x dollars.
2. Solar panel cost: $250 per square foot, so the total cost of solar panels will be 250x dollars.
3. Maintenance cost: $100k flat cost per year + $10 per square foot, so the total maintenance cost will be $100k + $10x.
4. Total cost: Add up the three costs calculated above, so the total cost will be:
Total cost = Land cost + Solar panel cost + Maintenance cost
= 100x + 250x + ($100k + $10x)
= 360x + $100k
Therefore, the total cost for the first year of operations is $360x + $100k.
Is the total cost in student’s solution exactly the same as the that of the actual solution just calculated? Yes
Student grade: Correct

챗GPT에게 스스로 문제 풀이를 먼저 하고, 이후에 학생이 제출한 정답과 비교하도록 시켰더니 지시한데로 잘 따라합니다. 챗GPT가 스스로 계산한 정답은 “360x + 100,000”이고, 학생이 제출한 답안은 “450x + 100,000”이라라서, 학생이 제출한 답안과 스스로 풀이한 결과가 다릅니다. 하지만, 챗GPT는 이후의 질문에 대해서 학생의 풀이가 맞았고, 정답이라고 대답하네요. 동일한 openai API (model=“gpt-3.5-turbo”)를 이용하여 동일한 내용을 질의하면, 학생의 대답이 틀렸다고 제대로 대답해 줍니다.

챗GPT 모델이 지닌 한계: 망상(Hallucinations)

챗GPT는 종종 사실이 아닌 그럴듯한 문장을 생성해서 대답해주곤 하는데요, 환각은 그럴듯하게 들리지만 사실이 아닌 진술을 의미합니다.

환각을 줄이려면, 먼저 챗GPT에서 질문과 관련있는 정보를 제공하고, 관련 정보를 기반으로 질문에 대답을 할 수 있도록 프롬프트를 작성하는 훈련을 해야 합니다.

참고) 위의 내용은 파이썬 기반으로 진행하는 DeepLearning.AI의 "ChatGPT Prompt Engineering for Developers" 강의에서 Guideline 부분을 파이썬으로 실습하지 않고 chatgpt 프롬프트에서 테스트 하면서 얻은 결과 입니다.