// education & ai

대화형 AI 챗봇 구현과 대화 이력 관리

LLM API는 자체적으로 이전 대화를 기억하지 않는 Stateless(무상태성) 통신 방식을 사용합니다. 따라서 챗봇이 대화 맥락을 기억하게 하려면 개발자가 이전 대화 기록(Chat History)을 배열에 유지하여 매 요청마다 전달해야 합니다.


1. 대화 이력 용어 사전 (Glossary)


2. 슬라이딩 윈도우 대화 메모리 파이썬 챗봇 클래스

class MemoryChatbot:
    def __init__(self, client, max_history_turns=5):
        self.client = client
        self.max_turns = max_history_turns
        self.system_message = {"role": "system", "content": "너는 DAVHAVE의 다정한 AI 상담사야."}
        self.history = [] # 대화 기록 저장소

    def chat(self, user_input):
        # 1. 사용자 메시지 추가
        self.history.append({"role": "user", "content": user_input})

        # 2. 슬라이딩 윈도우 적용 (최신 N개 턴만 슬라이싱)
        recent_history = self.history[-(self.max_turns * 2):]
        full_messages = [self.system_message] + recent_history

        # 3. API 호출
        response = self.client.chat.completions.create(
            model="gpt-4o-mini",
            messages=full_messages
        )

        bot_reply = response.choices[0].message.content
        self.history.append({"role": "assistant", "content": bot_reply})
        return bot_reply

# 챗봇 사용 테스트
bot = MemoryChatbot(client, max_history_turns=3)
print(bot.chat("안녕! 나는 서울에 사는 개발자 인상이야."))
print(bot.chat("내가 어디에 산다고 했지?")) # "서울에 사신다고 하셨어요!" 정답 출력

3. 자주 묻는 질문 (Q&A)

Q. 다수의 웹 사용자가 동시에 접속할 때 대화 이력은 어떻게 구분하나요? A. 사용자별로 고유한 session_id (UUID)를 발급하고, Redis나 데이터베이스에 session_id를 키로 하여 대화 기록 리스트를 분리 관리해야 합니다.

🎓 DAVHAVE AI & 모바일 개발 마스터링

AI 및 마스터 가이드 수강 중 도움이 필요하시거나 사내 AI 교육 및 에이전트 도입 컨설팅이 필요하신가요?

AI 마스터 문의하기 →
https://davhave.com/education/ai/claude/ch07-conversational-ai-history
← 이전 레슨벡터 데이터베이스와 임베딩 다음 레슨 →에이전트 설계의 기본