File size: 12,398 Bytes
4eccf12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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)