File size: 13,334 Bytes
a236811
 
 
 
 
690700c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# ============================================================================
# backend/app/services/chat_service.py
# ============================================================================


"""
Chat Service - Main RAG Pipeline

Combines: Policy Network β†’ Retriever β†’ LLM Generator

This is the core service that orchestrates:
1. Policy decision (FETCH vs NO_FETCH)
2. Document retrieval (if FETCH)
3. Response generation (Groq/HuggingFace with Llama 3)
4. Logging to MongoDB

Adapted from your RAG.py workflow
"""

import time
from datetime import datetime
from typing import List, Dict, Any, Optional

from app.config import settings
from app.ml.policy_network import predict_policy_action
from app.ml.retriever import retrieve_documents, format_context
from app.core.llm_manager import llm_manager

# ============================================================================
# SYSTEM PROMPTS
# ============================================================================

BANKING_SYSTEM_PROMPT = """You are an expert banking assistant specialized in Indian financial regulations and banking practices. You have access to a comprehensive knowledge base of banking policies, procedures, and RBI regulations.

Instructions:
- Answer the user query accurately using the provided context when available
- If context is insufficient or query is outside banking domain, still respond helpfully but mention your banking specialization
- If no banking context is available, provide a general helpful response but acknowledge your expertise is in banking
- Never refuse to answer - always be helpful while being transparent about your specialization
- Cite relevant policy numbers or document references when available in context
- Never fabricate specific policies, rates, or eligibility criteria
- If uncertain about current rates or policies, acknowledge the limitation
- Maintain a helpful and professional tone
- Keep responses concise, clear, and actionable
"""

EVALUATION_PROMPT = """You are evaluating a banking assistant's response for quality and accuracy.

Criteria:
1. Accuracy: Is the response factually correct?
2. Relevance: Does it address the user's question?
3. Completeness: Are all aspects of the question covered?
4. Clarity: Is the response easy to understand?
5. Context Usage: Does it properly use the retrieved context?

Rate the response as:
- "Good": Accurate, relevant, complete, and clear
- "Bad": Inaccurate, irrelevant, incomplete, or unclear

Provide your rating and brief explanation."""

# ============================================================================
# CHAT SERVICE
# ============================================================================

class ChatService:
    """
    Main chat service that handles the complete RAG pipeline.
    
    Pipeline:
    1. User query comes in
    2. Policy network decides: FETCH or NO_FETCH
    3. If FETCH: Retrieve documents from FAISS
    4. Generate response using Groq/HuggingFace (with or without context)
    5. Return response + metadata
    """
    
    def __init__(self):
        """Initialize chat service"""
        print("πŸ€– ChatService initialized")
    
    async def process_query(
        self,
        query: str,
        conversation_history: List[Dict[str, str]] = None,
        user_id: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        Process a user query through the complete RAG pipeline.
        
        This is the MAIN function that combines everything:
        - Policy decision
        - Retrieval
        - Generation
        
        Args:
            query: User query text
            conversation_history: Previous conversation turns
                Format: [{'role': 'user'/'assistant', 'content': '...', 'metadata': {...}}]
            user_id: Optional user ID for logging
        
        Returns:
            dict: Complete response with metadata
            {
                'response': str,  # Generated response
                'policy_action': str,  # FETCH or NO_FETCH
                'policy_confidence': float,  # Confidence score
                'should_retrieve': bool,  # Whether retrieval was done
                'documents_retrieved': int,  # Number of docs retrieved
                'top_doc_score': float or None,  # Best similarity score
                'retrieval_time_ms': float,  # Time spent on retrieval
                'generation_time_ms': float,  # Time spent on generation
                'total_time_ms': float,  # Total processing time
                'timestamp': str  # ISO timestamp
            }
        """
        start_time = time.time()
        
        # Initialize history if None
        if conversation_history is None:
            conversation_history = []
        
        # Validate query
        if not query or query.strip() == "":
            return {
                'response': "I didn't receive a valid question. Could you please try again?",
                'policy_action': 'NO_FETCH',
                'policy_confidence': 1.0,
                'should_retrieve': False,
                'documents_retrieved': 0,
                'top_doc_score': None,
                'retrieval_time_ms': 0,
                'generation_time_ms': 0,
                'total_time_ms': 0,
                'timestamp': datetime.now().isoformat()
            }
        
        # ====================================================================
        # STEP 1: POLICY DECISION (Local BERT model)
        # ====================================================================
        print(f"\n{'='*80}")
        print(f"πŸ” Processing Query: {query[:50]}...")
        print(f"{'='*80}")
        
        policy_start = time.time()
        
        # Predict action using policy network
        policy_result = predict_policy_action(
            query=query,
            history=conversation_history,
            return_probs=True
        )
        
        policy_time = (time.time() - policy_start) * 1000
        
        print(f"\nπŸ“Š Policy Decision:")
        print(f"   Action: {policy_result['action']}")
        print(f"   Confidence: {policy_result['confidence']:.3f}")
        print(f"   Should Retrieve: {policy_result['should_retrieve']}")
        print(f"   Time: {policy_time:.2f}ms")
        
        # ====================================================================
        # STEP 2: RETRIEVAL (if FETCH or low confidence NO_FETCH)
        # ====================================================================
        retrieved_docs = []
        context = ""
        retrieval_time = 0
        
        if policy_result['should_retrieve']:
            print(f"\nπŸ”Ž Retrieving documents...")
            retrieval_start = time.time()
            
            try:
                # Retrieve documents using custom retriever + FAISS
                retrieved_docs = retrieve_documents(
                    query=query,
                    top_k=settings.TOP_K,
                    min_similarity=settings.SIMILARITY_THRESHOLD
                )
                
                retrieval_time = (time.time() - retrieval_start) * 1000
                
                if retrieved_docs:
                    print(f"   βœ… Retrieved {len(retrieved_docs)} documents")
                    print(f"   Top score: {retrieved_docs[0]['score']:.3f}")
                    
                    # Format context for LLM
                    context = format_context(
                        retrieved_docs,
                        max_context_length=settings.MAX_CONTEXT_LENGTH
                    )
                else:
                    print(f"   ⚠️ No documents above threshold")
            
            except Exception as e:
                print(f"   ❌ Retrieval error: {e}")
                # Continue without retrieval
        
        else:
            print(f"\n🚫 Skipping retrieval (Policy: {policy_result['action']})")
        
        # ====================================================================
        # STEP 3: GENERATE RESPONSE (Groq/HuggingFace with fallback)
        # ====================================================================
        print(f"\nπŸ’¬ Generating response...")
        generation_start = time.time()
        
        try:
            # Generate response using LLM manager (Groq β†’ HuggingFace fallback)
            response = await llm_manager.generate_chat_response(
                query=query,
                context=context,
                history=conversation_history
            )
            
            generation_time = (time.time() - generation_start) * 1000
            
            print(f"   βœ… Response generated")
            print(f"   Length: {len(response)} chars")
            print(f"   Time: {generation_time:.2f}ms")
        
        except Exception as e:
            print(f"   ❌ Generation error: {e}")
            response = "I apologize, but I encountered an error generating a response. Please try again."
            generation_time = (time.time() - generation_start) * 1000
        
        # ====================================================================
        # STEP 4: COMPILE RESULTS
        # ====================================================================
        total_time = (time.time() - start_time) * 1000
        
        result = {
            'response': response,
            'policy_action': policy_result['action'],
            'policy_confidence': policy_result['confidence'],
            'should_retrieve': policy_result['should_retrieve'],
            'documents_retrieved': len(retrieved_docs),
            'top_doc_score': retrieved_docs[0]['score'] if retrieved_docs else None,
            'retrieval_time_ms': round(retrieval_time, 2),
            'generation_time_ms': round(generation_time, 2),
            'total_time_ms': round(total_time, 2),
            'timestamp': datetime.now().isoformat()
        }
        
        # Add retrieved docs metadata (for logging, not sent to user)
        if retrieved_docs:
            result['retrieved_docs_metadata'] = [
                {
                    'faq_id': doc['faq_id'],
                    'score': doc['score'],
                    'category': doc['category'],
                    'rank': doc['rank']
                }
                for doc in retrieved_docs
            ]
        
        print(f"\n{'='*80}")
        print(f"βœ… Query processed successfully")
        print(f"   Total time: {total_time:.2f}ms")
        print(f"{'='*80}\n")
        
        return result
    
    async def health_check(self) -> Dict[str, Any]:
        """
        Check health of all service components.
        
        Returns:
            dict: Health status
        """
        health = {
            'service': 'chat_service',
            'status': 'healthy',
            'components': {}
        }
        
        # Check policy network
        try:
            from app.ml.policy_network import POLICY_MODEL
            health['components']['policy_network'] = 'loaded' if POLICY_MODEL else 'not_loaded'
        except Exception as e:
            health['components']['policy_network'] = f'error: {str(e)}'
        
        # Check retriever
        try:
            from app.ml.retriever import RETRIEVER_MODEL, FAISS_INDEX
            health['components']['retriever'] = 'loaded' if RETRIEVER_MODEL else 'not_loaded'
            health['components']['faiss_index'] = 'loaded' if FAISS_INDEX else 'not_loaded'
        except Exception as e:
            health['components']['retriever'] = f'error: {str(e)}'
        
        # Check LLM manager
        try:
            from app.core.llm_manager import llm_manager as llm
            health['components']['groq'] = 'enabled' if llm.groq else 'disabled'
            health['components']['huggingface'] = 'enabled' if llm.huggingface else 'disabled'
        except Exception as e:
            health['components']['llm_manager'] = f'error: {str(e)}'
        
        # Overall status
        failed_components = [k for k, v in health['components'].items() if 'error' in str(v)]
        if failed_components:
            health['status'] = 'degraded'
            health['failed_components'] = failed_components
        
        return health

# ============================================================================
# GLOBAL CHAT SERVICE INSTANCE
# ============================================================================

chat_service = ChatService()

# ============================================================================
# USAGE EXAMPLE (for reference)
# ============================================================================
"""
# In your API endpoint (chat.py):
from app.services.chat_service import chat_service

# Process user query
result = await chat_service.process_query(
    query="What is my account balance?",
    conversation_history=[
        {'role': 'user', 'content': 'Hello'},
        {'role': 'assistant', 'content': 'Hi! How can I help?', 'metadata': {'policy_action': 'NO_FETCH'}}
    ],
    user_id="user_123"
)

# Result contains:
# - response: "Your account balance is $1,234.56"
# - policy_action: "FETCH"
# - documents_retrieved: 3
# - total_time_ms: 450.23
# etc.

# Get service health
health = await chat_service.health_check()
"""