File size: 6,723 Bytes
4739096 |
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 |
# src/utils/conversation_manager.py
"""
๋ํ ํ์คํ ๋ฆฌ ๊ด๋ฆฌ์ (๋ฉ๋ชจ๋ฆฌ ๊ธฐ๋ฐ)
๊ธฐ๋ฅ:
- UI ํ์์ฉ / ๋ถ์์ฉ ํ์คํ ๋ฆฌ ๋ถ๋ฆฌ
- ์ ์ฒด ๋ํ ์ ์ฅ (greeting, thanks, document, out_of_scope)
- JSON ๋ด๋ณด๋ด๊ธฐ
- ํต๊ณ ๊ธฐ๋ฅ
"""
from datetime import datetime
from typing import List, Dict, Optional
import json
import logging
logger = logging.getLogger(__name__)
class ConversationManager:
"""
๋ํ ํ์คํ ๋ฆฌ ๊ด๋ฆฌ (๋ฉ๋ชจ๋ฆฌ ๊ธฐ๋ฐ)
Streamlit session_state์ ํจ๊ป ์ฌ์ฉ:
- UI ํ์คํ ๋ฆฌ: Streamlit ๋ฉ์์ง ํ์
- DB ํ์คํ ๋ฆฌ: ๋ถ์/์ ์ฅ์ฉ ํ์
"""
def __init__(self):
"""์ด๊ธฐํ"""
self.ui_history: List[Dict] = [] # Streamlit ํ์์ฉ
self.db_history: List[Dict] = [] # ๋ถ์/์ ์ฅ์ฉ
logger.info("๐ฌ ConversationManager ์ด๊ธฐํ ์๋ฃ")
def add_message(
self,
user_msg: str,
ai_msg: str,
query_type: str,
sources: Optional[List] = None,
usage: Optional[Dict] = None,
search_mode: Optional[str] = None,
used_retrieval: bool = False,
routing_info: Optional[Dict] = None
):
"""
๋ฉ์์ง ์ถ๊ฐ (์ ์ฒด ์ ์ฅ)
Args:
user_msg: ์ฌ์ฉ์ ์ง๋ฌธ
ai_msg: AI ๋ต๋ณ
query_type: ์ง๋ฌธ ์ ํ (greeting/thanks/document/out_of_scope)
sources: ์ฐธ๊ณ ๋ฌธ์ ๋ฆฌ์คํธ
usage: ํ ํฐ ์ฌ์ฉ๋
search_mode: ๊ฒ์ ๋ชจ๋
used_retrieval: ๊ฒ์ ์ฌ์ฉ ์ฌ๋ถ
routing_info: ๋ผ์ฐํ
์ ๋ณด
"""
timestamp = datetime.now()
# ===== UI ํ์คํ ๋ฆฌ (Streamlit ๋ฉ์์ง ํ์) =====
# ์ฌ์ฉ์ ๋ฉ์์ง
self.ui_history.append({
'role': 'user',
'content': user_msg,
'timestamp': timestamp
})
# AI ๋ฉ์์ง
self.ui_history.append({
'role': 'assistant',
'content': ai_msg,
'sources': sources or [],
'usage': usage or {},
'search_mode': search_mode,
'used_retrieval': used_retrieval,
'routing_info': routing_info,
'type': query_type, # ๋ถ์์ฉ ์ถ๊ฐ
'timestamp': timestamp
})
# ===== DB ํ์คํ ๋ฆฌ (๋ถ์์ฉ) =====
self.db_history.append({
'user': user_msg,
'assistant': ai_msg,
'type': query_type,
'timestamp': timestamp.isoformat(),
'sources_count': len(sources) if sources else 0,
'used_retrieval': used_retrieval,
'search_mode': search_mode,
'routing_info': routing_info
})
logger.info(f"๐พ ๋ํ ์ ์ฅ: {query_type} - {user_msg[:30]}...")
def get_ui_history(self) -> List[Dict]:
"""
UI ํ์์ฉ ํ์คํ ๋ฆฌ ๋ฐํ (Streamlit ํ์)
Returns:
Streamlit ๋ฉ์์ง ๋ฆฌ์คํธ
"""
return self.ui_history
def get_db_history(self, last_n: Optional[int] = None) -> List[Dict]:
"""
๋ถ์/์ ์ฅ์ฉ ํ์คํ ๋ฆฌ ๋ฐํ
Args:
last_n: ์ต๊ทผ N๊ฐ๋ง ๋ฐํ (None์ด๋ฉด ์ ์ฒด)
Returns:
๋ํ ๊ธฐ๋ก ๋ฆฌ์คํธ
"""
if last_n:
return self.db_history[-last_n:]
return self.db_history
def get_history_by_type(self, query_type: str) -> List[Dict]:
"""
ํน์ ์ง๋ฌธ ์ ํ๋ง ํํฐ๋ง
Args:
query_type: 'greeting', 'thanks', 'document', 'out_of_scope'
Returns:
ํํฐ๋ง๋ ๋ํ ๋ฆฌ์คํธ
"""
return [
msg for msg in self.db_history
if msg['type'] == query_type
]
def get_statistics(self) -> Dict[str, int]:
"""
์ง๋ฌธ ์ ํ๋ณ ํต๊ณ
Returns:
{'greeting': 5, 'document': 20, ...}
"""
from collections import Counter
types = [msg['type'] for msg in self.db_history]
stats = dict(Counter(types))
# ์ด ๋ํ ์ ์ถ๊ฐ
stats['total'] = len(self.db_history)
return stats
def export_to_json(self) -> str:
"""
JSON ํ์์ผ๋ก ๋ด๋ณด๋ด๊ธฐ
Returns:
JSON ๋ฌธ์์ด
"""
export_data = {
'timestamp': datetime.now().isoformat(),
'total_conversations': len(self.db_history),
'statistics': self.get_statistics(),
'conversations': self.db_history
}
return json.dumps(export_data, ensure_ascii=False, indent=2)
def clear(self):
"""ํ์คํ ๋ฆฌ ์ด๊ธฐํ"""
self.ui_history = []
self.db_history = []
logger.info("๐๏ธ ๋ํ ํ์คํ ๋ฆฌ ์ด๊ธฐํ")
def __len__(self):
"""๋ํ ๊ฐ์ (์ฌ์ฉ์ ์ง๋ฌธ ๊ธฐ์ค)"""
return len(self.db_history)
def __repr__(self):
stats = self.get_statistics()
return (
f"ConversationManager("
f"total={stats.get('total', 0)}, "
f"document={stats.get('document', 0)}, "
f"greeting={stats.get('greeting', 0)}, "
f"thanks={stats.get('thanks', 0)}, "
f"out_of_scope={stats.get('out_of_scope', 0)})"
)
# ===== ํ
์คํธ ์ฝ๋ =====
if __name__ == "__main__":
# ํ
์คํธ
manager = ConversationManager()
# ๋ํ ์ถ๊ฐ
manager.add_message(
user_msg="์๋
ํ์ธ์",
ai_msg="์๋
ํ์ธ์! ๋ฌด์์ ๋์๋๋ฆด๊น์?",
query_type="greeting"
)
manager.add_message(
user_msg="์์ฐ์ด ์ผ๋ง์ธ๊ฐ์?",
ai_msg="์์ฐ์ 5์ต์์
๋๋ค.",
query_type="document",
sources=[{'content': '์์ฐ: 5์ต์', 'score': 0.95}],
used_retrieval=True,
search_mode="hybrid_rerank"
)
manager.add_message(
user_msg="๊ณ ๋ง์์",
ai_msg="์ฒ๋ง์์! ์ธ์ ๋ ์ง๋ฌธํ์ธ์.",
query_type="thanks"
)
# ํต๊ณ ์ถ๋ ฅ
print("\n===== ํต๊ณ =====")
print(manager.get_statistics())
# ํ์คํ ๋ฆฌ ์ถ๋ ฅ
print("\n===== DB ํ์คํ ๋ฆฌ =====")
for msg in manager.get_db_history():
print(f"{msg['type']}: {msg['user'][:20]}...")
# JSON ๋ด๋ณด๋ด๊ธฐ
print("\n===== JSON Export =====")
print(manager.export_to_json())
# Representation
print("\n===== Manager Info =====")
print(manager) |