Spaces:
Sleeping
Sleeping
File size: 6,397 Bytes
7afbd6c | 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 | import os
import asyncio
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Optional, Dict
from dotenv import load_dotenv
import logging
# Load environment variables
load_dotenv()
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Import the existing RAG agent functionality
from agent import RAGAgent
# Create FastAPI app
app = FastAPI(
title="RAG Agent API",
description="API for RAG Agent with document retrieval and question answering",
version="1.0.0"
)
# Add CORS middleware for development
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # In production, replace with specific origins
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Pydantic models
class QueryRequest(BaseModel):
query: str
class ChatRequest(BaseModel):
query: str
message: str
session_id: str
selected_text: Optional[str] = None
query_type: str = "global"
top_k: int = 5
class MatchedChunk(BaseModel):
content: str
url: str
position: int
similarity_score: float
class QueryResponse(BaseModel):
answer: str
sources: List[str]
matched_chunks: List[MatchedChunk]
error: Optional[str] = None
status: str # "success", "error", "empty"
query_time_ms: Optional[float] = None
confidence: Optional[str] = None
class ChatResponse(BaseModel):
response: str
citations: List[Dict[str, str]]
session_id: str
query_type: str
timestamp: str
class HealthResponse(BaseModel):
status: str
message: str
# Global RAG agent instance
rag_agent = None
@app.on_event("startup")
async def startup_event():
"""Initialize the RAG agent on startup"""
global rag_agent
logger.info("Initializing RAG Agent...")
try:
rag_agent = RAGAgent()
logger.info("RAG Agent initialized successfully")
except Exception as e:
logger.error(f"Failed to initialize RAG Agent: {e}")
raise
@app.post("/ask", response_model=QueryResponse)
async def ask_rag(request: QueryRequest):
"""
Process a user query through the RAG agent and return the response
"""
logger.info(f"Processing query: {request.query[:50]}...")
try:
# Validate input
if not request.query or len(request.query.strip()) == 0:
raise HTTPException(status_code=400, detail="Query cannot be empty")
if len(request.query) > 2000:
raise HTTPException(status_code=400, detail="Query too long, maximum 2000 characters")
# Process query through RAG agent
response = rag_agent.query_agent(request.query)
# Format response
formatted_response = QueryResponse(
answer=response.get("answer", ""),
sources=response.get("sources", []),
matched_chunks=[
MatchedChunk(
content=chunk.get("content", ""),
url=chunk.get("url", ""),
position=chunk.get("position", 0),
similarity_score=chunk.get("similarity_score", 0.0)
)
for chunk in response.get("matched_chunks", [])
],
error=response.get("error"),
status="error" if response.get("error") else "success",
query_time_ms=response.get("query_time_ms"),
confidence=response.get("confidence")
)
logger.info(f"Query processed successfully in {response.get('query_time_ms', 0):.2f}ms")
return formatted_response
except HTTPException:
raise
except Exception as e:
logger.error(f"Error processing query: {e}")
return QueryResponse(
answer="",
sources=[],
matched_chunks=[],
error=str(e),
status="error"
)
@app.post("/api", response_model=ChatResponse)
async def chat_endpoint(request: ChatRequest):
"""
Main chat endpoint that handles conversation with RAG capabilities
"""
logger.info(f"Processing chat query: {request.query[:50]}...")
try:
# Validate input
if not request.query or len(request.query.strip()) == 0:
raise HTTPException(status_code=400, detail="Query cannot be empty")
if not request.session_id or len(request.session_id.strip()) == 0:
raise HTTPException(status_code=400, detail="Session ID cannot be empty")
if len(request.query) > 2000:
raise HTTPException(status_code=400, detail="Query too long, maximum 2000 characters")
# Process query through RAG agent
response = rag_agent.query_agent(request.query)
# Format response to match expected structure
from datetime import datetime
timestamp = datetime.utcnow().isoformat()
# Convert matched chunks to citations format
citations = []
for chunk in response.get("matched_chunks", []):
citation = {
"document_id": "",
"title": chunk.get("url", ""),
"chapter": "",
"section": "",
"page_reference": ""
}
citations.append(citation)
formatted_response = ChatResponse(
response=response.get("answer", ""),
citations=citations,
session_id=request.session_id,
query_type=request.query_type,
timestamp=timestamp
)
logger.info(f"Chat query processed successfully")
return formatted_response
except HTTPException:
raise
except Exception as e:
logger.error(f"Error processing chat query: {e}")
from datetime import datetime
return ChatResponse(
response="",
citations=[],
session_id=request.session_id,
query_type=request.query_type,
timestamp=datetime.utcnow().isoformat()
)
@app.get("/health", response_model=HealthResponse)
async def health_check():
"""
Health check endpoint
"""
return HealthResponse(
status="healthy",
message="RAG Agent API is running"
)
# For running with uvicorn
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) |