ChatBot / api.py
AyeshaZawar
adding
4eccf12
Raw History Blame Contribute Delete
12.4 kB
#!/usr/bin/env python3
"""
FastAPI server for RAG System Integration.
This module creates a FastAPI server that exposes a query endpoint
for the RAG agent, allowing frontend applications to send queries
and receive responses with document retrieval capabilities.
"""
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from typing import Optional, List, Dict, Any
import logging
import asyncio
from agent import AgentWithRetrieval
import uuid
from datetime import datetime, timedelta
from typing import Dict, List, Tuple
import re
from collections import defaultdict
import time
from qdrant_client import models
# Initialize FastAPI app
app = FastAPI(title="RAG System Query API", version="1.0.0")
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# Create singleton agent instance
agent_instance = AgentWithRetrieval()
# Rate limiting storage
class RateLimiter:
def __init__(self, max_requests: int = 10, window_seconds: int = 60):
self.max_requests = max_requests
self.window_seconds = window_seconds
self.requests = defaultdict(list) # ip -> list of request timestamps
def is_allowed(self, client_ip: str) -> bool:
"""Check if a client is allowed to make a request."""
now = time.time()
# Remove old requests outside the window
self.requests[client_ip] = [req_time for req_time in self.requests[client_ip]
if now - req_time < self.window_seconds]
if len(self.requests[client_ip]) < self.max_requests:
self.requests[client_ip].append(now)
return True
return False
# Initialize rate limiter
rate_limiter = RateLimiter(max_requests=30, window_seconds=60) # 30 requests per minute per IP
# In-memory session storage for conversation history
class SessionManager:
def __init__(self):
self.sessions: Dict[str, Dict] = {}
self.max_session_age = timedelta(hours=1) # Sessions expire after 1 hour of inactivity
def create_session(self) -> str:
"""Create a new session and return the session ID."""
session_id = str(uuid.uuid4())
self.sessions[session_id] = {
"created_at": datetime.now(),
"last_accessed": datetime.now(),
"conversation_history": []
}
logger.info(f"Created new session: {session_id}")
return session_id
def get_session(self, session_id: str) -> Dict:
"""Get session data by ID, or None if not found or expired."""
if session_id not in self.sessions:
return None
session = self.sessions[session_id]
# Check if session has expired
if datetime.now() - session["last_accessed"] > self.max_session_age:
del self.sessions[session_id]
logger.info(f"Session {session_id} expired and removed")
return None
# Update last accessed time
session["last_accessed"] = datetime.now()
return session
def update_session_history(self, session_id: str, query: str, response: str):
"""Add a query-response pair to the session's conversation history."""
session = self.get_session(session_id)
if session:
session["conversation_history"].append({
"query": query,
"response": response,
"timestamp": datetime.now()
})
logger.info(f"Updated conversation history for session {session_id}")
def cleanup_expired_sessions(self):
"""Remove all expired sessions from storage."""
expired_sessions = []
now = datetime.now()
for session_id, session_data in self.sessions.items():
if now - session_data["last_accessed"] > self.max_session_age:
expired_sessions.append(session_id)
for session_id in expired_sessions:
del self.sessions[session_id]
logger.info(f"Cleaned up expired session: {session_id}")
return len(expired_sessions)
# Initialize session manager
session_manager = SessionManager()
# Pydantic models for request/response validation
class QueryRequest(BaseModel):
"""Request model for query endpoint."""
query_text: str = Field(..., description="The user's query text", max_length=1000)
session_id: Optional[str] = Field(None, description="Optional session ID for conversation history")
metadata: Optional[Dict[str, Any]] = Field(None, description="Additional metadata for the query")
class Citation(BaseModel):
"""Model for citation information."""
source_url: str
source_title: str
class QueryResponse(BaseModel):
"""Response model for query endpoint."""
response_text: str
citations: Optional[List[Citation]] = None
session_id: Optional[str] = None
status: str # "success" or "error"
error_message: Optional[str] = None
class ErrorResponse(BaseModel):
"""Response model for error cases."""
status: str = "error"
error_message: str
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # In production, replace with specific origins
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# API Response utility functions
def create_success_response(response_text: str, session_id: Optional[str] = None, citations: Optional[List[Citation]] = None) -> QueryResponse:
"""Create a success response with the given parameters."""
return QueryResponse(
response_text=response_text,
citations=citations,
session_id=session_id,
status="success"
)
def create_error_response(error_message: str, session_id: Optional[str] = None) -> QueryResponse:
"""Create an error response with the given error message."""
return QueryResponse(
response_text="",
session_id=session_id,
status="error",
error_message=error_message
)
def filter_input_content(text: str) -> str:
"""
Filter input content for security.
Remove or sanitize potentially harmful content.
"""
# Remove potential command injection patterns
filtered_text = re.sub(r'[;&|`$<>]', '', text)
# Remove potential SQL injection patterns
filtered_text = re.sub(r"(?i)(union|select|insert|update|delete|drop|create|alter|exec|execute)",
lambda m: m.group(0)[:1] + '*'*(len(m.group(0))-1),
filtered_text)
# Additional security filtering could be added here
return filtered_text
def extract_citations_from_response(response_text: str) -> Optional[List[Citation]]:
"""
Extract citation information from the agent's response.
This is a placeholder implementation - in a real system,
citations would be extracted from the RAG agent's response.
"""
# In a real implementation, this would parse the response for citation information
# For now, return None as a placeholder
# Future implementation could look for patterns like [source_url] or parse metadata
return []
@app.get("/health")
async def health_check():
"""Health check endpoint to verify API is running."""
return {"status": "healthy"}
@app.post("/query", response_model=QueryResponse)
async def query_endpoint(request: QueryRequest, request_obj: Request = None):
"""
Process a user query through the RAG agent.
This endpoint receives a query from the frontend, processes it through
the RAG agent with document retrieval capabilities, and returns a response.
"""
# Get client IP for rate limiting
client_ip = request_obj.client.host if request_obj else "127.0.0.1"
logger.info(f"Processing query from {client_ip}: '{request.query_text[:50]}...'")
# Check rate limit
if not rate_limiter.is_allowed(client_ip):
error_detail = "Rate limit exceeded. Please try again later."
logger.warning(f"Rate limit exceeded for {client_ip}")
raise HTTPException(
status_code=429,
detail=error_detail
)
try:
# Validate query text is not empty after stripping whitespace
if not request.query_text.strip():
error_detail = "Query text is required and cannot be empty"
logger.warning(f"Validation error: {error_detail}")
# Return 400 error with proper error response format
raise HTTPException(
status_code=400,
detail=error_detail
)
# Validate query length (max 1000 characters)
if len(request.query_text) > 1000:
error_detail = "Query text must be less than 1000 characters"
logger.warning(f"Validation error: {error_detail}")
raise HTTPException(
status_code=400,
detail=error_detail
)
# Filter input content for security
filtered_query_text = filter_input_content(request.query_text)
# Get or create session ID
session_id = request.session_id
if not session_id:
session_id = session_manager.create_session()
else:
# Check if session exists, create new one if expired
existing_session = session_manager.get_session(session_id)
if not existing_session:
session_id = session_manager.create_session()
# Call the RAG agent's run_query method with the filtered query
agent_response = await agent_instance.run_query(filtered_query_text)
# Extract citations from the response (placeholder implementation)
citations = extract_citations_from_response(agent_response)
# Update session history with the query and response
session_manager.update_session_history(session_id, filtered_query_text, agent_response)
# Create and return success response
response = create_success_response(
response_text=agent_response,
session_id=session_id,
citations=citations
)
logger.info(f"Query processed successfully for session {session_id}")
return response
except HTTPException as e:
# Re-raise HTTP exceptions (like 400 validation errors)
logger.warning(f"HTTP error: {e.detail}")
raise
except Exception as e:
# Handle internal server errors (500)
logger.error(f"Internal server error processing query: {str(e)}")
error_detail = f"An error occurred while processing your query: {str(e)}"
raise HTTPException(
status_code=500,
detail=error_detail
)
@app.get("/session/{session_id}")
async def get_session_history(session_id: str):
"""
Retrieve session history for testing conversation continuity.
This endpoint is for testing purposes only.
"""
session = session_manager.get_session(session_id)
if not session:
raise HTTPException(status_code=404, detail="Session not found or expired")
return {
"session_id": session_id,
"created_at": session["created_at"],
"last_accessed": session["last_accessed"],
"conversation_history": session["conversation_history"]
}
@app.get("/admin/cleanup-sessions")
async def cleanup_sessions():
"""
Admin endpoint to manually clean up expired sessions.
"""
expired_count = session_manager.cleanup_expired_sessions()
return {
"message": f"Cleaned up {expired_count} expired sessions",
"timestamp": datetime.now()
}
# Periodic cleanup task
async def periodic_cleanup():
"""Periodically clean up expired sessions."""
while True:
await asyncio.sleep(300) # Run every 5 minutes
expired_count = session_manager.cleanup_expired_sessions()
if expired_count > 0:
logger.info(f"Periodic cleanup removed {expired_count} expired sessions")
@app.on_event("startup")
async def startup_event():
"""Start the periodic cleanup task when the application starts."""
asyncio.create_task(periodic_cleanup())
logger.info("Started periodic cleanup task")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)