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RAG Chatbot using LangGraph
|
| 3 |
+
|
| 4 |
+
This system implements a 3-agent architecture:
|
| 5 |
+
1. Main Agent: Handles conversation flow, follow-ups, and determines when to call RAG
|
| 6 |
+
2. RAG Agent: Rewrites queries and applies filters for document retrieval
|
| 7 |
+
3. Response Agent: Generates final answers from retrieved documents
|
| 8 |
+
|
| 9 |
+
Each agent has specialized prompts and responsibilities.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import os
|
| 13 |
+
import json
|
| 14 |
+
import time
|
| 15 |
+
import logging
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from datetime import datetime
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import Dict, List, Any, Optional, TypedDict
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
import re
|
| 23 |
+
from langchain_core.tools import tool
|
| 24 |
+
from langgraph.graph import StateGraph, END
|
| 25 |
+
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
|
| 26 |
+
from langchain_core.prompts import ChatPromptTemplate
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
from src.pipeline import PipelineManager
|
| 30 |
+
from src.config.loader import load_config
|
| 31 |
+
from src.llm.adapters import get_llm_client
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 35 |
+
logger = logging.getLogger(__name__)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@dataclass
|
| 39 |
+
class QueryContext:
|
| 40 |
+
"""Context extracted from conversation"""
|
| 41 |
+
has_district: bool = False
|
| 42 |
+
has_source: bool = False
|
| 43 |
+
has_year: bool = False
|
| 44 |
+
extracted_district: Optional[str] = None
|
| 45 |
+
extracted_source: Optional[str] = None
|
| 46 |
+
extracted_year: Optional[str] = None
|
| 47 |
+
ui_filters: Dict[str, List[str]] = None
|
| 48 |
+
confidence_score: float = 0.0
|
| 49 |
+
needs_follow_up: bool = False
|
| 50 |
+
follow_up_question: Optional[str] = None
|
| 51 |
+
|
| 52 |
+
class MultiAgentState(TypedDict):
|
| 53 |
+
"""State for the multi-agent conversation flow"""
|
| 54 |
+
conversation_id: str
|
| 55 |
+
messages: List[Any]
|
| 56 |
+
current_query: str
|
| 57 |
+
query_context: Optional[QueryContext]
|
| 58 |
+
rag_query: Optional[str]
|
| 59 |
+
rag_filters: Optional[Dict[str, Any]]
|
| 60 |
+
retrieved_documents: Optional[List[Any]]
|
| 61 |
+
final_response: Optional[str]
|
| 62 |
+
agent_logs: List[str]
|
| 63 |
+
conversation_context: Dict[str, Any]
|
| 64 |
+
session_start_time: float
|
| 65 |
+
last_ai_message_time: float
|
| 66 |
+
|
| 67 |
+
class MultiAgentRAGChatbot:
|
| 68 |
+
"""Multi-agent RAG chatbot with specialized agents"""
|
| 69 |
+
|
| 70 |
+
def __init__(self, config_path: str = "auditqa/config/settings.yaml"):
|
| 71 |
+
"""Initialize the multi-agent chatbot"""
|
| 72 |
+
self.config = load_config(config_path)
|
| 73 |
+
|
| 74 |
+
# Get LLM provider from config
|
| 75 |
+
reader_config = self.config.get("reader", {})
|
| 76 |
+
default_type = reader_config.get("default_type", "INF_PROVIDERS")
|
| 77 |
+
provider_name = default_type.lower()
|
| 78 |
+
|
| 79 |
+
self.llm_adapter = get_llm_client(provider_name, self.config)
|
| 80 |
+
|
| 81 |
+
# Create a simple wrapper for LangChain compatibility
|
| 82 |
+
class LLMWrapper:
|
| 83 |
+
def __init__(self, adapter):
|
| 84 |
+
self.adapter = adapter
|
| 85 |
+
|
| 86 |
+
def invoke(self, messages):
|
| 87 |
+
# Convert LangChain messages to the format expected by the adapter
|
| 88 |
+
if isinstance(messages, list):
|
| 89 |
+
formatted_messages = []
|
| 90 |
+
for msg in messages:
|
| 91 |
+
if hasattr(msg, 'content'):
|
| 92 |
+
role = "user" if msg.__class__.__name__ == "HumanMessage" else "assistant"
|
| 93 |
+
formatted_messages.append({"role": role, "content": msg.content})
|
| 94 |
+
else:
|
| 95 |
+
formatted_messages.append({"role": "user", "content": str(msg)})
|
| 96 |
+
else:
|
| 97 |
+
formatted_messages = [{"role": "user", "content": str(messages)}]
|
| 98 |
+
|
| 99 |
+
# Use the adapter to get response
|
| 100 |
+
response = self.adapter.generate(formatted_messages)
|
| 101 |
+
|
| 102 |
+
# Return a mock response object
|
| 103 |
+
class MockResponse:
|
| 104 |
+
def __init__(self, content):
|
| 105 |
+
self.content = content
|
| 106 |
+
|
| 107 |
+
return MockResponse(response.content)
|
| 108 |
+
|
| 109 |
+
self.llm = LLMWrapper(self.llm_adapter)
|
| 110 |
+
|
| 111 |
+
# Initialize pipeline manager early to load models
|
| 112 |
+
logger.info("π Initializing pipeline manager and loading models...")
|
| 113 |
+
self.pipeline_manager = PipelineManager(self.config)
|
| 114 |
+
logger.info("β
Pipeline manager initialized and models loaded")
|
| 115 |
+
|
| 116 |
+
# Connect to vector store
|
| 117 |
+
logger.info("π Connecting to vector store...")
|
| 118 |
+
if not self.pipeline_manager.connect_vectorstore():
|
| 119 |
+
logger.error("β Failed to connect to vector store")
|
| 120 |
+
raise RuntimeError("Vector store connection failed")
|
| 121 |
+
logger.info("β
Vector store connected successfully")
|
| 122 |
+
|
| 123 |
+
# Load dynamic data
|
| 124 |
+
self._load_dynamic_data()
|
| 125 |
+
|
| 126 |
+
# Build the multi-agent graph
|
| 127 |
+
self.graph = self._build_graph()
|
| 128 |
+
|
| 129 |
+
# Conversations directory
|
| 130 |
+
self.conversations_dir = Path("conversations")
|
| 131 |
+
self.conversations_dir.mkdir(exist_ok=True)
|
| 132 |
+
|
| 133 |
+
logger.info("π€ Multi-Agent RAG Chatbot initialized")
|
| 134 |
+
|
| 135 |
+
def _load_dynamic_data(self):
|
| 136 |
+
"""Load dynamic data from filter_options.json and add_district_metadata.py"""
|
| 137 |
+
# Load filter options
|
| 138 |
+
try:
|
| 139 |
+
fo = Path("filter_options.json")
|
| 140 |
+
if fo.exists():
|
| 141 |
+
with open(fo) as f:
|
| 142 |
+
data = json.load(f)
|
| 143 |
+
self.year_whitelist = [str(y).strip() for y in data.get("years", [])]
|
| 144 |
+
self.source_whitelist = [str(s).strip() for s in data.get("sources", [])]
|
| 145 |
+
self.district_whitelist = [str(d).strip() for d in data.get("districts", [])]
|
| 146 |
+
else:
|
| 147 |
+
# Fallback to default values
|
| 148 |
+
self.year_whitelist = ['2018', '2019', '2020', '2021', '2022', '2023', '2024']
|
| 149 |
+
self.source_whitelist = ['Consolidated', 'Local Government', 'Ministry, Department and Agency']
|
| 150 |
+
self.district_whitelist = ['Kampala', 'Gulu', 'Kalangala']
|
| 151 |
+
except Exception as e:
|
| 152 |
+
logger.warning(f"Could not load filter options: {e}")
|
| 153 |
+
self.year_whitelist = ['2018', '2019', '2020', '2021', '2022', '2023', '2024']
|
| 154 |
+
self.source_whitelist = ['Consolidated', 'Local Government', 'Ministry, Department and Agency']
|
| 155 |
+
self.district_whitelist = ['Kampala', 'Gulu', 'Kalangala']
|
| 156 |
+
|
| 157 |
+
# Enrich district list from add_district_metadata.py
|
| 158 |
+
try:
|
| 159 |
+
from add_district_metadata import DistrictMetadataProcessor
|
| 160 |
+
proc = DistrictMetadataProcessor()
|
| 161 |
+
names = set()
|
| 162 |
+
for key, mapping in proc.district_mappings.items():
|
| 163 |
+
if getattr(mapping, 'is_district', True):
|
| 164 |
+
names.add(mapping.name)
|
| 165 |
+
if names:
|
| 166 |
+
merged = list(self.district_whitelist)
|
| 167 |
+
for n in sorted(names):
|
| 168 |
+
if n not in merged:
|
| 169 |
+
merged.append(n)
|
| 170 |
+
self.district_whitelist = merged
|
| 171 |
+
logger.info(f"π§ District whitelist enriched: {len(self.district_whitelist)} entries")
|
| 172 |
+
except Exception as e:
|
| 173 |
+
logger.info(f"βΉοΈ Could not enrich districts: {e}")
|
| 174 |
+
|
| 175 |
+
# Calculate current year dynamically
|
| 176 |
+
self.current_year = str(datetime.now().year)
|
| 177 |
+
self.previous_year = str(datetime.now().year - 1)
|
| 178 |
+
|
| 179 |
+
# Log the actual filter values for debugging
|
| 180 |
+
logger.info(f"π ACTUAL FILTER VALUES:")
|
| 181 |
+
logger.info(f" Years: {self.year_whitelist}")
|
| 182 |
+
logger.info(f" Sources: {self.source_whitelist}")
|
| 183 |
+
logger.info(f" Districts: {len(self.district_whitelist)} districts (first 10: {self.district_whitelist[:10]})")
|
| 184 |
+
|
| 185 |
+
def _build_graph(self) -> StateGraph:
|
| 186 |
+
"""Build the multi-agent LangGraph"""
|
| 187 |
+
graph = StateGraph(MultiAgentState)
|
| 188 |
+
|
| 189 |
+
# Add nodes for each agent
|
| 190 |
+
graph.add_node("main_agent", self._main_agent)
|
| 191 |
+
graph.add_node("rag_agent", self._rag_agent)
|
| 192 |
+
graph.add_node("response_agent", self._response_agent)
|
| 193 |
+
|
| 194 |
+
# Define the flow
|
| 195 |
+
graph.set_entry_point("main_agent")
|
| 196 |
+
|
| 197 |
+
# Main agent decides next step
|
| 198 |
+
graph.add_conditional_edges(
|
| 199 |
+
"main_agent",
|
| 200 |
+
self._should_call_rag,
|
| 201 |
+
{
|
| 202 |
+
"follow_up": END,
|
| 203 |
+
"call_rag": "rag_agent"
|
| 204 |
+
}
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
# RAG agent calls response agent
|
| 208 |
+
graph.add_edge("rag_agent", "response_agent")
|
| 209 |
+
|
| 210 |
+
# Response agent returns to main agent for potential follow-ups
|
| 211 |
+
graph.add_edge("response_agent", "main_agent")
|
| 212 |
+
|
| 213 |
+
return graph.compile()
|
| 214 |
+
|
| 215 |
+
def _should_call_rag(self, state: MultiAgentState) -> str:
|
| 216 |
+
"""Determine if we should call RAG or ask follow-up"""
|
| 217 |
+
# If we already have a final response (from response agent), end
|
| 218 |
+
if state.get("final_response"):
|
| 219 |
+
return "follow_up"
|
| 220 |
+
|
| 221 |
+
context = state["query_context"]
|
| 222 |
+
if context and context.needs_follow_up:
|
| 223 |
+
return "follow_up"
|
| 224 |
+
return "call_rag"
|
| 225 |
+
|
| 226 |
+
def _main_agent(self, state: MultiAgentState) -> MultiAgentState:
|
| 227 |
+
"""Main Agent: Handles conversation flow and follow-ups"""
|
| 228 |
+
logger.info("π― MAIN AGENT: Starting analysis")
|
| 229 |
+
|
| 230 |
+
# If we already have a final response from response agent, end gracefully
|
| 231 |
+
if state.get("final_response"):
|
| 232 |
+
logger.info("π― MAIN AGENT: Final response already exists, ending conversation flow")
|
| 233 |
+
return state
|
| 234 |
+
|
| 235 |
+
query = state["current_query"]
|
| 236 |
+
messages = state["messages"]
|
| 237 |
+
|
| 238 |
+
logger.info(f"π― MAIN AGENT: Extracting UI filters from query")
|
| 239 |
+
ui_filters = self._extract_ui_filters(query)
|
| 240 |
+
logger.info(f"π― MAIN AGENT: UI filters extracted: {ui_filters}")
|
| 241 |
+
|
| 242 |
+
# Analyze query context
|
| 243 |
+
logger.info(f"π― MAIN AGENT: Analyzing query context")
|
| 244 |
+
context = self._analyze_query_context(query, messages, ui_filters)
|
| 245 |
+
|
| 246 |
+
# Log agent decision
|
| 247 |
+
state["agent_logs"].append(f"MAIN AGENT: Context analyzed - district={context.has_district}, source={context.has_source}, year={context.has_year}")
|
| 248 |
+
logger.info(f"π― MAIN AGENT: Context analysis complete - district={context.has_district}, source={context.has_source}, year={context.has_year}")
|
| 249 |
+
|
| 250 |
+
# Store context
|
| 251 |
+
state["query_context"] = context
|
| 252 |
+
|
| 253 |
+
# If follow-up needed, generate response
|
| 254 |
+
if context.needs_follow_up:
|
| 255 |
+
logger.info(f"π― MAIN AGENT: Follow-up needed, generating question")
|
| 256 |
+
response = context.follow_up_question
|
| 257 |
+
state["final_response"] = response
|
| 258 |
+
state["last_ai_message_time"] = time.time()
|
| 259 |
+
logger.info(f"π― MAIN AGENT: Follow-up question generated: {response[:100]}...")
|
| 260 |
+
else:
|
| 261 |
+
logger.info("π― MAIN AGENT: No follow-up needed, proceeding to RAG")
|
| 262 |
+
|
| 263 |
+
return state
|
| 264 |
+
|
| 265 |
+
def _rag_agent(self, state: MultiAgentState) -> MultiAgentState:
|
| 266 |
+
"""RAG Agent: Rewrites queries and applies filters"""
|
| 267 |
+
logger.info("π RAG AGENT: Starting query rewriting and filter preparation")
|
| 268 |
+
|
| 269 |
+
context = state["query_context"]
|
| 270 |
+
messages = state["messages"]
|
| 271 |
+
|
| 272 |
+
logger.info(f"π RAG AGENT: Context received - district={context.has_district}, source={context.has_source}, year={context.has_year}")
|
| 273 |
+
|
| 274 |
+
# Rewrite query for RAG
|
| 275 |
+
logger.info(f"π RAG AGENT: Rewriting query for optimal retrieval")
|
| 276 |
+
rag_query = self._rewrite_query_for_rag(messages, context)
|
| 277 |
+
logger.info(f"π RAG AGENT: Query rewritten: '{rag_query}'")
|
| 278 |
+
|
| 279 |
+
# Build filters
|
| 280 |
+
logger.info(f"π RAG AGENT: Building filters from context")
|
| 281 |
+
filters = self._build_filters(context)
|
| 282 |
+
logger.info(f"π RAG AGENT: Filters built: {filters}")
|
| 283 |
+
|
| 284 |
+
# Log RAG preparation
|
| 285 |
+
state["agent_logs"].append(f"RAG AGENT: Query='{rag_query}', Filters={filters}")
|
| 286 |
+
|
| 287 |
+
# Store for response agent
|
| 288 |
+
state["rag_query"] = rag_query
|
| 289 |
+
state["rag_filters"] = filters
|
| 290 |
+
|
| 291 |
+
logger.info(f"π RAG AGENT: Preparation complete, ready for retrieval")
|
| 292 |
+
|
| 293 |
+
return state
|
| 294 |
+
|
| 295 |
+
def _response_agent(self, state: MultiAgentState) -> MultiAgentState:
|
| 296 |
+
"""Response Agent: Generates final answer from retrieved documents"""
|
| 297 |
+
logger.info("π RESPONSE AGENT: Starting document retrieval and answer generation")
|
| 298 |
+
|
| 299 |
+
rag_query = state["rag_query"]
|
| 300 |
+
filters = state["rag_filters"]
|
| 301 |
+
|
| 302 |
+
logger.info(f"π RESPONSE AGENT: Starting RAG retrieval with query: '{rag_query}'")
|
| 303 |
+
logger.info(f"π RESPONSE AGENT: Using filters: {filters}")
|
| 304 |
+
|
| 305 |
+
# Perform RAG retrieval
|
| 306 |
+
logger.info(f"π RESPONSE AGENT: Calling pipeline manager for retrieval")
|
| 307 |
+
logger.info(f"π ACTUAL RAG QUERY: '{rag_query}'")
|
| 308 |
+
logger.info(f"π ACTUAL FILTERS: {filters}")
|
| 309 |
+
try:
|
| 310 |
+
# Extract filenames from filters if present
|
| 311 |
+
filenames = filters.get("filenames") if filters else None
|
| 312 |
+
|
| 313 |
+
result = self.pipeline_manager.run(
|
| 314 |
+
query=rag_query,
|
| 315 |
+
sources=filters.get("sources") if filters else None,
|
| 316 |
+
auto_infer_filters=False,
|
| 317 |
+
filters=filters if filters else None
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
logger.info(f"π RESPONSE AGENT: RAG retrieval completed - {len(result.sources)} documents retrieved")
|
| 321 |
+
logger.info(f"π RETRIEVAL DEBUG: Result type: {type(result)}")
|
| 322 |
+
logger.info(f"π RETRIEVAL DEBUG: Result sources type: {type(result.sources)}")
|
| 323 |
+
# logger.info(f"π RETRIEVAL DEBUG: Result metadata: {getattr(result, 'metadata', 'No metadata')}")
|
| 324 |
+
|
| 325 |
+
if len(result.sources) == 0:
|
| 326 |
+
logger.warning(f"β οΈ NO DOCUMENTS RETRIEVED: Query='{rag_query}', Filters={filters}")
|
| 327 |
+
logger.warning(f"β οΈ RETRIEVAL DEBUG: This could be due to:")
|
| 328 |
+
logger.warning(f" - Query too specific for available documents")
|
| 329 |
+
logger.warning(f" - Filters too restrictive")
|
| 330 |
+
logger.warning(f" - Vector store connection issues")
|
| 331 |
+
logger.warning(f" - Embedding model issues")
|
| 332 |
+
else:
|
| 333 |
+
logger.info(f"β
DOCUMENTS RETRIEVED: {len(result.sources)} documents found")
|
| 334 |
+
for i, doc in enumerate(result.sources[:3]): # Log first 3 docs
|
| 335 |
+
logger.info(f" Doc {i+1}: {getattr(doc, 'metadata', {}).get('filename', 'Unknown')[:50]}...")
|
| 336 |
+
|
| 337 |
+
state["retrieved_documents"] = result.sources
|
| 338 |
+
state["agent_logs"].append(f"RESPONSE AGENT: Retrieved {len(result.sources)} documents")
|
| 339 |
+
|
| 340 |
+
# Check highest similarity score
|
| 341 |
+
highest_score = 0.0
|
| 342 |
+
if result.sources:
|
| 343 |
+
# Check reranked_score first (more accurate), fallback to original_score
|
| 344 |
+
for doc in result.sources:
|
| 345 |
+
score = doc.metadata.get('reranked_score') or doc.metadata.get('original_score', 0.0)
|
| 346 |
+
if score > highest_score:
|
| 347 |
+
highest_score = score
|
| 348 |
+
|
| 349 |
+
logger.info(f"π RESPONSE AGENT: Highest similarity score: {highest_score:.4f}")
|
| 350 |
+
|
| 351 |
+
# If highest score is too low, don't use retrieved documents
|
| 352 |
+
if highest_score <= 0.15:
|
| 353 |
+
logger.warning(f"β οΈ RESPONSE AGENT: Low similarity score ({highest_score:.4f} <= 0.15), using LLM knowledge only")
|
| 354 |
+
response = self._generate_conversational_response_without_docs(
|
| 355 |
+
state["current_query"],
|
| 356 |
+
state["messages"]
|
| 357 |
+
)
|
| 358 |
+
else:
|
| 359 |
+
# Generate conversational response with documents
|
| 360 |
+
logger.info(f"π RESPONSE AGENT: Generating conversational response from {len(result.sources)} documents")
|
| 361 |
+
response = self._generate_conversational_response(
|
| 362 |
+
state["current_query"],
|
| 363 |
+
result.sources,
|
| 364 |
+
result.answer,
|
| 365 |
+
state["messages"]
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
logger.info(f"π RESPONSE AGENT: Response generated: {response[:100]}...")
|
| 369 |
+
|
| 370 |
+
state["final_response"] = response
|
| 371 |
+
state["last_ai_message_time"] = time.time()
|
| 372 |
+
|
| 373 |
+
logger.info(f"π RESPONSE AGENT: Answer generation complete")
|
| 374 |
+
|
| 375 |
+
except Exception as e:
|
| 376 |
+
logger.error(f"β RESPONSE AGENT ERROR: {e}")
|
| 377 |
+
state["final_response"] = "I apologize, but I encountered an error while retrieving information. Please try again."
|
| 378 |
+
state["last_ai_message_time"] = time.time()
|
| 379 |
+
|
| 380 |
+
return state
|
| 381 |
+
|
| 382 |
+
def _extract_ui_filters(self, query: str) -> Dict[str, List[str]]:
|
| 383 |
+
"""Extract UI filters from query"""
|
| 384 |
+
filters = {}
|
| 385 |
+
|
| 386 |
+
# Look for FILTER CONTEXT in query
|
| 387 |
+
if "FILTER CONTEXT:" in query:
|
| 388 |
+
# Extract the entire filter section (until USER QUERY: or end of query)
|
| 389 |
+
filter_section = query.split("FILTER CONTEXT:")[1]
|
| 390 |
+
if "USER QUERY:" in filter_section:
|
| 391 |
+
filter_section = filter_section.split("USER QUERY:")[0]
|
| 392 |
+
filter_section = filter_section.strip()
|
| 393 |
+
|
| 394 |
+
# Parse sources
|
| 395 |
+
if "Sources:" in filter_section:
|
| 396 |
+
sources_line = [line for line in filter_section.split('\n') if line.strip().startswith('Sources:')][0]
|
| 397 |
+
sources_str = sources_line.split("Sources:")[1].strip()
|
| 398 |
+
if sources_str and sources_str != "None":
|
| 399 |
+
filters["sources"] = [s.strip() for s in sources_str.split(",")]
|
| 400 |
+
|
| 401 |
+
# Parse years
|
| 402 |
+
if "Years:" in filter_section:
|
| 403 |
+
years_line = [line for line in filter_section.split('\n') if line.strip().startswith('Years:')][0]
|
| 404 |
+
years_str = years_line.split("Years:")[1].strip()
|
| 405 |
+
if years_str and years_str != "None":
|
| 406 |
+
filters["years"] = [y.strip() for y in years_str.split(",")]
|
| 407 |
+
|
| 408 |
+
# Parse districts
|
| 409 |
+
if "Districts:" in filter_section:
|
| 410 |
+
districts_line = [line for line in filter_section.split('\n') if line.strip().startswith('Districts:')][0]
|
| 411 |
+
districts_str = districts_line.split("Districts:")[1].strip()
|
| 412 |
+
if districts_str and districts_str != "None":
|
| 413 |
+
filters["districts"] = [d.strip() for d in districts_str.split(",")]
|
| 414 |
+
|
| 415 |
+
# Parse filenames
|
| 416 |
+
if "Filenames:" in filter_section:
|
| 417 |
+
filenames_line = [line for line in filter_section.split('\n') if line.strip().startswith('Filenames:')][0]
|
| 418 |
+
filenames_str = filenames_line.split("Filenames:")[1].strip()
|
| 419 |
+
if filenames_str and filenames_str != "None":
|
| 420 |
+
filters["filenames"] = [f.strip() for f in filenames_str.split(",")]
|
| 421 |
+
|
| 422 |
+
return filters
|
| 423 |
+
|
| 424 |
+
def _analyze_query_context(self, query: str, messages: List[Any], ui_filters: Dict[str, List[str]]) -> QueryContext:
|
| 425 |
+
"""Analyze query context using LLM"""
|
| 426 |
+
logger.info(f"π QUERY ANALYSIS: '{query[:50]}...' | UI filters: {ui_filters} | Messages: {len(messages)}")
|
| 427 |
+
|
| 428 |
+
# Build conversation context
|
| 429 |
+
conversation_context = ""
|
| 430 |
+
for i, msg in enumerate(messages[-6:]): # Last 6 messages
|
| 431 |
+
if isinstance(msg, HumanMessage):
|
| 432 |
+
conversation_context += f"User: {msg.content}\n"
|
| 433 |
+
elif isinstance(msg, AIMessage):
|
| 434 |
+
conversation_context += f"Assistant: {msg.content}\n"
|
| 435 |
+
|
| 436 |
+
# Create analysis prompt
|
| 437 |
+
analysis_prompt = ChatPromptTemplate.from_messages([
|
| 438 |
+
SystemMessage(content=f"""You are the Main Agent in an advanced multi-agent RAG system for audit report analysis.
|
| 439 |
+
|
| 440 |
+
π― PRIMARY GOAL: Intelligently analyze user queries and determine the optimal conversation flow, whether that's answering directly, asking follow-ups, or proceeding to RAG retrieval.
|
| 441 |
+
|
| 442 |
+
π§ INTELLIGENCE LEVEL: You are a sophisticated conversational AI that can handle any type of user interaction - from greetings to complex audit queries.
|
| 443 |
+
|
| 444 |
+
π YOUR EXPERTISE: You specialize in analyzing audit reports from various sources (Local Government, Ministry, Hospital, etc.) across different years and districts in Uganda.
|
| 445 |
+
|
| 446 |
+
π AVAILABLE FILTERS:
|
| 447 |
+
- Years: {', '.join(self.year_whitelist)}
|
| 448 |
+
- Current year: {self.current_year}, Previous year: {self.previous_year}
|
| 449 |
+
- Sources: {', '.join(self.source_whitelist)}
|
| 450 |
+
- Districts: {', '.join(self.district_whitelist[:50])}... (and {len(self.district_whitelist)-50} more)
|
| 451 |
+
|
| 452 |
+
ποΈ UI FILTERS PROVIDED: {ui_filters}
|
| 453 |
+
|
| 454 |
+
π UI FILTER HANDLING:
|
| 455 |
+
- If UI filters contain multiple values (e.g., districts: ['Lwengo', 'Kiboga']), extract ALL values
|
| 456 |
+
- For multiple districts: extract each district separately and validate each one
|
| 457 |
+
- For multiple years: extract each year separately and validate each one
|
| 458 |
+
- For multiple sources: extract each source separately and validate each one
|
| 459 |
+
- UI filters take PRIORITY over conversation context - use them first
|
| 460 |
+
|
| 461 |
+
π§ CONVERSATION FLOW INTELLIGENCE:
|
| 462 |
+
|
| 463 |
+
1. **GREETINGS & GENERAL CHAT**:
|
| 464 |
+
- If user greets you ("Hi", "Hello", "How are you"), respond warmly and guide them to audit-related questions
|
| 465 |
+
- Example: "Hello! I'm here to help you analyze audit reports. What would you like to know about budget allocations, expenditures, or audit findings?"
|
| 466 |
+
|
| 467 |
+
2. **EDGE CASES**:
|
| 468 |
+
- Handle "What can you do?", "Help", "I don't know what to ask" with helpful guidance
|
| 469 |
+
- Example: "I can help you analyze audit reports! Try asking about budget allocations, salary management, PDM implementation, or any specific audit findings."
|
| 470 |
+
|
| 471 |
+
3. **AUDIT QUERIES**:
|
| 472 |
+
- Extract ONLY values that EXACTLY match the available lists above
|
| 473 |
+
- DO NOT hallucinate or infer values not in the lists
|
| 474 |
+
- If user mentions "salary payroll management" - this is NOT a valid source filter
|
| 475 |
+
|
| 476 |
+
**YEAR EXTRACTION**:
|
| 477 |
+
- If user mentions "2023" and it's in the years list - extract "2023"
|
| 478 |
+
- If user mentions "2022 / 23" - extract ["2022", "2023"] (as a JSON array)
|
| 479 |
+
- If user mentions "2022-2023" - extract ["2022", "2023"] (as a JSON array)
|
| 480 |
+
- If user mentions "latest couple of years" - extract the 2 most recent years from available data as JSON array
|
| 481 |
+
- Always return years as JSON arrays when multiple years are mentioned
|
| 482 |
+
|
| 483 |
+
**DISTRICT EXTRACTION**:
|
| 484 |
+
- If user mentions "Kampala" and it's in the districts list - extract "Kampala"
|
| 485 |
+
- If user mentions "Pader District" - extract "Pader" (remove "District" suffix)
|
| 486 |
+
- If user mentions "Lwengo, Kiboga and Namutumba" - extract ["Lwengo", "Kiboga", "Namutumba"] (as JSON array)
|
| 487 |
+
- If user mentions "Lwengo District and Kiboga District" - extract ["Lwengo", "Kiboga"] (as JSON array, remove "District" suffix)
|
| 488 |
+
- Always return districts as JSON arrays when multiple districts are mentioned
|
| 489 |
+
- If no exact matches found, set extracted values to null
|
| 490 |
+
|
| 491 |
+
4. **FILENAME FILTERING (MUTUALLY EXCLUSIVE)**:
|
| 492 |
+
- If UI provides filenames filter - ONLY use that, ignore all other filters (year, district, source)
|
| 493 |
+
- With filenames filter, no follow-ups needed - proceed directly to RAG
|
| 494 |
+
- When filenames are specified, skip filter inference entirely
|
| 495 |
+
|
| 496 |
+
5. **HALLUCINATION PREVENTION**:
|
| 497 |
+
- If user asks about a specific report but NO filename is selected in UI and NONE is extracted from conversation - DO NOT hallucinate
|
| 498 |
+
- Clearly state: "I don't have any specific report selected. Could you please select a report from the list or tell me which report you'd like to analyze?"
|
| 499 |
+
- DO NOT pretend to know which report they mean
|
| 500 |
+
- DO NOT infer reports from context alone - only use explicitly mentioned reports
|
| 501 |
+
|
| 502 |
+
6. **CONVERSATION CONTEXT AWARENESS**:
|
| 503 |
+
- ALWAYS consider the full conversation context when extracting filters
|
| 504 |
+
- If district was mentioned in previous messages, include it in current analysis
|
| 505 |
+
- If year was mentioned in previous messages, include it in current analysis
|
| 506 |
+
- If source was mentioned in previous messages, include it in current analysis
|
| 507 |
+
- Example: If conversation shows "User: Tell me about Pader District" then "User: 2023", extract both: district="Pader" and year="2023"
|
| 508 |
+
|
| 509 |
+
5. **SMART FOLLOW-UP STRATEGY**:
|
| 510 |
+
- NEVER ask the same question twice in a row
|
| 511 |
+
- If user provides source info, ask for year or district next
|
| 512 |
+
- If user provides year info, ask for source or district next
|
| 513 |
+
- If user provides district info, ask for year or source next
|
| 514 |
+
- If user provides 2+ pieces of info, proceed to RAG instead of asking more
|
| 515 |
+
- Make follow-ups conversational and contextual, not robotic
|
| 516 |
+
|
| 517 |
+
5. **DYNAMIC FOLLOW-UP EXAMPLES**:
|
| 518 |
+
- Budget queries: "What year are you interested in?" or "Which department - Local Government or Ministry?"
|
| 519 |
+
- PDM queries: "Which district are you interested in?" or "What year?"
|
| 520 |
+
- General queries: "Could you be more specific about what you'd like to know?"
|
| 521 |
+
|
| 522 |
+
π― DECISION LOGIC:
|
| 523 |
+
- If query is a greeting/general chat β needs_follow_up: true, provide helpful guidance
|
| 524 |
+
- If query has 2+ pieces of info β needs_follow_up: false, proceed to RAG
|
| 525 |
+
- If query has 1 piece of info β needs_follow_up: true, ask for missing piece
|
| 526 |
+
- If query has 0 pieces of info β needs_follow_up: true, ask for clarification
|
| 527 |
+
|
| 528 |
+
RESPOND WITH JSON ONLY:
|
| 529 |
+
{{
|
| 530 |
+
"has_district": boolean,
|
| 531 |
+
"has_source": boolean,
|
| 532 |
+
"has_year": boolean,
|
| 533 |
+
"extracted_district": "single district name or JSON array of districts or null",
|
| 534 |
+
"extracted_source": "single source name or JSON array of sources or null",
|
| 535 |
+
"extracted_year": "single year or JSON array of years or null",
|
| 536 |
+
"confidence_score": 0.0-1.0,
|
| 537 |
+
"needs_follow_up": boolean,
|
| 538 |
+
"follow_up_question": "conversational question or helpful guidance or null"
|
| 539 |
+
}}"""),
|
| 540 |
+
HumanMessage(content=f"""Query: {query}
|
| 541 |
+
|
| 542 |
+
Conversation Context:
|
| 543 |
+
{conversation_context}
|
| 544 |
+
|
| 545 |
+
CRITICAL: You MUST analyze the FULL conversation context above, not just the current query.
|
| 546 |
+
- If ANY district was mentioned in previous messages, extract it
|
| 547 |
+
- If ANY year was mentioned in previous messages, extract it
|
| 548 |
+
- If ANY source was mentioned in previous messages, extract it
|
| 549 |
+
- Combine information from ALL messages in the conversation
|
| 550 |
+
|
| 551 |
+
Analyze this query using ONLY the exact values provided above:""")
|
| 552 |
+
])
|
| 553 |
+
|
| 554 |
+
try:
|
| 555 |
+
response = self.llm.invoke(analysis_prompt.format_messages())
|
| 556 |
+
|
| 557 |
+
# Clean the response to extract JSON
|
| 558 |
+
content = response.content.strip()
|
| 559 |
+
if content.startswith("```json"):
|
| 560 |
+
# Remove markdown formatting
|
| 561 |
+
content = content.replace("```json", "").replace("```", "").strip()
|
| 562 |
+
elif content.startswith("```"):
|
| 563 |
+
# Remove generic markdown formatting
|
| 564 |
+
content = content.replace("```", "").strip()
|
| 565 |
+
|
| 566 |
+
# Clean and parse JSON with better error handling
|
| 567 |
+
try:
|
| 568 |
+
# Remove comments (// and /* */) from JSON
|
| 569 |
+
import re
|
| 570 |
+
# Remove single-line comments
|
| 571 |
+
content = re.sub(r'//.*?$', '', content, flags=re.MULTILINE)
|
| 572 |
+
# Remove multi-line comments
|
| 573 |
+
content = re.sub(r'/\*.*?\*/', '', content, flags=re.DOTALL)
|
| 574 |
+
|
| 575 |
+
analysis = json.loads(content)
|
| 576 |
+
logger.info(f"π QUERY ANALYSIS: β
Parsed successfully")
|
| 577 |
+
except json.JSONDecodeError as e:
|
| 578 |
+
logger.error(f"β JSON parsing failed: {e}")
|
| 579 |
+
logger.error(f"β Raw content: {content[:200]}...")
|
| 580 |
+
|
| 581 |
+
# Try to extract JSON from text if embedded
|
| 582 |
+
import re
|
| 583 |
+
json_match = re.search(r'\{.*\}', content, re.DOTALL)
|
| 584 |
+
if json_match:
|
| 585 |
+
try:
|
| 586 |
+
# Clean the extracted JSON
|
| 587 |
+
cleaned_json = json_match.group()
|
| 588 |
+
cleaned_json = re.sub(r'//.*?$', '', cleaned_json, flags=re.MULTILINE)
|
| 589 |
+
cleaned_json = re.sub(r'/\*.*?\*/', '', cleaned_json, flags=re.DOTALL)
|
| 590 |
+
analysis = json.loads(cleaned_json)
|
| 591 |
+
logger.info(f"π QUERY ANALYSIS: β
Extracted and cleaned JSON from text")
|
| 592 |
+
except json.JSONDecodeError as e2:
|
| 593 |
+
logger.error(f"β Failed to extract JSON from text: {e2}")
|
| 594 |
+
# Return fallback context
|
| 595 |
+
context = QueryContext(
|
| 596 |
+
has_district=False,
|
| 597 |
+
has_source=False,
|
| 598 |
+
has_year=False,
|
| 599 |
+
extracted_district=None,
|
| 600 |
+
extracted_source=None,
|
| 601 |
+
extracted_year=None,
|
| 602 |
+
confidence_score=0.0,
|
| 603 |
+
needs_follow_up=True,
|
| 604 |
+
follow_up_question="I apologize, but I'm having trouble processing your request. Could you please rephrase it or ask for help?"
|
| 605 |
+
)
|
| 606 |
+
return context
|
| 607 |
+
else:
|
| 608 |
+
# Return fallback context
|
| 609 |
+
context = QueryContext(
|
| 610 |
+
has_district=False,
|
| 611 |
+
has_source=False,
|
| 612 |
+
has_year=False,
|
| 613 |
+
extracted_district=None,
|
| 614 |
+
extracted_source=None,
|
| 615 |
+
extracted_year=None,
|
| 616 |
+
confidence_score=0.0,
|
| 617 |
+
needs_follow_up=True,
|
| 618 |
+
follow_up_question="I apologize, but I'm having trouble processing your request. Could you please rephrase it or ask for help?"
|
| 619 |
+
)
|
| 620 |
+
return context
|
| 621 |
+
|
| 622 |
+
# Validate extracted values against whitelists
|
| 623 |
+
extracted_district = analysis.get("extracted_district")
|
| 624 |
+
extracted_source = analysis.get("extracted_source")
|
| 625 |
+
extracted_year = analysis.get("extracted_year")
|
| 626 |
+
|
| 627 |
+
logger.info(f"π QUERY ANALYSIS: Raw extracted values - district: {extracted_district}, source: {extracted_source}, year: {extracted_year}")
|
| 628 |
+
|
| 629 |
+
# Validate district (handle both single values and arrays)
|
| 630 |
+
if extracted_district:
|
| 631 |
+
if isinstance(extracted_district, list):
|
| 632 |
+
# Validate each district in the array
|
| 633 |
+
valid_districts = []
|
| 634 |
+
for district in extracted_district:
|
| 635 |
+
if district in self.district_whitelist:
|
| 636 |
+
valid_districts.append(district)
|
| 637 |
+
else:
|
| 638 |
+
# Try removing "District" suffix
|
| 639 |
+
district_name = district.replace(" District", "").replace(" district", "")
|
| 640 |
+
if district_name in self.district_whitelist:
|
| 641 |
+
valid_districts.append(district_name)
|
| 642 |
+
|
| 643 |
+
if valid_districts:
|
| 644 |
+
extracted_district = valid_districts[0] if len(valid_districts) == 1 else valid_districts
|
| 645 |
+
logger.info(f"π QUERY ANALYSIS: Extracted districts: {extracted_district}")
|
| 646 |
+
else:
|
| 647 |
+
logger.warning(f"β οΈ No valid districts found in: '{extracted_district}'")
|
| 648 |
+
extracted_district = None
|
| 649 |
+
else:
|
| 650 |
+
# Single district validation
|
| 651 |
+
if extracted_district not in self.district_whitelist:
|
| 652 |
+
# Try removing "District" suffix
|
| 653 |
+
district_name = extracted_district.replace(" District", "").replace(" district", "")
|
| 654 |
+
if district_name in self.district_whitelist:
|
| 655 |
+
logger.info(f"π QUERY ANALYSIS: Normalized district '{extracted_district}' to '{district_name}'")
|
| 656 |
+
extracted_district = district_name
|
| 657 |
+
else:
|
| 658 |
+
logger.warning(f"β οΈ Invalid district extracted: '{extracted_district}' not in whitelist")
|
| 659 |
+
extracted_district = None
|
| 660 |
+
|
| 661 |
+
# Validate source (handle both single values and arrays)
|
| 662 |
+
if extracted_source:
|
| 663 |
+
if isinstance(extracted_source, list):
|
| 664 |
+
# Validate each source in the array
|
| 665 |
+
valid_sources = []
|
| 666 |
+
for source in extracted_source:
|
| 667 |
+
if source in self.source_whitelist:
|
| 668 |
+
valid_sources.append(source)
|
| 669 |
+
else:
|
| 670 |
+
logger.warning(f"β οΈ Invalid source in array: '{source}' not in whitelist")
|
| 671 |
+
|
| 672 |
+
if valid_sources:
|
| 673 |
+
extracted_source = valid_sources[0] if len(valid_sources) == 1 else valid_sources
|
| 674 |
+
logger.info(f"π QUERY ANALYSIS: Extracted sources: {extracted_source}")
|
| 675 |
+
else:
|
| 676 |
+
logger.warning(f"β οΈ No valid sources found in: '{extracted_source}'")
|
| 677 |
+
extracted_source = None
|
| 678 |
+
else:
|
| 679 |
+
# Single source validation
|
| 680 |
+
if extracted_source not in self.source_whitelist:
|
| 681 |
+
logger.warning(f"β οΈ Invalid source extracted: '{extracted_source}' not in whitelist")
|
| 682 |
+
extracted_source = None
|
| 683 |
+
|
| 684 |
+
# Validate year (handle both single values and arrays)
|
| 685 |
+
if extracted_year:
|
| 686 |
+
if isinstance(extracted_year, list):
|
| 687 |
+
# Validate each year in the array
|
| 688 |
+
valid_years = []
|
| 689 |
+
for year in extracted_year:
|
| 690 |
+
year_str = str(year)
|
| 691 |
+
if year_str in self.year_whitelist:
|
| 692 |
+
valid_years.append(year_str)
|
| 693 |
+
|
| 694 |
+
if valid_years:
|
| 695 |
+
extracted_year = valid_years[0] if len(valid_years) == 1 else valid_years
|
| 696 |
+
logger.info(f"π QUERY ANALYSIS: Extracted years: {extracted_year}")
|
| 697 |
+
else:
|
| 698 |
+
logger.warning(f"β οΈ No valid years found in: '{extracted_year}'")
|
| 699 |
+
extracted_year = None
|
| 700 |
+
else:
|
| 701 |
+
# Single year validation
|
| 702 |
+
year_str = str(extracted_year)
|
| 703 |
+
if year_str not in self.year_whitelist:
|
| 704 |
+
logger.warning(f"β οΈ Invalid year extracted: '{extracted_year}' not in whitelist")
|
| 705 |
+
extracted_year = None
|
| 706 |
+
else:
|
| 707 |
+
extracted_year = year_str
|
| 708 |
+
|
| 709 |
+
logger.info(f"π QUERY ANALYSIS: Validated values - district: {extracted_district}, source: {extracted_source}, year: {extracted_year}")
|
| 710 |
+
|
| 711 |
+
# Create QueryContext object
|
| 712 |
+
context = QueryContext(
|
| 713 |
+
has_district=bool(extracted_district),
|
| 714 |
+
has_source=bool(extracted_source),
|
| 715 |
+
has_year=bool(extracted_year),
|
| 716 |
+
extracted_district=extracted_district,
|
| 717 |
+
extracted_source=extracted_source,
|
| 718 |
+
extracted_year=extracted_year,
|
| 719 |
+
ui_filters=ui_filters,
|
| 720 |
+
confidence_score=analysis.get("confidence_score", 0.0),
|
| 721 |
+
needs_follow_up=analysis.get("needs_follow_up", False),
|
| 722 |
+
follow_up_question=analysis.get("follow_up_question")
|
| 723 |
+
)
|
| 724 |
+
|
| 725 |
+
logger.info(f"π QUERY ANALYSIS: Analysis complete - needs_follow_up: {context.needs_follow_up}, confidence: {context.confidence_score}")
|
| 726 |
+
|
| 727 |
+
# If filenames are provided in UI, skip follow-ups and proceed to RAG
|
| 728 |
+
if ui_filters and ui_filters.get("filenames"):
|
| 729 |
+
logger.info(f"π QUERY ANALYSIS: Filenames provided, skipping follow-ups, proceeding to RAG")
|
| 730 |
+
context.needs_follow_up = False
|
| 731 |
+
context.follow_up_question = None
|
| 732 |
+
|
| 733 |
+
# Additional smart decision logic
|
| 734 |
+
if context.needs_follow_up:
|
| 735 |
+
# Check if we have enough information to proceed
|
| 736 |
+
info_count = sum([
|
| 737 |
+
bool(context.extracted_district),
|
| 738 |
+
bool(context.extracted_source),
|
| 739 |
+
bool(context.extracted_year)
|
| 740 |
+
])
|
| 741 |
+
|
| 742 |
+
# Check if user is asking for more info vs providing it
|
| 743 |
+
query_lower = query.lower()
|
| 744 |
+
is_requesting_info = any(phrase in query_lower for phrase in [
|
| 745 |
+
"please provide", "could you provide", "can you provide",
|
| 746 |
+
"what is", "what are", "how much", "which", "what year",
|
| 747 |
+
"what district", "what source", "tell me about"
|
| 748 |
+
])
|
| 749 |
+
|
| 750 |
+
# If we have 2+ pieces of info AND user is not requesting more info, proceed to RAG
|
| 751 |
+
if info_count >= 2 and not is_requesting_info:
|
| 752 |
+
logger.info(f"π QUERY ANALYSIS: Smart override - have {info_count} pieces of info and user not requesting more, proceeding to RAG")
|
| 753 |
+
context.needs_follow_up = False
|
| 754 |
+
context.follow_up_question = None
|
| 755 |
+
elif info_count >= 2 and is_requesting_info:
|
| 756 |
+
logger.info(f"π QUERY ANALYSIS: User requesting more info despite having {info_count} pieces, proceeding to RAG with comprehensive answer")
|
| 757 |
+
context.needs_follow_up = False
|
| 758 |
+
context.follow_up_question = None
|
| 759 |
+
|
| 760 |
+
return context
|
| 761 |
+
|
| 762 |
+
except Exception as e:
|
| 763 |
+
logger.error(f"β Query analysis failed: {e}")
|
| 764 |
+
# Fallback: proceed with RAG
|
| 765 |
+
return QueryContext(
|
| 766 |
+
has_district=bool(ui_filters.get("districts")),
|
| 767 |
+
has_source=bool(ui_filters.get("sources")),
|
| 768 |
+
has_year=bool(ui_filters.get("years")),
|
| 769 |
+
ui_filters=ui_filters,
|
| 770 |
+
confidence_score=0.5,
|
| 771 |
+
needs_follow_up=False
|
| 772 |
+
)
|
| 773 |
+
|
| 774 |
+
def _rewrite_query_for_rag(self, messages: List[Any], context: QueryContext) -> str:
|
| 775 |
+
"""Rewrite query for optimal RAG retrieval"""
|
| 776 |
+
logger.info("π QUERY REWRITING: Starting query rewrite for RAG")
|
| 777 |
+
logger.info(f"π QUERY REWRITING: Processing {len(messages)} messages")
|
| 778 |
+
|
| 779 |
+
# Build conversation context
|
| 780 |
+
logger.info(f"π QUERY REWRITING: Building conversation context from last 6 messages")
|
| 781 |
+
conversation_lines = []
|
| 782 |
+
for i, msg in enumerate(messages[-6:]):
|
| 783 |
+
if isinstance(msg, HumanMessage):
|
| 784 |
+
conversation_lines.append(f"User: {msg.content}")
|
| 785 |
+
logger.info(f"π QUERY REWRITING: Message {i+1}: User - {msg.content[:50]}...")
|
| 786 |
+
elif isinstance(msg, AIMessage):
|
| 787 |
+
conversation_lines.append(f"Assistant: {msg.content}")
|
| 788 |
+
logger.info(f"π QUERY REWRITING: Message {i+1}: Assistant - {msg.content[:50]}...")
|
| 789 |
+
|
| 790 |
+
convo_text = "\n".join(conversation_lines)
|
| 791 |
+
logger.info(f"π QUERY REWRITING: Conversation context built ({len(convo_text)} chars)")
|
| 792 |
+
|
| 793 |
+
# Create rewrite prompt
|
| 794 |
+
rewrite_prompt = ChatPromptTemplate.from_messages([
|
| 795 |
+
SystemMessage(content=f"""You are a query rewriter for RAG retrieval.
|
| 796 |
+
|
| 797 |
+
GOAL: Create the best possible search query for document retrieval.
|
| 798 |
+
|
| 799 |
+
CRITICAL RULES:
|
| 800 |
+
1. Focus on the core information need from the conversation
|
| 801 |
+
2. Remove meta-verbs like "summarize", "list", "compare", "how much", "what" - keep the content focus
|
| 802 |
+
3. DO NOT include filter details (years, districts, sources) - these are applied separately as filters
|
| 803 |
+
4. DO NOT include specific years, district names, or source types in the query
|
| 804 |
+
5. Output ONE clear sentence suitable for vector search
|
| 805 |
+
6. Keep it generic and focused on the topic/subject matter
|
| 806 |
+
|
| 807 |
+
EXAMPLES:
|
| 808 |
+
- "What are the top challenges in budget allocation?" β "budget allocation challenges"
|
| 809 |
+
- "How were PDM administrative costs utilized in 2023?" β "PDM administrative costs utilization"
|
| 810 |
+
- "Compare salary management across districts" β "salary management"
|
| 811 |
+
- "How much was budget allocation for Local Government in 2023?" β "budget allocation"
|
| 812 |
+
|
| 813 |
+
OUTPUT FORMAT:
|
| 814 |
+
Provide your response in this exact format:
|
| 815 |
+
|
| 816 |
+
EXPLANATION: [Your reasoning here]
|
| 817 |
+
QUERY: [One clean sentence for retrieval]
|
| 818 |
+
|
| 819 |
+
The QUERY line will be extracted and used directly for RAG retrieval."""),
|
| 820 |
+
HumanMessage(content=f"""Conversation:
|
| 821 |
+
{convo_text}
|
| 822 |
+
|
| 823 |
+
Rewrite the best retrieval query:""")
|
| 824 |
+
])
|
| 825 |
+
|
| 826 |
+
try:
|
| 827 |
+
logger.info(f"π QUERY REWRITING: Calling LLM for query rewrite")
|
| 828 |
+
response = self.llm.invoke(rewrite_prompt.format_messages())
|
| 829 |
+
logger.info(f"π QUERY REWRITING: LLM response received: {response.content[:100]}...")
|
| 830 |
+
|
| 831 |
+
rewritten = response.content.strip()
|
| 832 |
+
|
| 833 |
+
# Extract only the QUERY line from the structured response
|
| 834 |
+
lines = rewritten.split('\n')
|
| 835 |
+
query_line = None
|
| 836 |
+
for line in lines:
|
| 837 |
+
if line.strip().startswith('QUERY:'):
|
| 838 |
+
query_line = line.replace('QUERY:', '').strip()
|
| 839 |
+
break
|
| 840 |
+
|
| 841 |
+
if query_line and len(query_line) > 5:
|
| 842 |
+
logger.info(f"π QUERY REWRITING: Query rewritten successfully: '{query_line[:50]}...'")
|
| 843 |
+
return query_line
|
| 844 |
+
else:
|
| 845 |
+
logger.info(f"π QUERY REWRITING: No QUERY line found or too short, using fallback")
|
| 846 |
+
# Fallback to last user message
|
| 847 |
+
for msg in reversed(messages):
|
| 848 |
+
if isinstance(msg, HumanMessage):
|
| 849 |
+
logger.info(f"π QUERY REWRITING: Using fallback message: '{msg.content[:50]}...'")
|
| 850 |
+
return msg.content
|
| 851 |
+
logger.info(f"π QUERY REWRITING: Using default fallback")
|
| 852 |
+
return "audit report information"
|
| 853 |
+
|
| 854 |
+
except Exception as e:
|
| 855 |
+
logger.error(f"β QUERY REWRITING: Error during rewrite: {e}")
|
| 856 |
+
# Fallback
|
| 857 |
+
for msg in reversed(messages):
|
| 858 |
+
if isinstance(msg, HumanMessage):
|
| 859 |
+
logger.info(f"π QUERY REWRITING: Using error fallback message: '{msg.content[:50]}...'")
|
| 860 |
+
return msg.content
|
| 861 |
+
logger.info(f"π QUERY REWRITING: Using default error fallback")
|
| 862 |
+
return "audit report information"
|
| 863 |
+
|
| 864 |
+
def _build_filters(self, context: QueryContext) -> Dict[str, Any]:
|
| 865 |
+
"""Build filters for RAG retrieval"""
|
| 866 |
+
logger.info("π§ FILTER BUILDING: Starting filter construction")
|
| 867 |
+
filters = {}
|
| 868 |
+
|
| 869 |
+
# Check for filename filtering first (mutually exclusive)
|
| 870 |
+
if context.ui_filters and context.ui_filters.get("filenames"):
|
| 871 |
+
logger.info(f"π§ FILTER BUILDING: Filename filtering requested (mutually exclusive mode)")
|
| 872 |
+
filters["filenames"] = context.ui_filters["filenames"]
|
| 873 |
+
logger.info(f"π§ FILTER BUILDING: Added filenames filter: {context.ui_filters['filenames']}")
|
| 874 |
+
logger.info(f"π§ FILTER BUILDING: Final filters: {filters}")
|
| 875 |
+
return filters # Return early, skip all other filters
|
| 876 |
+
|
| 877 |
+
# UI filters take priority, but merge with extracted context if UI filters are incomplete
|
| 878 |
+
if context.ui_filters:
|
| 879 |
+
logger.info(f"π§ FILTER BUILDING: UI filters present: {context.ui_filters}")
|
| 880 |
+
|
| 881 |
+
# Add UI filters first
|
| 882 |
+
if context.ui_filters.get("sources"):
|
| 883 |
+
filters["sources"] = context.ui_filters["sources"]
|
| 884 |
+
logger.info(f"π§ FILTER BUILDING: Added sources filter from UI: {context.ui_filters['sources']}")
|
| 885 |
+
|
| 886 |
+
if context.ui_filters.get("years"):
|
| 887 |
+
filters["year"] = context.ui_filters["years"]
|
| 888 |
+
logger.info(f"π§ FILTER BUILDING: Added years filter from UI: {context.ui_filters['years']}")
|
| 889 |
+
|
| 890 |
+
if context.ui_filters.get("districts"):
|
| 891 |
+
# Normalize district names to title case (match Qdrant metadata format)
|
| 892 |
+
normalized_districts = [d.title() for d in context.ui_filters['districts']]
|
| 893 |
+
filters["district"] = normalized_districts
|
| 894 |
+
logger.info(f"π§ FILTER BUILDING: Added districts filter from UI: {context.ui_filters['districts']} β normalized: {normalized_districts}")
|
| 895 |
+
|
| 896 |
+
# Merge with extracted context for missing filters
|
| 897 |
+
if not filters.get("year") and context.extracted_year:
|
| 898 |
+
# Handle both single values and arrays
|
| 899 |
+
if isinstance(context.extracted_year, list):
|
| 900 |
+
filters["year"] = context.extracted_year
|
| 901 |
+
else:
|
| 902 |
+
filters["year"] = [context.extracted_year]
|
| 903 |
+
logger.info(f"π§ FILTER BUILDING: Added extracted year filter (UI missing): {context.extracted_year}")
|
| 904 |
+
|
| 905 |
+
if not filters.get("district") and context.extracted_district:
|
| 906 |
+
# Handle both single values and arrays
|
| 907 |
+
if isinstance(context.extracted_district, list):
|
| 908 |
+
# Normalize district names to title case (match Qdrant metadata format)
|
| 909 |
+
normalized = [d.title() for d in context.extracted_district]
|
| 910 |
+
filters["district"] = normalized
|
| 911 |
+
else:
|
| 912 |
+
filters["district"] = [context.extracted_district.title()]
|
| 913 |
+
logger.info(f"π§ FILTER BUILDING: Added extracted district filter (UI missing): {context.extracted_district}")
|
| 914 |
+
|
| 915 |
+
if not filters.get("sources") and context.extracted_source:
|
| 916 |
+
# Handle both single values and arrays
|
| 917 |
+
if isinstance(context.extracted_source, list):
|
| 918 |
+
filters["sources"] = context.extracted_source
|
| 919 |
+
else:
|
| 920 |
+
filters["sources"] = [context.extracted_source]
|
| 921 |
+
logger.info(f"π§ FILTER BUILDING: Added extracted source filter (UI missing): {context.extracted_source}")
|
| 922 |
+
else:
|
| 923 |
+
logger.info(f"π§ FILTER BUILDING: No UI filters, using extracted context")
|
| 924 |
+
# Use extracted context
|
| 925 |
+
if context.extracted_source:
|
| 926 |
+
# Handle both single values and arrays
|
| 927 |
+
if isinstance(context.extracted_source, list):
|
| 928 |
+
filters["sources"] = context.extracted_source
|
| 929 |
+
else:
|
| 930 |
+
filters["sources"] = [context.extracted_source]
|
| 931 |
+
logger.info(f"π§ FILTER BUILDING: Added extracted source filter: {context.extracted_source}")
|
| 932 |
+
|
| 933 |
+
if context.extracted_year:
|
| 934 |
+
# Handle both single values and arrays
|
| 935 |
+
if isinstance(context.extracted_year, list):
|
| 936 |
+
filters["year"] = context.extracted_year
|
| 937 |
+
else:
|
| 938 |
+
filters["year"] = [context.extracted_year]
|
| 939 |
+
logger.info(f"π§ FILTER BUILDING: Added extracted year filter: {context.extracted_year}")
|
| 940 |
+
|
| 941 |
+
if context.extracted_district:
|
| 942 |
+
# Handle both single values and arrays
|
| 943 |
+
if isinstance(context.extracted_district, list):
|
| 944 |
+
filters["district"] = context.extracted_district
|
| 945 |
+
else:
|
| 946 |
+
filters["district"] = [context.extracted_district]
|
| 947 |
+
logger.info(f"π§ FILTER BUILDING: Added extracted district filter: {context.extracted_district}")
|
| 948 |
+
|
| 949 |
+
logger.info(f"π§ FILTER BUILDING: Final filters: {filters}")
|
| 950 |
+
return filters
|
| 951 |
+
|
| 952 |
+
def _generate_conversational_response(self, query: str, documents: List[Any], rag_answer: str, messages: List[Any]) -> str:
|
| 953 |
+
"""Generate conversational response from RAG results"""
|
| 954 |
+
logger.info("π¬ RESPONSE GENERATION: Starting conversational response generation")
|
| 955 |
+
logger.info(f"π¬ RESPONSE GENERATION: Processing {len(documents)} documents")
|
| 956 |
+
logger.info(f"π¬ RESPONSE GENERATION: Query: '{query[:50]}...'")
|
| 957 |
+
|
| 958 |
+
# Create response prompt
|
| 959 |
+
logger.info(f"π¬ RESPONSE GENERATION: Building response prompt")
|
| 960 |
+
response_prompt = ChatPromptTemplate.from_messages([
|
| 961 |
+
SystemMessage(content="""You are a helpful audit report assistant. Generate a natural, conversational response.
|
| 962 |
+
|
| 963 |
+
RULES:
|
| 964 |
+
1. Answer the user's question directly and clearly
|
| 965 |
+
2. Use the retrieved documents as evidence
|
| 966 |
+
3. Be conversational, not technical
|
| 967 |
+
4. Don't mention scores, retrieval details, or technical implementation
|
| 968 |
+
5. If relevant documents were found, reference them naturally
|
| 969 |
+
6. If no relevant documents, explain based on your knowledge (if you have it) or just say you do not have enough information.
|
| 970 |
+
7. If the passages have useful facts or numbers, use them in your answer.
|
| 971 |
+
8. When you use information from a passage, mention where it came from by using [Doc i] at the end of the sentence. i stands for the number of the document.
|
| 972 |
+
9. Do not use the sentence 'Doc i says ...' to say where information came from.
|
| 973 |
+
10. If the same thing is said in more than one document, you can mention all of them like this: [Doc i, Doc j, Doc k]
|
| 974 |
+
11. Do not just summarize each passage one by one. Group your summaries to highlight the key parts in the explanation.
|
| 975 |
+
12. If it makes sense, use bullet points and lists to make your answers easier to understand.
|
| 976 |
+
13. You do not need to use every passage. Only use the ones that help answer the question.
|
| 977 |
+
14. If the documents do not have the information needed to answer the question, just say you do not have enough information.
|
| 978 |
+
|
| 979 |
+
|
| 980 |
+
TONE: Professional but friendly, like talking to a colleague."""),
|
| 981 |
+
HumanMessage(content=f"""User Question: {query}
|
| 982 |
+
|
| 983 |
+
Retrieved Documents: {len(documents)} documents found
|
| 984 |
+
|
| 985 |
+
RAG Answer: {rag_answer}
|
| 986 |
+
|
| 987 |
+
Generate a conversational response:""")
|
| 988 |
+
])
|
| 989 |
+
|
| 990 |
+
try:
|
| 991 |
+
logger.info(f"π¬ RESPONSE GENERATION: Calling LLM for final response")
|
| 992 |
+
response = self.llm.invoke(response_prompt.format_messages())
|
| 993 |
+
logger.info(f"π¬ RESPONSE GENERATION: LLM response received: {response.content[:100]}...")
|
| 994 |
+
return response.content.strip()
|
| 995 |
+
except Exception as e:
|
| 996 |
+
logger.error(f"β RESPONSE GENERATION: Error during generation: {e}")
|
| 997 |
+
logger.info(f"π¬ RESPONSE GENERATION: Using RAG answer as fallback")
|
| 998 |
+
return rag_answer # Fallback to RAG answer
|
| 999 |
+
|
| 1000 |
+
def _generate_conversational_response_without_docs(self, query: str, messages: List[Any]) -> str:
|
| 1001 |
+
"""Generate conversational response using only LLM knowledge and conversation history"""
|
| 1002 |
+
logger.info("π¬ RESPONSE GENERATION (NO DOCS): Starting response generation without documents")
|
| 1003 |
+
logger.info(f"π¬ RESPONSE GENERATION (NO DOCS): Query: '{query[:50]}...'")
|
| 1004 |
+
|
| 1005 |
+
# Build conversation context
|
| 1006 |
+
conversation_context = ""
|
| 1007 |
+
for i, msg in enumerate(messages[-6:]): # Last 6 messages for context
|
| 1008 |
+
if isinstance(msg, HumanMessage):
|
| 1009 |
+
conversation_context += f"User: {msg.content}\n"
|
| 1010 |
+
elif isinstance(msg, AIMessage):
|
| 1011 |
+
conversation_context += f"Assistant: {msg.content}\n"
|
| 1012 |
+
|
| 1013 |
+
# Create response prompt
|
| 1014 |
+
logger.info(f"π¬ RESPONSE GENERATION (NO DOCS): Building response prompt")
|
| 1015 |
+
response_prompt = ChatPromptTemplate.from_messages([
|
| 1016 |
+
SystemMessage(content="""You are a helpful audit report assistant. Generate a natural, conversational response.
|
| 1017 |
+
|
| 1018 |
+
RULES:
|
| 1019 |
+
1. Answer the user's question directly and clearly based on your knowledge
|
| 1020 |
+
2. Use conversation history for context
|
| 1021 |
+
3. Be conversational, not technical
|
| 1022 |
+
4. Acknowledge if the answer is based on general knowledge rather than specific documents
|
| 1023 |
+
5. Stay professional but friendly
|
| 1024 |
+
|
| 1025 |
+
TONE: Professional but friendly, like talking to a colleague."""),
|
| 1026 |
+
HumanMessage(content=f"""Current Question: {query}
|
| 1027 |
+
|
| 1028 |
+
Conversation History:
|
| 1029 |
+
{conversation_context}
|
| 1030 |
+
|
| 1031 |
+
Generate a conversational response based on your knowledge:""")
|
| 1032 |
+
])
|
| 1033 |
+
|
| 1034 |
+
try:
|
| 1035 |
+
logger.info(f"π¬ RESPONSE GENERATION (NO DOCS): Calling LLM")
|
| 1036 |
+
response = self.llm.invoke(response_prompt.format_messages())
|
| 1037 |
+
logger.info(f"π¬ RESPONSE GENERATION (NO DOCS): LLM response received: {response.content[:100]}...")
|
| 1038 |
+
return response.content.strip()
|
| 1039 |
+
except Exception as e:
|
| 1040 |
+
logger.error(f"β RESPONSE GENERATION (NO DOCS): Error during generation: {e}")
|
| 1041 |
+
return "I apologize, but I encountered an error. Please try asking your question differently."
|
| 1042 |
+
|
| 1043 |
+
def chat(self, user_input: str, conversation_id: str = "default") -> Dict[str, Any]:
|
| 1044 |
+
"""Main chat interface"""
|
| 1045 |
+
logger.info(f"π¬ MULTI-AGENT CHAT: Processing '{user_input[:50]}...'")
|
| 1046 |
+
|
| 1047 |
+
# Load conversation
|
| 1048 |
+
logger.info(f"π¬ MULTI-AGENT CHAT: Loading conversation {conversation_id}")
|
| 1049 |
+
conversation_file = self.conversations_dir / f"{conversation_id}.json"
|
| 1050 |
+
conversation = self._load_conversation(conversation_file)
|
| 1051 |
+
logger.info(f"π¬ MULTI-AGENT CHAT: Loaded {len(conversation['messages'])} previous messages")
|
| 1052 |
+
|
| 1053 |
+
# Add user message
|
| 1054 |
+
conversation["messages"].append(HumanMessage(content=user_input))
|
| 1055 |
+
logger.info(f"π¬ MULTI-AGENT CHAT: Added user message to conversation")
|
| 1056 |
+
|
| 1057 |
+
# Prepare state
|
| 1058 |
+
logger.info(f"π¬ MULTI-AGENT CHAT: Preparing state for graph execution")
|
| 1059 |
+
state = MultiAgentState(
|
| 1060 |
+
conversation_id=conversation_id,
|
| 1061 |
+
messages=conversation["messages"],
|
| 1062 |
+
current_query=user_input,
|
| 1063 |
+
query_context=None,
|
| 1064 |
+
rag_query=None,
|
| 1065 |
+
rag_filters=None,
|
| 1066 |
+
retrieved_documents=None,
|
| 1067 |
+
final_response=None,
|
| 1068 |
+
agent_logs=[],
|
| 1069 |
+
conversation_context=conversation.get("context", {}),
|
| 1070 |
+
session_start_time=conversation["session_start_time"],
|
| 1071 |
+
last_ai_message_time=conversation["last_ai_message_time"]
|
| 1072 |
+
)
|
| 1073 |
+
|
| 1074 |
+
# Run multi-agent graph
|
| 1075 |
+
logger.info(f"π¬ MULTI-AGENT CHAT: Executing multi-agent graph")
|
| 1076 |
+
final_state = self.graph.invoke(state)
|
| 1077 |
+
logger.info(f"π¬ MULTI-AGENT CHAT: Graph execution completed")
|
| 1078 |
+
|
| 1079 |
+
# Add AI response to conversation
|
| 1080 |
+
if final_state["final_response"]:
|
| 1081 |
+
conversation["messages"].append(AIMessage(content=final_state["final_response"]))
|
| 1082 |
+
logger.info(f"π¬ MULTI-AGENT CHAT: Added AI response to conversation")
|
| 1083 |
+
|
| 1084 |
+
# Update conversation
|
| 1085 |
+
conversation["last_ai_message_time"] = final_state["last_ai_message_time"]
|
| 1086 |
+
conversation["context"] = final_state["conversation_context"]
|
| 1087 |
+
|
| 1088 |
+
# Save conversation
|
| 1089 |
+
logger.info(f"π¬ MULTI-AGENT CHAT: Saving conversation")
|
| 1090 |
+
self._save_conversation(conversation_file, conversation)
|
| 1091 |
+
|
| 1092 |
+
logger.info("β
MULTI-AGENT CHAT: Completed")
|
| 1093 |
+
|
| 1094 |
+
# Return response and RAG results
|
| 1095 |
+
return {
|
| 1096 |
+
'response': final_state["final_response"],
|
| 1097 |
+
'rag_result': {
|
| 1098 |
+
'sources': final_state["retrieved_documents"] or [],
|
| 1099 |
+
'answer': final_state["final_response"]
|
| 1100 |
+
},
|
| 1101 |
+
'agent_logs': final_state["agent_logs"],
|
| 1102 |
+
'actual_rag_query': final_state.get("rag_query", "")
|
| 1103 |
+
}
|
| 1104 |
+
|
| 1105 |
+
def _load_conversation(self, conversation_file: Path) -> Dict[str, Any]:
|
| 1106 |
+
"""Load conversation from file"""
|
| 1107 |
+
if conversation_file.exists():
|
| 1108 |
+
try:
|
| 1109 |
+
with open(conversation_file) as f:
|
| 1110 |
+
data = json.load(f)
|
| 1111 |
+
# Convert message dicts back to LangChain messages
|
| 1112 |
+
messages = []
|
| 1113 |
+
for msg_data in data.get("messages", []):
|
| 1114 |
+
if msg_data["type"] == "human":
|
| 1115 |
+
messages.append(HumanMessage(content=msg_data["content"]))
|
| 1116 |
+
elif msg_data["type"] == "ai":
|
| 1117 |
+
messages.append(AIMessage(content=msg_data["content"]))
|
| 1118 |
+
data["messages"] = messages
|
| 1119 |
+
return data
|
| 1120 |
+
except Exception as e:
|
| 1121 |
+
logger.warning(f"Could not load conversation: {e}")
|
| 1122 |
+
|
| 1123 |
+
# Return default conversation
|
| 1124 |
+
return {
|
| 1125 |
+
"messages": [],
|
| 1126 |
+
"session_start_time": time.time(),
|
| 1127 |
+
"last_ai_message_time": time.time(),
|
| 1128 |
+
"context": {}
|
| 1129 |
+
}
|
| 1130 |
+
|
| 1131 |
+
def _save_conversation(self, conversation_file: Path, conversation: Dict[str, Any]):
|
| 1132 |
+
"""Save conversation to file"""
|
| 1133 |
+
try:
|
| 1134 |
+
# Convert messages to serializable format
|
| 1135 |
+
messages_data = []
|
| 1136 |
+
for msg in conversation["messages"]:
|
| 1137 |
+
if isinstance(msg, HumanMessage):
|
| 1138 |
+
messages_data.append({"type": "human", "content": msg.content})
|
| 1139 |
+
elif isinstance(msg, AIMessage):
|
| 1140 |
+
messages_data.append({"type": "ai", "content": msg.content})
|
| 1141 |
+
|
| 1142 |
+
conversation_data = {
|
| 1143 |
+
"messages": messages_data,
|
| 1144 |
+
"session_start_time": conversation["session_start_time"],
|
| 1145 |
+
"last_ai_message_time": conversation["last_ai_message_time"],
|
| 1146 |
+
"context": conversation.get("context", {})
|
| 1147 |
+
}
|
| 1148 |
+
|
| 1149 |
+
with open(conversation_file, 'w') as f:
|
| 1150 |
+
json.dump(conversation_data, f, indent=2)
|
| 1151 |
+
|
| 1152 |
+
except Exception as e:
|
| 1153 |
+
logger.error(f"Could not save conversation: {e}")
|
| 1154 |
+
|
| 1155 |
+
|
| 1156 |
+
def get_multi_agent_chatbot():
|
| 1157 |
+
"""Get multi-agent chatbot instance"""
|
| 1158 |
+
return MultiAgentRAGChatbot()
|
| 1159 |
+
|
| 1160 |
+
if __name__ == "__main__":
|
| 1161 |
+
# Test the multi-agent system
|
| 1162 |
+
chatbot = MultiAgentRAGChatbot()
|
| 1163 |
+
|
| 1164 |
+
# Test conversation
|
| 1165 |
+
result = chatbot.chat("List me top 10 challenges in budget allocation for the last 3 years")
|
| 1166 |
+
print("Response:", result['response'])
|
| 1167 |
+
print("Agent Logs:", result['agent_logs'])
|