티스토리 뷰

챗봇으로 연차, 반차 작성해보기


 

 


※ 연차, 반차 예시

 

※ 연차, 반차 구동

 

 

연차.gif

 

반차.gif

 

 


 

 

 

nlu.yml 작성하기


아래와 같이 사용자의 말뭉치에서 뽑아낼 Entity명Slot명을 작성 후 이후에 사용할만한 말뭉치를 추가로 작성
모델 training을 위해 여러 예시 문장을 작성하시면 됩니다.
연차, 반차에 필요한 날짜(inform_date)와 사유(reason) intent를 추가로 작성해주시면 됩니다.

 

nlu 예시파일


더보기
version: "2.0"

nlu:
- intent: greet
  examples: |
    - 좋은 아침
    - 안녕
    - 반가워

- intent: mood_answer
  examples: |
    - 오늘 기분 어때?
    - 밥은 잘 잡쉈어?
    - 하는 일 모두 무탈하지?
    - 잘 지내지?

- intent: request_dayoff
  examples: |
    - [연차](docuType) 쓸래
    - [연차](docuType) 쓸거야
    - [연차](docuType) 쓰고싶어

- intent: request_halfoff
  examples: |
    - [반차](docuType)
    - [반차](docuType) 쓸래
    - [반차](docuType) 쓰고싶어
    - [반차](docuType) 써줘 
    - [반차](docuType) 사용하고 싶어 
    - 나 [반차](docuType) 쓸 예정이야
    - 나 [반차](docuType) 쓸래

- intent: inform_date
  examples: |
    - [2022-12-17](time)
    - [2022-3-2](time)

- intent: reason
  examples: |
    - 개인사정
    - 환갑잔치
    - 결혼식
    - 장례식
    - 제사
    - 가족여행

 

 

 

rules.yml 작성하기



① Rule
: rule 제목 (별도 문법적 제약없이 주석으로 봐도 무관)
② Condition : 조건문
     Active_loop : dayoff_form이 실행중일 경우
③ Steps : 해당 condition(조건문)일 경우 차례대로 action과 action_loop를 진행
     Action : 챗봇이 실행할 응답 or Form
     Action_loop : null  → form에 모든 slot이 채워졌을 때

* form은 domain.yml에서 정의한 form명을 그대로 써줘야합니다.

 

rules.yml 코드


더보기

 

version: "2.0"

rules:

  # 연차
  - rule : submit dayoff form
    condition:
    - active_loop: dayoff_form
    steps:
      - action: dayoff_form
      - active_loop: null
      - action: utter_slots_values

  # 반차
  - rule : submit halff form
    condition:
    - active_loop: halfoff_form
    steps:
      - action: halfoff_form
      - active_loop: null
      - action: utter_slots_values

 

 

 

stories.yml 작성하기


stories의 경우 rules에서 정의한 순서에서 벗어나 중간에 발생할 수 있는 상황을 정의해줘야 합니다.
해당 파일에서는 happy path 즉, 정상적으로 수행될 경우에만 맞춰 설계했기 때문에 사용자별로 수정하셔서 사용하시면 됩니다.

 

stories.yml 코드


더보기
version: "2.0"

stories:

  - story: happy path
    steps:
    - intent: greet
    - action: utter_greet
    - intent: mood_answer
    - action: utter_mood_answer

 # 상황1 : 연차 정상 실행
  - story: dayoff
    steps:
      - intent: request_dayoff
      - action: dayoff_form
      - active_loop: dayoff_form
      - action: utter_slots_values

# 상황2 : 반차 정상 실행
  - story: halfoff
    steps:
      - intent: request_halfoff
      - action: halfoff_form
      - active_loop: halfoff_form
      - action: utter_slots_values

 

 

config.yml 작성하기


 

config.yml은 아래 코드를 그대로 복붙해주시면 됩니다.
tokenizer의 경우 별도 customizing 한 파일을 첨부파일로 공유해드리니 아래 절차에 따라 진행해주시면 됩니다.

 

custom_tokenizer.py
0.01MB

 

 

 

1. custom_tokenizer.py 복붙 위치

설치경로: C:\Users\...\anaconda3\envs\rasa\Lib\site-packages\rasa\nlu\tokenizers

 

 

2. custom_tokenizer 등록하기

 

 

 

config.yml 코드


더보기

 

# Configuration for Rasa NLU.
# https://rasa.com/docs/rasa/nlu/components/
language: ko

pipeline:
# No configuration for the NLU pipeline was provided. The following default pipeline was used to train your model.
# If you'd like to customize it, uncomment and adjust the pipeline.
# See https://rasa.com/docs/rasa/tuning-your-model for more information.
  - name: SpacyNLP
    model: "ko_core_news_sm"
  - name: custom_tokenizer
  - name: RegexFeaturizer
  - name: LexicalSyntacticFeaturizer
  - name: CountVectorsFeaturizer
  - name: CountVectorsFeaturizer
    analyzer: char_wb
    min_ngram: 1
    max_ngram: 4
  - name: DIETClassifier
    epochs: 100
    constrain_similarities: true
  - name: EntitySynonymMapper
  - name: ResponseSelector
    epochs: 100
    constrain_similarities: true
  - name: FallbackClassifier
    threshold: 0.3
    ambiguity_threshold: 0.1
  - name: RegexFeaturizer
  - name: LexicalSyntacticFeaturizer
  - name: CountVectorsFeaturizer
  - name: CountVectorsFeaturizer
    analyzer: char_wb
    min_ngram: 1
    max_ngram: 4
  - name: EntitySynonymMapper
  - name: ResponseSelector
    epochs: 100
    constrain_similarities: true
  - name: FallbackClassifier
    threshold: 0.3
    ambiguity_threshold: 0.1

# Configuration for Rasa Core.
# https://rasa.com/docs/rasa/core/policies/
policies:
# # No configuration for policies was provided. The following default policies were used to train your model.
# # If you'd like to customize them, uncomment and adjust the policies.
# # See https://rasa.com/docs/rasa/policies for more information.
#   - name: MemoizationPolicy
#   - name: RulePolicy
#   - name: UnexpecTEDIntentPolicy
#     max_history: 5
#     epochs: 100
#   - name: TEDPolicy
#     max_history: 5
#     epochs: 100
#     constrain_similarities: true

 

 

 

domain.yml 작성하기


 

1. nlu.yml에서 작성한 intent는 모두 domain.yml의 intents에 등록되어야합니다.

2. nlu.yml에서 정의한 entity명은 모두 domain.yml의 entities에 등록되어야합니다.

3. 추출된 entity와 text를 api로 전달하기위해서 slot에 담아야하는데, domain.yml에서 slot을 정의해야합니다.
   - type은 categorical(2~3개의)과 text를 사용했습니다만 아래 url을 참고하시어, 다양한 방법으로 사용가능합니다.
   - 참고 url : https://learning.rasa.com/archive/conversational-ai-2/slots/

4. response는  'utter_intent명'으로 입력해주셔야합니다. intent명은 nlu.yml에서 정의한 intent명입니다.

주요내용은 아래 코드에 주석으로 남겨두었습니다.

 

 

 

domain.yml 코드


더보기
version: "2.0"

# 사용자의 의도로 뽑아낼 intent 정의
intents:
  - greet
  - mood_answer
  - affirm
  - request_dayoff
  - request_halfoff
  - reason
  - inform_offdate
  - inform_utime

# 사용자의 말에서 뽑아내고 싶은 주요단어
entities:
  - docuType
  - time
  - utime
 
# 뽑아낸 주요 단어를 담을 slot 정의
slots:
  docuType:
    type: categorical
    values:
        - "연차"
        - "반차"
    influence_conversation: false

  startDate: # 시작일
    type: text
    influence_conversation: false

  endDate: # 종료일
    type: text
    influence_conversation: false

  utime:
    type: categorical
    values:
        - "오전"
        - "오후"
    influence_conversation: false

  reason: # 사유
    type: text
    influence_conversation: false

# 봇의 답변
responses:
  utter_greet:
  - text: "안녕하세요 저는 오늘의 챗봇 입니다!"

  utter_mood_answer:
  - text: "저야 뭐 매일 똑같죠 ㅎㅎ!"

  utter_ask_startDate: # 연차 시작일
  - condition:
      - type: slot
        name: docuType
        value: "연차"
    text: "연차 시작일을 말씀해주세요.\n
          \nex) 2022-08-23 "

  - condition: # 반차 사용일
      - type: slot
        name: docuType
        value: "반차"
    text: "반차를 사용하실 날짜를 말씀해주세요.\n
          \nex) 2022-08-23 "  

  utter_ask_endDate: #연차 종료일
  - condition:
      - type: slot
        name: docuType
        value: "연차"
    text: "연차 종료일을 말씀해주세요.\n
          \nex) 2022-08-23 "

  utter_ask_utime: #오전 or 오후 반차 선택
    - text: "반차를 사용하실 시간을 선택해주세요."
      buttons: # 버튼형식으로 클릭
      - title: "오전"
        payload: '/inform_utime{{"utime":"오전"}}'
      - title: "오후"
        payload: '/inform_utime{{"utime":"오후"}}'

  utter_ask_reason:
    - text: "사유를 말씀해주세요."

  utter_success:
    - text: "{docuType} 제출이 완료되었습니다."
  
  utter_slots_values:
  - condition:
      - type: slot
        name: docuType
        value: "연차"
    text: "아래와 같이 기안문 작성이 완료 됐습니다.\n
          - 문서종류: {docuType}\n
          - 연차 시작일: {startDate}\n
          - 연차 종료일: {endDate}\n
          - 사유: {reason}\n"

  - condition:
      - type: slot
        name: docuType
        value: "반차"
    text: "아래와 같이 기안문 작성이 완료 됐습니다.\n
          - 문서종류: {docuType}\n
          - 반차일자: {startDate}\n
          - 오전/오후: {utime}\n
          - 사유: {reason}\n"

forms:
  dayoff_form:
    ignored_intents:
    
    required_slots:
      docuType: 
        - type: from_entity
          entity: docuType

      startDate:
        - type: from_entity
          entity: time

      endDate:
        - type: from_entity
          entity: time

      reason:
        - type: from_text

  halfoff_form:
    ignored_intents:
    
    required_slots:
      docuType: 
        - type: from_entity
          entity: docuType

      startDate:
        - type: from_entity
          entity: time

      utime:
        - type: from_entity
          entity: utime

      reason:
        - type: from_text

actions:
  - action_restart



session_config:
  session_expiration_time: 1
  carry_over_slots_to_new_session: true

 

 

 

 

actions.py 작성하기


아래 코드를 그대로 사용해주시면 됩니다. 해당 클래스는 restart 기능을 위해 정의한 것으로 채팅창에서
restart 를 입력해주시면 챗봇이 초기화 됩니다.

 

 

actions.py 코드


더보기
from rasa_sdk import Action, Tracker
from rasa_sdk.events import Restarted
from typing import Any, Dict, List, Text, Optional

class ActionRestarted(Action):
    
    def name(self) -> Text:
        return "action_restart"   
    
    async def run(
        self, dispatcher, tracker: Tracker, domain: Dict[Text, Any]
        ) -> List[Dict[Text, Any]]:

        return [Restarted()]

 

 

 

 

Rasa 트레이닝 및 실행하기


Rasa 실행 명령어


rasa train 
rasa run -m models --enable-api --cors "*" -vv
rasa run actions (별도창에서 실행)

 

 

 


 

이상으로 해당 포스팅을 마칩니다.

추가로 문의사항 있으시면 댓글로 남겨주세요

긴 글 읽어주셔서 감사합니다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함