TIL Day 73.

Jen Devver·2024년 5월 29일

내배캠 TIL

목록 보기
80/91

Django 최종 팀 프로젝트

AI 프롬프트 수정

메뉴 추천 AI 프롬프트

  • 기존 문제: 하나의 프롬프트에 메시지를 장문으로 담아 실행함에 따라 메뉴 추천의 정확도가 떨어지고, 소비자에게 전달하는 메시지가 어색함.
  • 튜터님 해결방안: 프롬프트를 단계를 나누어 여러 개를 돌리면 정확도가 올라감. 대신 단계가 늘어나면 돌리는 데에 시간이 오래 걸림. 아니면 세 개의 서버를 이용해 각 서버에서 프롬프트를 하나씩 돌리는 방법도 있다고는 하는데 방법이 더 어려울 듯 해서 절충안으로 두 개로 나누어 돌리는 방법으로 실행해보기로.
  • 로직 수정: 기존 bot() 하나에서 해결한 것을 메뉴 추천 프롬프트로 세 가지 메뉴 추천 → 메시지 생성 프롬프트로 받아온 메뉴에 기반하여 메시지 생성 → 두 함수를 실행해서 결과를 받아오는 함수 bot() 의 로직으로 세 개의 함수로 구현
def get_recommended_menus(client, input_text, current_user):
    # 사용자의 카테고리 가져오기
    category = current_user.category

    # 사용자의 메뉴 및 해시태그 가져오기
    menu, hashtags = get_user_menu_and_hashtags(current_user)

    # 카테고리에 따라 시스템 지침 작성
    if category == "CH":
        category_text = "치킨"
    elif category == "CA":
        category_text = "카페"
    else:
        category_text = "음식점"

    system_data = f"""
        You are considered a staff member related to {category_text}.
        Our store offers the following menu items: {menu}.
        Additionally, we use the following hashtags in our store: {hashtags}.
        """

    system_output = f"""
        The format of the data I desire as a result is:
        "Recommended Menu: [menu_name]"
        For the "Recommended Menu" section, select three options that are most closely related to the customer's request and rank them accordingly.
        The main format of recommended menu should be "Recommended Menu: menu_name, menu_name, menu_name".
        The output of recommended menus must include three items. If fulfilling three items is difficult to achieve, go through the menu table to find the closest menu possible.
        It would be easier for you to consider hashtags when finding related menu.
        When there are more than one keyword that you take into account, you should prioritize the keyword that is related to the menu.
        For example, when the customer asks for 'iced coffee', you should consider the menu that is 'coffee', rather than 'iced' beverages.
        """

    completion = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": system_data},
            {"role": "system", "content": system_output},
            {"role": "user", "content": input_text},
        ],
    )

    ai_response = completion.choices[0].message.content
    recommended_menu = []

    try:
        for line in ai_response.split('\n'):
            line = line.strip()  # Remove whitespace from both ends
            if line.startswith('Recommended Menu:'):
                recommended_menu = line.split('Recommended Menu: ')[1].strip().split(', ')
                break  # We don't need to continue once we have extracted the recommended menus

    except IndexError:
        recommended_menu = []

    print("recommended_men >>>>>>>", recommended_menu)
    return recommended_menu


def generate_final_response(client, recommended_menu, current_user):

    system_instructions = f"""
        When delivering a message to the customer,
        kindly determine their desired menu item and keep the message concise, preferably to one sentence.
        The message you respond must include the menu name of recommended_menu[0].
        The message must be in Korean, and think that you are having a small talk with your customer.
        There should not be a greetings, though.
        The format of the data I desire as a result is:
        "Message: [content]
        Recommended Menu: {', '.join(recommended_menu)}"
        """

    completion = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": system_instructions},
            {"role": "user", "content": f"Recommended Menu: {', '.join(recommended_menu)}"},
        ],
    )

    ai_response = completion.choices[0].message.content
    customer_message = ""

    try:
        for line in ai_response.split('\n'):
            line = line.strip()  # Remove whitespace from both ends
            if line.startswith('Message:'):
                customer_message = line.split('Message: ')[1].strip()
                break  # We don't need to continue once we have extracted the customer message

    except IndexError:
        customer_message = "죄송합니다. 다시 한 번 이야기 해주세요"

    print("customer_message >>>>>>>>>>>>", customer_message)
    return customer_message



def bot(request, input_text, current_user):
    client = OpenAI(api_key=settings.OPEN_API_KEY)

    # Getting the recommended menus
    recommended_menu = get_recommended_menus(client, input_text, current_user)

    # Generating the final response
    customer_message = generate_final_response(client, recommended_menu, current_user)

    return customer_message, recommended_menu
profile
발전 중...

0개의 댓글