React.js를 사용한 간단한 챗봇 애플리케이션

21216 단어 reactapitutorial
"Alexa, Taylor Swift의 버드나무 연주"
"시리야, 오늘 날씨 어때?"
...

우리 모두는 매일은 아니지만 적어도 한 번은 이러한 대사를 들었을 것입니다. 인공 지능(AI)은 우리의 삶을 더 쉽고 더 안전하게 만드는 데 큰 역할을 했습니다(운전 중에 더 이상 문자 메시지를 보낼 필요가 없습니다!). 나는 항상 그 이면에 있는 논리에 호기심을 갖고 흥미를 느꼈습니다. Flatiron School의 캡스톤 프로젝트에서 저는 Hipstew이라는 레시피 검색을 구축했습니다 | Demo 가상 비서 Stewy가 있습니다. 제가 어떻게 Stewy를 만들었는지 궁금하시다면(스포일러 경고: Stewy는 사람의 목소리를 말하고 이해합니다) 계속 읽어주세요 :).

이 블로그에서는 React.js를 사용하여 내 챗봇을 다시 만들려고 시도하지만 더 간단한 버전입니다. 자유롭게 이것을 템플릿으로 사용하고 나중에 챗봇에 더 많은 기술을 추가하세요 ;)!

먼저 create-react-app 패키지를 사용하여 반응 앱을 만듭니다.
npx create-react-app chatbot-example
그런 다음 react-bootstrap 패키지를 설치합니다(선택 사항).
npm install react-bootstrap bootstrap
src/index.js 또는 App.js에서 스크립트 가져오기:
import 'bootstrap/dist/css/bootstrap.min.css'
괜찮은! 첫 번째 구성 요소ChatBot.js를 만들고 입력 필드를 추가해 보겠습니다.

import React, { useState } from 'react'
import Form from 'react-bootstrap/Form'
import InputGroup from 'react-bootstrap/InputGroup'
import '../css/ChatBot.css'

export default function ChatBot(){
    const [userInput, setUserInput] = useState('')

    return (
        <div className='chatbot-card'>
            <div>
                <img 
                    className='bot-cover-photo'
                    src='https://www.userlike.com/api/proxy/resize/do-i-need-a-chatbot/header-chat-box.png?height=720' 
                    alt='chatbot-pic'
                />  
            </div>

            <div className='human-input'>
                <InputGroup className="mb-3">

                    <Form.Control
                        className="mb-2"
                        type="text" 
                        placeholder="Ask me something"
                        value={userInput}
                        onChange={handleChange}
                    />

                </InputGroup>
            </div>

        </div>
    )}
}


다음과 같이 DOM에 챗봇 사진과 입력 필드가 표시되어야 합니다.



사용자 입력을 처리하는 로직 추가:

  const [userInput, setUserInput] = useState('')
  const [userHistory, setUserHistory] = useState([])
  const [botHistory, setBotHistory] = useState([])
  const handleChange = (e) => setUserInput(e.target.value)


나중에 대화에서 표시하기 위해 사용자 입력 및 봇의 응답을 추적하기 위해 userHistorybotHistory 상태를 추가했습니다.

챗봇의 핵심인 가장 중요한 부분은 다음과 같습니다.

const matchReply = (userInput) => {
        const trigger = [
            ["hi", "hey", "hello"],
            ["how are you", "how are things", "how you doing"],
            ["what is going on", "what is up"],
            ["happy", "good", "amazing", "fantastic", "cool"],
            ["bad", "bored", "tired", "sad"],
            ["thanks", "thank you"],
            ["bye", "good bye", "goodbye"]
        ];

        const reply = [
            ["Hello", "Hi", "It's nice seeing you!"],
            ["I'm doing good... how are you?", "I feel kind of lonely, how are you?", "I feel happy, how are you?"],
            ["Nothing much", "Exciting things!", "I'm happy to see you!"],
            ["Glad to hear it", "Yayyy!! That's the spirit!"],
            ["There is always a rainbow after the rain!"],
            ["You're welcome", "No problem", "It's my pleasure!"],
            ["Goodbye, it was a nice talk"]
        ];

        const alternative = ["Same", "Go on...", "Try again please?", "I'm listening..."];

        let botMsg = generateReply(trigger, reply, userInput)

        if(!botMsg){
            botMsg = alternative[Math.floor(Math.random()*alternative.length)]
        }

        setBotHistory([botMsg, ...botHistory])

}


이 기능은 사용자의 입력을 올바른 봇의 응답과 일치시키고 해당 응답을 채팅 기록에 저장하는 데 도움이 됩니다. 이 함수 내에 도우미 함수generateReply가 있음을 알 수 있습니다. 구현해 봅시다:

const generateReply = (trigger, reply, text) => {
        let item;
        let items;
        for (let x = 0; x < trigger.length; x++) {
            for (let y = 0; y < reply.length; y++) {
                if (text.includes(trigger[x][y])) {
                    items = reply[x];
                    item = items[Math.floor(Math.random() * items.length)];
                }
            }
        }
        return item;
}


이 함수는 3개의 인수를 사용합니다.
  • trigger: matchReply 함수의 트리거 배열, 사용자가 트리거 키워드 중 하나가 포함된 문장을 입력할 때마다 해당 응답이 추가됩니다.
  • 답장: 트리거에 해당하는 답장 배열입니다.
  • 텍스트: 사용자 입력.

  • 사용자가 트리거 키워드가 포함된 구문을 입력할 때마다 챗봇이 해당 응답으로 응답합니다.

    이 챗봇에 약간의 CSS를 적용했습니다. 자유롭게 살펴보세요.

    .bot-cover-photo {
        width: 100vw;
    }
    
    .chatbot-card {
      background-color: rgba(140, 192, 247, 0.735);
    }
    
    .human-input {
        padding-left: 30vw;
        padding-right: 30vw;
        margin: 10px;
    }
    
    h3 {
        margin-bottom: 0 !important;
    }
    
    #user-input {
        background-color: rgba(132, 136, 249, 0.646);
    }
    
    #bot-reply {
        background-color: rgba(231, 228, 228, 0.687);
    }
    
    #user-input, #bot-reply {
        padding: 0.4rem;
        padding-left: 1rem;
        border-radius: 10px;
        text-align: left;
    }
    
    .conversation-box {
        padding-left: 20vw;
        padding-right: 20vw;
    }
    
    .chatbox {
        overflow-y: scroll;
        overflow-y: auto;
        height: 230px;
    }
    


    이것은 챗봇과 간단한 대화를 만드는 최종 결과입니다.


    다음 주에 작은 챗봇에 더 많은 기술을 추가하는 방법에 대한 또 다른 블로그 게시물을 공개하겠습니다 :). 여기까지 해주셔서 정말 감사합니다! 나중에 보자.

    좋은 웹페이지 즐겨찾기