-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb_operations.py
More file actions
370 lines (289 loc) ยท 10.7 KB
/
db_operations.py
File metadata and controls
370 lines (289 loc) ยท 10.7 KB
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
from typing import List, Optional, Dict
from sqlalchemy.orm import Session
from sqlalchemy import desc, func
from datetime import datetime
import bcrypt
from database import User, ChatSession, Message, ToolLog, UserFeedback
# ============================================================================
# User Operations
# ============================================================================
def get_password_hash(password: str) -> str:
"""๋น๋ฐ๋ฒํธ ํด์ฑ"""
password_bytes = password.encode('utf-8')[:72]
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(password_bytes, salt)
return hashed.decode('utf-8')
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""๋น๋ฐ๋ฒํธ ๊ฒ์ฆ"""
try:
password_bytes = plain_password.encode('utf-8')[:72]
hashed_bytes = hashed_password.encode('utf-8')
return bcrypt.checkpw(password_bytes, hashed_bytes)
except Exception as e:
print(f"Password verification error: {e}")
return False
def create_user(db: Session, username: str, email: str, password: str, display_name: str = None) -> User:
"""์ ์ฌ์ฉ์ ์์ฑ"""
password_hash = get_password_hash(password)
user = User(
username=username,
email=email,
password_hash=password_hash,
display_name=display_name or username
)
db.add(user)
db.commit()
db.refresh(user)
return user
def get_user_by_username(db: Session, username: str) -> Optional[User]:
"""์ฌ์ฉ์๋ช
์ผ๋ก ์ฌ์ฉ์ ์กฐํ"""
return db.query(User).filter(User.username == username).first()
def get_user_by_email(db: Session, email: str) -> Optional[User]:
"""์ด๋ฉ์ผ๋ก ์ฌ์ฉ์ ์กฐํ"""
return db.query(User).filter(User.email == email).first()
def get_user_by_id(db: Session, user_id: int) -> Optional[User]:
"""ID๋ก ์ฌ์ฉ์ ์กฐํ"""
return db.query(User).filter(User.id == user_id).first()
def authenticate_user(db: Session, username: str, password: str) -> Optional[User]:
"""์ฌ์ฉ์ ์ธ์ฆ"""
user = get_user_by_username(db, username)
if not user:
return None
if not verify_password(password, user.password_hash):
return None
# ๋ง์ง๋ง ๋ก๊ทธ์ธ ์๊ฐ ์
๋ฐ์ดํธ
user.last_login = datetime.now()
db.commit()
return user
def update_user(db: Session, user_id: int, **kwargs) -> Optional[User]:
"""์ฌ์ฉ์ ์ ๋ณด ์
๋ฐ์ดํธ"""
user = get_user_by_id(db, user_id)
if not user:
return None
for key, value in kwargs.items():
if hasattr(user, key):
setattr(user, key, value)
db.commit()
db.refresh(user)
return user
# ============================================================================
# Chat Session Operations
# ============================================================================
def create_session(db: Session, session_id: str, user_id: int, title: str = "์ ์ฑํ
") -> ChatSession:
"""์ ์ฑํ
์ธ์
์์ฑ"""
db_session = ChatSession(
session_id=session_id,
user_id=user_id,
title=title
)
db.add(db_session)
db.commit()
db.refresh(db_session)
return db_session
def get_session(db: Session, session_id: str) -> Optional[ChatSession]:
"""์ธ์
์กฐํ"""
return db.query(ChatSession).filter(ChatSession.session_id == session_id).first()
def get_or_create_session(db: Session, session_id: str, user_id: int, title: str = "์ ์ฑํ
") -> ChatSession:
"""์ธ์
์กฐํ ๋๋ ์์ฑ"""
session = get_session(db, session_id)
if not session:
session = create_session(db, session_id, user_id, title)
return session
def get_user_sessions(db: Session, user_id: int, limit: int = 50) -> List[ChatSession]:
"""์ฌ์ฉ์์ ์ธ์
๋ชฉ๋ก"""
return (
db.query(ChatSession)
.filter(ChatSession.user_id == user_id)
.order_by(desc(ChatSession.updated_at))
.limit(limit)
.all()
)
def update_session_title(db: Session, session_id: str, title: str) -> Optional[ChatSession]:
"""์ธ์
์ ๋ชฉ ์
๋ฐ์ดํธ"""
session = get_session(db, session_id)
if session:
session.title = title
db.commit()
db.refresh(session)
return session
def delete_session(db: Session, session_id: str, user_id: int) -> bool:
"""์ธ์
์ญ์ (๊ถํ ํ์ธ)"""
session = get_session(db, session_id)
if session and session.user_id == user_id:
db.delete(session)
db.commit()
return True
return False
# ============================================================================
# Message Operations
# ============================================================================
def create_message(
db: Session,
session_id: str,
role: str,
content: str,
mode: str = "chat",
thinking_process: Optional[List[Dict]] = None,
tool_usage: Optional[List[Dict]] = None
) -> Message:
"""๋ฉ์์ง ์์ฑ (์ฌ๊ณ ๊ณผ์ ๋ฐ ๋๊ตฌ ์ฌ์ฉ ํฌํจ)"""
message = Message(
session_id=session_id,
role=role,
content=content,
mode=mode,
thinking_process=thinking_process, # JSON์ผ๋ก ์ ์ฅ
tool_usage=tool_usage # JSON์ผ๋ก ์ ์ฅ
)
db.add(message)
db.commit()
db.refresh(message)
return message
def get_session_messages(
db: Session,
session_id: str,
limit: Optional[int] = None
) -> List[Message]:
"""์ธ์
์ ๋ฉ์์ง ์กฐํ"""
query = db.query(Message).filter(Message.session_id == session_id).order_by(Message.created_at)
if limit:
query = query.limit(limit)
return query.all()
def get_recent_messages(
db: Session,
session_id: str,
count: int = 10
) -> List[Message]:
"""์ต๊ทผ ๋ฉ์์ง ์กฐํ"""
return (
db.query(Message)
.filter(Message.session_id == session_id)
.order_by(desc(Message.created_at))
.limit(count)
.all()
)[::-1]
def delete_session_messages(db: Session, session_id: str) -> int:
"""์ธ์
์ ๋ชจ๋ ๋ฉ์์ง ์ญ์ """
count = db.query(Message).filter(Message.session_id == session_id).delete()
db.commit()
return count
# ============================================================================
# Tool Log Operations
# ============================================================================
def create_tool_log(
db: Session,
session_id: str,
tool_name: str,
tool_input: str,
tool_output: str,
success: bool = True,
error_message: Optional[str] = None,
message_id: Optional[int] = None
) -> ToolLog:
"""๋๊ตฌ ์ฌ์ฉ ๋ก๊ทธ ์์ฑ"""
log = ToolLog(
session_id=session_id,
message_id=message_id,
tool_name=tool_name,
tool_input=tool_input,
tool_output=tool_output,
success=success,
error_message=error_message
)
db.add(log)
db.commit()
db.refresh(log)
return log
def get_tool_logs(
db: Session,
session_id: Optional[str] = None,
tool_name: Optional[str] = None,
limit: int = 100
) -> List[ToolLog]:
"""๋๊ตฌ ๋ก๊ทธ ์กฐํ"""
query = db.query(ToolLog)
if session_id:
query = query.filter(ToolLog.session_id == session_id)
if tool_name:
query = query.filter(ToolLog.tool_name == tool_name)
return query.order_by(desc(ToolLog.created_at)).limit(limit).all()
# ============================================================================
# User Feedback Operations
# ============================================================================
def create_feedback(
db: Session,
session_id: str,
rating: int,
feedback_text: Optional[str] = None,
message_id: Optional[int] = None
) -> UserFeedback:
"""์ฌ์ฉ์ ํผ๋๋ฐฑ ์์ฑ"""
feedback = UserFeedback(
session_id=session_id,
message_id=message_id,
rating=rating,
feedback_text=feedback_text
)
db.add(feedback)
db.commit()
db.refresh(feedback)
return feedback
def get_session_feedback(db: Session, session_id: str) -> List[UserFeedback]:
"""์ธ์
์ ํผ๋๋ฐฑ ์กฐํ"""
return (
db.query(UserFeedback)
.filter(UserFeedback.session_id == session_id)
.order_by(desc(UserFeedback.created_at))
.all()
)
def get_feedback_stats(db: Session, user_id: Optional[int] = None) -> Dict:
"""ํผ๋๋ฐฑ ํต๊ณ"""
query = db.query(UserFeedback)
if user_id:
# ํน์ ์ฌ์ฉ์์ ์ธ์
์ ๋ํ ํผ๋๋ฐฑ๋ง
query = query.join(ChatSession).filter(ChatSession.user_id == user_id)
total = query.count()
avg_rating = query.with_entities(func.avg(UserFeedback.rating)).scalar()
return {
"total_feedback": total or 0,
"average_rating": float(avg_rating) if avg_rating else 0.0
}
# ============================================================================
# History Management
# ============================================================================
def get_formatted_history(db: Session, session_id: str, include_thinking: bool = True, include_tool: bool = True) -> List[Dict[str, any]]:
"""ํฌ๋งท๋ ๋ํ ๊ธฐ๋ก ๋ฐํ (์ฌ๊ณ ๊ณผ์ ๋ฐ ๋๊ตฌ ์ฌ์ฉ ํฌํจ ์ต์
)"""
messages = get_session_messages(db, session_id)
result = []
for msg in messages:
message_dict = {
"role": msg.role,
"content": msg.content,
"mode": msg.mode,
"timestamp": msg.created_at.isoformat()
}
# think ๋ชจ๋์ด๊ณ ์ฌ๊ณ ๊ณผ์ ์ด ์์ผ๋ฉด ํฌํจ
if include_thinking and msg.mode == "think" and msg.thinking_process:
message_dict["thinking_process"] = msg.thinking_process
# tool ๋ชจ๋์ด๊ณ ๋๊ตฌ ์ฌ์ฉ์ด ์์ผ๋ฉด ํฌํจ
if include_tool and msg.mode == "tool" and msg.tool_usage:
message_dict["tool_usage"] = msg.tool_usage
result.append(message_dict)
return result
def clear_session_history(db: Session, session_id: str, user_id: int) -> Dict:
"""์ธ์
๊ธฐ๋ก ์ญ์ (๊ถํ ํ์ธ)"""
session = get_session(db, session_id)
if not session or session.user_id != user_id:
return {"error": "Unauthorized or session not found"}
# ๋ฉ์์ง ์ญ์
message_count = delete_session_messages(db, session_id)
# ๋๊ตฌ ๋ก๊ทธ ์ญ์
tool_log_count = db.query(ToolLog).filter(ToolLog.session_id == session_id).delete()
# ํผ๋๋ฐฑ ์ญ์
feedback_count = db.query(UserFeedback).filter(UserFeedback.session_id == session_id).delete()
db.commit()
return {
"messages_deleted": message_count,
"tool_logs_deleted": tool_log_count,
"feedback_deleted": feedback_count
}