개발자를 위한 ChatGPT 프롬프트 엔지니어링 (3) 프롬프트 엔지니어링으로 할 수 있는 일

Jiwon Kang·2023년 5월 22일
1
post-thumbnail
  • 아래 내용은 DeepLearning.AI의 <ChatGPT Prompt Engineering for Developers> 강의를 정리한 포스트입니다.
  • 공식 강의 페이지에서 듣는 것을 추천합니다(무료). 한국어는 지원되지 않습니다. 그러나 강의 비디오 옆에 쥬피터 노트북이 함께 제공되며, OpenAI API Key도 무료로 제공됩니다. 로컬에서 실행하고 싶은 경우 아래 포스트를 참조하여 OpenAPI Key를 발급받으세요.
  • 오류나 추가 사항이 있으면 언제든 댓글로 알려주세요 🤗

  • 지난번까지 프롬프트를 작성하는 방법개선하는 방법을 배웠습니다
  • 이번엔은 프롬프트 엔지니어링으로 할 수 있는 작업에 대해 알아봅니다
    • 우리는 LLM과 함께 Summarizing, Inferring, Transforming, Expanding 작업을 수행할 수 있습니다
  • 강의에서는 각각의 작업 예시를 노트북과 함께 제공하고 있는데요. 본 포스트에서는 (1) 사용 사례, (2) 프롬프트 예시를 위주로 정리해 볼게요. 이런게 있구나라면서 적용하고 싶은 사례를 찾아보는 걸 추천합니다.
  • 맨 마지막 Expanding 사례에서는 텍스트 생성 옵션 중 하나인 Temerture 개념도 짚고 넘어가니 처음 들어 본 분들은 확인하고 넘어가길 추천드려요 🤗

Summarizing

사용 사례: 고객 리뷰 요약하기

prod_review = """
Got this panda plush toy for my daughter's birthday, \
who loves it and takes it everywhere. It's soft and \ 
super cute, and its face has a friendly look. It's \ 
a bit small for what I paid though. I think there \ 
might be other options that are bigger for the \ 
same price. It arrived a day earlier than expected, \ 
so I got to play with it myself before I gave it \ 
to her.
"""

프롬프트 예시

  • 리뷰 N자 이내로 요약하기
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: ```{prod_review}```
"""
  • "가격"에 초점을 맞춰 요약하기
prompt = f"""
Your task is to generate a short summary of a product \
review from an ecommerce site to give feedback to the \
pricing deparmtment, responsible for determining the \
price of the product.  

Summarize the review below, delimited by triple 
backticks, in at most 30 words, and focusing on any aspects \
that are relevant to the price and perceived value. 

Review: ```{prod_review}```
"""
  • 리뷰에서 특정 정보(배송 정보)만 추출하기
prompt = f"""
Your task is to extract relevant information from \ 
a product review from an ecommerce site to give \
feedback to the Shipping department. 

From the review below, delimited by triple quotes \
extract the information relevant to shipping and \ 
delivery. Limit to 30 words. 

Review: ```{prod_review}```
"""

Inferring: Sentiment/Emotion Classification, Topic Extraction, Named Entity Recognition

  • 원래는 감성 분석, 개체명 추출 등의 문제는 개별 다운스트림 테스크를 위한 모델을 개발하고 배포하는 것이 일반적이었는데요. 프롬프트만 잘 작성한다면 이러한 작업들 없이 LLM 하나만으로 다운스트림 테스크를 해결할 수도 있습니다

사용 사례 1: 고객 리뷰의 감성, 키워드 분석하기

lamp_review = """
Needed a nice lamp for my bedroom, and this one had \
additional storage and not too high of a price point. \
Got it fast.  The string to our lamp broke during the \
transit and the company happily sent over a new one. \
Came within a few days as well. It was easy to put \
together.  I had a missing part, so I contacted their \
support and they very quickly got me the missing piece! \
Lumina seems to me to be a great company that cares \
about their customers and products!!
"""

사용 사례 1의 프롬프트 예시

  • 긍/부정 분류하기
prompt = f"""
What is the sentiment of the following product review, 
which is delimited with triple backticks?

Review text: '''{lamp_review}'''
"""
  • 관련 감정 추출하기
prompt = f"""
What is the sentiment of the following product review, 
which is delimited with triple backticks?

Review text: '''{lamp_review}'''
"""
  
# output: happy, satisfied, grateful, impressed, content
  • 특정 감정 (anger) 있는지 확인하기
prompt = f"""
Is the writer of the following review expressing anger?\
The review is delimited with triple backticks. \
Give your answer as either yes or no.

Review text: '''{lamp_review}'''
"""
  
# output: No
  • 특정 정보 (구매 아이템, 제조사) 추출하기 = NER
prompt = f"""
Identify the following items from the review text: 
- Item purchased by reviewer
- Company that made the item

The review is delimited with triple backticks. \
Format your response as a JSON object with \
"Item" and "Brand" as the keys. 
If the information isn't present, use "unknown" \
as the value.
Make your response as short as possible.
  
Review text: '''{lamp_review}'''
"""
  • ...그리고 이 모든 걸 멀티테스킹(multi-tasking)으로도 가능합니다
prompt = f"""
Identify the following items from the review text: 
- Sentiment (positive or negative)
- Is the reviewer expressing anger? (true or false)
- Item purchased by reviewer
- Company that made the item

The review is delimited with triple backticks. \
Format your response as a JSON object with \
"Sentiment", "Anger", "Item" and "Brand" as the keys.
If the information isn't present, use "unknown" \
as the value.
Make your response as short as possible.
Format the Anger value as a boolean.

Review text: '''{lamp_review}'''
"""

사용 사례 2: 뉴스 주제 분석하기

story = """
In a recent survey conducted by the government, 
public sector employees were asked to rate their level 
of satisfaction with the department they work at. 
The results revealed that NASA was the most popular 
department with a satisfaction rating of 95%.

One NASA employee, John Smith, commented on the findings, 
stating, "I'm not surprised that NASA came out on top. 
It's a great place to work with amazing people and 
incredible opportunities. I'm proud to be a part of 
such an innovative organization."

The results were also welcomed by NASA's management team, 
with Director Tom Johnson stating, "We are thrilled to 
hear that our employees are satisfied with their work at NASA. 
We have a talented and dedicated team who work tirelessly 
to achieve our goals, and it's fantastic to see that their 
hard work is paying off."

The survey also revealed that the 
Social Security Administration had the lowest satisfaction 
rating, with only 45% of employees indicating they were 
satisfied with their job. The government has pledged to 
address the concerns raised by employees in the survey and 
work towards improving job satisfaction across all departments.
"""

사용 사례 2의 프롬프트 예시

  • 주제어(5개) 찾아내기
prompt = f"""
Determine five topics that are being discussed in the \
following text, which is delimited by triple backticks.

Make each item one or two words long. 

Format your response as a list of items separated by commas.

Text sample: '''{story}'''
"""
  • 위의 프롬프트를 이용하면 관심있을 만한 주제의 뉴스기사를 알려주는 알림 기능도 만들 수 있습니다
    • 먼저 프롬프트를 통해 뉴스기사의 주제어를 추출하고
    • 추출된 주제어 중에서 관심 키워드가 있으면 알려주는 식으로요

Transforming: Translation, Tone Transformation, Format Conversion, Spellcheck/Grammar check

번역 관련 프롬프트 예시

  • 언어 인식하기
prompt = f"""
Tell me which language this is: 
```Combien coûte le lampadaire?```
"""
  • 번역 하기
prompt = f"""
Translate the following English text to Spanish: \ 
```Hi, I would like to order a blender```
"""

스타일 변환 관련 프롬프트 예시

  • 정중한 비즈니스 이메일 스타일로 수정하기
prompt = f"""
Translate the following from slang to a business letter: 
'Dude, This is Joe, check out this spec on this standing lamp.'
"""

형식 변환 관련 프롬프트 예시

  • JSON을 HTML Table로 변경하기
data_json = { "resturant employees" :[ 
    {"name":"Shyam", "email":"shyamjaiswal@gmail.com"},
    {"name":"Bob", "email":"bob32@gmail.com"},
    {"name":"Jai", "email":"jai87@gmail.com"}
]}

prompt = f"""
Translate the following python dictionary from JSON to an HTML \
table with column headers and title: {data_json}
"""

문법 수정 관련 프롬프트 예시

prompt = f"""Proofread and correct the following text
    and rewrite the corrected version. If you don't find
    and errors, just say "No errors found". Don't use 
    any punctuation around the text:
    ```{t}```"""

Expanding

  • 확장 관련 테스크는 짧은 문장에서 긴 문장으로 가야하는 생성 작업들을 의미합니다. 어떤 주제에 대해 써줘!라고 쓰면 원하는 텍스트를 생성해주는 사례인데요.
  • 이 작업을 위해서 temperature라는 개념을 짚고 넘어가보도록 합시다
  • temperature가 모델은 다양한 생성 결과를 제공합니다 높아질수록 모델이 다양한 텍스트를 생성. 아래 그림에서 temperature 값에 따른 생성 텍스트 변화를 참고해보세요

  • 만약 우리가 LLM을 사용하려는 사례가 답변의 다양성, 창의성이 요구되면 temperature을 높이고, 답변의 신뢰성, 예측가능성이 요구되면 temperature을 0로 설정해두는 걸 추천합니다
  • temperature 설정은 프롬프트가 아닌 API 설정에서 할 수 있습니다
def get_completion(prompt, model="gpt-3.5-turbo",temperature=0): # Andrew mentioned that the prompt/ completion paradigm is preferable for this class
    messages = [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=temperature, # 여기!
    )
    return response.choices[0].message["content"]

고객의 이메일의 긍부정에 따라 이메일 작성해주는 프롬프트 예시

prompt = f"""
You are a customer service AI assistant.
Your task is to send an email reply to a valued customer.
Given the customer email delimited by ```, \
Generate a reply to thank the customer for their review.
If the sentiment is positive or neutral, thank them for \
their review.
If the sentiment is negative, apologize and suggest that \
they can reach out to customer service. 
Make sure to use specific details from the review.
Write in a concise and professional tone.
Sign the email as `AI customer agent`.
Customer review: ```{review}```
Review sentiment: {sentiment}
"""

profile
도파민 중독

0개의 댓글