Spaces:
No application file
No application file
AyeshaZawar commited on
Commit ·
4eccf12
1
Parent(s): 4db6bce
adding
Browse files- Dockerfile +12 -0
- agent.py +253 -0
- api.py +349 -0
- requirements.txt +22 -0
Dockerfile
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /
|
| 4 |
+
|
| 5 |
+
COPY requirements.txt .
|
| 6 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 7 |
+
|
| 8 |
+
COPY . .
|
| 9 |
+
|
| 10 |
+
EXPOSE 7860
|
| 11 |
+
|
| 12 |
+
CMD ["uvicorn", "api:app", "--host", "0.0.0.0", "--port", "7860"]
|
agent.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ent with Retrieval-Augmented Generation capabilities.
|
| 4 |
+
|
| 5 |
+
This script creates an AI agent using the OpenAI Agents SDK that integrates
|
| 6 |
+
with the existing Qdrant retrieval system to answer questions using book content only.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import json
|
| 11 |
+
import logging
|
| 12 |
+
from typing import List, Dict, Any, Optional
|
| 13 |
+
from agents import Agent, Runner, function_tool
|
| 14 |
+
from pydantic import BaseModel, Field
|
| 15 |
+
from agents import OpenAIChatCompletionsModel
|
| 16 |
+
from openai import AsyncOpenAI
|
| 17 |
+
# Load environment variables
|
| 18 |
+
from dotenv import load_dotenv
|
| 19 |
+
load_dotenv()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# Note: OpenRouter client will be initialized in the AgentWithRetrieval class
|
| 23 |
+
|
| 24 |
+
# Configure logging
|
| 25 |
+
logging.basicConfig(
|
| 26 |
+
level=logging.INFO,
|
| 27 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 28 |
+
)
|
| 29 |
+
logger = logging.getLogger(__name__)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class RetrievedChunk(BaseModel):
|
| 33 |
+
"""Represents a chunk retrieved from Qdrant."""
|
| 34 |
+
id: str
|
| 35 |
+
score: float
|
| 36 |
+
content: str
|
| 37 |
+
content_preview: str
|
| 38 |
+
source_url: str
|
| 39 |
+
source_title: str
|
| 40 |
+
chunk_index: int
|
| 41 |
+
chunk_total: int
|
| 42 |
+
created_at: str
|
| 43 |
+
original_word_count: int
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class AgentWithRetrieval:
|
| 47 |
+
"""
|
| 48 |
+
AI Agent with Retrieval-Augmented Generation capabilities.
|
| 49 |
+
Uses OpenAI Agents SDK and integrates with existing Qdrant retrieval logic.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
def __init__(self):
|
| 53 |
+
"""Initialize the agent with OpenAI Agent SDK and retrieval tools."""
|
| 54 |
+
|
| 55 |
+
# Initialize the OpenRouter client with the free model you want to use
|
| 56 |
+
openrouter_api_key = os.getenv("OPENROUTER_API_KEY")
|
| 57 |
+
if not openrouter_api_key:
|
| 58 |
+
logger.warning("OPENROUTER_API_KEY environment variable not set. Please check your .env file.")
|
| 59 |
+
|
| 60 |
+
# Use your specified OpenRouter configuration
|
| 61 |
+
Client = AsyncOpenAI(
|
| 62 |
+
api_key=openrouter_api_key or "dummy-key-for-testing", # Will be replaced by actual key from .env
|
| 63 |
+
base_url="https://openrouter.ai/api/v1"
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
# Get model from environment variable, default to a free model if not set
|
| 67 |
+
openrouter_model = os.getenv("OPENROUTER_MODEL", "openrouter/mistral:mistral-7b-instruct:free")
|
| 68 |
+
third_party_model = OpenAIChatCompletionsModel(
|
| 69 |
+
openai_client=Client,
|
| 70 |
+
model=openrouter_model
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
# Create the agent with retrieval tools using the new Agent SDK
|
| 74 |
+
self.agent = Agent(
|
| 75 |
+
name="Book Content Assistant",
|
| 76 |
+
instructions=(
|
| 77 |
+
"You are a helpful assistant that answers questions based only on retrieved book content. "
|
| 78 |
+
"Always use the retrieval tool to get relevant information before answering. "
|
| 79 |
+
"Only provide information that comes from the retrieved chunks. "
|
| 80 |
+
"Do not make up information or hallucinate. "
|
| 81 |
+
"Always cite the source URLs when providing information."
|
| 82 |
+
),
|
| 83 |
+
model=third_party_model, # Using the OpenRouter model
|
| 84 |
+
tools=[self.search_qdrant_tool]
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
logger.info("Agent initialized with retrieval capabilities")
|
| 88 |
+
|
| 89 |
+
@function_tool
|
| 90 |
+
def _search_qdrant_function(self, query: str, top_k: int = 5) -> Dict[str, Any]:
|
| 91 |
+
"""
|
| 92 |
+
Search the Qdrant database for relevant book content chunks.
|
| 93 |
+
This is the tool function that will be called by the agent.
|
| 94 |
+
"""
|
| 95 |
+
# Call the existing search_qdrant method and return the result
|
| 96 |
+
chunks = self.search_qdrant(query, top_k)
|
| 97 |
+
|
| 98 |
+
# Format the output
|
| 99 |
+
output = {
|
| 100 |
+
"retrieved_chunks": chunks,
|
| 101 |
+
"count": len(chunks),
|
| 102 |
+
"sources": list(set([chunk["source_url"] for chunk in chunks if chunk["source_url"]]))
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
return output
|
| 106 |
+
|
| 107 |
+
# Reference the decorated function as the tool
|
| 108 |
+
search_qdrant_tool = _search_qdrant_function
|
| 109 |
+
|
| 110 |
+
def search_qdrant(self, query: str, top_k: int = 5) -> List[Dict[str, Any]]:
|
| 111 |
+
"""
|
| 112 |
+
Search Qdrant for relevant content chunks.
|
| 113 |
+
This reuses the existing retrieval pipeline logic.
|
| 114 |
+
"""
|
| 115 |
+
try:
|
| 116 |
+
# Import the existing retrieval system from the backend
|
| 117 |
+
import sys
|
| 118 |
+
import os
|
| 119 |
+
# No need to modify path since we're already in the backend directory
|
| 120 |
+
from retrieve import RagRetrievalSystem
|
| 121 |
+
|
| 122 |
+
# Create retrieval system instance
|
| 123 |
+
retrieval_system = RagRetrievalSystem()
|
| 124 |
+
|
| 125 |
+
# Perform retrieval
|
| 126 |
+
results = retrieval_system.retrieve_and_validate(query, top_k=top_k)
|
| 127 |
+
|
| 128 |
+
# Extract relevant chunks
|
| 129 |
+
chunks = []
|
| 130 |
+
for chunk in results['retrieved_chunks']:
|
| 131 |
+
chunk_obj = RetrievedChunk(
|
| 132 |
+
id=chunk.get('id', ''),
|
| 133 |
+
score=chunk.get('score', 0.0),
|
| 134 |
+
content=chunk.get('content', ''),
|
| 135 |
+
content_preview=chunk.get('content_preview', ''),
|
| 136 |
+
source_url=chunk.get('source_url', ''),
|
| 137 |
+
source_title=chunk.get('source_title', ''),
|
| 138 |
+
chunk_index=chunk.get('chunk_index', 0),
|
| 139 |
+
chunk_total=chunk.get('chunk_total', 0),
|
| 140 |
+
created_at=chunk.get('created_at', ''),
|
| 141 |
+
original_word_count=chunk.get('original_word_count', 0)
|
| 142 |
+
)
|
| 143 |
+
chunks.append(chunk_obj.model_dump())
|
| 144 |
+
|
| 145 |
+
logger.info(f"Retrieved {len(chunks)} chunks for query: '{query[:50]}...'")
|
| 146 |
+
return chunks
|
| 147 |
+
|
| 148 |
+
except ImportError as e:
|
| 149 |
+
logger.error(f"Failed to import retrieval system: {str(e)}")
|
| 150 |
+
return []
|
| 151 |
+
except Exception as e:
|
| 152 |
+
logger.error(f"Error searching Qdrant: {str(e)}")
|
| 153 |
+
return []
|
| 154 |
+
|
| 155 |
+
async def run_query(self, query: str) -> str:
|
| 156 |
+
"""
|
| 157 |
+
Run a query through the agent and return the response.
|
| 158 |
+
The agent will use retrieval tools to get relevant content before answering.
|
| 159 |
+
"""
|
| 160 |
+
try:
|
| 161 |
+
# Run the agent using the new Agent SDK
|
| 162 |
+
result = await Runner.run(self.agent, query)
|
| 163 |
+
|
| 164 |
+
# Get the final output from the result
|
| 165 |
+
return result.final_output
|
| 166 |
+
|
| 167 |
+
except Exception as e:
|
| 168 |
+
logger.error(f"Error running query: {str(e)}")
|
| 169 |
+
return f"An error occurred while processing your query: {str(e)}"
|
| 170 |
+
|
| 171 |
+
async def test_connection(self) -> bool:
|
| 172 |
+
"""
|
| 173 |
+
Test the connection to both OpenAI and Qdrant.
|
| 174 |
+
"""
|
| 175 |
+
try:
|
| 176 |
+
# Test Qdrant connection by doing a simple search
|
| 177 |
+
test_chunks = self.search_qdrant("test", top_k=1)
|
| 178 |
+
|
| 179 |
+
# Test the agent by running a simple query
|
| 180 |
+
test_result = await self.run_query("Say hello")
|
| 181 |
+
|
| 182 |
+
logger.info("Connection test successful")
|
| 183 |
+
return True
|
| 184 |
+
|
| 185 |
+
except Exception as e:
|
| 186 |
+
logger.error(f"Connection test failed: {str(e)}")
|
| 187 |
+
return False
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
import asyncio
|
| 191 |
+
|
| 192 |
+
async def async_main():
|
| 193 |
+
"""Main async function to demonstrate the agent."""
|
| 194 |
+
logger.info("Initializing Agent with Retrieval...")
|
| 195 |
+
|
| 196 |
+
try:
|
| 197 |
+
# Create agent instance
|
| 198 |
+
agent = AgentWithRetrieval()
|
| 199 |
+
|
| 200 |
+
# Test connection
|
| 201 |
+
logger.info("Testing connections...")
|
| 202 |
+
if not await agent.test_connection():
|
| 203 |
+
logger.error("Failed to connect to services. Exiting.")
|
| 204 |
+
return
|
| 205 |
+
|
| 206 |
+
logger.info("Agent is ready to answer questions!")
|
| 207 |
+
logger.info("Type 'quit' to exit, 'help' for instructions")
|
| 208 |
+
|
| 209 |
+
# Interactive loop
|
| 210 |
+
while True:
|
| 211 |
+
try:
|
| 212 |
+
query = input("\nEnter your question: ").strip()
|
| 213 |
+
|
| 214 |
+
if query.lower() == 'quit':
|
| 215 |
+
logger.info("Exiting agent...")
|
| 216 |
+
break
|
| 217 |
+
elif query.lower() == 'help':
|
| 218 |
+
print("\nInstructions:")
|
| 219 |
+
print("- Ask any question about the book content")
|
| 220 |
+
print("- The agent will retrieve relevant information and answer based on it")
|
| 221 |
+
print("- Type 'quit' to exit")
|
| 222 |
+
continue
|
| 223 |
+
elif not query:
|
| 224 |
+
continue
|
| 225 |
+
|
| 226 |
+
logger.info(f"Processing query: '{query[:50]}...'")
|
| 227 |
+
|
| 228 |
+
# Get response from agent (now async)
|
| 229 |
+
response = await agent.run_query(query)
|
| 230 |
+
|
| 231 |
+
print(f"\nAgent Response:\n{response}")
|
| 232 |
+
|
| 233 |
+
except KeyboardInterrupt:
|
| 234 |
+
logger.info("\nExiting agent...")
|
| 235 |
+
break
|
| 236 |
+
except Exception as e:
|
| 237 |
+
logger.error(f"Error in main loop: {str(e)}")
|
| 238 |
+
print(f"An error occurred: {str(e)}")
|
| 239 |
+
|
| 240 |
+
except Exception as e:
|
| 241 |
+
logger.error(f"Failed to initialize agent: {str(e)}")
|
| 242 |
+
print(f"Error initializing agent: {str(e)}")
|
| 243 |
+
print("Please check your API keys and model availability.")
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def main():
|
| 247 |
+
"""Main function to demonstrate the agent."""
|
| 248 |
+
# Run the async main function
|
| 249 |
+
asyncio.run(async_main())
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
if __name__ == "__main__":
|
| 253 |
+
main()
|
api.py
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
FastAPI server for RAG System Integration.
|
| 4 |
+
|
| 5 |
+
This module creates a FastAPI server that exposes a query endpoint
|
| 6 |
+
for the RAG agent, allowing frontend applications to send queries
|
| 7 |
+
and receive responses with document retrieval capabilities.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from fastapi import FastAPI, HTTPException, Request
|
| 11 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 12 |
+
from pydantic import BaseModel, Field
|
| 13 |
+
from typing import Optional, List, Dict, Any
|
| 14 |
+
import logging
|
| 15 |
+
import asyncio
|
| 16 |
+
from agent import AgentWithRetrieval
|
| 17 |
+
import uuid
|
| 18 |
+
from datetime import datetime, timedelta
|
| 19 |
+
from typing import Dict, List, Tuple
|
| 20 |
+
import re
|
| 21 |
+
from collections import defaultdict
|
| 22 |
+
import time
|
| 23 |
+
from qdrant_client import models
|
| 24 |
+
|
| 25 |
+
# Initialize FastAPI app
|
| 26 |
+
app = FastAPI(title="RAG System Query API", version="1.0.0")
|
| 27 |
+
|
| 28 |
+
# Configure logging
|
| 29 |
+
logging.basicConfig(
|
| 30 |
+
level=logging.INFO,
|
| 31 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 32 |
+
)
|
| 33 |
+
logger = logging.getLogger(__name__)
|
| 34 |
+
|
| 35 |
+
# Create singleton agent instance
|
| 36 |
+
agent_instance = AgentWithRetrieval()
|
| 37 |
+
|
| 38 |
+
# Rate limiting storage
|
| 39 |
+
class RateLimiter:
|
| 40 |
+
def __init__(self, max_requests: int = 10, window_seconds: int = 60):
|
| 41 |
+
self.max_requests = max_requests
|
| 42 |
+
self.window_seconds = window_seconds
|
| 43 |
+
self.requests = defaultdict(list) # ip -> list of request timestamps
|
| 44 |
+
|
| 45 |
+
def is_allowed(self, client_ip: str) -> bool:
|
| 46 |
+
"""Check if a client is allowed to make a request."""
|
| 47 |
+
now = time.time()
|
| 48 |
+
# Remove old requests outside the window
|
| 49 |
+
self.requests[client_ip] = [req_time for req_time in self.requests[client_ip]
|
| 50 |
+
if now - req_time < self.window_seconds]
|
| 51 |
+
|
| 52 |
+
if len(self.requests[client_ip]) < self.max_requests:
|
| 53 |
+
self.requests[client_ip].append(now)
|
| 54 |
+
return True
|
| 55 |
+
return False
|
| 56 |
+
|
| 57 |
+
# Initialize rate limiter
|
| 58 |
+
rate_limiter = RateLimiter(max_requests=30, window_seconds=60) # 30 requests per minute per IP
|
| 59 |
+
|
| 60 |
+
# In-memory session storage for conversation history
|
| 61 |
+
class SessionManager:
|
| 62 |
+
def __init__(self):
|
| 63 |
+
self.sessions: Dict[str, Dict] = {}
|
| 64 |
+
self.max_session_age = timedelta(hours=1) # Sessions expire after 1 hour of inactivity
|
| 65 |
+
|
| 66 |
+
def create_session(self) -> str:
|
| 67 |
+
"""Create a new session and return the session ID."""
|
| 68 |
+
session_id = str(uuid.uuid4())
|
| 69 |
+
self.sessions[session_id] = {
|
| 70 |
+
"created_at": datetime.now(),
|
| 71 |
+
"last_accessed": datetime.now(),
|
| 72 |
+
"conversation_history": []
|
| 73 |
+
}
|
| 74 |
+
logger.info(f"Created new session: {session_id}")
|
| 75 |
+
return session_id
|
| 76 |
+
|
| 77 |
+
def get_session(self, session_id: str) -> Dict:
|
| 78 |
+
"""Get session data by ID, or None if not found or expired."""
|
| 79 |
+
if session_id not in self.sessions:
|
| 80 |
+
return None
|
| 81 |
+
|
| 82 |
+
session = self.sessions[session_id]
|
| 83 |
+
# Check if session has expired
|
| 84 |
+
if datetime.now() - session["last_accessed"] > self.max_session_age:
|
| 85 |
+
del self.sessions[session_id]
|
| 86 |
+
logger.info(f"Session {session_id} expired and removed")
|
| 87 |
+
return None
|
| 88 |
+
|
| 89 |
+
# Update last accessed time
|
| 90 |
+
session["last_accessed"] = datetime.now()
|
| 91 |
+
return session
|
| 92 |
+
|
| 93 |
+
def update_session_history(self, session_id: str, query: str, response: str):
|
| 94 |
+
"""Add a query-response pair to the session's conversation history."""
|
| 95 |
+
session = self.get_session(session_id)
|
| 96 |
+
if session:
|
| 97 |
+
session["conversation_history"].append({
|
| 98 |
+
"query": query,
|
| 99 |
+
"response": response,
|
| 100 |
+
"timestamp": datetime.now()
|
| 101 |
+
})
|
| 102 |
+
logger.info(f"Updated conversation history for session {session_id}")
|
| 103 |
+
|
| 104 |
+
def cleanup_expired_sessions(self):
|
| 105 |
+
"""Remove all expired sessions from storage."""
|
| 106 |
+
expired_sessions = []
|
| 107 |
+
now = datetime.now()
|
| 108 |
+
for session_id, session_data in self.sessions.items():
|
| 109 |
+
if now - session_data["last_accessed"] > self.max_session_age:
|
| 110 |
+
expired_sessions.append(session_id)
|
| 111 |
+
|
| 112 |
+
for session_id in expired_sessions:
|
| 113 |
+
del self.sessions[session_id]
|
| 114 |
+
logger.info(f"Cleaned up expired session: {session_id}")
|
| 115 |
+
|
| 116 |
+
return len(expired_sessions)
|
| 117 |
+
|
| 118 |
+
# Initialize session manager
|
| 119 |
+
session_manager = SessionManager()
|
| 120 |
+
|
| 121 |
+
# Pydantic models for request/response validation
|
| 122 |
+
class QueryRequest(BaseModel):
|
| 123 |
+
"""Request model for query endpoint."""
|
| 124 |
+
query_text: str = Field(..., description="The user's query text", max_length=1000)
|
| 125 |
+
session_id: Optional[str] = Field(None, description="Optional session ID for conversation history")
|
| 126 |
+
metadata: Optional[Dict[str, Any]] = Field(None, description="Additional metadata for the query")
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class Citation(BaseModel):
|
| 130 |
+
"""Model for citation information."""
|
| 131 |
+
source_url: str
|
| 132 |
+
source_title: str
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class QueryResponse(BaseModel):
|
| 136 |
+
"""Response model for query endpoint."""
|
| 137 |
+
response_text: str
|
| 138 |
+
citations: Optional[List[Citation]] = None
|
| 139 |
+
session_id: Optional[str] = None
|
| 140 |
+
status: str # "success" or "error"
|
| 141 |
+
error_message: Optional[str] = None
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class ErrorResponse(BaseModel):
|
| 145 |
+
"""Response model for error cases."""
|
| 146 |
+
status: str = "error"
|
| 147 |
+
error_message: str
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
# Add CORS middleware
|
| 151 |
+
app.add_middleware(
|
| 152 |
+
CORSMiddleware,
|
| 153 |
+
allow_origins=["*"], # In production, replace with specific origins
|
| 154 |
+
allow_credentials=True,
|
| 155 |
+
allow_methods=["*"],
|
| 156 |
+
allow_headers=["*"],
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
# API Response utility functions
|
| 160 |
+
def create_success_response(response_text: str, session_id: Optional[str] = None, citations: Optional[List[Citation]] = None) -> QueryResponse:
|
| 161 |
+
"""Create a success response with the given parameters."""
|
| 162 |
+
return QueryResponse(
|
| 163 |
+
response_text=response_text,
|
| 164 |
+
citations=citations,
|
| 165 |
+
session_id=session_id,
|
| 166 |
+
status="success"
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
def create_error_response(error_message: str, session_id: Optional[str] = None) -> QueryResponse:
|
| 170 |
+
"""Create an error response with the given error message."""
|
| 171 |
+
return QueryResponse(
|
| 172 |
+
response_text="",
|
| 173 |
+
session_id=session_id,
|
| 174 |
+
status="error",
|
| 175 |
+
error_message=error_message
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
def filter_input_content(text: str) -> str:
|
| 179 |
+
"""
|
| 180 |
+
Filter input content for security.
|
| 181 |
+
Remove or sanitize potentially harmful content.
|
| 182 |
+
"""
|
| 183 |
+
# Remove potential command injection patterns
|
| 184 |
+
filtered_text = re.sub(r'[;&|`$<>]', '', text)
|
| 185 |
+
|
| 186 |
+
# Remove potential SQL injection patterns
|
| 187 |
+
filtered_text = re.sub(r"(?i)(union|select|insert|update|delete|drop|create|alter|exec|execute)",
|
| 188 |
+
lambda m: m.group(0)[:1] + '*'*(len(m.group(0))-1),
|
| 189 |
+
filtered_text)
|
| 190 |
+
|
| 191 |
+
# Additional security filtering could be added here
|
| 192 |
+
|
| 193 |
+
return filtered_text
|
| 194 |
+
|
| 195 |
+
def extract_citations_from_response(response_text: str) -> Optional[List[Citation]]:
|
| 196 |
+
"""
|
| 197 |
+
Extract citation information from the agent's response.
|
| 198 |
+
This is a placeholder implementation - in a real system,
|
| 199 |
+
citations would be extracted from the RAG agent's response.
|
| 200 |
+
"""
|
| 201 |
+
# In a real implementation, this would parse the response for citation information
|
| 202 |
+
# For now, return None as a placeholder
|
| 203 |
+
# Future implementation could look for patterns like [source_url] or parse metadata
|
| 204 |
+
return []
|
| 205 |
+
|
| 206 |
+
@app.get("/health")
|
| 207 |
+
async def health_check():
|
| 208 |
+
"""Health check endpoint to verify API is running."""
|
| 209 |
+
return {"status": "healthy"}
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
@app.post("/query", response_model=QueryResponse)
|
| 213 |
+
async def query_endpoint(request: QueryRequest, request_obj: Request = None):
|
| 214 |
+
"""
|
| 215 |
+
Process a user query through the RAG agent.
|
| 216 |
+
|
| 217 |
+
This endpoint receives a query from the frontend, processes it through
|
| 218 |
+
the RAG agent with document retrieval capabilities, and returns a response.
|
| 219 |
+
"""
|
| 220 |
+
# Get client IP for rate limiting
|
| 221 |
+
client_ip = request_obj.client.host if request_obj else "127.0.0.1"
|
| 222 |
+
|
| 223 |
+
logger.info(f"Processing query from {client_ip}: '{request.query_text[:50]}...'")
|
| 224 |
+
|
| 225 |
+
# Check rate limit
|
| 226 |
+
if not rate_limiter.is_allowed(client_ip):
|
| 227 |
+
error_detail = "Rate limit exceeded. Please try again later."
|
| 228 |
+
logger.warning(f"Rate limit exceeded for {client_ip}")
|
| 229 |
+
raise HTTPException(
|
| 230 |
+
status_code=429,
|
| 231 |
+
detail=error_detail
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
try:
|
| 235 |
+
# Validate query text is not empty after stripping whitespace
|
| 236 |
+
if not request.query_text.strip():
|
| 237 |
+
error_detail = "Query text is required and cannot be empty"
|
| 238 |
+
logger.warning(f"Validation error: {error_detail}")
|
| 239 |
+
# Return 400 error with proper error response format
|
| 240 |
+
raise HTTPException(
|
| 241 |
+
status_code=400,
|
| 242 |
+
detail=error_detail
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
# Validate query length (max 1000 characters)
|
| 246 |
+
if len(request.query_text) > 1000:
|
| 247 |
+
error_detail = "Query text must be less than 1000 characters"
|
| 248 |
+
logger.warning(f"Validation error: {error_detail}")
|
| 249 |
+
raise HTTPException(
|
| 250 |
+
status_code=400,
|
| 251 |
+
detail=error_detail
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
# Filter input content for security
|
| 255 |
+
filtered_query_text = filter_input_content(request.query_text)
|
| 256 |
+
|
| 257 |
+
# Get or create session ID
|
| 258 |
+
session_id = request.session_id
|
| 259 |
+
if not session_id:
|
| 260 |
+
session_id = session_manager.create_session()
|
| 261 |
+
else:
|
| 262 |
+
# Check if session exists, create new one if expired
|
| 263 |
+
existing_session = session_manager.get_session(session_id)
|
| 264 |
+
if not existing_session:
|
| 265 |
+
session_id = session_manager.create_session()
|
| 266 |
+
|
| 267 |
+
# Call the RAG agent's run_query method with the filtered query
|
| 268 |
+
agent_response = await agent_instance.run_query(filtered_query_text)
|
| 269 |
+
|
| 270 |
+
# Extract citations from the response (placeholder implementation)
|
| 271 |
+
citations = extract_citations_from_response(agent_response)
|
| 272 |
+
|
| 273 |
+
# Update session history with the query and response
|
| 274 |
+
session_manager.update_session_history(session_id, filtered_query_text, agent_response)
|
| 275 |
+
|
| 276 |
+
# Create and return success response
|
| 277 |
+
response = create_success_response(
|
| 278 |
+
response_text=agent_response,
|
| 279 |
+
session_id=session_id,
|
| 280 |
+
citations=citations
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
logger.info(f"Query processed successfully for session {session_id}")
|
| 284 |
+
return response
|
| 285 |
+
|
| 286 |
+
except HTTPException as e:
|
| 287 |
+
# Re-raise HTTP exceptions (like 400 validation errors)
|
| 288 |
+
logger.warning(f"HTTP error: {e.detail}")
|
| 289 |
+
raise
|
| 290 |
+
except Exception as e:
|
| 291 |
+
# Handle internal server errors (500)
|
| 292 |
+
logger.error(f"Internal server error processing query: {str(e)}")
|
| 293 |
+
error_detail = f"An error occurred while processing your query: {str(e)}"
|
| 294 |
+
raise HTTPException(
|
| 295 |
+
status_code=500,
|
| 296 |
+
detail=error_detail
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
@app.get("/session/{session_id}")
|
| 301 |
+
async def get_session_history(session_id: str):
|
| 302 |
+
"""
|
| 303 |
+
Retrieve session history for testing conversation continuity.
|
| 304 |
+
This endpoint is for testing purposes only.
|
| 305 |
+
"""
|
| 306 |
+
session = session_manager.get_session(session_id)
|
| 307 |
+
if not session:
|
| 308 |
+
raise HTTPException(status_code=404, detail="Session not found or expired")
|
| 309 |
+
|
| 310 |
+
return {
|
| 311 |
+
"session_id": session_id,
|
| 312 |
+
"created_at": session["created_at"],
|
| 313 |
+
"last_accessed": session["last_accessed"],
|
| 314 |
+
"conversation_history": session["conversation_history"]
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
@app.get("/admin/cleanup-sessions")
|
| 319 |
+
async def cleanup_sessions():
|
| 320 |
+
"""
|
| 321 |
+
Admin endpoint to manually clean up expired sessions.
|
| 322 |
+
"""
|
| 323 |
+
expired_count = session_manager.cleanup_expired_sessions()
|
| 324 |
+
return {
|
| 325 |
+
"message": f"Cleaned up {expired_count} expired sessions",
|
| 326 |
+
"timestamp": datetime.now()
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
# Periodic cleanup task
|
| 331 |
+
async def periodic_cleanup():
|
| 332 |
+
"""Periodically clean up expired sessions."""
|
| 333 |
+
while True:
|
| 334 |
+
await asyncio.sleep(300) # Run every 5 minutes
|
| 335 |
+
expired_count = session_manager.cleanup_expired_sessions()
|
| 336 |
+
if expired_count > 0:
|
| 337 |
+
logger.info(f"Periodic cleanup removed {expired_count} expired sessions")
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
@app.on_event("startup")
|
| 341 |
+
async def startup_event():
|
| 342 |
+
"""Start the periodic cleanup task when the application starts."""
|
| 343 |
+
asyncio.create_task(periodic_cleanup())
|
| 344 |
+
logger.info("Started periodic cleanup task")
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
if __name__ == "__main__":
|
| 348 |
+
import uvicorn
|
| 349 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
requirements.txt
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
requests
|
| 2 |
+
beautifulsoup4
|
| 3 |
+
cohere
|
| 4 |
+
qdrant-client
|
| 5 |
+
python-dotenv
|
| 6 |
+
tqdm
|
| 7 |
+
lxml
|
| 8 |
+
fastapi
|
| 9 |
+
uvicorn
|
| 10 |
+
pydantic
|
| 11 |
+
pydantic-settings
|
| 12 |
+
langchain
|
| 13 |
+
langchain-community
|
| 14 |
+
langchain-core
|
| 15 |
+
openai-agents
|
| 16 |
+
sentence-transformers
|
| 17 |
+
numpy
|
| 18 |
+
pandas
|
| 19 |
+
scikit-learn
|
| 20 |
+
asyncio
|
| 21 |
+
aiohttp
|
| 22 |
+
pyyaml
|