Spaces:
Runtime error
Runtime error
Upload 2 files
Browse files- app.py +379 -379
- session_manager.py +63 -1
app.py
CHANGED
|
@@ -1,379 +1,379 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Law RAG Chatbot API using FastAPI, Langchain, Groq, and ChromaDB
|
| 3 |
-
"""
|
| 4 |
-
|
| 5 |
-
import os
|
| 6 |
-
import time
|
| 7 |
-
import logging
|
| 8 |
-
from typing import List, Dict, Any, Optional
|
| 9 |
-
from fastapi import FastAPI, HTTPException, Depends, Header
|
| 10 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 11 |
-
from pydantic import BaseModel
|
| 12 |
-
import uvicorn
|
| 13 |
-
|
| 14 |
-
from config import *
|
| 15 |
-
from rag_system import RAGSystem
|
| 16 |
-
from session_manager import SessionManager
|
| 17 |
-
|
| 18 |
-
# Configure logging
|
| 19 |
-
logging.basicConfig(level=logging.INFO)
|
| 20 |
-
logger = logging.getLogger(__name__)
|
| 21 |
-
|
| 22 |
-
# Initialize FastAPI app
|
| 23 |
-
app = FastAPI(
|
| 24 |
-
title=API_TITLE,
|
| 25 |
-
version=API_VERSION,
|
| 26 |
-
description=API_DESCRIPTION
|
| 27 |
-
)
|
| 28 |
-
|
| 29 |
-
# Add CORS middleware
|
| 30 |
-
app.add_middleware(
|
| 31 |
-
CORSMiddleware,
|
| 32 |
-
allow_origins=["*"],
|
| 33 |
-
allow_credentials=True,
|
| 34 |
-
allow_methods=["*"],
|
| 35 |
-
allow_headers=["*"],
|
| 36 |
-
)
|
| 37 |
-
|
| 38 |
-
# Pydantic models for API requests/responses
|
| 39 |
-
class ChatRequest(BaseModel):
|
| 40 |
-
question: str
|
| 41 |
-
context_length: int = 5 # Increased default context length
|
| 42 |
-
session_id: Optional[str] = None
|
| 43 |
-
|
| 44 |
-
class ChatResponse(BaseModel):
|
| 45 |
-
answer: str
|
| 46 |
-
sources: List[Dict[str, Any]]
|
| 47 |
-
confidence: float
|
| 48 |
-
processing_time: float
|
| 49 |
-
question: str
|
| 50 |
-
session_id: str
|
| 51 |
-
chat_history_count: int
|
| 52 |
-
|
| 53 |
-
class SessionCreateRequest(BaseModel):
|
| 54 |
-
user_info: Optional[str] = None
|
| 55 |
-
metadata: Optional[Dict[str, Any]] = None
|
| 56 |
-
|
| 57 |
-
class SessionResponse(BaseModel):
|
| 58 |
-
session_id: str
|
| 59 |
-
created_at: str
|
| 60 |
-
user_info: str
|
| 61 |
-
metadata: Dict[str, Any]
|
| 62 |
-
|
| 63 |
-
class HealthResponse(BaseModel):
|
| 64 |
-
status: str
|
| 65 |
-
message: str
|
| 66 |
-
components: Dict[str, str]
|
| 67 |
-
|
| 68 |
-
class SessionListResponse(BaseModel):
|
| 69 |
-
sessions: List[Dict[str, Any]]
|
| 70 |
-
total_count: int
|
| 71 |
-
limit: int
|
| 72 |
-
offset: int
|
| 73 |
-
has_more: bool
|
| 74 |
-
|
| 75 |
-
# Global instances
|
| 76 |
-
rag_system: RAGSystem = None
|
| 77 |
-
session_manager: SessionManager = None
|
| 78 |
-
|
| 79 |
-
@app.on_event("startup")
|
| 80 |
-
async def startup_event():
|
| 81 |
-
"""Initialize the RAG system and session manager on startup"""
|
| 82 |
-
global rag_system, session_manager
|
| 83 |
-
try:
|
| 84 |
-
logger.info("Initializing RAG system...")
|
| 85 |
-
rag_system = RAGSystem()
|
| 86 |
-
await rag_system.initialize()
|
| 87 |
-
logger.info("RAG system initialized successfully")
|
| 88 |
-
|
| 89 |
-
logger.info("Initializing session manager...")
|
| 90 |
-
session_manager = SessionManager()
|
| 91 |
-
logger.info("Session manager initialized successfully")
|
| 92 |
-
|
| 93 |
-
except Exception as e:
|
| 94 |
-
logger.error(f"Failed to initialize systems: {e}")
|
| 95 |
-
raise
|
| 96 |
-
|
| 97 |
-
@app.get("/", response_model=HealthResponse)
|
| 98 |
-
async def root():
|
| 99 |
-
"""Root endpoint with health check"""
|
| 100 |
-
return HealthResponse(
|
| 101 |
-
status="healthy",
|
| 102 |
-
message="Law RAG Chatbot API is running",
|
| 103 |
-
components={
|
| 104 |
-
"api": "running",
|
| 105 |
-
"rag_system": "running" if rag_system else "not_initialized",
|
| 106 |
-
"session_manager": "running" if session_manager else "not_initialized",
|
| 107 |
-
"vector_db": "connected" if rag_system and rag_system.is_ready() else "disconnected"
|
| 108 |
-
}
|
| 109 |
-
)
|
| 110 |
-
|
| 111 |
-
@app.get("/health", response_model=HealthResponse)
|
| 112 |
-
async def health_check():
|
| 113 |
-
"""Health check endpoint"""
|
| 114 |
-
if not rag_system:
|
| 115 |
-
raise HTTPException(status_code=503, detail="RAG system not initialized")
|
| 116 |
-
|
| 117 |
-
if not rag_system.is_ready():
|
| 118 |
-
raise HTTPException(status_code=503, detail="RAG system not ready")
|
| 119 |
-
|
| 120 |
-
if not session_manager:
|
| 121 |
-
raise HTTPException(status_code=503, detail="Session manager not initialized")
|
| 122 |
-
|
| 123 |
-
return HealthResponse(
|
| 124 |
-
status="healthy",
|
| 125 |
-
message="All systems operational",
|
| 126 |
-
components={
|
| 127 |
-
"api": "running",
|
| 128 |
-
"rag_system": "ready",
|
| 129 |
-
"session_manager": "ready",
|
| 130 |
-
"vector_db": "connected",
|
| 131 |
-
"embeddings": "ready",
|
| 132 |
-
"llm": "ready"
|
| 133 |
-
}
|
| 134 |
-
)
|
| 135 |
-
|
| 136 |
-
@app.post("/sessions", response_model=SessionResponse)
|
| 137 |
-
async def create_session(request: SessionCreateRequest):
|
| 138 |
-
"""Create a new chat session"""
|
| 139 |
-
if not session_manager:
|
| 140 |
-
raise HTTPException(status_code=503, detail="Session manager not initialized")
|
| 141 |
-
|
| 142 |
-
try:
|
| 143 |
-
session_id = session_manager.create_session(
|
| 144 |
-
user_info=request.user_info,
|
| 145 |
-
metadata=request.metadata
|
| 146 |
-
)
|
| 147 |
-
|
| 148 |
-
session = session_manager.get_session(session_id)
|
| 149 |
-
|
| 150 |
-
return SessionResponse(
|
| 151 |
-
session_id=session_id,
|
| 152 |
-
created_at=session["created_at"].isoformat(),
|
| 153 |
-
user_info=session["user_info"],
|
| 154 |
-
metadata=session["metadata"]
|
| 155 |
-
)
|
| 156 |
-
|
| 157 |
-
except Exception as e:
|
| 158 |
-
logger.error(f"Error creating session: {e}")
|
| 159 |
-
raise HTTPException(status_code=500, detail=f"Failed to create session: {str(e)}")
|
| 160 |
-
|
| 161 |
-
@app.get("/sessions/{session_id}", response_model=Dict[str, Any])
|
| 162 |
-
async def get_session_info(session_id: str):
|
| 163 |
-
"""Get session information and statistics"""
|
| 164 |
-
if not session_manager:
|
| 165 |
-
raise HTTPException(status_code=503, detail="Session manager not initialized")
|
| 166 |
-
|
| 167 |
-
try:
|
| 168 |
-
session_stats = session_manager.get_session_stats(session_id)
|
| 169 |
-
|
| 170 |
-
if not session_stats:
|
| 171 |
-
raise HTTPException(status_code=404, detail="Session not found")
|
| 172 |
-
|
| 173 |
-
return session_stats
|
| 174 |
-
|
| 175 |
-
except HTTPException:
|
| 176 |
-
raise
|
| 177 |
-
except Exception as e:
|
| 178 |
-
logger.error(f"Error getting session info: {e}")
|
| 179 |
-
raise HTTPException(status_code=500, detail=f"Failed to get session info: {str(e)}")
|
| 180 |
-
|
| 181 |
-
@app.get("/sessions/{session_id}/history")
|
| 182 |
-
async def get_chat_history(session_id: str, limit: int = 10):
|
| 183 |
-
"""Get chat history for a session"""
|
| 184 |
-
if not session_manager:
|
| 185 |
-
raise HTTPException(status_code=503, detail="Session manager not initialized")
|
| 186 |
-
|
| 187 |
-
try:
|
| 188 |
-
history = session_manager.get_chat_history(session_id, limit)
|
| 189 |
-
return {
|
| 190 |
-
"session_id": session_id,
|
| 191 |
-
"history": history,
|
| 192 |
-
"total": len(history)
|
| 193 |
-
}
|
| 194 |
-
|
| 195 |
-
except Exception as e:
|
| 196 |
-
logger.error(f"Error getting chat history: {e}")
|
| 197 |
-
raise HTTPException(status_code=500, detail=f"Failed to get chat history: {str(e)}")
|
| 198 |
-
|
| 199 |
-
@app.get("/allsessions", response_model=SessionListResponse)
|
| 200 |
-
async def list_all_sessions(limit: int = 100, offset: int = 0):
|
| 201 |
-
"""List all sessions with pagination"""
|
| 202 |
-
if not session_manager:
|
| 203 |
-
raise HTTPException(status_code=503, detail="Session manager not initialized")
|
| 204 |
-
|
| 205 |
-
try:
|
| 206 |
-
# Validate parameters
|
| 207 |
-
if limit < 1 or limit > 1000:
|
| 208 |
-
raise HTTPException(status_code=400, detail="Limit must be between 1 and 1000")
|
| 209 |
-
|
| 210 |
-
if offset < 0:
|
| 211 |
-
raise HTTPException(status_code=400, detail="Offset must be non-negative")
|
| 212 |
-
|
| 213 |
-
result = session_manager.list_all_sessions(limit=limit, offset=offset)
|
| 214 |
-
|
| 215 |
-
if "error" in result:
|
| 216 |
-
raise HTTPException(status_code=500, detail=result["error"])
|
| 217 |
-
|
| 218 |
-
return SessionListResponse(**result)
|
| 219 |
-
|
| 220 |
-
except HTTPException:
|
| 221 |
-
raise
|
| 222 |
-
except Exception as e:
|
| 223 |
-
logger.error(f"Error listing sessions: {e}")
|
| 224 |
-
raise HTTPException(status_code=500, detail=f"Failed to list sessions: {str(e)}")
|
| 225 |
-
|
| 226 |
-
@app.post("/chat", response_model=ChatResponse)
|
| 227 |
-
async def chat(request: ChatRequest):
|
| 228 |
-
"""Main chat endpoint for legal questions with session support"""
|
| 229 |
-
if not rag_system:
|
| 230 |
-
raise HTTPException(status_code=503, detail="RAG system not initialized")
|
| 231 |
-
|
| 232 |
-
if not rag_system.is_ready():
|
| 233 |
-
raise HTTPException(status_code=503, detail="RAG system not ready")
|
| 234 |
-
|
| 235 |
-
if not session_manager:
|
| 236 |
-
raise HTTPException(status_code=503, detail="Session manager not initialized")
|
| 237 |
-
|
| 238 |
-
try:
|
| 239 |
-
start_time = time.time()
|
| 240 |
-
|
| 241 |
-
# Handle session
|
| 242 |
-
if not request.session_id:
|
| 243 |
-
# Create new session if none provided
|
| 244 |
-
request.session_id = session_manager.create_session()
|
| 245 |
-
logger.info(f"Created new session: {request.session_id}")
|
| 246 |
-
|
| 247 |
-
# Verify session exists
|
| 248 |
-
session = session_manager.get_session(request.session_id)
|
| 249 |
-
if not session:
|
| 250 |
-
raise HTTPException(status_code=404, detail="Session not found")
|
| 251 |
-
|
| 252 |
-
# Get response from RAG system
|
| 253 |
-
response = await rag_system.get_response(
|
| 254 |
-
question=request.question,
|
| 255 |
-
context_length=request.context_length
|
| 256 |
-
)
|
| 257 |
-
|
| 258 |
-
processing_time = time.time() - start_time
|
| 259 |
-
|
| 260 |
-
# Store chat response in session
|
| 261 |
-
session_manager.store_chat_response(
|
| 262 |
-
session_id=request.session_id,
|
| 263 |
-
question=request.question,
|
| 264 |
-
answer=response["answer"],
|
| 265 |
-
sources=response["sources"],
|
| 266 |
-
confidence=response["confidence"],
|
| 267 |
-
processing_time=processing_time
|
| 268 |
-
)
|
| 269 |
-
|
| 270 |
-
# Get chat history count
|
| 271 |
-
chat_history = session_manager.get_chat_history(request.session_id, limit=1)
|
| 272 |
-
chat_history_count = len(chat_history)
|
| 273 |
-
|
| 274 |
-
return ChatResponse(
|
| 275 |
-
answer=response["answer"],
|
| 276 |
-
sources=response["sources"],
|
| 277 |
-
confidence=response["confidence"],
|
| 278 |
-
processing_time=processing_time,
|
| 279 |
-
question=request.question,
|
| 280 |
-
session_id=request.session_id,
|
| 281 |
-
chat_history_count=chat_history_count
|
| 282 |
-
)
|
| 283 |
-
|
| 284 |
-
except HTTPException:
|
| 285 |
-
raise
|
| 286 |
-
except Exception as e:
|
| 287 |
-
logger.error(f"Error processing chat request: {e}")
|
| 288 |
-
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
|
| 289 |
-
|
| 290 |
-
@app.get("/search")
|
| 291 |
-
async def search(query: str, limit: int = 5, session_id: Optional[str] = None):
|
| 292 |
-
"""Search for relevant legal documents with optional session tracking"""
|
| 293 |
-
if not rag_system:
|
| 294 |
-
raise HTTPException(status_code=503, detail="RAG system not initialized")
|
| 295 |
-
|
| 296 |
-
try:
|
| 297 |
-
results = await rag_system.search_documents(query, limit)
|
| 298 |
-
|
| 299 |
-
# Store search query if session provided
|
| 300 |
-
if session_id and session_manager:
|
| 301 |
-
session_manager.store_search_query(session_id, query, len(results))
|
| 302 |
-
|
| 303 |
-
return {
|
| 304 |
-
"query": query,
|
| 305 |
-
"results": results,
|
| 306 |
-
"total": len(results),
|
| 307 |
-
"session_id": session_id
|
| 308 |
-
}
|
| 309 |
-
except Exception as e:
|
| 310 |
-
logger.error(f"Error in search: {e}")
|
| 311 |
-
raise HTTPException(status_code=500, detail=f"Search failed: {str(e)}")
|
| 312 |
-
|
| 313 |
-
@app.get("/stats")
|
| 314 |
-
async def get_stats():
|
| 315 |
-
"""Get system statistics"""
|
| 316 |
-
if not rag_system:
|
| 317 |
-
raise HTTPException(status_code=503, detail="RAG system not initialized")
|
| 318 |
-
|
| 319 |
-
try:
|
| 320 |
-
rag_stats = await rag_system.get_stats()
|
| 321 |
-
|
| 322 |
-
# Add session statistics
|
| 323 |
-
if session_manager:
|
| 324 |
-
# Get total sessions count (this would need to be implemented in session manager)
|
| 325 |
-
session_stats = {
|
| 326 |
-
"session_manager": "active",
|
| 327 |
-
"total_sessions": "available" # Could implement actual count
|
| 328 |
-
}
|
| 329 |
-
else:
|
| 330 |
-
session_stats = {"session_manager": "not_initialized"}
|
| 331 |
-
|
| 332 |
-
return {**rag_stats, **session_stats}
|
| 333 |
-
|
| 334 |
-
except Exception as e:
|
| 335 |
-
logger.error(f"Error getting stats: {e}")
|
| 336 |
-
raise HTTPException(status_code=500, detail=f"Failed to get stats: {str(e)}")
|
| 337 |
-
|
| 338 |
-
@app.post("/reindex")
|
| 339 |
-
async def reindex():
|
| 340 |
-
"""Reindex the vector database"""
|
| 341 |
-
if not rag_system:
|
| 342 |
-
raise HTTPException(status_code=503, detail="RAG system not initialized")
|
| 343 |
-
|
| 344 |
-
try:
|
| 345 |
-
await rag_system.reindex()
|
| 346 |
-
return {"message": "Reindexing completed successfully"}
|
| 347 |
-
except Exception as e:
|
| 348 |
-
logger.error(f"Error in reindexing: {e}")
|
| 349 |
-
raise HTTPException(status_code=500, detail=f"Reindexing failed: {str(e)}")
|
| 350 |
-
|
| 351 |
-
@app.delete("/sessions/{session_id}")
|
| 352 |
-
async def delete_session(session_id: str):
|
| 353 |
-
"""Delete a session and all its data"""
|
| 354 |
-
if not session_manager:
|
| 355 |
-
raise HTTPException(status_code=503, detail="Session manager not initialized")
|
| 356 |
-
|
| 357 |
-
try:
|
| 358 |
-
session_manager.delete_session(session_id)
|
| 359 |
-
return {"message": f"Session {session_id} deleted successfully"}
|
| 360 |
-
|
| 361 |
-
except Exception as e:
|
| 362 |
-
logger.error(f"Error deleting session: {e}")
|
| 363 |
-
raise HTTPException(status_code=500, detail=f"Failed to delete session: {str(e)}")
|
| 364 |
-
|
| 365 |
-
if __name__ == "__main__":
|
| 366 |
-
uvicorn.run(
|
| 367 |
-
"app:app",
|
| 368 |
-
host=HOST,
|
| 369 |
-
port=PORT,
|
| 370 |
-
reload=True,
|
| 371 |
-
log_level="info"
|
| 372 |
-
)
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Law RAG Chatbot API using FastAPI, Langchain, Groq, and ChromaDB
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import time
|
| 7 |
+
import logging
|
| 8 |
+
from typing import List, Dict, Any, Optional
|
| 9 |
+
from fastapi import FastAPI, HTTPException, Depends, Header
|
| 10 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 11 |
+
from pydantic import BaseModel
|
| 12 |
+
import uvicorn
|
| 13 |
+
|
| 14 |
+
from config import *
|
| 15 |
+
from rag_system import RAGSystem
|
| 16 |
+
from session_manager import SessionManager
|
| 17 |
+
|
| 18 |
+
# Configure logging
|
| 19 |
+
logging.basicConfig(level=logging.INFO)
|
| 20 |
+
logger = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
# Initialize FastAPI app
|
| 23 |
+
app = FastAPI(
|
| 24 |
+
title=API_TITLE,
|
| 25 |
+
version=API_VERSION,
|
| 26 |
+
description=API_DESCRIPTION
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
# Add CORS middleware
|
| 30 |
+
app.add_middleware(
|
| 31 |
+
CORSMiddleware,
|
| 32 |
+
allow_origins=["*"],
|
| 33 |
+
allow_credentials=True,
|
| 34 |
+
allow_methods=["*"],
|
| 35 |
+
allow_headers=["*"],
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
# Pydantic models for API requests/responses
|
| 39 |
+
class ChatRequest(BaseModel):
|
| 40 |
+
question: str
|
| 41 |
+
context_length: int = 5 # Increased default context length
|
| 42 |
+
session_id: Optional[str] = None
|
| 43 |
+
|
| 44 |
+
class ChatResponse(BaseModel):
|
| 45 |
+
answer: str
|
| 46 |
+
sources: List[Dict[str, Any]]
|
| 47 |
+
confidence: float
|
| 48 |
+
processing_time: float
|
| 49 |
+
question: str
|
| 50 |
+
session_id: str
|
| 51 |
+
chat_history_count: int
|
| 52 |
+
|
| 53 |
+
class SessionCreateRequest(BaseModel):
|
| 54 |
+
user_info: Optional[str] = None
|
| 55 |
+
metadata: Optional[Dict[str, Any]] = None
|
| 56 |
+
|
| 57 |
+
class SessionResponse(BaseModel):
|
| 58 |
+
session_id: str
|
| 59 |
+
created_at: str
|
| 60 |
+
user_info: str
|
| 61 |
+
metadata: Dict[str, Any]
|
| 62 |
+
|
| 63 |
+
class HealthResponse(BaseModel):
|
| 64 |
+
status: str
|
| 65 |
+
message: str
|
| 66 |
+
components: Dict[str, str]
|
| 67 |
+
|
| 68 |
+
class SessionListResponse(BaseModel):
|
| 69 |
+
sessions: List[Dict[str, Any]]
|
| 70 |
+
total_count: int
|
| 71 |
+
limit: int
|
| 72 |
+
offset: int
|
| 73 |
+
has_more: bool
|
| 74 |
+
|
| 75 |
+
# Global instances
|
| 76 |
+
rag_system: RAGSystem = None
|
| 77 |
+
session_manager: SessionManager = None
|
| 78 |
+
|
| 79 |
+
@app.on_event("startup")
|
| 80 |
+
async def startup_event():
|
| 81 |
+
"""Initialize the RAG system and session manager on startup"""
|
| 82 |
+
global rag_system, session_manager
|
| 83 |
+
try:
|
| 84 |
+
logger.info("Initializing RAG system...")
|
| 85 |
+
rag_system = RAGSystem()
|
| 86 |
+
await rag_system.initialize()
|
| 87 |
+
logger.info("RAG system initialized successfully")
|
| 88 |
+
|
| 89 |
+
logger.info("Initializing session manager...")
|
| 90 |
+
session_manager = SessionManager()
|
| 91 |
+
logger.info("Session manager initialized successfully")
|
| 92 |
+
|
| 93 |
+
except Exception as e:
|
| 94 |
+
logger.error(f"Failed to initialize systems: {e}")
|
| 95 |
+
raise
|
| 96 |
+
|
| 97 |
+
@app.get("/", response_model=HealthResponse)
|
| 98 |
+
async def root():
|
| 99 |
+
"""Root endpoint with health check"""
|
| 100 |
+
return HealthResponse(
|
| 101 |
+
status="healthy",
|
| 102 |
+
message="Law RAG Chatbot API is running",
|
| 103 |
+
components={
|
| 104 |
+
"api": "running",
|
| 105 |
+
"rag_system": "running" if rag_system else "not_initialized",
|
| 106 |
+
"session_manager": "running" if session_manager else "not_initialized",
|
| 107 |
+
"vector_db": "connected" if rag_system and rag_system.is_ready() else "disconnected"
|
| 108 |
+
}
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
@app.get("/health", response_model=HealthResponse)
|
| 112 |
+
async def health_check():
|
| 113 |
+
"""Health check endpoint"""
|
| 114 |
+
if not rag_system:
|
| 115 |
+
raise HTTPException(status_code=503, detail="RAG system not initialized")
|
| 116 |
+
|
| 117 |
+
if not rag_system.is_ready():
|
| 118 |
+
raise HTTPException(status_code=503, detail="RAG system not ready")
|
| 119 |
+
|
| 120 |
+
if not session_manager:
|
| 121 |
+
raise HTTPException(status_code=503, detail="Session manager not initialized")
|
| 122 |
+
|
| 123 |
+
return HealthResponse(
|
| 124 |
+
status="healthy",
|
| 125 |
+
message="All systems operational",
|
| 126 |
+
components={
|
| 127 |
+
"api": "running",
|
| 128 |
+
"rag_system": "ready",
|
| 129 |
+
"session_manager": "ready",
|
| 130 |
+
"vector_db": "connected",
|
| 131 |
+
"embeddings": "ready",
|
| 132 |
+
"llm": "ready"
|
| 133 |
+
}
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
@app.post("/sessions", response_model=SessionResponse)
|
| 137 |
+
async def create_session(request: SessionCreateRequest):
|
| 138 |
+
"""Create a new chat session"""
|
| 139 |
+
if not session_manager:
|
| 140 |
+
raise HTTPException(status_code=503, detail="Session manager not initialized")
|
| 141 |
+
|
| 142 |
+
try:
|
| 143 |
+
session_id = session_manager.create_session(
|
| 144 |
+
user_info=request.user_info,
|
| 145 |
+
metadata=request.metadata
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
session = session_manager.get_session(session_id)
|
| 149 |
+
|
| 150 |
+
return SessionResponse(
|
| 151 |
+
session_id=session_id,
|
| 152 |
+
created_at=session["created_at"].isoformat(),
|
| 153 |
+
user_info=session["user_info"],
|
| 154 |
+
metadata=session["metadata"]
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
except Exception as e:
|
| 158 |
+
logger.error(f"Error creating session: {e}")
|
| 159 |
+
raise HTTPException(status_code=500, detail=f"Failed to create session: {str(e)}")
|
| 160 |
+
|
| 161 |
+
@app.get("/sessions/{session_id}", response_model=Dict[str, Any])
|
| 162 |
+
async def get_session_info(session_id: str):
|
| 163 |
+
"""Get session information and statistics"""
|
| 164 |
+
if not session_manager:
|
| 165 |
+
raise HTTPException(status_code=503, detail="Session manager not initialized")
|
| 166 |
+
|
| 167 |
+
try:
|
| 168 |
+
session_stats = session_manager.get_session_stats(session_id)
|
| 169 |
+
|
| 170 |
+
if not session_stats:
|
| 171 |
+
raise HTTPException(status_code=404, detail="Session not found")
|
| 172 |
+
|
| 173 |
+
return session_stats
|
| 174 |
+
|
| 175 |
+
except HTTPException:
|
| 176 |
+
raise
|
| 177 |
+
except Exception as e:
|
| 178 |
+
logger.error(f"Error getting session info: {e}")
|
| 179 |
+
raise HTTPException(status_code=500, detail=f"Failed to get session info: {str(e)}")
|
| 180 |
+
|
| 181 |
+
@app.get("/sessions/{session_id}/history")
|
| 182 |
+
async def get_chat_history(session_id: str, limit: int = 10):
|
| 183 |
+
"""Get chat history for a session"""
|
| 184 |
+
if not session_manager:
|
| 185 |
+
raise HTTPException(status_code=503, detail="Session manager not initialized")
|
| 186 |
+
|
| 187 |
+
try:
|
| 188 |
+
history = session_manager.get_chat_history(session_id, limit)
|
| 189 |
+
return {
|
| 190 |
+
"session_id": session_id,
|
| 191 |
+
"history": history,
|
| 192 |
+
"total": len(history)
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
except Exception as e:
|
| 196 |
+
logger.error(f"Error getting chat history: {e}")
|
| 197 |
+
raise HTTPException(status_code=500, detail=f"Failed to get chat history: {str(e)}")
|
| 198 |
+
|
| 199 |
+
@app.get("/allsessions", response_model=SessionListResponse)
|
| 200 |
+
async def list_all_sessions(limit: int = 100, offset: int = 0):
|
| 201 |
+
"""List all sessions with pagination"""
|
| 202 |
+
if not session_manager:
|
| 203 |
+
raise HTTPException(status_code=503, detail="Session manager not initialized")
|
| 204 |
+
|
| 205 |
+
try:
|
| 206 |
+
# Validate parameters
|
| 207 |
+
if limit < 1 or limit > 1000:
|
| 208 |
+
raise HTTPException(status_code=400, detail="Limit must be between 1 and 1000")
|
| 209 |
+
|
| 210 |
+
if offset < 0:
|
| 211 |
+
raise HTTPException(status_code=400, detail="Offset must be non-negative")
|
| 212 |
+
|
| 213 |
+
result = session_manager.list_all_sessions(limit=limit, offset=offset)
|
| 214 |
+
|
| 215 |
+
if "error" in result:
|
| 216 |
+
raise HTTPException(status_code=500, detail=result["error"])
|
| 217 |
+
|
| 218 |
+
return SessionListResponse(**result)
|
| 219 |
+
|
| 220 |
+
except HTTPException:
|
| 221 |
+
raise
|
| 222 |
+
except Exception as e:
|
| 223 |
+
logger.error(f"Error listing sessions: {e}")
|
| 224 |
+
raise HTTPException(status_code=500, detail=f"Failed to list sessions: {str(e)}")
|
| 225 |
+
|
| 226 |
+
@app.post("/chat", response_model=ChatResponse)
|
| 227 |
+
async def chat(request: ChatRequest):
|
| 228 |
+
"""Main chat endpoint for legal questions with session support"""
|
| 229 |
+
if not rag_system:
|
| 230 |
+
raise HTTPException(status_code=503, detail="RAG system not initialized")
|
| 231 |
+
|
| 232 |
+
if not rag_system.is_ready():
|
| 233 |
+
raise HTTPException(status_code=503, detail="RAG system not ready")
|
| 234 |
+
|
| 235 |
+
if not session_manager:
|
| 236 |
+
raise HTTPException(status_code=503, detail="Session manager not initialized")
|
| 237 |
+
|
| 238 |
+
try:
|
| 239 |
+
start_time = time.time()
|
| 240 |
+
|
| 241 |
+
# Handle session
|
| 242 |
+
if not request.session_id:
|
| 243 |
+
# Create new session if none provided
|
| 244 |
+
request.session_id = session_manager.create_session()
|
| 245 |
+
logger.info(f"Created new session: {request.session_id}")
|
| 246 |
+
|
| 247 |
+
# Verify session exists
|
| 248 |
+
session = session_manager.get_session(request.session_id)
|
| 249 |
+
if not session:
|
| 250 |
+
raise HTTPException(status_code=404, detail="Session not found")
|
| 251 |
+
|
| 252 |
+
# Get response from RAG system
|
| 253 |
+
response = await rag_system.get_response(
|
| 254 |
+
question=request.question,
|
| 255 |
+
context_length=request.context_length
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
processing_time = time.time() - start_time
|
| 259 |
+
|
| 260 |
+
# Store chat response in session
|
| 261 |
+
session_manager.store_chat_response(
|
| 262 |
+
session_id=request.session_id,
|
| 263 |
+
question=request.question,
|
| 264 |
+
answer=response["answer"],
|
| 265 |
+
sources=response["sources"],
|
| 266 |
+
confidence=response["confidence"],
|
| 267 |
+
processing_time=processing_time
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
# Get chat history count
|
| 271 |
+
chat_history = session_manager.get_chat_history(request.session_id, limit=1)
|
| 272 |
+
chat_history_count = len(chat_history)
|
| 273 |
+
|
| 274 |
+
return ChatResponse(
|
| 275 |
+
answer=response["answer"],
|
| 276 |
+
sources=response["sources"],
|
| 277 |
+
confidence=response["confidence"],
|
| 278 |
+
processing_time=processing_time,
|
| 279 |
+
question=request.question,
|
| 280 |
+
session_id=request.session_id,
|
| 281 |
+
chat_history_count=chat_history_count
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
except HTTPException:
|
| 285 |
+
raise
|
| 286 |
+
except Exception as e:
|
| 287 |
+
logger.error(f"Error processing chat request: {e}")
|
| 288 |
+
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
|
| 289 |
+
|
| 290 |
+
@app.get("/search")
|
| 291 |
+
async def search(query: str, limit: int = 5, session_id: Optional[str] = None):
|
| 292 |
+
"""Search for relevant legal documents with optional session tracking"""
|
| 293 |
+
if not rag_system:
|
| 294 |
+
raise HTTPException(status_code=503, detail="RAG system not initialized")
|
| 295 |
+
|
| 296 |
+
try:
|
| 297 |
+
results = await rag_system.search_documents(query, limit)
|
| 298 |
+
|
| 299 |
+
# Store search query if session provided
|
| 300 |
+
if session_id and session_manager:
|
| 301 |
+
session_manager.store_search_query(session_id, query, len(results))
|
| 302 |
+
|
| 303 |
+
return {
|
| 304 |
+
"query": query,
|
| 305 |
+
"results": results,
|
| 306 |
+
"total": len(results),
|
| 307 |
+
"session_id": session_id
|
| 308 |
+
}
|
| 309 |
+
except Exception as e:
|
| 310 |
+
logger.error(f"Error in search: {e}")
|
| 311 |
+
raise HTTPException(status_code=500, detail=f"Search failed: {str(e)}")
|
| 312 |
+
|
| 313 |
+
@app.get("/stats")
|
| 314 |
+
async def get_stats():
|
| 315 |
+
"""Get system statistics"""
|
| 316 |
+
if not rag_system:
|
| 317 |
+
raise HTTPException(status_code=503, detail="RAG system not initialized")
|
| 318 |
+
|
| 319 |
+
try:
|
| 320 |
+
rag_stats = await rag_system.get_stats()
|
| 321 |
+
|
| 322 |
+
# Add session statistics
|
| 323 |
+
if session_manager:
|
| 324 |
+
# Get total sessions count (this would need to be implemented in session manager)
|
| 325 |
+
session_stats = {
|
| 326 |
+
"session_manager": "active",
|
| 327 |
+
"total_sessions": "available" # Could implement actual count
|
| 328 |
+
}
|
| 329 |
+
else:
|
| 330 |
+
session_stats = {"session_manager": "not_initialized"}
|
| 331 |
+
|
| 332 |
+
return {**rag_stats, **session_stats}
|
| 333 |
+
|
| 334 |
+
except Exception as e:
|
| 335 |
+
logger.error(f"Error getting stats: {e}")
|
| 336 |
+
raise HTTPException(status_code=500, detail=f"Failed to get stats: {str(e)}")
|
| 337 |
+
|
| 338 |
+
@app.post("/reindex")
|
| 339 |
+
async def reindex():
|
| 340 |
+
"""Reindex the vector database"""
|
| 341 |
+
if not rag_system:
|
| 342 |
+
raise HTTPException(status_code=503, detail="RAG system not initialized")
|
| 343 |
+
|
| 344 |
+
try:
|
| 345 |
+
await rag_system.reindex()
|
| 346 |
+
return {"message": "Reindexing completed successfully"}
|
| 347 |
+
except Exception as e:
|
| 348 |
+
logger.error(f"Error in reindexing: {e}")
|
| 349 |
+
raise HTTPException(status_code=500, detail=f"Reindexing failed: {str(e)}")
|
| 350 |
+
|
| 351 |
+
@app.delete("/sessions/{session_id}")
|
| 352 |
+
async def delete_session(session_id: str):
|
| 353 |
+
"""Delete a session and all its data"""
|
| 354 |
+
if not session_manager:
|
| 355 |
+
raise HTTPException(status_code=503, detail="Session manager not initialized")
|
| 356 |
+
|
| 357 |
+
try:
|
| 358 |
+
session_manager.delete_session(session_id)
|
| 359 |
+
return {"message": f"Session {session_id} deleted successfully"}
|
| 360 |
+
|
| 361 |
+
except Exception as e:
|
| 362 |
+
logger.error(f"Error deleting session: {e}")
|
| 363 |
+
raise HTTPException(status_code=500, detail=f"Failed to delete session: {str(e)}")
|
| 364 |
+
|
| 365 |
+
if __name__ == "__main__":
|
| 366 |
+
uvicorn.run(
|
| 367 |
+
"app:app",
|
| 368 |
+
host=HOST,
|
| 369 |
+
port=PORT,
|
| 370 |
+
reload=True,
|
| 371 |
+
log_level="info"
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
|
session_manager.py
CHANGED
|
@@ -441,4 +441,66 @@ class SessionManager:
|
|
| 441 |
logger.info(f"Deleted session: {session_id}")
|
| 442 |
|
| 443 |
except Exception as e:
|
| 444 |
-
logger.error(f"Failed to delete session {session_id}: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 441 |
logger.info(f"Deleted session: {session_id}")
|
| 442 |
|
| 443 |
except Exception as e:
|
| 444 |
+
logger.error(f"Failed to delete session {session_id}: {e}")
|
| 445 |
+
|
| 446 |
+
def list_all_sessions(self, limit: int = 100, offset: int = 0) -> Dict[str, Any]:
|
| 447 |
+
"""List all sessions with basic information"""
|
| 448 |
+
try:
|
| 449 |
+
conn = sqlite3.connect(self.db_path)
|
| 450 |
+
cursor = conn.cursor()
|
| 451 |
+
|
| 452 |
+
# Get total count
|
| 453 |
+
cursor.execute('SELECT COUNT(*) FROM sessions')
|
| 454 |
+
total_count = cursor.fetchone()[0]
|
| 455 |
+
|
| 456 |
+
# Get sessions with pagination
|
| 457 |
+
cursor.execute('''
|
| 458 |
+
SELECT session_id, created_at, last_activity, user_info, metadata
|
| 459 |
+
FROM sessions
|
| 460 |
+
ORDER BY last_activity DESC
|
| 461 |
+
LIMIT ? OFFSET ?
|
| 462 |
+
''', (limit, offset))
|
| 463 |
+
|
| 464 |
+
rows = cursor.fetchall()
|
| 465 |
+
|
| 466 |
+
sessions = []
|
| 467 |
+
for row in rows:
|
| 468 |
+
session_id = row[0]
|
| 469 |
+
|
| 470 |
+
# Get counts for each session
|
| 471 |
+
cursor.execute('SELECT COUNT(*) FROM chat_history WHERE session_id = ?', (session_id,))
|
| 472 |
+
chat_count = cursor.fetchone()[0]
|
| 473 |
+
|
| 474 |
+
cursor.execute('SELECT COUNT(*) FROM search_history WHERE session_id = ?', (session_id,))
|
| 475 |
+
search_count = cursor.fetchone()[0]
|
| 476 |
+
|
| 477 |
+
sessions.append({
|
| 478 |
+
"session_id": session_id,
|
| 479 |
+
"created_at": row[1],
|
| 480 |
+
"last_activity": row[2],
|
| 481 |
+
"user_info": row[3],
|
| 482 |
+
"metadata": json.loads(row[4]) if row[4] else {},
|
| 483 |
+
"chat_count": chat_count,
|
| 484 |
+
"search_count": search_count
|
| 485 |
+
})
|
| 486 |
+
|
| 487 |
+
conn.close()
|
| 488 |
+
|
| 489 |
+
return {
|
| 490 |
+
"sessions": sessions,
|
| 491 |
+
"total_count": total_count,
|
| 492 |
+
"limit": limit,
|
| 493 |
+
"offset": offset,
|
| 494 |
+
"has_more": offset + len(sessions) < total_count
|
| 495 |
+
}
|
| 496 |
+
|
| 497 |
+
except Exception as e:
|
| 498 |
+
logger.error(f"Failed to list sessions: {e}")
|
| 499 |
+
return {
|
| 500 |
+
"sessions": [],
|
| 501 |
+
"total_count": 0,
|
| 502 |
+
"limit": limit,
|
| 503 |
+
"offset": offset,
|
| 504 |
+
"has_more": False,
|
| 505 |
+
"error": str(e)
|
| 506 |
+
}
|