확장
강의의 확장 예제는 짧은 리뷰와 조건을 바탕으로 이메일을 작성하는 작업입니다. 뒤에서는 사용자·어시스턴트 메시지를 누적해 주문 챗봇의 대화를 유지하는 구성을 다룹니다.
`# 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 고객 에이전트’로 서명하도록 요청합니다. 리뷰 감정을 먼저 추출한 뒤 답장에 전달하는 강의 예제입니다.
`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로 설정해 봅시다. 낮은 temperature는 출력 변동을 줄일 수 있지만, 0이라고 동일한 출력이 항상 보장되지는 않습니다. 이 예제의 설정을 모델 재현성 보장으로 해석하면 안 됩니다.
temperature를 높이면 샘플링에 따른 출력 차이가 커질 수 있습니다. 매 호출마다 반드시 다른 결과가 나온다는 뜻은 아닙니다. 요약하자면, 높은 온도에서는 모델의 출력이 좀 더 무작위적입니다. 다른 의미로는 높은 온도에서는 어시스턴트가 더 쉽게 산만해지지만 아마 더 창의적일 수 있다고 생각할 수 있습니다.
Chatbot
OrderBot은 강의의 피자 주문 챗봇 예제입니다. 메뉴와 역할을 지정한 메시지에 사용자 요청과 모델 응답을 차례로 추가합니다. 아래 코드는 당시 OpenAI Python SDK와 Chat Completions 형식을 사용합니다.
`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!`도우미 함수는 UI에서 받은 사용자 메시지를 context 리스트에 추가하고 모델을 호출합니다. 모델 응답도 같은 리스트에 넣어 다음 호출에 전달합니다. 이렇게 대화 이력과 메뉴 정보를 유지하는 예제입니다.
`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