새소식

카테고리 없음

개발자를 위한 챗 GPT 프롬프트 엔지니어링 #7. Chatbot (챗봇)

  • -

이전 글

 

 

이번 강의는 마지막 강의로 챗봇에 관해 다루고 있습니다. 식당의 메뉴 및 가격 정보를 주고, 그 정보를 기반으로 주문을 받는 챗봇입니다.

 

1. 챗봇

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

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

 

[결과]

결과를 확인해보니 어떤 피자를 어떤 사이즈로 할지, 사이드 메뉴를 추가 할지 등을 꼼꼼하게 묻고, 마지막에 주문 메뉴와 금액을 확인하는 식으로 답변을 주고 있습니다. 포장, 배달 여부도 체크해서 이정도면 웬만한 직원 역할을 대체할 수 있을 것 같습니다. 다만 총 금액이 정확하지 않은 경우도 있어서 실 사용을 한다면 일부 알고리즘으로 보완이 되어야 할 것 같습니다.

GUI 챗봇

 

2. JSON 변환

위에서 받은 주문을 JSON 형식으로 변환하는 코드입니다. 대략 잘 나와서 API 요청으로도 활용할 수 있는데 실제 사용하려면 응답값의 형식을 좀 더 명확히 지정해줘야 할 것 같습니다. ("pizza는 1개여도 array로 처리해라" 등)

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)

 

[결과]

더보기



```json
{
    "pizza": [
        {"item": "pepperoni pizza (large)", "price": 12.95},
        {"item": "cheese pizza (large)", "price": 10.95}
    ],
    "toppings": [],
    "drinks": [
        {"item": "coke (large)", "price": 3.00},
        {"item": "coke (large)", "price": 3.00},
        {"item": "coke (large)", "price": 3.00}
    ],
    "sides": [
        {"item": "fries", "price": 4.50}
    ],
    "total price": 54.85
}
```

 

 

얼마 전 유튜브에서 회사 제규정집을 GPT 연계한 챗봇으로 만든 사례도 봤다. 복잡한 문서에 지침 같은 걸 정해놓고 필요할 때 찾아보는 경우가 많은데 이럴 때 유용하게 쓸 수 있을 것 같다. 영상 1시간 25분 쯤부터 보면 될 것 같다.

 

 

챗GPT가 성능이 좋다는 건 알았지만 역시 직접 써보니 훨씬 와닿는 점이 많았다. 덕분에 다양한 분야에 응용해볼 수 있을 것 같다. 아직도 문토 같은 서비스에서 Chat GPT 교육 신청이 매번 전석마감되고 펀딩 사이트에서 1억 이상 펀딩되고 있다. 관심을 갖고 배우기는 쉽지만 개발자가 아닌 사람들한테는 어느 정도 벽으로 느껴지는 듯하다. 나도 좀 더 써보면서 쉽게 알려줄 만한 방법이 있나 생각해봐야겠다.

 

 

이 강의는 1시간 내외로 짧지만 핵심 내용들이 많아 듣기 정말 잘했다. 덕분에 고정관념도 많이 깨지고 새로운 기회도 많이 얻게 될 것 같다. 

Contents

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

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