Haru's 개발 블로그

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

머신러닝 & 딥러닝/LLM

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

Haru_29 2023. 9. 20. 00:56

확장

확장하는 것은 짧은 텍스트를 예를 들어 지시사항이나 주제 목록을 큰 언어 모델이 생성하도록 하는 긴 텍스트, 예를 들어 이메일이나 어떤 주제에 대한 에세이를 만드는 것입니다. 
이것의 좋은 사용 예는, 브레인스토밍 파트너로 큰 언어 모델을 사용하는 경우입니다. 
다만, 누군가가 이를 사용하여 대량의 스팸을 생성하는 경우같이 문제가 될 수 있는 사용 사례도 있을 수 있습니다.
그래서, 큰 언어 모델의 이런 기능을 사용할 때는 책임감 있게, 그리고 사람들에게 도움이 되는 방식으로만 사용해야합니다.

# given the sentiment from the lesson on "inferring",
# and the original customer message, customize the email
sentiment = "negative"

# review for a blender
review = f"""
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.
"""
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}
"""
response = get_completion(prompt)
print(response)
Dear Valued Customer,

Thank you for taking the time to share your review with us. We appreciate your feedback 
and apologize for any inconvenience you may have experienced.

We are sorry to hear about the price increase you noticed in December. We strive to 
provide competitive pricing for our products, and we understand your frustration. 
If you have any further concerns regarding pricing or any other issues, we encourage you 
to reach out to our customer service team. They will be more than happy to assist you.

We also appreciate your feedback regarding the base of the system. We continuously work 
to improve the quality of our products, and your comments will be taken into consideration 
for future enhancements.

We apologize for any inconvenience caused by the motor issue you encountered. Our customer 
service team is always available to assist with any warranty-related concerns. We understand 
that the warranty had expired, but we would still like to address this matter further. Please 
feel free to contact our customer service team, and they will do their best to assist you.

Thank you once again for your review. We value your feedback and appreciate your loyalty 
to our brand. If you have any further questions or concerns, please do not hesitate to contactus.

Best regards,

AI customer agent


위의 예시로 일부 정보를 기반으로 개인화된 이메일을 생성하였습니다.
이 이메일은 앤드류가 언급했듯이 매우 중요한 AI 봇이 보낸 것이라고 하였습니다.
리뷰에서의 구체적인 세부사항을 사용하고, 간결하고 전문적인 어조로 작성하며, 'AI 고객 에이전트'로 서명하세요." 
언어 모델을 사용하여 사용자에게 보여줄 텍스트를 생성할 때, 매우 중요한 것은 이런 종류의 투명성을 가지고 사용자에게 그들이 보는 텍스트가 AI에 의해 생성되었다는 것을 알려주는 것입니다. 
그리고 나서 우리는 고객의 리뷰를 입력하고 리뷰의 감정을 입력하게 됩니다. 
리뷰의 감정을 추출하고, 그 다음 단계에서 이메일을 작성할 수 있기 때문입니다. 

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}
"""
response = get_completion(prompt, temperature=0.7)
print(response)
Dear Valued Customer,

Thank you for taking the time to review our product. We appreciate your feedback and apologize for any inconvenience you may have experienced.

We are sorry to hear that you noticed an increase in prices for our 17 piece and 11 piece systems during December. We strive to provide competitive pricing for our customers and we apologize if this was not reflected in your recent purchase.

Regarding the base of the system, we understand your concerns about the blade locking mechanism. We will take this feedback into consideration and work towards improving the design in future editions.

In regards to the motor making a funny noise after a year of use, we apologize for any inconvenience caused. Unfortunately, if the warranty has expired, we recommend reaching out to our customer service team for further assistance. They will be able to provide you with the best possible solution.

We appreciate your loyalty to our brand and value your feedback as it helps us to improve our products and services. If there is anything else we can assist you with, please do not hesitate to contact our customer service team.

Thank you once again for your review.

Best regards,
AI customer agent

일반적으로, 예측 가능한 응답을 원하는 애플리케이션을 구축할 때는 온도를 0으로 설정하는 것을 추천합니다. 
이제 방금 사용한 동일한 프롬프트를 가지고, 온도를 높게 설정하여 이메일을 생성해봅시다. 
기존의 프롬프트를 사용하고, 온도를 0.7로 설정해 봅시다. 
온도가 0인 경우, 같은 프롬프트를 실행할 때마다 같은 완성을 기대해야 하고 모델은 항상 가장 가능성이 높은 다음 단어를 선택합니다.

그러나 0.7인 경우, 매번 다른 출력을 얻게 됩니다. 
요약하자면, 높은 온도에서는 모델의 출력이 좀 더 무작위적입니다. 
다른 의미로는 높은 온도에서는 어시스턴트가 더 쉽게 산만해지지만 아마 더 창의적일 수 있다고 생각할 수 있습니다.

 

Chatbot

큰 언어 모델에 대해 흥미로운 점 중 하나는 당신이 그것을 사용하여 적은 노력으로 맞춤형 챗봇을 만들 수 있다는 것입니다. ChatGPT, 웹 인터페이스는 대화형 인터페이스, 큰 언어 모델을 통한 대화를 가질 수 있는 방법입니다. 
하지만 멋진 점 중 하나는 큰 언어 모델을 사용하여 AI 고객 서비스 에이전트나 레스토랑의 AI 주문 접수원 역할을 하는 맞춤형 챗봇을 만들 수 있다는 것입니다. 
저는 OpenAI 챗봇 완성 형식의 구성 요소를 자세히 설명하고, 그런 다음 여러분이 직접 챗봇을 만들게 됩니다. 

import os
import openai
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file

openai.api_key  = os.getenv('OPENAI_API_KEY')


먼저, 평소처럼 OpenAI 파이썬 패키지를 설정하겠습니다. 
ChatGPT와 같은 채팅 모델은 실제로 일련의 메시지를 입력으로 받아 모델이 생성한 메시지를 출력으로 반환합니다. 
따라서 채팅 형식은 멀티턴 대화를 쉽게 만들도록 설계되었지만, 이전의 비디오에서 보았듯이 대화 없이 단일턴 작업에도 
마찬가지로 유용합니다. 

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

def get_completion_from_messages(messages, model="gpt-3.5-turbo", temperature=0):
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=temperature, # this is the degree of randomness of the model's output
    )
#     print(str(response.choices[0].message))
    return response.choices[0].message["content"]


그래서 다음으로 두 개의 도우미 함수를 정의하겠습니다. 
이것은 우리가 모든 비디오에서 사용해온 것이며, "get_completion" 함수입니다. 
하지만 이것을 살펴보면, 우리는 프롬프트를 제공하지만 함수 내부에서 실제로 하는 것은 이 프롬프트를 사용자 메시지 같은 것에 넣는 것입니다. 
이것은 ChatGPT 모델이 채팅 모델이기 때문인데, 이는 일련의 메시지를 입력으로 받아서 모델이 생성한 메시지를 출력으로 반환합니다. 
여기서 사용자 메시지가 입력이고 보조 메시지가 출력입니다. 

messages =  [  
{'role':'system', 'content':'You are an assistant that speaks like Shakespeare.'},    
{'role':'user', 'content':'tell me a joke'},   
{'role':'assistant', 'content':'Why did the chicken cross the road'},   
{'role':'user', 'content':'I don\'t know'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)
To traverse the thoroughfare, fair sir, in quest of enlightenment and adventure 
on the other side!

그래서 첫 번째 메시지는 시스템 메시지로 전반적인 지시를 제공하고 이 메시지 이후에는 사용자와 보조 프로그램 사이에 차례가 있고 이것이 계속될 것입니다. 
여기서 사용자의 메시지는 사용자 메시지이고, ChatGPT의 메시지는 보조 메시지입니다. 
따라서 시스템 메시지는 보조 프로그램의 행동과 인격을 설정하는 데 도움을 주며 대화에 대한 고수준의 지시 역할을 합니다. 
따라서 사용자로서, 만약 ChatGPT를 사용해 본 적이 있다면 ChatGPT의 시스템 메시지에 무엇이 있는지 아마 모를 것입니다. 
시스템 메시지의 장점은 개발자인 여러분이 대화를 구성하는 방법을 제공하면서도 요청 자체를 대화의 일부로 만들지 않는 것입니다. 
따라서 여러분은 조수를 안내하고, 그의 귓속말을 통해 응답을 안내할 수 있으며 사용자가 인지하지 못하게 할 수 있습니다. 

def collect_messages(_):
    prompt = inp.value_input
    inp.value = ''
    context.append({'role':'user', 'content':f"{prompt}"})
    response = get_completion_from_messages(context) 
    context.append({'role':'assistant', 'content':f"{response}"})
    panels.append(
        pn.Row('User:', pn.pane.Markdown(prompt, width=600)))
    panels.append(
        pn.Row('Assistant:', pn.pane.Markdown(response, width=600, style={'background-color': '#F6F6F6'})))
 
    return pn.Column(*panels)
import panel as pn  # GUI
pn.extension()

panels = [] # collect display 

context = [ {'role':'system', 'content':"""
You are OrderBot, an automated service to collect orders for a pizza restaurant. \
You first greet the customer, then collects the order, \
and then asks if it's a pickup or delivery. \
You wait to collect the entire order, then summarize it and check for a final \
time if the customer wants to add anything else. \
If it's a delivery, you ask for an address. \
Finally you collect the payment.\
Make sure to clarify all options, extras and sizes to uniquely \
identify the item from the menu.\
You respond in a short, very conversational friendly style. \
The menu includes \
pepperoni pizza  12.95, 10.00, 7.00 \
cheese pizza   10.95, 9.25, 6.50 \
eggplant pizza   11.95, 9.75, 6.75 \
fries 4.50, 3.50 \
greek salad 7.25 \
Toppings: \
extra cheese 2.00, \
mushrooms 1.50 \
sausage 3.00 \
canadian bacon 3.50 \
AI sauce 1.50 \
peppers 1.00 \
Drinks: \
coke 3.00, 2.00, 1.00 \
sprite 3.00, 2.00, 1.00 \
bottled water 5.00 \
"""} ]  # accumulate messages


inp = pn.widgets.TextInput(value="Hi", placeholder='Enter text here…')
button_conversation = pn.widgets.Button(name="Chat!")

interactive_conversation = pn.bind(collect_messages, button_conversation)

dashboard = pn.Column(
    inp,
    pn.Row(button_conversation),
    pn.panel(interactive_conversation, loading_indicator=True, height=300),
)

dashboard

 

Assistant: Hey there! Welcome to our pizza restaurant. How can I assist you today?
User: 페퍼로니 피자 미디움 하나요
Assistant: Sure thing! Just to confirm, you’d like a medium pepperoni pizza, right? Is there anything else you’d like to add to your order?
User: 콜라도 추가해 주세요
Assistant: Great choice! Adding a coke to your order. Is there anything else you’d like to add?
User: 괜찮아요
Assistant: Alright, no problem! So just to confirm, you’d like a medium pepperoni pizza and a coke. Is that correct?
User: 네 맞아요
Assistant: Perfect! Now, is this order for pickup or delivery?
User: 픽업으로 부탁드려요
Assistant: Got it! Your order for a medium pepperoni pizza and a coke is for pickup. Is there anything else I can assist you with?
User: 아니요 괜찮아요
Assistant: Alright, no problem! Your order for a medium pepperoni pizza and a coke for pickup is all set. Just to confirm, your total comes to $15.95. When you’re ready, you can come by our restaurant to pick up your order. Thank you for choosing our pizza restaurant!

이 챗봇의 이름은 "OrderBot"이며, 우리는 사용자 프롬프트의 수집을 자동화할 것입니다. 
이 챗봇은 피자 가게에서 주문을 받을 것이며, 먼저 우리는 이 도우미 함수를 정의할 것입니다. 이 함수는 
사용자 메시지를 수집하는 역할을 합니다. 
이렇게 하면 우리가 위에서 했던 것처럼 직접 타이핑하는 것을 피할 수 있습니다. 이 함수는 사용자 인터페이스에서 프롬프트를 수집하고 아래에서 만들 사용자 인터페이스에서 프롬프트를 수집한 후 "context"라는 리스트에 추가하고, 그 리스트를 가지고 모델을 호출할 것입니다. 
그리고 모델의 응답도 context에 추가됩니다. 따라서 모델의 메시지가 context에 추가되고, 사용자의 메시지도 추가되며, 이런 식으로 계속해서 길어져 나갑니다. 
이렇게 하면 모델이 다음에 무엇을 해야 할지 결정하는 데 필요한 정보를 가질 수 있습니다. 
그럼 이제 이런 종류의 UI를 설정하고 실행하여 Autobot을 표시해 보겠습니다. 
여기가 컨텍스트이고, 이 안에는 메뉴가 포함된 시스템 메시지가 있습니다. 
언어 모델을 호출할 때마다 동일한 컨텍스트를 사용하며, 시간이 지남에 따라 컨텍스트가 구축됩니다. 

messages =  context.copy()
messages.append(
{'role':'system', 'content':'create a json summary of the previous food order. Itemize the price for each item\
 The fields should be 1) pizza, include size 2) list of toppings 3) list of drinks, include size   4) list of sides include size  5)total price '},    
)
 #The fields should be 1) pizza, price 2) list of toppings 3) list of drinks, include size include price  4) list of sides include size include price, 5)total price '},    

response = get_completion_from_messages(messages, temperature=0)
print(response)
{
  "pizza": {
    "size": "medium",
    "type": "pepperoni",
    "price": 12.95
  },
  "toppings": [],
  "drinks": [
    {
      "type": "coke",
      "size": "regular",
      "price": 3.00
    }
  ],
  "sides": [],
  "total_price": 15.95
}


그래서, 이제 사용자는 모델에게 대화를 기반으로 주문 시스템에 보낼 수 있는 JSON 요약을 생성하도록 요청할 수 있습니다. 

필드는 1) 피자, 사이드 포함, 2) 토핑 목록, 3) 음료 목록, 그리고 4) 사이드 목록이어야 합니다. 
마지막으로, 총 가격입니다. 여기에 사용자 메시지를 사용할 수도 있습니다. 

대화형 에이전트의 경우, 당신은 더 높은 온도를 사용하고 싶을 수 있습니다. 
그러나 이 경우에는, 고객 지원 챗봇의 경우, 출력이 좀 더 예측 가능하길 원할 수도 있기 때문에 낮은 온도를 사용할 수도 있습니다. 

출처 : https://learn.deeplearning.ai/chatgpt-prompt-eng/lesson/7/expanding

 

 

Comments