새소식

딥러닝, 머신러닝/프롬프트 엔지니어링

개발자를 위한 챗 GPT 프롬프트 엔지니어링 #2. Guidelines

  • -

https://www.deeplearning.ai/short-courses/chatgpt-prompt-engineering-for-developers/

chatGPT prompt Engineering for Developers 영상 강의를 듣고 정리한 내용입니다. 
(무료, 한글자막)

 

 

앤드류 응 교수님과 OpenAI 기술 이사(이사 풀포드)님이 같이 설명해주는 강의로, 개발자를 위한 프롬프트 엔지니어링 팁을 다루고 있다. 이 분들이 설명하는 LLM을 사용할 때 알아야 할 2가지 원칙은 다음과 같다.

 

 

1. 명확하고 구체적으로 지시해라 : 신입생에게 과제를 주는 교수님이라 생각해보자.

2. 모델에게 생각할 시간을 줘라 : 복잡한 작업은 단계를 나눠서 전달해라.

 

 


 

1. 명확하게 하기

1-1) 문장 영역을 기호로 확실하게 구분하기

예시 : "3개의 backtick(```)으로 감싸진 걸 1문장으로 요약해라" 라고 전달해서 참고할 단락이 별도로 있다는 걸 명시하는 게 좋다.

 

text = f"""
You should express what you want a model to do by \ 
providing instructions that are as clear and \ 
specific as you can possibly make them. \ 
This will guide the model towards the desired output, \ 
and reduce the chances of receiving irrelevant \ 
or incorrect responses. Don't confuse writing a \ 
clear prompt with writing a short prompt. \ 
In many cases, longer prompts provide more clarity \ 
and context for the model, which can lead to \ 
more detailed and relevant outputs.
"""
prompt = f"""
Summarize the text delimited by triple backticks \ 
into a single sentence.
```{text}```
"""
response = get_completion(prompt)
print(response)

 

[결과]

Providing clear and specific instructions to a model will guide it towards the desired output, reducing the chances of irrelevant or incorrect responses, and longer prompts can provide more clarity and context for more detailed and relevant outputs.

 

 

1-2) JSON 포맷으로 결과 출력하기 

"Provide them in JSON format with the following keys: book_id, title, author, genre" 라고 JSON 포맷과 key ID 값을 명시해서 전달한다.

import openai
import os

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

openai.api_key  = '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"]

prompt = f"""
Generate a list of three made-up book titles along \ 
with their authors and genres. 
Provide them in JSON format with the following keys: 
book_id, title, author, genre.
"""
response = get_completion(prompt)
print(response)

 

[결과]

[
    {
        "book_id": 1,
        "title": "The Midnight Garden",
        "author": "Elena Rivers",
        "genre": "Fantasy"
    },
    {
        "book_id": 2,
        "title": "Echoes of the Past",
        "author": "Nathan Black",
        "genre": "Mystery"
    },
    {
        "book_id": 3,
        "title": "Whispers in the Wind",
        "author": "Samantha Reed",
        "genre": "Romance"
    }
]

 

 

1-3) 단계별로 내용 요약하기 : 레시피 요약 등을 해서 가독성 좋게 만들어 줄 수 있음

text_1 = f"""
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.
"""
prompt = f"""
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:

1 - ...
2 - …
…
N - …

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

\"\"\"{text_1}\"\"\"
"""
response = get_completion(prompt)
print("Completion for Text 1:")
print(response)

 

[결과]

Completion for Text 1:
1 - Get some water boiling.
2 - Grab a cup and put a tea bag in it.
3 - Pour the hot water over the tea bag.
4 - Let the tea steep for a bit.
5 - Take out the tea bag.
6 - Add sugar or milk to taste.
7 - Enjoy your delicious cup of tea.

 

 

1-4) 비슷한 톤으로 대화 이어가기

: "Your task is to answer in a consistent style." 로 계속 비슷한 톤으로 대답하란 걸 명시했다. 초반에 SYSTEM 으로 정보를 주고, 이런 대화를 몇개 만들어주면 상담 챗봇으로도 활용이 가능할 것 같다.

prompt = f"""
Your task is to answer in a consistent style.

<child>: Teach me about patience.

<grandparent>: The river that carves the deepest \ 
valley flows from a modest spring; the \ 
grandest symphony originates from a single note; \ 
the most intricate tapestry begins with a solitary thread.

<child>: Teach me about resilience.
"""
response = get_completion(prompt)
print(response)

 

[결과]

<grandparent>: The tallest trees withstand the strongest winds; the brightest stars shine through the darkest nights; the strongest hearts endure the toughest trials.

 

 


 

2. 모델에게 생각할 시간 주기

한 번에 처리하기 힘들고, 여러 단계를 거쳐서 해야 하는 복잡한 작업은 단계별로 할 일들을 명시해 주는 게 좋다.

아래 예시에서는 이런 단계를 거친다.

 

1. 글을 1문장으로 요약하기

2. 요약을 프랑스어로 번역하기

3. 프랑스 요약문에서 이름들을 목록화하기

4. 결과물을 JSON 형식으로 출력하기 (key : french_summary, num_names) : 이름별로 나온 횟수를 출력

text = f"""
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.
"""
# example 1
prompt_1 = f"""
Perform the following actions: 
1 - Summarize the following text delimited by triple \
backticks 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.

Separate your answers with line breaks.

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

 

 

강의에서는 모델의 한계로 "할루시네이션(환각)"을 지적하고 있다. 할루시네이션은 모델이 잘 알지 못하는 주제에 관한 질문이 주어질 때 사실은 아니지만 그럴듯해 보이는 답변을 하는 걸 말한다.

 

할루시네이션 예시

 

Chat GPT로 블로그 글이나, 전자책을 쓴다는 사람들이 이런 방식을 많이 사용하는 것 같다. 그럴 듯해 보여서 초안 만들거나, 아이디어 잡기에 좋을 것 같다. 확실히 카피라이팅 같은 작업들은 공부와 경험이 많이 필요한데 Chat GPT만 잘 써도 많이 보완이 될 수 있다. 현재 LLM을 쓰려는 회사들도 많아지는 만큼 프롬프트 엔지니어링을 알아두는 것도 많은 도움이 될 것 같다. 덕분에 더 많은 기회가 생길 것 같다. 

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.