웹사이트 검색

Python의 초보자 코딩: 가능한 가장 간단한 AI 채팅 도우미 구축


AI 챗봇을 사용해 본 적이 있다면 그것이 어떻게 작동하는지, 직접 만들 수 있는지 궁금할 것입니다. Python을 사용하면 이는 가능한 것 이상입니다. 여기서는 가능한 가장 간단한 챗봇을 구축하는 방법을 다루고 이를 업그레이드하기 위한 몇 가지 조언을 제공합니다.

Python으로 NLTK에 대해 배우기

Python을 사용하는 가장 강력한 이유 중 하나는 모듈식 특성입니다. 우리는 Tkinter를 사용하여 애플리케이션의 기본 GUI를 만들 때 간단한 비용 추적기에서 이것을 보았습니다. 하지만 챗봇은 그렇게 정교할 필요는 없으며 터미널에서 문제 없이 실행할 수 있습니다. 저는 이 앱의 UI를 디자인하지는 않겠지만 직접 시도해 보시는 것도 좋습니다.

우리 앱의 기본은 챗봇의 기본 구성 요소를 제공하는 Python 라이브러리인 NLTK(자연어 도구 키트)입니다. NLTK를 설치하려면 터미널에서 Python 설치 위치를 열고 다음을 입력하세요.

pip install nltk

NLTK 라이브러리가 다운로드되고 업데이트되는 것을 볼 수 있습니다. 다른 포함과 마찬가지로 다음과 같이 코드 상단에서 NLTK를 가져와야 합니다.

        import nltk
from nltk.tokenize import word_tokenize
from nltk.sentiment import SentimentIntensityAnalyzer
from nltk.corpus import stopwords
from nltk.tag import pos_tag
import string
import random
import re
# Download required NLTK data
nltk.download('punkt_tab')
nltk.download('vader_lexicon')
nltk.download('stopwords')
nltk.download('averaged_perceptron_tagger_eng')
    

여기에 "다운로드" 키워드가 추가된 것을 눈치채셨을 것입니다. 이를 통해 우리는 매우 간단한 챗봇이 이미 알고 있는 응답 및 정보를 포함한 기본 데이터 세트를 다운로드할 수 있습니다. 챗봇을 작동시키는 방법을 살펴보겠습니다.

챗봇 인터페이스 만들기

챗봇 인터페이스를 사용하여 간단하게 유지할 것이므로 Python에서 간단한 할 일 목록을 작성한 방법과 유사할 것입니다. 우리는 입력과 출력을 위해 터미널 창을 사용할 것입니다.

        class SmartAIChatbot:
   def __init__(self):
       # Enhanced knowledge base with question-answer pairs
       self.knowledge_base = {
           'greetings': {
               'patterns': ['hello', 'hi', 'hey'],
               'responses': [
                   "Hi there! How can I help you today?",
                   "Hello! Nice to meet you!",
                   "Hey! What's on your mind?"
               ]
           },
           'questions': {
               'what': {
                   'patterns': ['what is', 'what are', 'what can'],
                   'responses': [
                       "Let me think about {topic}...",
                       "Regarding {topic}, I would say...",
                       "When it comes to {topic}, here's what I know..."
                   ]
               },
               'how': {
                   'patterns': ['how do', 'how can', 'how does'],
                   'responses': [
                       "Here's a way to approach {topic}...",
                       "When dealing with {topic}, you might want to...",
                       "The process for {topic} typically involves..."
                   ]
               },
               'why': {
                   'patterns': ['why is', 'why do', 'why does'],
                   'responses': [
                       "The reason for {topic} might be...",
                       "Thinking about {topic}, I believe...",
                       "Let me explain why {topic}..."
                   ]
               }
           },
           'farewell': {
               'patterns': ['bye', 'goodbye', 'see you'],
               'responses': [
                   "Goodbye! Have a great day!",
                   "See you later!",
                   "Bye! Come back soon!"
               ]
           }
       }
       self.sentiment_analyzer = SentimentIntensityAnalyzer()
       self.stop_words = set(stopwords.words('english'))
    

이를 통해 챗봇은 기본적인 상호 작용과 프롬프트 단어는 물론 질문을 처리하는 방법의 시작을 제공합니다. 이제 이 AI 봇이 어떻게 프롬프트를 받아들이고 우리가 입력하는 내용을 어떻게 이해하는지 살펴보겠습니다.

봇에게 읽기를 가르치는 방법

이전 가져오기에서 "tokenize"라는 단어를 발견했을 수도 있습니다. "토큰"은 우리가 말하는 내용을 이해하기 위해 봇이 사용하는 것입니다. 토론하고 싶은 주제를 결정하기 위해 토큰과 태그를 사용하고 질문과 같은 항목을 처리합니다.

         def tokenize_and_tag(self, user_input):
        """Clean, tokenize, and POS tag user input"""
        # Clean and tokenize
        cleaned = user_input.lower().translate(str.maketrans('', '', string.punctuation))
        tokens = word_tokenize(cleaned)
        # POS tagging
        tagged = pos_tag(tokens)
        return tokens, tagged
    def extract_topic(self, tokens, question_word):
        """Extract the main topic after a question word"""
        # Find the question word's position
        try:
            q_pos = tokens.index(question_word.lower())
            # Get everything after the question word and auxiliary verbs
            topic_words = tokens[q_pos + 2:]  # Skip question word and auxiliary verb
            # Remove stop words from topic
            topic = ' '.join([word for word in topic_words if word not in self.stop_words])
            return topic if topic else "that"
        except ValueError:
            return "that"
    def identify_question_type(self, user_input, tagged_tokens):
        """Identify the type of question and extract relevant information"""
        question_words = {
            'what': 'what', 'why': 'why', 'how': 'how',
            'when': 'when', 'where': 'where', 'who': 'who'
        }
        
        # Check if it's a question
        is_question = any([
            user_input.endswith('?'),
            any(word.lower() in question_words for word, tag in tagged_tokens),
            any(pattern in user_input.lower() for qtype in self.knowledge_base['questions']
                for pattern in self.knowledge_base['questions'][qtype]['patterns'])
        ])
        
        if not is_question:
            return None, None
        # Identify question type and topic
        for q_type, q_info in self.knowledge_base['questions'].items():
            for pattern in q_info['patterns']:
                if pattern in user_input.lower():
                    topic = self.extract_topic(user_input.split(), q_type)
                    return q_type, topic
        
        return 'general', 'that'
    

봇의 (기본) 두뇌 구축

이것은 간단한 AI 챗봇이므로 복잡한 사고 처리를 수행하지 않습니다. 대신, 사용자 입력을 처리하고 감정을 결정하는 방법을 개발하겠습니다.

        def get_response(self, user_input):
        """Generate a more thoughtful response based on input type"""
        tokens, tagged_tokens = self.tokenize_and_tag(user_input)
        
        # Check for greetings and farewells first
        for category in ['greetings', 'farewell']:
            if any(pattern in user_input.lower() for pattern in self.knowledge_base[category]['patterns']):
                return random.choice(self.knowledge_base[category]['responses'])
        
        # Handle questions
        q_type, topic = self.identify_question_type(user_input, tagged_tokens)
        if q_type:
            if q_type in self.knowledge_base['questions']:
                template = random.choice(self.knowledge_base['questions'][q_type]['responses'])
                return template.format(topic=topic)
            else:
                # Handle general questions
                return f"That's an interesting question about {topic}. Let me think... "
        # If not a question, use sentiment analysis for response
        sentiment = self.analyze_sentiment(user_input)
        if sentiment > 0.2:
            return "I sense your enthusiasm! Tell me more about your thoughts on this."
        elif sentiment < -0.2:
            return "I understand this might be challenging. Would you like to explore this further?"
        else:
            return "I see what you mean. Can you elaborate on that?"
    def analyze_sentiment(self, text):
        """Analyze the sentiment of user input"""
        scores = self.sentiment_analyzer.polarity_scores(text)
        return scores['compound']
    

우리는 vader_lexicon을 사용하여 사용자의 입력 감정이 어떻게 느껴지는지 알려주고 거기에서 어떤 유형의 출력을 제공할지 결정할 수 있습니다.

우리 봇과 대화하기

코딩을 마무리하기 위해 채팅 인터페이스를 마무리하겠습니다.

        def chat(self):
        """Main chat loop"""
        print("Bot: Hi! I'm a smarter chatbot now. I can handle questions! Type 'bye' to exit.")
        
        while True:
            user_input = input("You: ")
            if user_input.lower() in ['bye', 'goodbye', 'exit']:
                print("Bot:", random.choice(self.knowledge_base['farewell']['responses']))
                break
                
            response = self.get_response(user_input)
            print("Bot:", response)
# Create and run the chatbot
if __name__ == "__main__":
    chatbot = SmartAIChatbot()
    chatbot.chat()
    

이를 통해 우리는 챗봇과 기본적인 채팅을 하고 응답을 얻을 수 있습니다.

모든 것을 하나로 모으고 개선하는 방법

챗봇을 실행하면 다음과 같은 내용이 표시됩니다.

이 시점에서 봇은 사용자의 입력을 읽고 무작위 응답을 제공할 수 있지만 실제로 사용자에게 생각하고 응답할 수는 없습니다. 하지만 토큰화 시스템 덕분에 사용자가 질문하려는 내용을 알아낼 수 있습니다. 응답할 데이터가 없습니다.

적절한 지식 기반을 갖춘 AI 챗봇을 구축하려면 단어 그물에 대해 자세히 알아보고 여기서 하려는 것보다 훨씬 더 많은 데이터 직렬화에 대해 배워야 합니다. 그러나 보다 기능적인 챗봇을 만들고 싶다면 알아야 할 사항을 가르쳐줄 수 있는 리소스가 많이 있습니다. 언제나 그렇듯이 이 코드는 내 GitHub에서 다운로드하거나 댓글을 달 수 있습니다.

실제 지식 기반을 제공하는 것부터 UI를 좀 더 세련되고 매력적으로 업그레이드하는 것까지 이 봇을 통해 개선할 수 있는 것들이 많이 있습니다. 이것을 실험하고 어떤 결과가 나오는지 확인하세요!

관련기사