Haru's 개발 블로그

Andrew Ng(앤드류 응) 프롬프트 엔지니어링 강의 요약(2) 본문

머신러닝 & 딥러닝/LLM

Andrew Ng(앤드류 응) 프롬프트 엔지니어링 강의 요약(2)

Haru_29 2023. 9. 19. 02:22

앞의 강의에 이어서 작성하면 프롬프트를 작성할 때 첫 번째 프롬프트가 작동하는지 여부는 중요하지 않습니다. 
가장 중요한 것은 애플리케이션에 적합한 프롬프트를 얻는 과정입니다.   


머신러닝 개발에서는 종종 아이디어를 가지고 그것을 구현한다는 다이어그램을 본 적이 있을 것입니다. 
즉, 코드를 작성하고, 데이터를 얻고, 모델을 훈련시키면 실험 결과를 얻을 수 있습니다. 
그리고 그 출력을 보고, 오류 분석을 하거나, 어떤 부분이 작동하거나 작동하지 않는지 파악하고, 
어떤 문제를 해결하려는지 또는 어떻게 접근할지에 대한 아이디어를 변경할 수도 있습니다. 
그리고 구현을 변경하고 다른 실험을 실행하고, 효과적인 머신러닝 모델을 얻기 위해 반복적으로 진행합니다. 
원하는 작업을 생각하고, 그 작업을 완료하기 위해 첫 번째 프롬프트를 작성해 보는 것입니다. 

이는 명확하고 구체적이어야 하며, 적절하다면 시스템에 생각할 시간을 줍니다. 그런 다음 실행하여 결과를 확인할 수 있습니다. 

반복적으로 프롬프트를 정제하기


처음에 잘 작동하지 않는다면, 예를 들어 명령이 충분히 명확하지 않았거나, 알고리즘에게 충분한 시간을 주지 않았다는 이유를 파악하는 반복적인 과정을 통해 아이디어를 정제하고, 프롬프트를 정제할 수 있습니다. 이 과정을 여러 번 반복하여 애플리케이션에 적합한 프롬프트를 만들 수 있습니다. 
이것이 바로 개인적으로 인터넷 기사에 그렇게 많은 주의를 기울이지 않는 이유입니다.

왜냐하면, 완벽한 프롬프트라는 것이 모든 것에 대해 존재하지 않을 것이라고 생각하기 때문입니다. 
특정 애플리케이션에 대한 좋은 프롬프트를 개발하는 과정을 가지는 것이 더 중요합니다. 

fact_sheet_chair = """
OVERVIEW
- Part of a beautiful family of mid-century inspired office furniture, 
including filing cabinets, desks, bookcases, meeting tables, and more.
- Several options of shell color and base finishes.
- Available with plastic back and front upholstery (SWC-100) 
or full upholstery (SWC-110) in 10 fabric and 6 leather options.
- Base finish options are: stainless steel, matte black, 
gloss white, or chrome.
- Chair is available with or without armrests.
- Suitable for home or business settings.
- Qualified for contract use.

CONSTRUCTION
- 5-wheel plastic coated aluminum base.
- Pneumatic chair adjust for easy raise/lower action.

DIMENSIONS
- WIDTH 53 CM | 20.87”
- DEPTH 51 CM | 20.08”
- HEIGHT 80 CM | 31.50”
- SEAT HEIGHT 44 CM | 17.32”
- SEAT DEPTH 41 CM | 16.14”

OPTIONS
- Soft or hard-floor caster options.
- Two choices of seat foam densities: 
 medium (1.8 lb/ft3) or high (2.8 lb/ft3)
- Armless or 8 position PU armrests 

MATERIALS
SHELL BASE GLIDER
- Cast Aluminum with modified nylon PA6/PA66 coating.
- Shell thickness: 10 mm.
SEAT
- HD36 foam

COUNTRY OF ORIGIN
- Italy
"""
prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.

Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.

Technical specifications: ```{fact_sheet_chair}```
"""
response = get_completion(prompt)
print(response)
Introducing our stunning mid-century inspired office chair, the perfect addition to any home 
or business setting. This chair is part of a beautiful family of office furniture, including 
filing cabinets, desks, bookcases, meeting tables, and more, all designed with a timeless 
mid-century aesthetic.

One of the standout features of this chair is the variety of customization options available. 
You can choose from several shell colors and base finishes to perfectly match your existing 
decor. The chair is available with either plastic back and front upholstery or full upholstery 
in a range of 10 fabric and 6 leather options, allowing you to create a look that is uniquely 
yours.

The chair is also available with or without armrests, giving you the flexibility to choose 
the option that best suits your needs. The base finish options include stainless steel, 
matte black, gloss white, or chrome, ensuring that you can find the perfect match for your 
space.

In terms of construction, this chair is built to last. It features a 5-wheel plastic coated 
aluminum base, providing stability and mobility. The pneumatic chair adjust allows for easy 
raise and lower action, ensuring optimal comfort throughout the day.

When it comes to dimensions, this chair is designed with both style and comfort in mind. 
With a width of 53 cm (20.87"), depth of 51 cm (20.08"), and height of 80 cm (31.50"), 
it offers ample space without overwhelming your space. The seat height is 44 cm (17.32") 
and the seat depth is 41 cm (16.14"), providing a comfortable seating experience for users 
of all heights.

We understand that every space is unique, which is why we offer a range of options to 
further customize your chair. You can choose between soft or hard-floor caster options, 
ensuring that your chair glides smoothly across any surface. Additionally, you have the 
choice between two seat foam densities: medium (1.8 lb/ft3) or high (2.8 lb/ft3), allowing 
you to select the level of support that suits your preferences. The chair is also available 
with armless design or 8 position PU armrests, providing additional comfort and versatility.

When it comes to materials, this chair is crafted with the utmost attention to quality. 
The shell base glider is made from cast aluminum with a modified nylon PA6/PA66 coating, 
ensuring durability and longevity. The shell thickness is 10 mm, providing a sturdy and 
reliable structure. The seat is made from HD36 foam, offering a comfortable and supportive 
seating experience.

Finally, this chair is proudly made in Italy, known for its exceptional craftsmanship and 
design. With its combination of style, functionality, and customization options, this 
mid-century inspired office chair is the perfect choice for those seeking a timeless and 
elegant addition to their workspace.

Please note that this chair is qualified for contract use, making it suitable for a wide 
range of professional settings. Upgrade your office or home with this exceptional piece 
of furniture and experience the perfect blend of style and comfort.

위의 예제는 의자에 대한 사실 시트를 요약하는 작업입니다. 
여기에는 미드 센츄리에서 영감을 받은 아름다운 가구 가족의 일부라는 설명이 있는 의자의 사실 시트가 있습니다. 
이것은 구조에 대해 이야기하고, 차원이 있고, 의자의 옵션, 재료 등이 있습니다. 이것은 이탈리아에서 왔습니다. 
그럼, 이 사실 시트를 가져와서 마케팅 팀이 온라인 소매점을 위한 설명을 작성하는 데 도움을 주려고 한다고 가정해봅시다. 이 세 가지를 빠르게 실행해 보겠습니다, 

여기 내 프롬프트는 이렇게 말하고 있습니다, 당신의 임무는 마케팅 팀을 도와 소매 웹사이트의 설명을 기술 사실 시트를 기반으로 한 제품에 대해 만들어내는 것이며, 제품 설명을 작성하는 것, 등등입니다. 
그래서 이것이 바로 사용자가 큰 언어 모델에게 작업을 설명하는 첫 시도입니다. 

 

이슈1: 텍스트가 너무 길다

 

prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.

Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.

Use at most 50 words.

Technical specifications: ```{fact_sheet_chair}```
"""
response = get_completion(prompt)
print(response)
Introducing our mid-century inspired office chair, part of a stunning furniture collection. 
With various color and finish options, choose between plastic or full upholstery in fabric 
or leather. The chair features a durable aluminum base with 5 wheels and pneumatic height 
adjustment. Perfect for home or business use. Made in Italy.

 

설명을 잘 작성한 것 같지만 처음 예제를 보면 정말로 긴 것 같습니다. 
따라서 우리는 이것을 조금 더 짧게 만들고 싶을 것입니다. 
그래서, 저는 생각을 했고, 프롬프트를 작성하고 결과를 얻었습니다. 
그래서 프롬프트를 명확히 하고, 최대 50단어를 사용하여 더 나은 지침을 제공하려고 합니다. 
이것은 실제로 제품에 대한 훨씬 더 좋은 짧은 설명처럼 보입니다.

 

잘못된 디테일에 집중되있는 텍스트

다만, 우리가 웹사이트를 위한 이 텍스트를 계속해서 개선하면서, 우리는 이 웹사이트가 소비자에게 직접 판매하는 것이 아니라, 실제로는 가구 판매업체에게 가구를 판매하려는 것이라고 판단할 수 있습니다. 

prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.

Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.

The description is intended for furniture retailers, 
so should be technical in nature and focus on the 
materials the product is constructed from.

At the end of the description, include every 7-character 
Product ID in the technical specification.

Use at most 50 words.

Technical specifications: ```{fact_sheet_chair}```
"""
response = get_completion(prompt)
print(response)
Introducing our mid-century inspired office chair, perfect for both home and business 
settings. This chair is part of a beautiful family of furniture, offering a range of options 
including filing cabinets, desks, bookcases, and meeting tables. The chair is available with 
plastic back and front upholstery or full upholstery in a variety of fabric and leather 
options. Choose from stainless steel, matte black, gloss white, or chrome base finishes. 
With its 5-wheel plastic coated aluminum base and pneumatic chair adjust, this chair offers 
easy raise/lower action. It is also available with or without armrests. The chair is 
constructed with a cast aluminum shell with a modified nylon coating, ensuring durability and 
strength. The seat is made with HD36 foam for ultimate comfort. Choose between soft or 
hard-floor caster options and two choices of seat foam densities. The chair is designed and 
manufactured in Italy, guaranteeing quality craftsmanship. Product ID: SWC-100, SWC-110.

 

그들은 의자의 기술적인 세부사항과 의자의 재료에 더 관심이 있을 것입니다. 
그런 경우에는, 이 프롬프트를 가져와서 더 정확한 기술적 세부사항을 얻기 위해 이 프롬프트를 수정하고 싶다고 말할 수 있습니다. 
그러니 계속해서 이 프롬프트를 수정을 하는데 이 설명은 가구 판매업체를 위한 것이므로, 기술적이어야 하며 재료에 초점을 맞춰야 하고, 제품과 제작 방법에 대해 설명해야 합니다. 

그리고 위에 있는 예시들은 반복적인 프롬프트 개발의 짧은 예시입니다. 
그리고 가이드라인에서 명확하고 구체적으로, 필요하다면, 모델에게 생각할 시간을 줍니다. 
그것들을 염두에 두고, 종종 프롬프트를 처음 작성하는 것이 가치 있는 일입니다, 결과를 보고 거기서부터 시작하여 
반복적으로 프롬프트를 정제하여 점점 더 필요한 결과에 가까워지게 됩니다. 그래서, 다양한 프로그램에서 볼 수 있는 성공적인 프롬프트들은 대부분 이런 반복적인 과정을 통해 도출되었습니다. 
무언가를 시도해 보고, 아직 원하는 것을 정확히 충족시키지 못한다면, 지시사항을 어떻게 명확하게 할지 생각해봅시다.
또는 경우에 따라서는, 어떻게 하면 더 많은 공간을 생각하게 해서 원하는 결과에 가깝게 만들 수 있을지 생각해봅시다.. 
그리고 저는, 효과적인 프롬프트 엔지니어가 되는 핵심은 완벽한 프롬프트를 알고 있는 것이 아니라, 효과적인 프롬프트를 개발하는 좋은 과정을 가지고 있는 것이라고 생각합니다.

텍스트를 요약하기

 

오늘날 세상에는 텍스트가 너무 많아, 우리 모두가 읽고 싶은 모든 것을 읽을 시간이 충분하지 않습니다. 
그래서 가장 흥미로운 응용 프로그램 중 하나는 대형 언어 모델을 사용하여 텍스트를 요약하는 것입니다. 

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.
"""

 

딸의 생일 선물로 판다 인형을 사줬는데, 그녀는 그것을 매우 좋아하고 어디든지 가져다 놓습니다. 등등. 
당신이 전자상거래 웹사이트를 만들고 있다면, 그리고 많은 양의 리뷰가 있다면, 긴 리뷰를 요약하는 도구가 있으면 빠르게 리뷰를 살펴볼 수 있는 방법이 될 수 있습니다. 

단어나 문장에 따라서 줄이기

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}```
"""

response = get_completion(prompt)
print(response)
This panda plush toy is loved by the reviewer's daughter, but they feel it is a 
bit small for the price.

위의 작업은 문장 수나 글자 수를 조절하여 전자상거래 웹사이트의 제품 리뷰를 간단하게 요약하는 것입니다. 

 

특정한 목적으로 요약하기

prompt = f"""
Your task is to generate a short summary of a product \
review from an ecommerce site to give feedback to the \
Shipping deparmtment. 

Summarize the review below, delimited by triple 
backticks, in at most 30 words, and focusing on any aspects \
that mention shipping and delivery of the product. 

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

response = get_completion(prompt)
print(response)
The customer is happy with the product but suggests offering larger options for 
the same price. They were pleased with the early delivery.

이제, 때때로 요약을 만들 때, 매우 특정한 목적이 있다면 프롬프트를 수정하여 그것을 반영할 수 있습니다. 당신의 사업에서. 예를 들어, 배송 부서에 피드백을 주기 위해 추가한다면, 이것을 시작으로 제품의 배송과 배달에 언급된 어떤 부분에도 집중하게 됩니다. 따라서 내용에는 예상보다 하루 빨리 도착했다는 사실에 집중하게 됩니다. 

또 다른 예로, 우리가 피드백을 주려고 하는 것이 아니라면 그들의 배송 부서에게가 아니라, 가령 우리가 가격 결정 부서에게 피드백을 주고 싶다고 해봅시다. 그래서 가격 결정 부서는 제품의 가격을 결정하는 것이 
그들의 책임이고, 저는 가격과 관련된 어떤 측면에도 집중하도록 말할 것입니다. 

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}```
"""

response = get_completion(prompt)
print(response)
The customer loves the panda plush toy for its softness and cuteness, 
but feels it is overpriced compared to other options available.


그런 다음, 이것은 다른 요약을 생성하는데, 그것은 아마도 가격이 크기에 비해 너무 높을 수 있다고 말합니다. 
이제 제가 배송 부서나 가격 결정 부서를 위해 생성한 요약에서는, 그것이 조금 더 그 특정 부서와 관련된 정보에 초점을 맞추고 있습니다. 

 

여러 리뷰 요약하기

마지막으로, 이것을 어떻게 사용하여 작업 흐름에 도움이 되는 구체적인 예를 여러 리뷰를 요약하여 읽기 쉽게 만드는지 공유하겠습니다. 

review_1 = prod_review 

# review for a standing lamp
review_2 = """
Needed a nice lamp for my bedroom, and this one \
had additional storage and not too high of a price \
point. Got it fast - arrived in 2 days. The string \
to the 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. Then I had a \
missing part, so I contacted their support and they \
very quickly got me the missing piece! Seems to me \
to be a great company that cares about their customers \
and products. 
"""

# review for an electric toothbrush
review_3 = """
My dental hygienist recommended an electric toothbrush, \
which is why I got this. The battery life seems to be \
pretty impressive so far. After initial charging and \
leaving the charger plugged in for the first week to \
condition the battery, I've unplugged the charger and \
been using it for twice daily brushing for the last \
3 weeks all on the same charge. But the toothbrush head \
is too small. I’ve seen baby toothbrushes bigger than \
this one. I wish the head was bigger with different \
length bristles to get between teeth better because \
this one doesn’t.  Overall if you can get this one \
around the $50 mark, it's a good deal. The manufactuer's \
replacements heads are pretty expensive, but you can \
get generic ones that're more reasonably priced. This \
toothbrush makes me feel like I've been to the dentist \
every day. My teeth feel sparkly clean! 
"""

# review for a blender
review_4 = """
So, they still had the 17 piece system on seasonal \
sale for around $49 in the month of November, about \
half off, but for some reason (call it price gouging) \
around the second week of December the prices all went \
up to about anywhere from between $70-$89 for the same \
system. And the 11 piece system went up around $10 or \
so in price also from the earlier sale price of $29. \
So it looks okay, but if you look at the base, the part \
where the blade locks into place doesn’t look as good \
as in previous editions from a few years ago, but I \
plan to be very gentle with it (example, I crush \
very hard items like beans, ice, rice, etc. in the \ 
blender first then pulverize them in the serving size \
I want in the blender then switch to the whipping \
blade for a finer flour, and use the cross cutting blade \
first when making smoothies, then use the flat blade \
if I need them finer/less pulpy). Special tip when making \
smoothies, finely cut and freeze the fruits and \
vegetables (if using spinach-lightly stew soften the \ 
spinach then freeze until ready for use-and if making \
sorbet, use a small to medium sized food processor) \ 
that you plan to use that way you can avoid adding so \
much ice if at all-when making your smoothie. \
After about a year, the motor was making a funny noise. \
I called customer service but the warranty expired \
already, so I had to buy another one. FYI: The overall \
quality has gone done in these types of products, so \
they are kind of counting on brand recognition and \
consumer loyalty to maintain sales. Got it in about \
two days.
"""

reviews = [review_1, review_2, review_3, review_4]
for i in range(len(reviews)):
    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 20 words. 

    Review: ```{reviews[i]}```
    """

    response = get_completion(prompt)
    print(i, response, "\n")
0 Panda plush toy loved by daughter, soft and cute, but small for the price. Arrived early. 

1 Great lamp with storage, fast delivery, excellent customer service, and easy assembly. Highly recommended. 

2 The reviewer recommends the electric toothbrush for its impressive battery life, but criticizes the small brush head. 

3 The reviewer found the price increase after the sale disappointing and noticed a decrease in quality.

 

위에는 몇 가지 리뷰가 있습니다. 
하지만 이 리뷰어들이 무엇을 썼는지 알고 싶지만, 
세세하게 모두 읽는 것을 멈추고 싶지 않다면 어떨까요? 그래서, 나는 첫 번째 리뷰를 설정할 것입니다. 
그리고 이 모든 리뷰를 리스트에 넣을 것입니다. 그리고 이제, 리뷰를 구현하거나 루프를 돌리면, 여기가 사용자의  
프롬프트입니다. 그리고 여기서 최대 20단어로 요약하도록 요청했습니다. 
그리고 첫 번째로 출력되는 것은 팬더 장난감 리뷰입니다, 그 다음은 램프의 요약 리뷰, 칫솔의 요약 리뷰, 그리고 블렌더입니다. 
따라서 수백 개의 리뷰가 있는 웹사이트가 있다면, 이를 어떻게 활용할 수 있을지 상상해볼 수 있습니다. 
대량의 리뷰를 받아 대시보드를 구축하고, 그것들의 짧은 요약을 생성하여 당신이나 다른 사람이 리뷰를 훨씬 더 빠르게 탐색할 수 있게 합니다. 그리고 원한다면, 원본 긴 리뷰를 보기 위해 클릭할 수도 있습니다. 
이를 통해 효율적으로 고객들이 어떤 생각을 가지고 있는지 더 잘 이해할 수 있습니다. 

 

출처 : https://learn.deeplearning.ai/chatgpt-prompt-eng/lesson/3/iterative

 

Comments