File size: 11,367 Bytes
52a84f2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 |
import os
import csv
import time
import torch
import argparse
import chromadb
import datetime
import gradio as gr
from groq import Groq
from pathlib import Path
from prompt_db import *
from chromadb.utils import embedding_functions
def get_chroma_collection(db_path: str, collection_name: str, *, embedf_name: str = "") -> chromadb.Collection | None:
"""
ChromaDB ํด๋ผ์ด์ธํธ ๋ฐ ์ปฌ๋ ์
๋ก๋
input
dp_path : chromadb colletion์ด ์กด์ฌํ๋ ์ ๋ ๊ฒฝ๋ก
collection_name : chromadb colletion์ ์ด๋ฆ
output
collectoin : chromadb collection ๊ฐ์ฒด
"""
if not os.path.exists(db_path):
print(f"collection {collection_name} ์(๋ฅผ) ์ฐพ์ ์ ์์ต๋๋ค. ๊ฒฝ๋ก๋ฅผ ๋ค์ ํ์ธํด์ฃผ์ธ์.")
return None
chro_client = chromadb.PersistentClient(path=db_path)
if embedf_name:
embed_fun = embedding_functions.SentenceTransformerEmbeddingFunction(
model_name = embedf_name,
device = "cuda" if torch.cuda.is_available() else "cpu"
)
print(f"์๋ฒ ๋ฉ ํจ์๋ก {embedf_name} ๋ฅผ ์ฌ์ฉํฉ๋๋ค. ")
else:
embed_fun = embedding_functions.DefaultEmbeddingFunction()
print("์๋ฒ ๋ฉ ํจ์๋ก ๊ธฐ๋ณธ ์๋ฒ ๋ฉ ํจ์๋ฅผ ์ฌ์ฉํฉ๋๋ค. ")
# ๊ธฐ์กด collection ๋ถ๋ฌ์ค๊ธฐ
try:
collection = chro_client.get_collection(
name = collection_name,
embedding_function = embed_fun)
print(f"Collection '{collection_name}' ์(๋ฅผ) ์ฑ๊ณต์ ์ผ๋ก ๋ถ๋ฌ์์ต๋๋ค. ")
return collection
except Exception as e:
print(f"Collection '{collection_name}' ์(๋ฅผ) ๋ถ๋ฌ์ค์ง ๋ชปํ์ต๋๋ค : {e}")
return None
def query_db(collection: chromadb.Collection,
query_text: str,
n_results: int) -> str:
"""
์ฌ์ฉ์ ์ง๋ฌธ๊ณผ ๊ด๋ จ๋ ๋ฌธ์๋ฅผ DB(collection)์์ ๊ฒ์ํ์ฌ ๋ฐํ
input
collection :
query_text :
n_results :
output
data : ์ฌ์ฉ์์ ์ง๋ฌธ๊ณผ ๊ด๋ จ๋ ๋ฌธ์
"""
if collection is None:
print("๋ฐ์ดํฐ๋ฒ ์ด์ค๊ฐ ์ฐ๊ฒฐ๋์ง ์์์ต๋๋ค.")
return ""
try:
results = collection.query(
query_texts = [query_text],
n_results = n_results
)
# ๊ฒ์๋ ๋ฌธ์๊ฐ ์๋ ๊ฒฝ์ฐ
if not results["documents"] or not results["documents"][0]:
print("๊ด๋ จ๋ ๋ฌธ์๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค.")
return ""
# ๊ฒ์๋ ๋ฌธ์๋ค์ ํ๋์ ๋ฌธ์์ด๋ก ๊ฒฐํฉ
documents = results["documents"][0]
metadatas = results["metadatas"][0]
context_parts = []
for i, doc in enumerate(documents):
source = metadatas[i].get("title", "์ ๋ชฉ ์์")
date = metadatas[i].get("date", "๋ ์ง ์์")
context_parts.append(f"๋ฌธ์{i+1} [์ ๋ชฉ: {source}, ๋ ์ง: {date}]\n๋ด์ฉ : {doc}")
data = "\n\n".join(context_parts)
return data
except Exception as e:
print(f"๊ฒ์ ์ค ์ค๋ฅ ๋ฐ์: {e}")
return ""
def save_log(base_dir, log_dir, request, user_message, assistant_message):
"""
๋ํ ๋ก๊ทธ ์ ์ฅ ํจ์
"""
log_path = os.path.join(base_dir, log_dir)
if not os.path.exists(log_path):
os.mkdir(log_path)
print(f"{log_dir} ํด๋๊ฐ ์์ฑ๋์์ต๋๋ค : {log_path}")
# ํ์ฌ ๊ฒฝ๋ก ๋ด์ ์๋ {log_dir} ํด๋ ๋ด์ ๋ํ ๋ก๊ทธ ํ์ผ์ด ์๋ ๊ฒฝ์ฐ -> csvํ์ผ ์์ฑ
# ๊ฐ csv ํ์ผ์ ๋ ์ง๋ณ๋ก ๊ตฌ๋ถ
today = datetime.datetime.now().strftime("%y%m%d")
file_name = f"chat_log_{today}.csv"
dest_file_path = os.path.join(log_path, file_name)
if not os.path.exists(dest_file_path):
with open(dest_file_path, mode = "w", newline = "", encoding = "utf-8") as file:
writer = csv.writer(file)
writer.writerow(["user_ip", "time_stamp", "user_message", "assistant_message"])
# ์ฑ๋ด๊ณผ์ ๋ํ ๋ก๊ทธ๋ฅผ ๊ธฐ๋ก
user_ip = request.client.host if request else "Unknown_IP"
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
user_conv_log = [user_ip, timestamp, user_message, assistant_message]
try:
with open(dest_file_path, mode = "a", newline = "", encoding = "utf-8") as file:
writer = csv.writer(file)
writer.writerow(user_conv_log)
except Exception as e:
print(f"๋ํ ๋ก๊ทธ ์ ์ฅ ์คํจ : {e}")
def get_response(user_message: str,
system_prompt: str,
collection: chromadb.Collection,
history: list[dict | list],
request: gr.Request,
client: Groq,
base_dir: str,
log_dir: str,
model_name: str,
n_results: int,
temperature: float):
if user_message.strip() == "๋๋":
end_message = "๋ํ๋ฅผ ์ข
๋ฃํฉ๋๋ค. ์ ๋ํ๋ฅผ ์์ํ๋ ค๋ฉด ์ค๋ฅธ์ชฝ ์๋จ์ Clear ๋ฒํผ(ํด์งํต ์์ด์ฝ)์ ํด๋ฆญํด์ฃผ์ธ์."
yield end_message
return
# RAG: ์ฌ์ฉ์ ์ง๋ฌธ๊ณผ ๊ด๋ จ๋ Context ๊ฒ์
context = query_db(collection = collection,
query_text = user_message,
n_results= n_results)
# System Prompt์ Context ์ฃผ์
formatted_system_prompt = system_prompt.format(context=context)
# ๋ฉ์์ง ๊ตฌ์ฑ
messages = [{"role": "system", "content": formatted_system_prompt}]
for chat in history:
if isinstance(chat, dict):
messages.append({"role": chat["role"], "content": chat["content"]})
# ๊ตฌ๋ฒ์ gradio ์ํจ
elif isinstance(chat, list) and len(chat) == 2:
messages.append({"role": "user", "content": chat[0]})
messages.append({"role": "assistant", "content": chat[1]})
messages.append({"role": "user", "content": user_message})
# LLM์๊ฒ ๋ต๋ณ ์์ฑ ์์ฒญ
try:
response = client.chat.completions.create(
model = model_name,
messages = messages,
temperature = temperature,
stream = True
)
# ์ฌ์ฉ์์๊ฒ ์ฑ๋ด์ ๋ต๋ณ์ด ์ค์๊ฐ์ผ๋ก ์
๋ ฅ๋๋ ๊ฒ์ฒ๋ผ ๋ณด์ฌ์ค
assistant_message = ""
for chunk in response:
delta = chunk.choices[0].delta.content
if delta:
assistant_message += delta
yield assistant_message
except Exception as e:
error_message = f"๋ต๋ณ ์์ฑ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค. : {str(e)}"
yield error_message
assistant_message = error_message
save_log(base_dir, log_dir, request, user_message, assistant_message)
def chat_with_rag(api_key: str,
collection: chromadb.Collection,
system_prompt: str,
args: argparse.ArgumentParser) -> None:
"""
RAG ์ฑ๋ด ์คํ
input
dd
output
-
"""
try:
groq_client = Groq(api_key = api_key)
except Exception as e:
print(f"Groq client๋ฅผ ๋ถ๋ฌ์ค์ง ๋ชปํ์ต๋๋ค. API Key๋ฅผ ํ์ธํด์ฃผ์ธ์ : {e}")
def predict(user_message, history, request: gr.Request):
yield from get_response(
user_message = user_message,
system_prompt = system_prompt,
collection = collection,
history = history,
request = request,
client = groq_client,
base_dir = args.base_dir,
log_dir = args.log_dir,
model_name = args.model_name,
n_results = args.n_results,
temperature = args.temperature
)
title = "ChaTech"
description = """
์์ธ๊ณผํ๊ธฐ์ ๋ํ๊ต ๊ณต์ง์ฌํญ ๊ธฐ๋ฐ ์ง์์๋ต ์ฑ๋ด์
๋๋ค.
๋ฐ์ดํฐ๋ฒ ์ด์ค์ ์ ์ฅ๋ ๊ณต์ง์ฌํญ ๋ด์ฉ์ ๋ฐํ์ผ๋ก ๋ต๋ณํฉ๋๋ค.
๋ํ ์ข
๋ฃ๋ฅผ ์ํ์ค ๊ฒฝ์ฐ ์ฑํ
์ฐฝ์ \'๋๋\'์ ์
๋ ฅํด์ฃผ์ธ์.
"""
demo = gr.ChatInterface(
fn = predict,
title = title,
description = description
).queue()
demo.launch(debug = True, share = True)
def get_system_prompt(prompt_type: str) -> str:
"""
prompt_db.py๋ก๋ถํฐ ์์คํ
ํ๋กฌํํธ๋ฅผ ๋ถ๋ฌ์์ ๋ฐํ
input
prompt_type : ์ฌ์ฉํ ์์คํ
ํ๋กฌํํธ ์ข
๋ฅ
v : vanilla prompt
adv1 : advanced prompt ver.1 (๋ฏธ๊ตฌํ)
output
system_prompt : ์์คํ
ํ๋กฌํํธ ์ ๋ฌธ
"""
if prompt_type == "v":
vanilla = Vanilla()
system_prompt = vanilla.get_prompt()
return system_prompt
# ๊ฐ์ ๋ ํ๋กฌํํธ ๋ฒ์ , ์์ง ๋ฏธ๊ตฌํ
elif prompt_type == "adv1":
system_prompt = ""
return system_prompt
else:
print("์ ํจํ์ง ์์ ํ๋กฌํํธ ํ์
์
๋๋ค. ๊ธฐ๋ณธ๊ฐ(Vanilla)์ ์ฌ์ฉํฉ๋๋ค. ")
system_prompt = vanilla.get_prompt()
return system_prompt
def main(args):
# chromadb collection ๊ฒฝ๋ก ์ค์
abs_db_path = os.path.join(args.base_dir, args.db_dir)
# collection ๊ฐ์ฒด ๋ถ๋ฌ์ค๊ธฐ
collection = get_chroma_collection(abs_db_path, args.collection_name)
# embedding function๋ก ๋ค๋ฅธ ๋ชจ๋ธ์ ์ฌ์ฉํ ๊ฒฝ์ฐ
# collection = get_chroma_collection(abs_db_path, args.collection_name, embedf_name = args.embedf_name)
if collection is None:
print("Chromadb Collection์ ๋ถ๋ฌ์ค์ง ๋ชปํ์ต๋๋ค. ํ๋ก๊ทธ๋จ์ ์ข
๋ฃํฉ๋๋ค. ")
return
# ์์คํ
ํ๋กฌํํธ ๋ถ๋ฌ์ค๊ธฐ
system_prompt = get_system_prompt(args.prompt_type)
# ์ฑ๋ด ์คํ
chat_with_rag(api_key = args.api_key,
collection = collection,
system_prompt = system_prompt,
args = args)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--api_key", type = str, default = "")
parser.add_argument("--base_dir", type = str, default = str(Path(__file__).resolve().parent))
parser.add_argument("--db_dir", type = str, default = "seoultech_data_db")
parser.add_argument("--log_dir", type = str, default = "chat_log")
parser.add_argument("--model_name", type = str, default = "llama-3.3-70b-versatile") # llama-3.1-8b-instant llama-3.3-70b-versatile openai/gpt-oss-120b
parser.add_argument("--temperature", type = float, default = 0.5)
parser.add_argument("--n_results", type = int, default = 3)
parser.add_argument("--collection_name", type = str, default = "seoultech_notices")
parser.add_argument("--embedf_name", type = str, default = "BAAI/bge-m3")
parser.add_argument("--prompt_type", type = str, default = "v")
args = parser.parse_args()
main(args)
|