mathanmithun's picture
Upload 39 files
f45a28c verified
Raw History Blame Contribute Delete
10 kB
# STEP 8 — FASTAPI BACKEND
# This file will be populated in STEP 8
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field, field_validator
from typing import List, Optional
import sys
import os
from datetime import datetime
# Add src directory to path
sys.path.append(os.path.join(os.path.dirname(__file__), "src"))
from logger_config import setup_logger
from rag_pipeline import rag_chat, rag_chat_with_history
from retriever import preload_models
logger = setup_logger(__name__)
# In-memory session storage for conversation history
# In production, consider using Redis or a database
conversation_sessions = {}
app = FastAPI(
title="Dhigrowth RAG Chatbot API",
description="RAG-based chatbot for Dhigrowth information",
version="1.0.0"
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # In production, specify actual origins
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.on_event("startup")
async def startup_event():
"""
Preload models when the server starts
This ensures faster response times for the first request
"""
logger.info("Starting up server...")
try:
preload_models()
logger.info("Server startup complete - models are ready")
except Exception as e:
logger.error(f"Error during startup: {str(e)}", exc_info=True)
# Don't raise - allow server to start but log the error
# This way the server can still run even if preloading fails
class Query(BaseModel):
"""Query model with validation"""
question: str = Field(..., min_length=1, max_length=1000, description="User question")
@field_validator('question')
@classmethod
def validate_question(cls, v):
"""Validate that question is not empty or whitespace only"""
if not v.strip():
raise ValueError('Question cannot be empty or whitespace only')
return v.strip()
class ChatMessage(BaseModel):
"""Chat message model"""
role: str = Field(..., description="Message role: 'user' or 'assistant'")
content: str = Field(..., min_length=1, description="Message content")
@field_validator('role')
@classmethod
def validate_role(cls, v):
"""Validate that role is either 'user' or 'assistant'"""
if v not in ["user", "assistant"]:
raise ValueError('Role must be either "user" or "assistant"')
return v
@field_validator('content')
@classmethod
def validate_content(cls, v):
"""Validate that content is not empty or whitespace only"""
if not v.strip():
raise ValueError('Content cannot be empty or whitespace only')
return v.strip()
class ChatRequest(BaseModel):
"""Chat request model with conversation history"""
question: str = Field(..., min_length=1, max_length=1000, description="User question")
session_id: Optional[str] = Field(None, description="Optional session ID for conversation tracking")
conversation_history: Optional[List[ChatMessage]] = Field(None, description="Previous conversation messages")
@field_validator('question')
@classmethod
def validate_question(cls, v):
"""Validate that question is not empty or whitespace only"""
if not v.strip():
raise ValueError('Question cannot be empty or whitespace only')
return v.strip()
@app.get("/health")
def health():
"""
Health check endpoint
Returns:
dict: Health status information
"""
return {
"status": "healthy",
"service": "Dhigrowth RAG Chatbot",
"version": "1.0.0"
}
@app.post("/ask")
def ask(query: Query):
"""
Ask a question to the RAG chatbot
Args:
query: Query object containing the question
Returns:
dict: Question and answer
"""
try:
logger.info(f"Received question: {query.question[:50]}...")
# Call RAG pipeline
answer = rag_chat(query.question)
logger.info(f"Generated answer for question")
return {
"question": query.question,
"answer": answer
}
except ValueError as e:
logger.warning(f"Validation error: {str(e)}")
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Error processing request: {str(e)}", exc_info=True)
raise HTTPException(
status_code=500,
detail="An error occurred while processing your request"
)
@app.post("/chat")
def chat(request: ChatRequest):
"""
Chat endpoint with conversation history support
Args:
request: ChatRequest object containing question, optional session_id, and conversation_history
Returns:
dict: Question, answer, updated conversation history, and session_id
"""
try:
logger.info(f"Received chat question: {request.question[:50]}...")
# Get or create session
session_id = request.session_id
if not session_id:
# Generate a simple session ID (in production, use UUID)
session_id = f"session_{datetime.now().timestamp()}"
# Get conversation history from session or request
if session_id in conversation_sessions:
# Use session history if available
history = conversation_sessions[session_id]
elif request.conversation_history:
# Use provided history
history = [{"role": msg.role, "content": msg.content} for msg in request.conversation_history]
else:
# Start new conversation
history = []
# Call RAG pipeline with history
answer = rag_chat_with_history(request.question, history if history else None)
# Update conversation history
history.append({"role": "user", "content": request.question})
history.append({"role": "assistant", "content": answer})
# Store updated history in session
conversation_sessions[session_id] = history
# Limit history length to prevent token overflow (keep last 10 exchanges = 20 messages)
max_history = 20
if len(history) > max_history:
history = history[-max_history:]
conversation_sessions[session_id] = history
logger.info(f"Generated chat answer for session: {session_id}")
return {
"question": request.question,
"answer": answer,
"session_id": session_id,
"conversation_history": history
}
except ValueError as e:
logger.warning(f"Validation error: {str(e)}")
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Error processing chat request: {str(e)}", exc_info=True)
raise HTTPException(
status_code=500,
detail="An error occurred while processing your request"
)
class ClearChatRequest(BaseModel):
"""Request model for clearing chat"""
session_id: str = Field(..., description="Session ID to clear")
@app.post("/chat/clear")
def clear_chat(request: ClearChatRequest):
"""
Clear conversation history for a session
Args:
request: ClearChatRequest object containing session_id
Returns:
dict: Success message
"""
try:
session_id = request.session_id
if session_id in conversation_sessions:
del conversation_sessions[session_id]
logger.info(f"Cleared conversation history for session: {session_id}")
return {
"status": "success",
"message": f"Conversation history cleared for session: {session_id}",
"session_id": session_id
}
else:
return {
"status": "success",
"message": f"Session {session_id} not found or already cleared",
"session_id": session_id
}
except Exception as e:
logger.error(f"Error clearing chat: {str(e)}", exc_info=True)
raise HTTPException(
status_code=500,
detail="An error occurred while clearing the conversation"
)
@app.post("/chat/clear/all")
def clear_all_chats():
"""
Clear all conversation histories (use with caution)
Returns:
dict: Success message with count of cleared sessions
"""
try:
count = len(conversation_sessions)
conversation_sessions.clear()
logger.info(f"Cleared all conversation histories ({count} sessions)")
return {
"status": "success",
"message": f"All conversation histories cleared ({count} sessions)",
"cleared_count": count
}
except Exception as e:
logger.error(f"Error clearing all chats: {str(e)}", exc_info=True)
raise HTTPException(
status_code=500,
detail="An error occurred while clearing all conversations"
)
@app.get("/")
def root():
"""Root endpoint"""
return {
"message": "Dhigrowth RAG Chatbot API",
"version": "1.0.0",
"endpoints": {
"health": "/health",
"ask": "/ask (POST) - Single question without history",
"chat": "/chat (POST) - Chat with conversation history",
"clear_chat": "/chat/clear (POST) - Clear conversation for a session",
"clear_all": "/chat/clear/all (POST) - Clear all conversations"
}
}