-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
634 lines (498 loc) ยท 19.5 KB
/
server.py
File metadata and controls
634 lines (498 loc) ยท 19.5 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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi import FastAPI, HTTPException, Depends, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from contextlib import asynccontextmanager
from pydantic import BaseModel, EmailStr
from datetime import datetime, timedelta
from sqlalchemy.orm import Session
from typing import Optional, List
from dotenv import load_dotenv
import json
import os
import jwt
from agent import VersatileAgent
from database import get_db, init_db, get_db_session
import db_operations as db_ops
# ํ๊ฒฝ ๋ณ์ ๋ก๋
load_dotenv()
# JWT ์ค์
SECRET_KEY = os.getenv("JWT_SECRET_KEY", "your-secret-key-change-this-in-production")
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # 7์ผ
security = HTTPBearer()
# ============================================================================
# API Models
# ============================================================================
class UserRegister(BaseModel):
username: str
email: EmailStr
password: str
display_name: Optional[str] = None
class UserLogin(BaseModel):
username: str
password: str
class Token(BaseModel):
access_token: str
token_type: str
user: dict
class UserResponse(BaseModel):
id: int
username: str
email: str
display_name: str
created_at: datetime
last_login: Optional[datetime]
class ChatRequest(BaseModel):
message: str
session_id: Optional[str] = None
mode: str = "chat"
class CreateSessionRequest(BaseModel):
title: str = "์ ์ฑํ
"
class UpdateSessionRequest(BaseModel):
title: str
class SessionResponse(BaseModel):
session_id: str
title: str
created_at: datetime
updated_at: datetime
message_count: int
class ClearHistoryRequest(BaseModel):
session_id: str
class HistoryResponse(BaseModel):
session_id: str
history: List[dict]
class FeedbackRequest(BaseModel):
session_id: str
message_id: Optional[int] = None
rating: int
feedback_text: Optional[str] = None
# ============================================================================
# JWT Functions
# ============================================================================
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
"""JWT ์ก์ธ์ค ํ ํฐ ์์ฑ"""
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)) -> dict:
"""JWT ํ ํฐ ๊ฒ์ฆ"""
try:
token = credentials.credentials
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
return payload
except jwt.ExpiredSignatureError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token has expired"
)
except jwt.JWTError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials"
)
def get_current_user(
token_data: dict = Depends(verify_token),
db: Session = Depends(get_db_session)
) -> db_ops.User:
"""ํ์ฌ ๋ก๊ทธ์ธํ ์ฌ์ฉ์ ์กฐํ"""
user_id = token_data.get("user_id")
if not user_id:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token"
)
user = db_ops.get_user_by_id(db, user_id)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User not found"
)
return user
# ============================================================================
# Global Agent Instance
# ============================================================================
agent: Optional[VersatileAgent] = None
# ============================================================================
# Application Lifecycle
# ============================================================================
@asynccontextmanager
async def lifespan(app: FastAPI):
"""์ ํ๋ฆฌ์ผ์ด์
์์/์ข
๋ฃ ์ ์คํ"""
global agent
# ๋ฐ์ดํฐ๋ฒ ์ด์ค ์ด๊ธฐํ
print("Initializing database...")
try:
init_db()
print("Database initialized successfully!")
except Exception as e:
print(f"Database initialization error: {e}")
# ๋ชจ๋ธ ๋ก๋
model_path = os.getenv("MODEL_PATH", './models/llama-3-Korean-Bllossom-8B/Q8_0.gguf')
print(f"Loading model from {model_path}...")
agent = VersatileAgent(model_path)
print("Model loaded successfully!")
yield
print("Shutting down...")
# ============================================================================
# FastAPI Application
# ============================================================================
app = FastAPI(
title="Versatile Agent API",
description="LLM ๊ธฐ๋ฐ ์์ด์ ํธ",
version="1.0.0",
lifespan=lifespan
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ============================================================================
# Auth Endpoints
# ============================================================================
@app.post("/auth/register", response_model=Token)
async def register(user_data: UserRegister, db: Session = Depends(get_db_session)):
"""ํ์๊ฐ์
"""
try:
if db_ops.get_user_by_username(db, user_data.username):
raise HTTPException(status_code=400, detail="Username already exists")
if db_ops.get_user_by_email(db, user_data.email):
raise HTTPException(status_code=400, detail="Email already exists")
user = db_ops.create_user(
db,
username=user_data.username,
email=user_data.email,
password=user_data.password,
display_name=user_data.display_name
)
access_token = create_access_token(data={"user_id": user.id})
return Token(
access_token=access_token,
token_type="bearer",
user={
"id": user.id,
"username": user.username,
"email": user.email,
"display_name": user.display_name
}
)
finally:
db.close()
@app.post("/auth/login", response_model=Token)
async def login(credentials: UserLogin, db: Session = Depends(get_db_session)):
"""๋ก๊ทธ์ธ"""
try:
user = db_ops.authenticate_user(db, credentials.username, credentials.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password"
)
access_token = create_access_token(data={"user_id": user.id})
return Token(
access_token=access_token,
token_type="bearer",
user={
"id": user.id,
"username": user.username,
"email": user.email,
"display_name": user.display_name
}
)
finally:
db.close()
@app.get("/auth/me", response_model=UserResponse)
async def get_me(current_user: db_ops.User = Depends(get_current_user)):
"""ํ์ฌ ์ฌ์ฉ์ ์ ๋ณด"""
return UserResponse(
id=current_user.id,
username=current_user.username,
email=current_user.email,
display_name=current_user.display_name,
created_at=current_user.created_at,
last_login=current_user.last_login
)
# ============================================================================
# Session Management Endpoints
# ============================================================================
@app.post("/sessions/create")
async def create_session(
request: CreateSessionRequest,
current_user: db_ops.User = Depends(get_current_user),
db: Session = Depends(get_db_session)
):
"""์ ์ธ์
์์ฑ"""
try:
session_id = f"user_{current_user.id}_{int(datetime.now().timestamp() * 1000)}"
session = db_ops.create_session(
db,
session_id=session_id,
user_id=current_user.id,
title=request.title
)
return {
"session_id": session.session_id,
"title": session.title,
"created_at": session.created_at.isoformat()
}
finally:
db.close()
@app.get("/sessions", response_model=List[SessionResponse])
async def list_sessions(
current_user: db_ops.User = Depends(get_current_user),
db: Session = Depends(get_db_session)
):
"""์ฌ์ฉ์์ ์ธ์
๋ชฉ๋ก"""
try:
sessions = db_ops.get_user_sessions(db, current_user.id)
result = []
for session in sessions:
message_count = db.query(db_ops.Message).filter(
db_ops.Message.session_id == session.session_id
).count()
result.append(SessionResponse(
session_id=session.session_id,
title=session.title,
created_at=session.created_at,
updated_at=session.updated_at,
message_count=message_count
))
return result
finally:
db.close()
@app.put("/sessions/{session_id}/title")
async def update_session_title(
session_id: str,
request: UpdateSessionRequest,
current_user: db_ops.User = Depends(get_current_user),
db: Session = Depends(get_db_session)
):
"""์ธ์
์ ๋ชฉ ์
๋ฐ์ดํธ"""
try:
session = db_ops.get_session(db, session_id)
if not session or session.user_id != current_user.id:
raise HTTPException(status_code=404, detail="Session not found")
updated_session = db_ops.update_session_title(db, session_id, request.title)
return {
"session_id": updated_session.session_id,
"title": updated_session.title
}
finally:
db.close()
@app.delete("/sessions/{session_id}")
async def delete_session(
session_id: str,
current_user: db_ops.User = Depends(get_current_user),
db: Session = Depends(get_db_session)
):
"""์ธ์
์ญ์ """
try:
success = db_ops.delete_session(db, session_id, current_user.id)
if not success:
raise HTTPException(status_code=404, detail="Session not found")
return {"status": "success", "message": "Session deleted"}
finally:
db.close()
# ============================================================================
# Chat Endpoints
# ============================================================================
@app.post("/chat")
async def chat(
request: ChatRequest,
current_user: db_ops.User = Depends(get_current_user),
db: Session = Depends(get_db_session)
):
"""์ฑํ
์๋ํฌ์ธํธ"""
if agent is None:
raise HTTPException(status_code=503, detail="Model not loaded")
try:
# ์ธ์
์ฒ๋ฆฌ
if not request.session_id:
session_id = f"user_{current_user.id}_{int(datetime.now().timestamp() * 1000)}"
title = request.message[:30] + "..." if len(request.message) > 30 else request.message
db_ops.create_session(db, session_id, current_user.id, title)
else:
session_id = request.session_id
session = db_ops.get_session(db, session_id)
if not session or session.user_id != current_user.id:
raise HTTPException(status_code=403, detail="Access denied")
# ์ฌ์ฉ์ ๋ฉ์์ง ์ ์ฅ
db_ops.create_message(db, session_id, "user", request.message, request.mode)
except HTTPException:
raise
except Exception as e:
db.close()
raise HTTPException(status_code=500, detail=str(e))
async def event_generator():
assistant_response = ""
thinking_process = [] # ์ฌ๊ณ ๊ณผ์ ์ ์ฅ
tool_usage = [] # ๋๊ตฌ ์ฌ์ฉ ์ ์ฅ
current_todo = None
current_tool = None
try:
if request.mode == "tool":
stream = agent.tool_stream(request.message, session_id)
elif request.mode == "think":
stream = agent.think_and_answer_stream(request.message, session_id)
else:
stream = agent.chat_stream(request.message, session_id)
async for event in stream:
if hasattr(event, 'to_dict'):
event_dict = event.to_dict()
else:
event_dict = {
"type": getattr(event, 'type', getattr(event, 'event_type', 'unknown')),
"content": getattr(event, 'content', ''),
"mode": getattr(event, 'mode', ''),
"is_start": getattr(event, 'is_start', False)
}
event_type = event_dict.get("type")
mode = event_dict.get("mode")
content = event_dict.get("content", "")
is_start = event_dict.get("is_start", False)
# Think ๋ชจ๋ ์ฌ๊ณ ๊ณผ์ ์์ง
if request.mode == "think":
if mode == "todo" and is_start and content:
# ์ todo ์์
if current_todo:
thinking_process.append(current_todo)
current_todo = {"todo": content, "content": ""}
elif mode == "result" and event_type == "stream" and content:
# result ๋ด์ฉ ์์ง
if current_todo:
current_todo["content"] += content
# Tool ๋ชจ๋ ๋๊ตฌ ์ฌ์ฉ ์์ง
elif request.mode == "tool":
if mode == "tool_call" and is_start and content:
# ๋๊ตฌ ํธ์ถ ์์
try:
tool_info = content.split(": ", 1)
tool_name = tool_info[0]
tool_input = tool_info[1] if len(tool_info) > 1 else "{}"
current_tool = {
"tool_name": tool_name,
"tool_input": tool_input,
"tool_output": ""
}
except Exception as e:
print(f"Tool info parse error: {e}")
elif mode == "tool_result" and is_start and content:
# ๋๊ตฌ ๊ฒฐ๊ณผ ์ ์ฅ
if current_tool:
current_tool["tool_output"] = content
tool_usage.append(current_tool)
current_tool = None
# ์ต์ข
์๋ต ์์ง
if event_type in ["text", "stream"] and mode == "basic":
if content:
assistant_response += content
yield f"data: {json.dumps(event_dict, ensure_ascii=False)}\n\n"
# ๋ง์ง๋ง todo ์ ์ฅ
if current_todo:
thinking_process.append(current_todo)
# ๋ง์ง๋ง tool ์ ์ฅ
if current_tool:
tool_usage.append(current_tool)
# ์ด์์คํดํธ ์๋ต ์ ์ฅ (์ฌ๊ณ ๊ณผ์ ๋๋ ๋๊ตฌ ์ฌ์ฉ ํฌํจ)
if assistant_response.strip():
try:
with get_db() as db_context:
db_ops.create_message(
db_context,
session_id,
"assistant",
assistant_response,
request.mode,
thinking_process=thinking_process if thinking_process else None,
tool_usage=tool_usage if tool_usage else None
)
except Exception as db_error:
print(f"Failed to save assistant message: {db_error}")
# ์ธ์
ID ์ ์ก
if not request.session_id:
yield f"data: {json.dumps({'type': 'session_created', 'session_id': session_id}, ensure_ascii=False)}\n\n"
yield "data: [DONE]\n\n"
except Exception as e:
import traceback
print(f"Stream error: {e}")
print(traceback.format_exc())
error_event = {"type": "error", "message": str(e)}
yield f"data: {json.dumps(error_event, ensure_ascii=False)}\n\n"
finally:
db.close()
return StreamingResponse(
event_generator(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no"
}
)
@app.get("/history/{session_id}")
async def get_history(
session_id: str,
current_user: db_ops.User = Depends(get_current_user),
db: Session = Depends(get_db_session)
):
"""๋ํ ๊ธฐ๋ก ์กฐํ"""
try:
session = db_ops.get_session(db, session_id)
if not session or session.user_id != current_user.id:
raise HTTPException(status_code=404, detail="Session not found")
formatted_history = db_ops.get_formatted_history(
db, session_id,
include_thinking=True,
include_tool=True
)
return HistoryResponse(
session_id=session_id,
history=formatted_history
)
finally:
db.close()
@app.post("/clear")
async def clear_history(
request: ClearHistoryRequest,
current_user: db_ops.User = Depends(get_current_user),
db: Session = Depends(get_db_session)
):
"""๋ํ ๊ธฐ๋ก ์ด๊ธฐํ"""
if agent is None:
raise HTTPException(status_code=503, detail="Model not loaded")
try:
result = db_ops.clear_session_history(db, request.session_id, current_user.id)
if "error" in result:
raise HTTPException(status_code=403, detail=result["error"])
agent.clear_history(request.session_id)
return {
"status": "success",
"message": f"History cleared for session: {request.session_id}",
"details": result
}
finally:
db.close()
# ============================================================================
# Other Endpoints
# ============================================================================
@app.get("/")
async def root():
"""ํฌ์ค ์ฒดํฌ"""
return {
"status": "running",
"message": "Versatile Agent API",
"version": "1.0.0"
}
if __name__ == "__main__":
import uvicorn
host = os.getenv("API_HOST", "0.0.0.0")
port = int(os.getenv("API_PORT", "8000"))
uvicorn.run(app, host=host, port=port)