Spaces:
Sleeping
Sleeping
fkt
commited on
Commit
·
0e3780a
1
Parent(s):
1b3c845
refactor code
Browse files
README.md
CHANGED
|
@@ -1,22 +1,67 @@
|
|
| 1 |
---
|
| 2 |
title: First Chatbot
|
| 3 |
-
emoji:
|
| 4 |
colorFrom: indigo
|
| 5 |
colorTo: pink
|
| 6 |
sdk: streamlit
|
| 7 |
sdk_version: 1.44.0
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
-
short_description:
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
| 14 |
|
| 15 |
-
|
| 16 |
|
|
|
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
|
|
|
| 19 |
|
| 20 |
-
|
| 21 |
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: First Chatbot
|
| 3 |
+
emoji: 🤖
|
| 4 |
colorFrom: indigo
|
| 5 |
colorTo: pink
|
| 6 |
sdk: streamlit
|
| 7 |
sdk_version: 1.44.0
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
+
short_description: A simple chatbot using Streamlit and Hugging Face.
|
| 11 |
---
|
| 12 |
|
| 13 |
+
# 🤖 나만의 개인 챗봇
|
| 14 |
|
| 15 |
+
Hugging Face 모델과 Streamlit을 사용하여 만든 간단한 대화형 챗봇입니다. 사이드바에서 AI의 성격, 시작 메시지, 아바타 등을 직접 설정하고 AI와 대화를 나눌 수 있습니다.
|
| 16 |
|
| 17 |
+
## ✨ 주요 기능
|
| 18 |
|
| 19 |
+
- **💬 실시간 채팅 인터페이스**: 사용자와 AI가 메시지를 주고받는 깔끔한 UI.
|
| 20 |
+
- **🔧 손쉬운 설정**: 사이드바에서 시스템 메시지, 시작 메시지, 최대 응답 길이를 쉽게 변경할 수 있습니다.
|
| 21 |
+
- **🎨 커스텀 아바타**: 사용자와 AI의 아바타를 원하는 이모티콘으로 선택할 수 있습니다.
|
| 22 |
+
- **🧠 유연한 모델 사용**: Hugging Face에 있는 다양한 언어 모델(`MODEL_ID` 변경)을 활용할 수 있습니다.
|
| 23 |
+
- **🔄 대화 초기화**: 버튼 클릭 한 번으로 대화 기록을 초기화하고 새 대화를 시작할 수 있습니다.
|
| 24 |
|
| 25 |
+
## 🛠️ 시작하기
|
| 26 |
|
| 27 |
+
### 1. 환경 설정
|
| 28 |
|
| 29 |
+
이 프로젝트는 `uv`와 같은 가상 환경 도구를 사용하는 것을 권장합니다.
|
| 30 |
+
|
| 31 |
+
먼저, 필요한 라이브러리를 설치하세요.
|
| 32 |
+
|
| 33 |
+
```bash
|
| 34 |
+
uv pip install -r requirements.txt
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
### 2. Hugging Face 토큰 설정
|
| 38 |
+
|
| 39 |
+
프로젝트 루트 디렉터리에 `.env` 파일을 생성하고, 여러분의 Hugging Face API 토큰을 추가하세요. 토큰은 [Hugging Face 설정](https://huggingface.co/settings/tokens)에서 발급받을 수 있습니다.
|
| 40 |
+
|
| 41 |
+
```
|
| 42 |
+
HF_TOKEN="ここにHugging Faceのトークンを貼り付けてください"
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
### 3. 애플리케이션 실행
|
| 46 |
+
|
| 47 |
+
터미널에서 아래 명령어를 실행하여 Streamlit 앱을 시작하세요.
|
| 48 |
+
|
| 49 |
+
```bash
|
| 50 |
+
uv run streamlit run app.py
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
앱이 실행되면 웹 브라우저에서 로컬 주소(예: `http://localhost:8501`)가 열립니다.
|
| 54 |
+
|
| 55 |
+
## 📂 코드 구조
|
| 56 |
+
|
| 57 |
+
`app.py` 파일은 가독성과 유지보수성을 높이기 위해 기능별로 모듈화되었습니다.
|
| 58 |
+
|
| 59 |
+
- **상수 정의**: `MODEL_ID`, `PROMPT_TEMPLATE` 등 주요 설정값을 파일 상단에서 관리합니다.
|
| 60 |
+
- **LLM 및 체인 설정 (`get_llm`, `get_chain`)**: Hugging Face 모델을 로드하고, LangChain으로 프롬프트와 모델을 연결하는 체인을 생성합니다.
|
| 61 |
+
- **UI 렌더링 (`initialize_session_state`, `setup_sidebar`, `display_chat_history`)**: Streamlit의 세션 상태를 초기화하고, 사이드바와 채팅 기록 UI를 구성합니다.
|
| 62 |
+
- **메인 로직 (`generate_response`, `main`)**: 사용자 입력을 받아 AI의 응답을 생성하고, 전체 애플리케이션의 흐름을 제어합니다.
|
| 63 |
+
|
| 64 |
+
## 📚 참고 자료
|
| 65 |
+
|
| 66 |
+
- [Creating Your Personal Chatbot Using Hugging Face Spaces and Streamlit](https://medium.com/@james.irving.phd/creating-your-personal-chatbot-using-hugging-face-spaces-and-streamlit-596a54b9e3ed)
|
| 67 |
+
- [Hugging Face Spaces Configuration Reference](https.huggingface.co/docs/hub/spaces-config-reference)
|
app.py
CHANGED
|
@@ -1,194 +1,198 @@
|
|
| 1 |
import os
|
| 2 |
-
|
| 3 |
-
from langchain_huggingface import HuggingFaceEndpoint
|
| 4 |
import streamlit as st
|
| 5 |
-
from
|
| 6 |
from langchain_core.output_parsers import StrOutputParser
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
# .env 파일 로드
|
| 12 |
-
load_dotenv()
|
| 13 |
|
|
|
|
| 14 |
|
| 15 |
-
def
|
| 16 |
"""
|
| 17 |
-
Hugging Face 추론을 위한 언어
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
- temperature (float): 모델에서 샘플링할 때의 온도 값입니다.
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
"""
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
token=os.getenv("HF_TOKEN"), # Hugging Face API 토큰 (환경 변수에서 가져옴)
|
| 33 |
)
|
| 34 |
-
return llm # 초기화된 언어 모델을 반환합니다.
|
| 35 |
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
st.markdown(
|
| 41 |
-
f"*이것은 HuggingFace transformers 라이브러리를 사용하여 텍스트 입력에 대한 응답을 생성하는 간단한 챗봇입니다. {model_id} 모델을 사용합니다.*"
|
| 42 |
-
)
|
| 43 |
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
st.session_state.avatars = {"user": None, "assistant": None}
|
| 47 |
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
| 51 |
|
| 52 |
-
# 모델 매개변수에 대한 세션 상태를 초기화합니다.
|
| 53 |
-
if "max_response_length" not in st.session_state:
|
| 54 |
-
st.session_state.max_response_length = 256
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
|
|
|
|
|
|
| 63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
-
# 설정을 위한 사이드바를 구성합니다.
|
| 66 |
-
with st.sidebar:
|
| 67 |
-
st.header("시스템 설정")
|
| 68 |
|
| 69 |
-
|
| 70 |
-
st.session_state.system_message = st.text_area(
|
| 71 |
-
"시스템 메시지", value="당신은 인간 사용자와 대화하는 친절한 AI입니다."
|
| 72 |
-
)
|
| 73 |
-
st.session_state.starter_message = st.text_area(
|
| 74 |
-
"첫 번째 AI 메시지", value="안녕하세요! 오늘 무엇을 도와드릴까요?"
|
| 75 |
-
)
|
| 76 |
|
| 77 |
-
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
col1, col2 = st.columns(2)
|
| 83 |
-
with col1:
|
| 84 |
-
st.session_state.avatars["assistant"] = st.selectbox(
|
| 85 |
-
"AI 아바타", options=["🤗", "💬", "🤖"], index=0
|
| 86 |
)
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
"사용자 아바타", options=["👤", "👱♂️", "👨🏾", "👩", "👧🏾"], index=0
|
| 90 |
)
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
"""
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
매개변수:
|
| 113 |
-
system_message (str): 대화의 시스템 메시지입니다.
|
| 114 |
-
chat_history (list): 이전 채팅 메시지 목록입니다.
|
| 115 |
-
user_text (str): 사용자의 입력 텍스트입니다.
|
| 116 |
-
model_id (str, optional): 사용할 Hugging Face 모델의 ID입니다.
|
| 117 |
-
eos_token_id (list, optional): 문장 종료 토큰 ID 목록입니다.
|
| 118 |
-
max_new_tokens (int, optional): 생성할 수 있는 최대 새 토큰 수입니다.
|
| 119 |
-
get_llm_hf_kws (dict, optional): get_llm_hf 함수에 전달할 추가 키워드 인자입니다.
|
| 120 |
-
|
| 121 |
-
반환값:
|
| 122 |
-
tuple: 생성된 응답과 업데이트된 채팅 기록을 포함하는 튜플입니다.
|
| 123 |
"""
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
"[INST] {system_message}"
|
| 131 |
-
"\n현재 대화:\n{chat_history}\n\n"
|
| 132 |
-
"\n사용자: {user_text}.\n [/INST]"
|
| 133 |
-
"\nAI:"
|
| 134 |
-
)
|
| 135 |
-
)
|
| 136 |
-
# 프롬프트를 연결하여 채팅 체인을 만듭니다.
|
| 137 |
-
chat = prompt | hf.bind(skip_prompt=True) | StrOutputParser(output_key="content")
|
| 138 |
-
|
| 139 |
-
# 응답을 생성합니다.
|
| 140 |
-
response = chat.invoke(
|
| 141 |
-
input=dict(
|
| 142 |
-
system_message=system_message,
|
| 143 |
-
user_text=user_text,
|
| 144 |
-
chat_history=chat_history,
|
| 145 |
-
)
|
| 146 |
-
)
|
| 147 |
-
# "AI:" 접두사를 제거합니다.
|
| 148 |
-
response = response.split("AI:")[-1]
|
| 149 |
|
| 150 |
-
# 채팅 기록을 업데이트합니다.
|
| 151 |
-
chat_history.append({"role": "user", "content": user_text})
|
| 152 |
-
chat_history.append({"role": "assistant", "content": response})
|
| 153 |
-
return response, chat_history
|
| 154 |
|
|
|
|
| 155 |
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
)
|
| 163 |
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
# 채팅 기록에 있는 각 메시지에 대해 반복합니다.
|
| 167 |
-
for message in st.session_state.chat_history:
|
| 168 |
-
# 시스템 메시지는 건너뜁니다.
|
| 169 |
-
if message["role"] == "system":
|
| 170 |
-
continue
|
| 171 |
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
message["role"], avatar=st.session_state["avatars"][message["role"]]
|
| 175 |
-
):
|
| 176 |
-
st.markdown(message["content"])
|
| 177 |
|
| 178 |
-
#
|
| 179 |
-
if st.
|
| 180 |
-
#
|
|
|
|
| 181 |
with st.chat_message("user", avatar=st.session_state.avatars["user"]):
|
| 182 |
-
st.markdown(
|
| 183 |
|
| 184 |
-
#
|
| 185 |
with st.chat_message("assistant", avatar=st.session_state.avatars["assistant"]):
|
| 186 |
with st.spinner("생각 중..."):
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
|
|
|
| 193 |
)
|
|
|
|
| 194 |
st.markdown(response)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
|
|
|
|
| 3 |
import streamlit as st
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
from langchain_core.output_parsers import StrOutputParser
|
| 6 |
+
from langchain_core.prompts import PromptTemplate
|
| 7 |
+
from langchain_huggingface import HuggingFaceEndpoint
|
| 8 |
+
|
| 9 |
+
# --- 상수 정의 ---
|
| 10 |
+
# 사용할 Hugging Face 모델 ID
|
| 11 |
+
MODEL_ID = "google/gemma-3n-e4b"
|
| 12 |
+
# 프롬프트 템플릿
|
| 13 |
+
PROMPT_TEMPLATE = """
|
| 14 |
+
[INST] {system_message}
|
| 15 |
+
현재 대화:
|
| 16 |
+
{chat_history}
|
| 17 |
|
| 18 |
+
사용자: {user_text}
|
| 19 |
+
[/INST]
|
| 20 |
+
AI:
|
| 21 |
+
"""
|
| 22 |
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
# --- LLM 및 체인 설정 함수 ---
|
| 25 |
|
| 26 |
+
def get_llm(max_new_tokens=128, temperature=0.1):
|
| 27 |
"""
|
| 28 |
+
Hugging Face 추론을 위한 언어 모델(LLM)을 생성하고 반환합니다.
|
| 29 |
|
| 30 |
+
Args:
|
| 31 |
+
max_new_tokens (int): 생성할 최대 토큰 수입니다.
|
| 32 |
+
temperature (float): 샘플링 온도로, 낮을수록 결정적인 답변을 생성합니다.
|
|
|
|
| 33 |
|
| 34 |
+
Returns:
|
| 35 |
+
HuggingFaceEndpoint: 설정된 언어 모델 객체입니다.
|
| 36 |
"""
|
| 37 |
+
return HuggingFaceEndpoint(
|
| 38 |
+
repo_id=MODEL_ID,
|
| 39 |
+
max_new_tokens=max_new_tokens,
|
| 40 |
+
temperature=temperature,
|
| 41 |
+
token=os.getenv("HF_TOKEN"),
|
|
|
|
| 42 |
)
|
|
|
|
| 43 |
|
| 44 |
|
| 45 |
+
def get_chain(llm):
|
| 46 |
+
"""
|
| 47 |
+
주어진 언어 모델(LLM)을 사용하여 대화 체인을 생성합니다.
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
+
Args:
|
| 50 |
+
llm (HuggingFaceEndpoint): 사용할 언어 모델입니다.
|
|
|
|
| 51 |
|
| 52 |
+
Returns:
|
| 53 |
+
RunnableSequence: LangChain 표현 언어(LCEL)로 구성된 실행 가능한 체인입니다.
|
| 54 |
+
"""
|
| 55 |
+
prompt = PromptTemplate.from_template(PROMPT_TEMPLATE)
|
| 56 |
+
return prompt | llm | StrOutputParser()
|
| 57 |
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
+
def generate_response(chain, system_message, chat_history, user_text):
|
| 60 |
+
"""
|
| 61 |
+
LLM 체인을 호출하여 사용자의 입력에 대한 응답을 생성합니다.
|
| 62 |
|
| 63 |
+
Args:
|
| 64 |
+
chain (RunnableSequence): 응답 생성을 위한 LLM 체인입니다.
|
| 65 |
+
system_message (str): AI의 역할을 정의하는 시스템 메시지입니다.
|
| 66 |
+
chat_history (list[dict]): 이전 대화 기록입니다.
|
| 67 |
+
user_text (str): 사용자의 현재 입력 메시지입니다.
|
| 68 |
|
| 69 |
+
Returns:
|
| 70 |
+
str: 생성된 AI의 응답 메시지입니다.
|
| 71 |
+
"""
|
| 72 |
+
history_str = "\n".join(
|
| 73 |
+
[f"{msg['role']}: {msg['content']}" for msg in chat_history]
|
| 74 |
+
)
|
| 75 |
+
response = chain.invoke({
|
| 76 |
+
"system_message": system_message,
|
| 77 |
+
"chat_history": history_str,
|
| 78 |
+
"user_text": user_text,
|
| 79 |
+
})
|
| 80 |
+
return response.split("AI:")[-1].strip()
|
| 81 |
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
+
# --- UI 렌더링 함수 ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
+
def initialize_session_state():
|
| 86 |
+
"""
|
| 87 |
+
Streamlit 세션 상태를 초기화합니다.
|
| 88 |
+
세션이 처음 시작될 때 기본값을 설정합니다.
|
| 89 |
+
"""
|
| 90 |
+
defaults = {
|
| 91 |
+
"avatars": {"user": "👤", "assistant": "🤗"},
|
| 92 |
+
"chat_history": [],
|
| 93 |
+
"max_response_length": 256,
|
| 94 |
+
"system_message": "당신은 인간 사용자와 대화하는 친절한 AI입니다.",
|
| 95 |
+
"starter_message": "안녕하세요! 오늘 무엇을 도와드릴까요?",
|
| 96 |
+
}
|
| 97 |
+
for key, value in defaults.items():
|
| 98 |
+
if key not in st.session_state:
|
| 99 |
+
st.session_state[key] = value
|
| 100 |
+
|
| 101 |
+
if not st.session_state.chat_history:
|
| 102 |
+
st.session_state.chat_history = [
|
| 103 |
+
{"role": "assistant", "content": st.session_state.starter_message}
|
| 104 |
+
]
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def setup_sidebar():
|
| 108 |
+
"""
|
| 109 |
+
사이드바 UI 구성 요소를 설정하고 렌더링합니다.
|
| 110 |
+
사용자는 이 사이드바에서 시스템 설정, AI 메시지, 모델 응답 길이 등을 조정할 수 있습니다.
|
| 111 |
+
"""
|
| 112 |
+
with st.sidebar:
|
| 113 |
+
st.header("시스템 설정")
|
| 114 |
|
| 115 |
+
st.session_state.system_message = st.text_area(
|
| 116 |
+
"시스템 메시지", value=st.session_state.system_message
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
)
|
| 118 |
+
st.session_state.starter_message = st.text_area(
|
| 119 |
+
"첫 번째 AI 메시지", value=st.session_state.starter_message
|
|
|
|
| 120 |
)
|
| 121 |
+
st.session_state.max_response_length = st.number_input(
|
| 122 |
+
"최대 응답 길이", value=st.session_state.max_response_length
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
st.markdown("*아바타 선택:*")
|
| 126 |
+
col1, col2 = st.columns(2)
|
| 127 |
+
with col1:
|
| 128 |
+
st.session_state.avatars["assistant"] = st.selectbox(
|
| 129 |
+
"AI 아바타", options=["🤗", "💬", "🤖"], index=0
|
| 130 |
+
)
|
| 131 |
+
with col2:
|
| 132 |
+
st.session_state.avatars["user"] = st.selectbox(
|
| 133 |
+
"사용자 아바타", options=["👤", "👱♂️", "👨🏾", "👩", "👧🏾"], index=0
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
if st.button("채팅 기록 초기화"):
|
| 137 |
+
st.session_state.chat_history = [
|
| 138 |
+
{"role": "assistant", "content": st.session_state.starter_message}
|
| 139 |
+
]
|
| 140 |
+
st.rerun()
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def display_chat_history():
|
| 144 |
"""
|
| 145 |
+
세션에 저장된 채팅 기록을 순회하며 화면에 메시지를 표시합니다.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
"""
|
| 147 |
+
for message in st.session_state.chat_history:
|
| 148 |
+
if message["role"] == "system":
|
| 149 |
+
continue
|
| 150 |
+
avatar = st.session_state.avatars.get(message["role"])
|
| 151 |
+
with st.chat_message(message["role"], avatar=avatar):
|
| 152 |
+
st.markdown(message["content"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
+
# --- 메인 애플리케이션 실행 ---
|
| 156 |
|
| 157 |
+
def main():
|
| 158 |
+
"""
|
| 159 |
+
메인 Streamlit 애플리케이션을 실행합니다.
|
| 160 |
+
"""
|
| 161 |
+
load_dotenv()
|
| 162 |
+
|
| 163 |
+
st.set_page_config(page_title="HuggingFace ChatBot", page_icon="🤗")
|
| 164 |
+
st.title("개인 HuggingFace 챗봇")
|
| 165 |
+
st.markdown(
|
| 166 |
+
f"*이것은 HuggingFace transformers 라이브러리를 사용하여 텍스트 입력에 대한 응답을 생성하는 간단한 챗봇입니다. {MODEL_ID} 모델을 사용합니다.*"
|
| 167 |
)
|
| 168 |
|
| 169 |
+
initialize_session_state()
|
| 170 |
+
setup_sidebar()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
+
# 채팅 기록 표시
|
| 173 |
+
display_chat_history()
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
+
# 사용자 입력 처리
|
| 176 |
+
if user_input := st.chat_input("여기에 텍스트를 입력하세요."):
|
| 177 |
+
# 사용자 메시지를 기록에 추가하고 화면에 표시
|
| 178 |
+
st.session_state.chat_history.append({"role": "user", "content": user_input})
|
| 179 |
with st.chat_message("user", avatar=st.session_state.avatars["user"]):
|
| 180 |
+
st.markdown(user_input)
|
| 181 |
|
| 182 |
+
# AI 응답 생성 및 표시
|
| 183 |
with st.chat_message("assistant", avatar=st.session_state.avatars["assistant"]):
|
| 184 |
with st.spinner("생각 중..."):
|
| 185 |
+
llm = get_llm(max_new_tokens=st.session_state.max_response_length)
|
| 186 |
+
chain = get_chain(llm)
|
| 187 |
+
response = generate_response(
|
| 188 |
+
chain,
|
| 189 |
+
st.session_state.system_message,
|
| 190 |
+
st.session_state.chat_history,
|
| 191 |
+
user_input,
|
| 192 |
)
|
| 193 |
+
st.session_state.chat_history.append({"role": "assistant", "content": response})
|
| 194 |
st.markdown(response)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
if __name__ == "__main__":
|
| 198 |
+
main()
|