✨Ai 프로젝트 만들기

6. OpenAI 를 활용하여 Aice 자격증 챗봇 만들기 (결과)

@ENFJ 2025. 6. 26. 22:14

결과 물 

슬랙에 다음처럼 안녕 이라고 하면 aice 챗봇이 댓글을 달아서 

스레드 채널이 생성됩니다.

 

그리고 @맨션  을 통하여 챗봇을 불러서 질문을 하면 아래 처럼 또 답을 해줍니다.

대화 내용을 메모리에 저장하여 이전에 나눴던 또는 내가 말했던 대화 내용들을 기억하는 것을 볼 수도  있습니다.


코드

 

app.py

import os
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
import ipdb # ipdb는 파이썬 디버거로, 코드 실행 중에 중단점을 설정하고 변수 상태를 확인할 수 있게 해줌
# ipdb는 개발 중에 코드의 동작을 디버깅하는 데 유용됨   
from backend import aice_chain

# Initializes your app with your bot token and socket mode handler
# Slack API에 연결되는 봇 인스턴스 생성
# 여기에 리스너(이벤트 핸들러)를 등록해서 슬랙 메시지에 반응할 수 있게 함
app = App(token=os.environ.get("SLACK_BOT_TOKEN"))

# Listens to incoming messages that contain "hello"
# 슬랙 채팅방에서 누군가가 "hello"라고 메시지를 보내면 이 함수가 실행
# 이 함수는 메시지를 받고, 그 메시지에 대한 응답을 생성해서 다시 채널에 보내는 역할을 함
# visit https://slack.dev/bolt-python/api-docs/slack_bolt/kwargs_injection/args.html
@app.message("안녕")
def message_hello(message, say):
    # say(...) 함수는 같은 채널에 메시지를 다시 보내주는 함수야
    # <@{user}> 문법은 슬랙에서 멘션을 의미함 (즉, 사용자에게 직접 말하는 것처럼 보여)
    # breakpoint()
    message_text = message.get("text")
    response = aice_chain(message_text)
    say(response,thread_ts=message.get("ts"))
    # say(f"안녕하세요  <@{message['user']}> 님!")


# Listens to app_mention events
# 이 이벤트는 봇이 멘션되었을 때 발생
# 사용자가 봇을 멘션하면 이 함수가 실행되어, 봇이 응답을 생성하고 채널에 메시지를 보내는 역할을 함
@app.event("app_mention")
def aice_player(event, say):
    thread_ts = event["thread_ts"] or event["ts"] # 스레드 메시지의 경우, thread_ts가 없으면 ts를 사용
    text = event["text"]
    conversations = app.client.conversations_replies(channel=event['channel'] ,ts=thread_ts) # conversations_replies 메서드는 스레드 메시지의 경우, thread_ts를 사용하여 대화에 응답
    context = [('ai'if msg['user'] == 'U091U2CE5EV' else 'human', msg['text']) for msg in conversations.data['messages']][:-1]
    response = aice_chain(text, context) # ✅ GPT 체인 실행
    say(text=response, thread_ts=thread_ts)# ✅ 응답 전송

    # conversations = app.client.conversations_replies(channel=event["channel"], ts=thread_ts) # 스레드 메시지의 경우, thread_ts를 사용하여 대화에 응답
    # context = [('ai' if msg['user'] =='U091E3JVCQ5'else 'human',msg['text']) 
            # for msg in conversations['messages'] if 'text' in msg and msg['text'] != ''] # 스레드 메시지의 경우, 대화 내용을 가져옴


# Start your app
# 이 핸들러는 슬랙 이벤트를 실시간으로 처리할 수 있게 해줌
if __name__ == "__main__":
    SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start()

 

 

backend.py

import os
import getpass

from dotenv import load_dotenv

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser


load_dotenv()
model = ChatOpenAI(model="gpt-4o", api_key=os.environ["OPENAI_API_KEY"])


# os.environ["OPENAI_API_KEY"] = getpass.getpass()

def aice_chain(text:str, context:list):
    system_prompt = '''
You are an expert tutor and test generator for the AICE (AI Certificate Exam).
You help students prepare for both the AICE Basic and Associate levels.
The student's goal is to pass the certification, and they are using you to review key concepts and solve practice questions.

Your tasks include:
- Summarizing key concepts in a simple, beginner-friendly way
- Generating 2 to 3 practice questions (multiple choice or short answer) based on real exam style
- Providing clear answers and explanations for each question
- Giving hints and feedback for common mistakes

Output your response in Markdown format with the following structure:
1. [Summary of Key Concepts]
2. [Practice Questions]
3. [Answers and Explanations]
4. [Tips for Further Study]

All explanations should be in simple English, and the tone should be encouraging and educational.
'''


    prompt_template = ChatPromptTemplate.from_messages([
            ("system", system_prompt), 
            *context,
            ("user", "{text}"),
            
            ])


    # result = prompt_template.invoke({"language": "italian", "text": "hi"})


    chain = prompt_template | model | StrOutputParser()


    return chain.invoke({'text': text})

 

requirements.txt

slack_bolt
python-dotenv
langchain
langchain-openai
ipython

 

.env

SLACK_APP_TOKEN= 본인 슬랙 앱 토큰 값
SLACK_BOT_TOKEN= 본인 슬랙 봇 토큰 값
OPENAI_API_KEY= 본인 오픈AI API 키 값

 

 

 

감사합니다. 🤗👍