File size: 10,025 Bytes
f45a28c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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"
        }
    }