Spaces:
Running
Running
Download src/agents/base_multi_agent_chatbot.py from akryldigital/audit_assistant: direct link, hf CLI and curl.
- Browser
- Download file 77.7 kB
-
https://huggingface.co/spaces/akryldigital/audit_assistant/resolve/main/src/agents/base_multi_agent_chatbot.py
- Command line
-
hf download hf://spaces/akryldigital/audit_assistant/src/agents/base_multi_agent_chatbot.py
-
curl -L -o base_multi_agent_chatbot.py https://huggingface.co/spaces/akryldigital/audit_assistant/resolve/main/src/agents/base_multi_agent_chatbot.py
77.7 kB
"""
Base Multi-Agent Chatbot - Abstract base class with sophisticated query analysis
This module extracts the core multi-agent logic from MultiAgentRAGChatbot:
- Sophisticated LLM-based query analysis
- Filter extraction and validation
- Query rewriting
- Conversation management
- Main agent, RAG agent, Response agent logic
Subclasses only need to implement:
- _perform_retrieval(): The actual retrieval mechanism (text-based RAG vs visual search)
"""
import re
import json
import time
import logging
import traceback
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Any, Optional
from abc import ABC, abstractmethod
from langgraph.graph import StateGraph, END
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
from src.llm.adapters import get_llm_client
from src.config.paths import PROJECT_DIR, CONVERSATIONS_DIR
from src.config.loader import load_config
from .state import _LLMResponse, LLMWrapper, QueryContext, MultiAgentState
from .metadata import _MetadataMixin
from .agent_filtering import _FiltersMixin
from .conversation_history import _ConversationHistoryMixin
from .prompts import build_query_analysis_prompt, build_query_rewriting_prompt
from ..llm.adapters import QuotaExhaustedError
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class BaseMultiAgentChatbot(_MetadataMixin, _FiltersMixin, _ConversationHistoryMixin, ABC):
"""
Abstract base class for multi-agent chatbots.
Provides the multi-agent orchestration:
- LLM-based query analysis
- Filter extraction and validation
- Query rewriting
- Main agent, RAG agent, Response agent
Composed mixins:
- :class:`_MetadataMixin` - corpus-metadata bootstrap and district
name normalisation (see ``src/agents/metadata.py``).
- :class:`_FiltersMixin` - Qdrant filter construction,
pre/post validation, value normalisation (see ``src/agents/agent_filtering.py``).
- :class:`_ConversationHistoryMixin` - per-conversation_id JSON disk
persistence of chat messages (see ``src/agents/conversation_history.py``).
Subclasses only need to implement:
- :meth:`_perform_retrieval` - the actual retrieval mechanism.
"""
def __init__(self, config_path: str = "src/config/settings.yaml"):
"""Initialize the base multi-agent chatbot"""
self.config = load_config(config_path)
reader_config = self.config.get("reader", {})
default_type = reader_config.get("default_type", "INF_PROVIDERS")
provider_name = default_type.lower()
self.llm_adapter = get_llm_client(provider_name, self.config)
# Tier 2: strong model for query analysis
try:
if "OPENAI_STRONG" in reader_config:
self.llm_strong_adapter = get_llm_client("openai_strong", self.config)
logger.info("π§ Strong model loaded for query analysis")
else:
self.llm_strong_adapter = self.llm_adapter
logger.info("βΉοΈ No OPENAI_STRONG config β using default model for all calls")
except Exception as e:
logger.warning(f"β οΈ Could not load strong model, falling back to default: {e}")
self.llm_strong_adapter = self.llm_adapter
# Tier 3: response model for final answer generation (falls back to strong)
try:
if "OPENAI_RESPONSE" in reader_config:
self.llm_response_adapter = get_llm_client("openai_response", self.config)
logger.info("π Response model loaded for final answer generation")
else:
self.llm_response_adapter = self.llm_strong_adapter
logger.info("βΉοΈ No OPENAI_RESPONSE config β using strong model for response generation")
except Exception as e:
logger.warning(f"β οΈ Could not load response model, falling back to strong: {e}")
self.llm_response_adapter = self.llm_strong_adapter
self.llm = LLMWrapper(self.llm_adapter)
# Tier 2: strong model for query analysis and filter extraction
self.llm_strong = LLMWrapper(self.llm_strong_adapter)
# Tier 3: response model for final answer construction
self.llm_response = LLMWrapper(self.llm_response_adapter)
# Load dynamic data (filter options)
self._load_dynamic_data()
# Build the multi-agent graph
self.graph = self._build_graph()
# Conversations directory
self.conversations_dir = CONVERSATIONS_DIR
try:
self.conversations_dir.mkdir(parents=True, mode=0o777, exist_ok=True)
except (PermissionError, OSError) as e:
logger.warning(f"Could not create conversations directory at {self.conversations_dir}: {e}")
self.conversations_dir = Path("conversations")
try:
self.conversations_dir.mkdir(parents=True, mode=0o777, exist_ok=True)
except (PermissionError, OSError) as e2:
logger.error(f"Could not create conversations directory at {self.conversations_dir}: {e2}")
raise RuntimeError(f"Failed to create conversations directory: {e2}")
logger.info("π€ Base Multi-Agent Chatbot initialized")
def _build_graph(self) -> StateGraph:
"""Build the multi-agent LangGraph"""
graph = StateGraph(MultiAgentState)
graph.add_node("main_agent", self._main_agent)
graph.add_node("resolver_agent", self._resolver_agent)
graph.add_node("response_agent", self._response_agent)
graph.set_entry_point("main_agent")
graph.add_conditional_edges(
"main_agent",
self._route_after_main,
{
"follow_up": END,
"needs_resolution": "resolver_agent",
"call_rag": "response_agent",
}
)
graph.add_edge("resolver_agent", "main_agent")
graph.add_edge("response_agent", "main_agent")
return graph.compile()
def _route_after_main(self, state: MultiAgentState) -> str:
"""Determine next step after main agent analysis."""
# Hard short-circuit: if any agent marked the service unavailable
# (e.g. OpenAI quota exhausted), bail to END immediately instead
# of routing the same broken request through another round of
# agents. The handler that set this flag also populated
# `final_response` with a user-visible explanation.
if state.get("service_unavailable"):
return "follow_up"
if state.get("final_response"):
return "follow_up"
context = state["query_context"]
if context and context.needs_follow_up:
return "follow_up"
if (context and context.needs_metadata_lookup
and not state.get("resolution_attempted")):
return "needs_resolution"
return "call_rag"
# βββ Service-unavailable handling (QuotaExhaustedError + GraphRecursionError) βββ
# User-visible message picked at handler time based on whether retrieval
# had already produced documents before the failure. Two cases:
_SERVICE_UNAVAILABLE_MESSAGE_NO_DOCS = (
"I can't generate a response right now β the AI service is "
"temporarily unavailable due to a provider issue (most likely "
"the OpenAI account quota is exhausted or the API key is "
"invalid). Please try again in a few minutes, or contact the "
"operator to top up the OpenAI account if this persists."
)
_SERVICE_UNAVAILABLE_MESSAGE_WITH_DOCS = (
"I retrieved the relevant documents (visible below) but couldn't "
"generate a written answer β the AI service is temporarily "
"unavailable due to a provider issue (most likely the OpenAI "
"account quota is exhausted or the API key is invalid). Please "
"try again in a few minutes, or contact the operator to top up "
"the OpenAI account if this persists."
)
_RECURSION_LIMIT_MESSAGE_NO_DOCS = (
"Hit an internal processing limit while handling your query "
"(no documents had been retrieved yet). This usually indicates "
"a transient agent-routing issue. Please try a simpler "
"rephrasing, or contact the operator if it persists."
)
_RECURSION_LIMIT_MESSAGE_WITH_DOCS = (
"Hit an internal processing limit while handling your query. "
"I did retrieve the relevant documents (visible below) but "
"couldn't complete the written answer. Please try again or "
"contact the operator if this persists."
)
def _handle_service_unavailable(
self,
state: "MultiAgentState",
incident_type: str,
details: str,
*,
last_agent: str = "unknown",
error_obj: Optional[Exception] = None,
) -> "MultiAgentState":
"""Centralised handler for permanent LLM failures or recursion-limit
breaches.
Picks a context-aware user-facing message (different wording when
documents were already retrieved vs not), sets state flags so the
graph routing short-circuits, emits a structured stdout
``π¨ INCIDENT`` line that's grep-friendly in HF Space logs, and
attaches structured incident metadata to ``state`` for the
per-turn dataset log (`src/logging.py::log_error`) and LangSmith
trace.
Args:
state: the current LangGraph state (mutated in place + returned)
incident_type: ``"quota_exhausted"`` | ``"recursion_limit"`` | other
details: free-text description, suitable for logs
last_agent: name of the agent that triggered the handler
error_obj: the underlying exception, if any (used by ``log_error``)
"""
has_docs = bool(state.get("retrieved_documents"))
if incident_type == "quota_exhausted":
message = (self._SERVICE_UNAVAILABLE_MESSAGE_WITH_DOCS
if has_docs
else self._SERVICE_UNAVAILABLE_MESSAGE_NO_DOCS)
elif incident_type == "recursion_limit":
message = (self._RECURSION_LIMIT_MESSAGE_WITH_DOCS
if has_docs
else self._RECURSION_LIMIT_MESSAGE_NO_DOCS)
else:
message = self._SERVICE_UNAVAILABLE_MESSAGE_NO_DOCS
# If we already retrieved docs but can't generate the answer, the
# user-facing message still references them β but they should be
# visible in the UI. The `retrieved_documents` field stays as-is.
state["service_unavailable"] = True
state["final_response"] = message
state["last_ai_message_time"] = time.time()
incident: Dict[str, Any] = {
"type": incident_type,
"details": details,
"last_agent": last_agent,
"had_retrieved_documents": has_docs,
"timestamp": time.time(),
"conversation_id": state.get("conversation_id"),
"query": (state.get("current_query") or "")[:200],
}
if error_obj is not None:
incident["error_class"] = type(error_obj).__name__
# QuotaExhaustedError carries structured metadata; capture it.
for attr in ("model", "error_code", "http_status"):
v = getattr(error_obj, attr, None)
if v is not None:
incident[attr] = v
state["incident"] = incident
# Grep-friendly stdout marker for HF Space logs.
logger.error(
"π¨ INCIDENT type=%s conv=%s last_agent=%s had_docs=%s "
"query=%r details=%s",
incident_type, state.get("conversation_id"), last_agent,
has_docs, incident["query"], details[:200],
)
state["agent_logs"].append(
f"INCIDENT type={incident_type} last_agent={last_agent}"
)
# Persistent log entry (HF Hub dataset GIZ/spaces_logs) β only if
# logging is enabled (env-gated, see src/logging.py).
try:
from src.logging import log_error
log_error(error_obj or RuntimeError(details), {
"component": "multi_agent_chatbot",
"incident_type": incident_type,
"conversation_id": state.get("conversation_id"),
"last_agent": last_agent,
"had_retrieved_documents": has_docs,
"query": incident["query"],
})
except Exception as log_exc: # noqa: BLE001 β incident logging must never crash the handler
logger.warning("Could not persist incident to dataset log: %s", log_exc)
return state
def _main_agent(self, state: MultiAgentState) -> MultiAgentState:
"""Main Agent: Handles conversation flow and follow-ups"""
logger.info("[L1.main] π― MAIN AGENT: Starting analysis")
# Short-circuit: if a prior pass through the graph already flagged
# the service as unavailable (quota / billing / invalid key),
# don't run query analysis again β just hand control back so the
# router can push us to END. Cheap, idempotent.
if state.get("service_unavailable"):
logger.info("π― MAIN AGENT: service_unavailable set; skipping analysis")
return state
if state.get("final_response"):
logger.info("π― MAIN AGENT: Final response already exists, ending")
return state
# Second pass after resolver β absorb resolution results and proceed
if state.get("resolution_attempted") and state.get("resolution_result"):
logger.info("π― MAIN AGENT: Post-resolution pass β enriching context")
context = state["query_context"]
res = state["resolution_result"]
note_parts = []
# Only inject resolver-computed top-N filters if the user's query
# ACTUALLY asks about that dimension. Otherwise the resolver
# silently adds filters the user never requested (e.g. "biggest
# ministries" auto-injecting top-5 districts even though the user
# said nothing about districts).
query_lower = (state.get("current_query") or "").lower()
if ("top_districts" in res
and not context.extracted_district
and any(w in query_lower for w in
("district", "region", "area", "northern", "southern",
"eastern", "western", "central", "karamoja"))):
top = [d["district"] for d in res["top_districts"][:5]]
context.extracted_district = top
context.has_district = True
note_parts.append(f"Dynamically resolved top districts: {', '.join(top)}.")
if ("top_sources" in res
and not context.extracted_source
and any(w in query_lower for w in
("source", "category", "type of report"))):
top = [s["source"] for s in res["top_sources"][:5]]
context.extracted_source = top
context.has_source = True
note_parts.append(f"Dynamically resolved top sources: {', '.join(top)}.")
if ("top_years" in res
and not context.extracted_year
and any(w in query_lower for w in ("year", "annual", "recent"))):
top = [str(y["year"]) for y in res["top_years"][:5]]
context.extracted_year = top
context.has_year = True
note_parts.append(f"Dynamically resolved top years: {', '.join(top)}.")
# Multi-turn fallback: "latest report for district X" -> inject year
if "latest_year_for_district" in res and not context.extracted_year:
lookup = res["latest_year_for_district"]
if lookup:
years = sorted(set(lookup.values()), key=lambda y: int(y))
context.extracted_year = years if len(years) > 1 else years[0]
context.has_year = True
note_parts.append(
f"Resolved latest available year per district: {lookup}."
)
if "earliest_year_for_district" in res and not context.extracted_year:
lookup = res["earliest_year_for_district"]
if lookup:
years = sorted(set(lookup.values()), key=lambda y: int(y))
context.extracted_year = years if len(years) > 1 else years[0]
context.has_year = True
note_parts.append(
f"Resolved earliest available year per district: {lookup}."
)
# Surface count metadata into resolution_notes so the response LLM
# knows the difference between "retrieved a top-N sample" and "this
# is the total in the database". Without this, the LLM tends to
# answer "I have 15 reports" when actually it retrieved 15 chunks
# out of e.g. 10,941 chunks across many files.
for count_key, label in (
("entity_type_counts", "entity_type"),
("district_counts", "district"),
("source_counts", "source"),
("year_counts", "year"),
):
if count_key in res and res[count_key]:
pairs = ", ".join(
f"{k}={v:,} chunks" for k, v in res[count_key].items()
)
note_parts.append(
f"Total chunks in database matching the {label} filter "
f"(NOT all retrieved β only the top-N most relevant are "
f"shown to you): {pairs}."
)
if note_parts:
notes = (context.resolution_notes or "") + " " + " ".join(note_parts)
context.resolution_notes = notes.strip()
context.needs_metadata_lookup = False
state["query_context"] = context
state["agent_logs"].append(
f"MAIN AGENT (post-resolve): district={context.extracted_district}, "
f"year={context.extracted_year}, source={context.extracted_source}"
)
return state
query = state["current_query"]
messages = state["messages"]
conv_ctx = state.get("conversation_context") or {}
logger.info(f"π― MAIN AGENT: Extracting UI filters from query")
ui_filters = self._extract_ui_filters(query)
logger.info(f"π― MAIN AGENT: UI filters extracted: {ui_filters}")
previous_filters = conv_ctx.get("last_filters", {})
previous_topic = conv_ctx.get("last_topic", "")
logger.info(f"π― MAIN AGENT: Analyzing query context (prev_filters={previous_filters})")
try:
context = self._analyze_query_context(
query, messages, ui_filters,
previous_filters=previous_filters,
previous_topic=previous_topic,
)
except QuotaExhaustedError as exc:
# OpenAI quota exhausted / billing disabled / invalid key β
# don't fall through with empty context (would cause the loop
# we used to see). Hand off to the centralised handler which
# picks a friendly user-facing message and sets the
# `service_unavailable` flag so routing bails to END.
return self._handle_service_unavailable(
state, incident_type="quota_exhausted",
details=str(exc), last_agent="_main_agent",
error_obj=exc,
)
state["agent_logs"].append(f"MAIN AGENT: Context analyzed - district={context.has_district}, source={context.has_source}, year={context.has_year}")
logger.info(f"π― MAIN AGENT: Context analysis complete")
state["query_context"] = context
active_filters = {}
if context.extracted_year and context.extracted_year != "ALL":
active_filters["year"] = context.extracted_year if isinstance(context.extracted_year, list) else [context.extracted_year]
if context.extracted_district and context.extracted_district != "ALL":
active_filters["district"] = context.extracted_district if isinstance(context.extracted_district, list) else [context.extracted_district]
if context.extracted_source and context.extracted_source != "ALL":
active_filters["source"] = context.extracted_source if isinstance(context.extracted_source, list) else [context.extracted_source]
if context.extracted_entity_type:
active_filters["entity_type"] = context.extracted_entity_type if isinstance(context.extracted_entity_type, list) else [context.extracted_entity_type]
if ui_filters:
for k, v in ui_filters.items():
if v:
active_filters[k] = v
conv_ctx["last_filters"] = active_filters
conv_ctx["last_topic"] = query[:200]
state["conversation_context"] = conv_ctx
if context.needs_follow_up:
logger.info(f"π― MAIN AGENT: Follow-up needed, generating question")
response = context.follow_up_question
state["final_response"] = response
state["last_ai_message_time"] = time.time()
else:
logger.info("π― MAIN AGENT: No follow-up needed, proceeding")
return state
_SUPERLATIVE_TOP_WORDS = ("biggest", "largest", "top", "most", "highest", "max")
_SUPERLATIVE_BOTTOM_WORDS = ("smallest", "fewest", "least", "bottom", "lowest", "min")
_LATEST_WORDS = ("latest", "most recent", "newest", "last")
_EARLIEST_WORDS = ("earliest", "oldest", "first")
_COVERAGE_WORDS = ("what do you have", "what reports", "available reports", "available data", "coverage")
@staticmethod
def _as_list(value):
"""Normalize a maybe-scalar / maybe-list value into a list, dropping ALL/None."""
if value is None or value == "ALL":
return []
return value if isinstance(value, list) else [value]
def _resolver_agent(self, state: MultiAgentState) -> MultiAgentState:
"""Resolver Agent: executes dynamic metadata lookups against Qdrant.
The resolver answers metadata-shaped questions ("biggest X", "what
years are available for Y", "what is the latest report for Z")
WITHOUT calling the LLM. It uses two data sources:
1. **Cached aggregates** on the chatbot instance (loaded once from
Qdrant via ``_MetadataMixin._load_db_metadata`` and refreshed
with TTL): ``district_doc_counts``, ``year_doc_counts``,
``source_doc_counts``, ``source_year_coverage``,
``district_year_coverage``, ``district_source_coverage``.
2. **Live Qdrant ``count()`` queries** for specific user-named
filter combinations that are not pre-aggregated (e.g. an
arbitrary district + year pair).
The resolver populates ``state["resolution_result"]`` with a dict
of capability-keyed payloads; downstream agents (``_main_agent``,
``_rag_agent``, ``_response_agent``) consume those payloads to
produce a final answer or to enrich the RAG filters.
"""
logger.info("[L2.resolver] π RESOLVER AGENT: Starting dynamic metadata resolution")
state["resolution_attempted"] = True
context = state["query_context"]
if not context:
state["agent_logs"].append("RESOLVER AGENT: No context to resolve")
return state
results: dict = {}
try:
vectorstore = self._get_vectorstore()
if vectorstore is None:
logger.warning("β οΈ RESOLVER AGENT: No vectorstore available for lookup")
state["resolution_result"] = results
return state
client = vectorstore._client
collection = vectorstore.collection_name
from qdrant_client import models as qmodels
query_lower = state["current_query"].lower()
has_top_word = any(w in query_lower for w in self._SUPERLATIVE_TOP_WORDS)
has_bottom_word = any(w in query_lower for w in self._SUPERLATIVE_BOTTOM_WORDS)
has_latest_word = any(w in query_lower for w in self._LATEST_WORDS)
has_earliest_word = any(w in query_lower for w in self._EARLIEST_WORDS)
has_coverage_word = any(w in query_lower for w in self._COVERAGE_WORDS)
districts_in_query = self._as_list(context.extracted_district)
years_in_query = self._as_list(context.extracted_year)
sources_in_query = self._as_list(context.extracted_source)
entity_types_in_query = self._as_list(context.extracted_entity_type)
# --- 1. Top/bottom rankings over cached aggregates ---
self._add_top_bottom_ranking(results, "districts", self.district_doc_counts,
has_top_word, has_bottom_word, query_lower)
self._add_top_bottom_ranking(results, "sources", self.source_doc_counts,
has_top_word, has_bottom_word, query_lower,
related_words=("source", "ministry", "ministries",
"department", "agency", "local government",
"hospital", "project", "vfm",
"value for money", "consolidated"))
self._add_top_bottom_ranking(results, "years", self.year_doc_counts,
has_top_word, has_bottom_word, query_lower,
related_words=("year", "annual", "annually"))
# --- 2. Per-dimension live counts for user-named values ---
for dist in districts_in_query[:5]:
results.setdefault("district_counts", {})[dist] = self._safe_count(
client, collection, qmodels, "metadata.district", dist
)
for yr in years_in_query[:10]:
results.setdefault("year_counts", {})[yr] = self._safe_count(
client, collection, qmodels, "metadata.year", yr
)
for src in sources_in_query[:10]:
results.setdefault("source_counts", {})[src] = self._safe_count(
client, collection, qmodels, "metadata.source", src
)
for ent in entity_types_in_query[:10]:
results.setdefault("entity_type_counts", {})[ent] = self._safe_count(
client, collection, qmodels, "metadata.entity_type", ent
)
# --- 3. Combination counts (2+ dimensions present) ---
dims_present = sum(bool(x) for x in
(districts_in_query, years_in_query, sources_in_query))
if dims_present >= 2:
results["combination_counts"] = self._compute_combination_counts(
client, collection, qmodels,
districts_in_query, years_in_query, sources_in_query,
)
# --- 4. Date range (overall + per filter dimension) ---
if has_latest_word or has_earliest_word or any(w in query_lower for w in
("date range", "from when", "until when", "year range")):
results["date_range"] = self._compute_date_range(
districts_in_query, sources_in_query
)
# --- 5. Latest year for a specific district (drives multi-turn fallback) ---
if has_latest_word and districts_in_query and not years_in_query:
latest = {}
for dist in districts_in_query[:5]:
yr_map = self.district_year_coverage.get(dist, {})
if yr_map:
latest[dist] = max(yr_map.keys(), key=lambda y: int(y))
if latest:
results["latest_year_for_district"] = latest
logger.info(f"π RESOLVER: latest_year_for_district = {latest}")
# --- 6. Earliest year for a district (symmetric to #5) ---
if has_earliest_word and districts_in_query and not years_in_query:
earliest = {}
for dist in districts_in_query[:5]:
yr_map = self.district_year_coverage.get(dist, {})
if yr_map:
earliest[dist] = min(yr_map.keys(), key=lambda y: int(y))
if earliest:
results["earliest_year_for_district"] = earliest
# --- 7. Coverage report ("what do you have on X") ---
if has_coverage_word and (districts_in_query or sources_in_query):
results["coverage"] = self._compute_coverage(
districts_in_query, sources_in_query
)
except Exception as e:
logger.error(f"β RESOLVER AGENT: Error during resolution: {e}")
state["resolution_result"] = results
state["agent_logs"].append(f"RESOLVER AGENT: Results = {results}")
logger.info(f"π RESOLVER AGENT: Resolution complete: {list(results.keys())}")
return state
def _add_top_bottom_ranking(self, results: dict, dim_name: str, counts: dict,
has_top: bool, has_bottom: bool, query_lower: str,
related_words: tuple = ()):
"""Add top/bottom 10 ranking for a dimension if the query asks for it.
For ``districts`` the topic words are implicit (default behaviour
of the original resolver). For other dimensions, also require at
least one ``related_word`` so we don't conflate "top districts"
with "top sources".
"""
if not counts:
return
topic_match = (dim_name == "districts") or any(w in query_lower for w in related_words)
if not topic_match:
return
if has_top:
sorted_items = sorted(counts.items(), key=lambda x: -x[1])[:10]
results[f"top_{dim_name}"] = [
{dim_name[:-1]: k, "doc_count": v} for k, v in sorted_items
]
logger.info(f"π RESOLVER: top_{dim_name} = {sorted_items[:5]}")
if has_bottom:
sorted_items = sorted(counts.items(), key=lambda x: x[1])[:10]
results[f"bottom_{dim_name}"] = [
{dim_name[:-1]: k, "doc_count": v} for k, v in sorted_items
]
@staticmethod
def _safe_count(client, collection, qmodels, key: str, value) -> int:
"""Run a single Qdrant ``count()`` query, returning 0 on any error."""
try:
result = client.count(
collection_name=collection,
count_filter=qmodels.Filter(must=[
qmodels.FieldCondition(key=key, match=qmodels.MatchValue(value=value))
]),
)
return int(result.count)
except Exception:
return 0
def _compute_combination_counts(self, client, collection, qmodels,
districts, years, sources) -> dict:
"""Count docs for the Cartesian product of named filter values.
Capped at 25 combinations to bound the number of Qdrant calls.
"""
from itertools import product
combos = []
if districts and years:
combos += [("district+year", d, y) for d, y in product(districts, years)]
if districts and sources:
combos += [("district+source", d, s) for d, s in product(districts, sources)]
if sources and years:
combos += [("source+year", s, y) for s, y in product(sources, years)]
combos = combos[:25]
out = {}
for combo_kind, v1, v2 in combos:
try:
if combo_kind == "district+year":
keys = ("metadata.district", "metadata.year")
elif combo_kind == "district+source":
keys = ("metadata.district", "metadata.source")
else:
keys = ("metadata.source", "metadata.year")
result = client.count(
collection_name=collection,
count_filter=qmodels.Filter(must=[
qmodels.FieldCondition(key=keys[0], match=qmodels.MatchValue(value=v1)),
qmodels.FieldCondition(key=keys[1], match=qmodels.MatchValue(value=v2)),
]),
)
out.setdefault(combo_kind, []).append(
{"a": v1, "b": v2, "doc_count": int(result.count)}
)
except Exception:
continue
return out
def _compute_date_range(self, districts, sources) -> dict:
"""Return overall and per-filter min/max year (all from cached aggregates)."""
out = {}
if self.year_doc_counts:
years = sorted(self.year_doc_counts.keys(), key=lambda y: int(y))
out["overall"] = {"min_year": years[0], "max_year": years[-1]}
for dist in districts[:5]:
yr_map = self.district_year_coverage.get(dist, {})
if yr_map:
yrs = sorted(yr_map.keys(), key=lambda y: int(y))
out.setdefault("per_district", {})[dist] = {
"min_year": yrs[0], "max_year": yrs[-1]
}
for src in sources[:5]:
yr_map = self.source_year_coverage.get(src, {})
if yr_map:
yrs = sorted(yr_map.keys(), key=lambda y: int(y))
out.setdefault("per_source", {})[src] = {
"min_year": yrs[0], "max_year": yrs[-1]
}
return out
def _compute_coverage(self, districts, sources) -> dict:
"""Summarize what the corpus contains for the named district(s) / source(s)."""
out = {}
for dist in districts[:5]:
entry = {
"total_docs": self.district_doc_counts.get(dist, 0),
"years": sorted(self.district_year_coverage.get(dist, {}).keys(),
key=lambda y: int(y)),
"sources": sorted(self.district_source_coverage.get(dist, {}).keys()),
}
out.setdefault("per_district", {})[dist] = entry
for src in sources[:5]:
entry = {
"total_docs": self.source_doc_counts.get(src, 0),
"years": sorted(self.source_year_coverage.get(src, {}).keys(),
key=lambda y: int(y)),
}
out.setdefault("per_source", {})[src] = entry
return out
def _get_vectorstore(self):
"""Return the vectorstore instance. Subclasses should override if needed."""
return None
def _rag_agent(self, state: MultiAgentState) -> MultiAgentState:
"""DEPRECATED β kept only for backward compatibility.
The filter-building work this method did was inlined into
``_response_agent`` (May 2026) to simplify the LangGraph trace.
This stub still exists so that any external caller / test that
invokes ``bot._rag_agent(state)`` directly still works. New code
should not depend on this method.
"""
context = state["query_context"]
filters, anchored_keys = self._build_filters(context)
state["rag_filters"] = filters
state["anchored_filter_keys"] = anchored_keys
return state
FILTER_RELAXATION_ORDER = ["entity_type", "sources", "year", "district"]
def _response_agent(self, state: MultiAgentState) -> MultiAgentState:
"""Response Agent: build filters β pre-validate β query rewrite β retrieval β smart relaxation β relevance check β answer.
Filter building (formerly a separate ``rag_agent`` graph node) is
now inlined as the first step here. It's pure-Python, no I/O, no
LLM β splitting it into its own node produced misleading
zero-duration entries in LangSmith traces and added no value
because the build always immediately preceded the retrieval logic
below. Merging makes the graph + traces simpler.
Pre-validation runs after the build (cheap Qdrant ``count()``).
If the filter combo has 0 matches and every failing dimension is
user-anchored, we return a follow-up suggestion immediately
without paying for the LLM query-rewrite call or the retrieval.
The rewrite only happens once we know retrieval will actually run.
"""
logger.info("[L4.response] π RESPONSE AGENT: Building filters, then pre-validation/retrieval/answer")
# --- Step 1: build filters from QueryContext (formerly _rag_agent) ---
context = state["query_context"]
filters, anchored_keys = self._build_filters(context)
state["rag_filters"] = filters
state["anchored_filter_keys"] = anchored_keys
state["agent_logs"].append(f"RESPONSE AGENT: filters built = {filters}")
logger.info(f"π RESPONSE AGENT: filters built: {filters} | anchored={anchored_keys}")
# --- Step 2: pre-validation + retrieval + answer (existing logic) ---
filters = dict(filters)
original_filters = dict(filters)
logger.info(f"π RESPONSE AGENT: filters={filters}, anchored={anchored_keys}")
relaxation_notes = []
try:
# --- Pre-validation: cheap count() check, runs BEFORE the query-rewrite LLM call ---
if filters:
diagnosis = self._prevalidate_filters(filters, anchored_keys)
if not diagnosis["ok"]:
logger.info(f"π RESPONSE AGENT: Pre-validation failed β {diagnosis}")
has_only_anchored = all(
dim_info["key"] in anchored_keys or
any(k in anchored_keys for k in dim_info["key"].split("+"))
for dim_info in diagnosis["gap_dimensions"]
)
if has_only_anchored and diagnosis["suggestion"]:
# Early exit: no LLM rewrite, no retrieval, just return the follow-up.
state["gap_follow_up"] = diagnosis["suggestion"]
state["final_response"] = diagnosis["suggestion"]
state["retrieved_documents"] = []
state["last_ai_message_time"] = time.time()
state["agent_logs"].append(f"RESPONSE AGENT: Pre-validation gap β {diagnosis['suggestion']}")
logger.info(f"[L4.1 prevalidate] π Returning follow-up instead of retrieval (saved query rewrite + retrieval)")
return state
for dim_info in diagnosis["gap_dimensions"]:
dim_key = dim_info["key"]
if "+" in dim_key:
parts = dim_key.split("+")
for part in parts:
if part not in anchored_keys and part in filters:
dropped_val = filters.pop(part)
note = f"Broadened search by removing {part} filter ({dropped_val}) β no data for that combination."
relaxation_notes.append(note)
logger.info(f"π RESPONSE AGENT: Pre-emptive drop {part}={dropped_val}")
break
elif dim_key not in anchored_keys and dim_key in filters:
dropped_val = filters.pop(dim_key)
note = f"Broadened search by removing {dim_key} filter ({dropped_val}) β no data found."
relaxation_notes.append(note)
logger.info(f"π RESPONSE AGENT: Pre-emptive drop {dim_key}={dropped_val}")
# --- Query rewriting: LLM call, runs only when retrieval will actually happen ---
logger.info("[L4.2 rewrite] π QUERY REWRITING: Starting (post-prevalidation)")
rag_query = self._rewrite_query_for_rag(state["messages"], state["query_context"])
logger.info(f"[L4.2 rewrite] π Query rewritten: '{rag_query}'")
state["rag_query"] = rag_query
state["agent_logs"].append(f"RESPONSE AGENT: Query='{rag_query}'")
# --- Main retrieval ---
logger.info("[L4.3 retrieve] π Calling _perform_retrieval")
result = self._perform_retrieval(rag_query, filters)
highest_score = self._best_score(result.sources)
logger.info(f"π RESPONSE AGENT: {len(result.sources)} docs, best_score={highest_score:.4f}")
RELAX_SCORE_THRESHOLD = 0.08
# --- Post-retrieval relaxation (only if 0 docs or very low score) ---
if (len(result.sources) == 0 or highest_score <= RELAX_SCORE_THRESHOLD) and filters:
for drop_key in self.FILTER_RELAXATION_ORDER:
if drop_key not in filters:
continue
if drop_key in anchored_keys:
logger.info(f"π RESPONSE AGENT: Skipping anchored filter '{drop_key}' during relaxation")
continue
dropped_value = filters.pop(drop_key)
note = f"Broadened search by removing {drop_key} filter ({dropped_value})."
relaxation_notes.append(note)
logger.info(f"π RESPONSE AGENT: Relaxed filter {drop_key}={dropped_value}, retryingβ¦")
state["agent_logs"].append(f"RESPONSE AGENT: Relaxed {drop_key}={dropped_value}")
result = self._perform_retrieval(rag_query, filters)
highest_score = self._best_score(result.sources)
logger.info(f"π RESPONSE AGENT: After relaxation β {len(result.sources)} docs, best_score={highest_score:.4f}")
if len(result.sources) > 0 and highest_score > RELAX_SCORE_THRESHOLD:
break
if len(result.sources) == 0 or highest_score <= RELAX_SCORE_THRESHOLD:
remaining_anchored = [k for k in filters if k in anchored_keys]
if remaining_anchored:
for drop_key in self.FILTER_RELAXATION_ORDER:
if drop_key not in filters:
continue
dropped_value = filters.pop(drop_key)
note = f"Broadened search by removing {drop_key} filter ({dropped_value})."
relaxation_notes.append(note)
logger.info(f"π RESPONSE AGENT: Last-resort relaxed anchored {drop_key}={dropped_value}")
result = self._perform_retrieval(rag_query, filters)
highest_score = self._best_score(result.sources)
logger.info(f"π RESPONSE AGENT: After last-resort relaxation β {len(result.sources)} docs, best_score={highest_score:.4f}")
if len(result.sources) > 0 and highest_score > RELAX_SCORE_THRESHOLD:
break
state["rag_filters"] = filters
# --- Post-relaxation relevance check ---
relevance = self._post_relaxation_relevance_check(result.sources, anchored_keys, original_filters)
if not relevance["relevant"] and len(result.sources) > 0:
logger.info(f"π RESPONSE AGENT: Post-relaxation relevance mismatch β {relevance['details']}")
_labels = {"sources": "source", "year": "year", "district": "district", "entity_type": "entity type"}
gap_parts = []
for key in anchored_keys:
if key in original_filters:
val = original_filters[key]
label = _labels.get(key, key)
friendly_val = ", ".join(val) if isinstance(val, list) else str(val)
gap_parts.append(f"{label} {friendly_val}")
gap_desc = " and ".join(gap_parts) if gap_parts else "your criteria"
follow_up = (
f"I found documents after broadening the search, but none specifically match {gap_desc}. "
f"This likely means the database doesn't have data for that exact combination. "
f"Would you like me to search with different criteria?"
)
state["gap_follow_up"] = follow_up
relaxation_notes.append(f"Retrieved documents don't match {gap_desc}.")
state["retrieved_documents"] = result.sources
state["agent_logs"].append(f"RESPONSE AGENT: Retrieved {len(result.sources)} documents (score={highest_score:.3f})")
if len(result.sources) == 0 or highest_score <= RELAX_SCORE_THRESHOLD:
logger.warning(f"β οΈ RESPONSE AGENT: Poor retrieval ({len(result.sources)} docs, score={highest_score:.4f}), using LLM knowledge only")
response = self._generate_conversational_response_without_docs(
state["current_query"],
state["messages"]
)
else:
context = state.get("query_context")
resolution_notes = context.resolution_notes if context else None
response = self._generate_conversational_response(
state["current_query"],
result.sources,
result.answer,
state["messages"],
filters,
resolution_notes=resolution_notes,
)
if state.get("gap_follow_up") and not state.get("final_response"):
response = response + "\n\n---\n\n" + state["gap_follow_up"]
context = state.get("query_context")
if context and context.resolution_notes:
logger.info(f"π Resolution notes: {context.resolution_notes}")
if relaxation_notes:
state["relaxation_notes"] = relaxation_notes
state["final_response"] = response
state["last_ai_message_time"] = time.time()
logger.info("π RESPONSE AGENT: Answer generation complete")
except QuotaExhaustedError as exc:
# Permanent OpenAI failure during query-rewrite or response
# generation. Hand off to the centralised handler so the
# graph short-circuits with a user-friendly message instead
# of looping (which is what happened in the May 2026
# `GraphRecursionError` incident). If retrieval already
# produced documents, the user-facing message acknowledges
# them; otherwise it advises to retry later.
self._handle_service_unavailable(
state, incident_type="quota_exhausted",
details=str(exc), last_agent="_response_agent",
error_obj=exc,
)
except Exception as e:
logger.error(f"β RESPONSE AGENT ERROR: {e}")
traceback.print_exc()
state["final_response"] = "I apologize, but I encountered an error while retrieving information. Please try again."
state["last_ai_message_time"] = time.time()
return state
@abstractmethod
def _perform_retrieval(self, query: str, filters: Dict[str, Any]) -> Any:
"""
Perform retrieval - must be implemented by subclasses.
Args:
query: The rewritten query
filters: The filters to apply
Returns:
Result object with .sources and .answer attributes
"""
pass
def _extract_ui_filters(self, query: str) -> Dict[str, List[str]]:
"""Extract UI filters from query"""
filters = {}
if "FILTER CONTEXT:" in query:
filter_section = query.split("FILTER CONTEXT:")[1]
if "USER QUERY:" in filter_section:
filter_section = filter_section.split("USER QUERY:")[0]
filter_section = filter_section.strip()
if "Sources:" in filter_section:
sources_line = [line for line in filter_section.split('\n') if line.strip().startswith('Sources:')][0]
sources_str = sources_line.split("Sources:")[1].strip()
if sources_str and sources_str != "None":
filters["sources"] = [s.strip() for s in sources_str.split("|") if s.strip()]
if "Years:" in filter_section:
years_line = [line for line in filter_section.split('\n') if line.strip().startswith('Years:')][0]
years_str = years_line.split("Years:")[1].strip()
if years_str and years_str != "None":
filters["years"] = [y.strip() for y in years_str.split("|") if y.strip()]
if "Districts:" in filter_section:
districts_line = [line for line in filter_section.split('\n') if line.strip().startswith('Districts:')][0]
districts_str = districts_line.split("Districts:")[1].strip()
if districts_str and districts_str != "None":
filters["districts"] = [d.strip() for d in districts_str.split("|") if d.strip()]
if "Filenames:" in filter_section:
filenames_line = [line for line in filter_section.split('\n') if line.strip().startswith('Filenames:')][0]
filenames_str = filenames_line.split("Filenames:")[1].strip()
if filenames_str and filenames_str != "None":
filters["filenames"] = [f.strip() for f in filenames_str.split("|") if f.strip()]
if "Entity Types:" in filter_section:
et_line = [line for line in filter_section.split('\n') if line.strip().startswith('Entity Types:')][0]
et_str = et_line.split("Entity Types:")[1].strip()
if et_str and et_str != "None":
filters["entity_types"] = [e.strip() for e in et_str.split("|") if e.strip()]
return filters
def _analyze_query_context(self, query: str, messages: List[Any], ui_filters: Dict[str, List[str]],
*, previous_filters: Dict = None, previous_topic: str = "") -> QueryContext:
"""LLM-based query analysis: extract filterable entities + decide search-vs-follow-up.
This is the system's main filter-inference step. Calls the strong LLM
(configured via ``OPENAI_STRONG`` in ``settings.yaml``) with the prompt
from :mod:`src.agents.prompts.query_analysis` and parses the JSON
response into a :class:`QueryContext`.
The LLM is given:
- The current user query
- Recent conversation messages (for follow-up context)
- UI filters set in the sidebar
- The previous turn's filter dict (for multi-turn carryover)
- The live database context (year/source/district stats)
Args:
query: the raw user query
messages: full LangChain message history (HumanMessage + AIMessage list)
ui_filters: filters set by the user in the Streamlit sidebar
previous_filters: the filter dict from the previous turn (drives carryover)
previous_topic: short summary of the previous turn's question
Returns:
QueryContext with extracted filters, follow-up decision, resolution_notes
"""
logger.info(f"π QUERY ANALYSIS: '{query[:50]}...' | UI filters: {ui_filters}")
conversation_context = ""
for msg in messages[-6:]:
if isinstance(msg, HumanMessage):
conversation_context += f"User: {msg.content}\n"
elif isinstance(msg, AIMessage):
conversation_context += f"Assistant: {msg.content}\n"
prev_filter_desc = "None β this is the first message in the conversation."
if previous_filters:
parts = []
if previous_filters.get("year"):
parts.append(f"year={previous_filters['year']}")
if previous_filters.get("district"):
parts.append(f"district={previous_filters['district']}")
if previous_filters.get("source"):
parts.append(f"source={previous_filters['source']}")
if previous_filters.get("sources"):
parts.append(f"sources={previous_filters['sources']}")
if previous_filters.get("years"):
parts.append(f"years={previous_filters['years']}")
if previous_filters.get("districts"):
parts.append(f"districts={previous_filters['districts']}")
if previous_filters.get("entity_type"):
parts.append(f"entity_type={previous_filters['entity_type']}")
if previous_filters.get("entity_types"):
parts.append(f"entity_types={previous_filters['entity_types']}")
if parts:
prev_filter_desc = ", ".join(parts)
if previous_topic:
prev_filter_desc += f"\nPrevious question topic: \"{previous_topic[:150]}\""
db_context = self.db_metadata_context or (
f"Available years: {', '.join(self.year_whitelist)}. "
f"Sources: {', '.join(self.source_whitelist)}. "
f"Districts: {', '.join(self.district_whitelist[:50])}."
)
analysis_prompt = build_query_analysis_prompt(
query=query,
conversation_context=conversation_context,
prev_filter_desc=prev_filter_desc,
db_context=db_context,
ui_filters=ui_filters,
current_year=self.current_year,
earliest_data_year=self.earliest_data_year,
latest_data_year=self.latest_data_year,
source_whitelist=self.source_whitelist,
)
try:
response = self.llm_strong.invoke(analysis_prompt.format_messages(), prompt_name="query_analysis")
# Clean and parse JSON
content = response.content.strip()
if content.startswith("```json"):
content = content.replace("```json", "").replace("```", "").strip()
elif content.startswith("```"):
content = content.replace("```", "").strip()
# Remove comments
content = re.sub(r'//.*?$', '', content, flags=re.MULTILINE)
content = re.sub(r'/\*.*?\*/', '', content, flags=re.DOTALL)
analysis = json.loads(content)
logger.info(f"π QUERY ANALYSIS: β
Parsed successfully")
extracted_district = analysis.get("extracted_district")
extracted_source = analysis.get("extracted_source")
extracted_year = analysis.get("extracted_year")
# "ALL" means no filter β pass through as-is, _build_filters handles it
if extracted_district and extracted_district != "ALL":
if isinstance(extracted_district, list):
valid_districts = []
for district in extracted_district:
normalized = self._normalize_district_name(district)
if normalized:
valid_districts.append(normalized)
extracted_district = valid_districts[0] if len(valid_districts) == 1 else (valid_districts if valid_districts else None)
else:
extracted_district = self._normalize_district_name(extracted_district)
if extracted_source and extracted_source != "ALL":
if isinstance(extracted_source, list):
valid_sources = [s for s in extracted_source if s in self.source_whitelist]
extracted_source = valid_sources[0] if len(valid_sources) == 1 else (valid_sources if valid_sources else None)
else:
extracted_source = extracted_source if extracted_source in self.source_whitelist else None
if extracted_year and extracted_year != "ALL":
if isinstance(extracted_year, list):
valid_years = [str(y) for y in extracted_year if str(y) in self.year_whitelist]
extracted_year = valid_years[0] if len(valid_years) == 1 else (valid_years if valid_years else None)
else:
extracted_year = str(extracted_year) if str(extracted_year) in self.year_whitelist else None
VALID_ENTITY_TYPES = {
"DLG", "City Council", "Municipal Council", "Ministry", "Board",
"Commission", "Agency", "Statutory Body", "State Enterprise",
"Mission", "University", "Tertiary Institution", "Hospital",
"VFM", "Project", "Consolidated",
}
extracted_entity_type = analysis.get("extracted_entity_type")
if extracted_entity_type:
if isinstance(extracted_entity_type, list):
valid_et = [e for e in extracted_entity_type if e in VALID_ENTITY_TYPES]
extracted_entity_type = valid_et[0] if len(valid_et) == 1 else (valid_et if valid_et else None)
else:
extracted_entity_type = extracted_entity_type if extracted_entity_type in VALID_ENTITY_TYPES else None
context = QueryContext(
has_district=bool(extracted_district),
has_source=bool(extracted_source),
has_year=bool(extracted_year),
has_entity_type=bool(extracted_entity_type),
extracted_district=extracted_district,
extracted_source=extracted_source,
extracted_year=extracted_year,
extracted_entity_type=extracted_entity_type,
ui_filters=ui_filters,
confidence_score=analysis.get("confidence_score", 0.0),
needs_follow_up=analysis.get("needs_follow_up", False),
follow_up_question=analysis.get("follow_up_question"),
resolution_notes=analysis.get("resolution_notes"),
needs_metadata_lookup=analysis.get("needs_metadata_lookup", False),
)
if ui_filters and ui_filters.get("filenames"):
context.needs_follow_up = False
context.follow_up_question = None
# Override: if query has substantive audit-related content, never block on missing filters
if context.needs_follow_up:
query_lower = query.lower()
has_topic = any(kw in query_lower for kw in [
"audit", "budget", "expenditure", "revenue", "findings",
"challenges", "recommendations", "compliance", "procurement",
"pdm", "parish", "road", "health", "education", "water",
"financial", "management", "accountability", "governance",
"irregularities", "mismanagement", "funding", "allocation",
"what", "how", "which", "compare", "list", "summarize",
"top", "main", "key", "major", "significant",
])
info_count = sum([bool(context.extracted_district), bool(context.extracted_source), bool(context.extracted_year)])
if has_topic or info_count >= 1:
context.needs_follow_up = False
context.follow_up_question = None
return context
except QuotaExhaustedError:
# Permanent provider failure (quota / billing / bad key).
# Don't swallow with a fake-empty fallback β let it propagate
# to ``_main_agent``, which routes it to the centralised
# handler that produces a user-visible message and stops the
# graph instead of looping.
raise
except Exception as e:
logger.error(f"β Query analysis failed: {e}")
return QueryContext(
has_district=bool(ui_filters.get("districts")),
has_source=bool(ui_filters.get("sources")),
has_year=bool(ui_filters.get("years")),
ui_filters=ui_filters,
confidence_score=0.5,
needs_follow_up=False
)
def _rewrite_query_for_rag(self, messages: List[Any], context: QueryContext) -> str:
"""LLM-based query rewrite: turn the user's NL question into a search-optimised sentence.
Uses the cost-efficient LLM (``OPENAI``, currently ``gpt-4o-mini``) with the
prompt from :mod:`src.agents.prompts.query_rewriting`. The rewritten sentence
is what gets embedded and sent to Qdrant for similarity search; filter values
are kept separate (they are applied as Qdrant metadata filters, not as words
in the query).
Note: this runs AFTER pre-validation (see ``_response_agent``), so it never
fires for queries with impossible filter combos.
Args:
messages: full LangChain message history (used for follow-up context)
context: the analysed :class:`QueryContext` from ``_analyze_query_context``
Returns:
A single retrieval-focused sentence, or the original last user message
if the LLM call fails or returns something unparseable.
"""
logger.info("π QUERY REWRITING: Starting")
conversation_lines = []
for msg in messages[-6:]:
if isinstance(msg, HumanMessage):
conversation_lines.append(f"User: {msg.content}")
elif isinstance(msg, AIMessage):
conversation_lines.append(f"Assistant: {msg.content}")
convo_text = "\n".join(conversation_lines)
rewrite_prompt = build_query_rewriting_prompt(conversation_text=convo_text)
try:
response = self.llm.invoke(rewrite_prompt.format_messages(), prompt_name="query_rewrite")
rewritten = response.content.strip()
# Extract QUERY line
lines = rewritten.split('\n')
for line in lines:
if line.strip().startswith('QUERY:'):
query_line = line.replace('QUERY:', '').strip()
if len(query_line) > 5:
return query_line
# Fallback
for msg in reversed(messages):
if isinstance(msg, HumanMessage):
return msg.content
return "audit report information"
except QuotaExhaustedError:
# Propagate to ``_response_agent`` for unified short-circuit
# handling β without this re-raise, the generic Exception
# block below would swallow it and the graph would loop.
raise
except Exception as e:
logger.error(f"β QUERY REWRITING: Error: {e}")
for msg in reversed(messages):
if isinstance(msg, HumanMessage):
return msg.content
return "audit report information"
def _build_filters(self, context: QueryContext) -> tuple:
"""Build filters for RAG retrieval. Returns (filters_dict, anchored_keys_set).
Anchored keys = explicitly set by the user (UI sidebar or query text).
Only non-anchored keys may be silently relaxed later.
Priority per dimension:
1. If the LLM detected new values in the query that DIFFER from the
sidebar β use LLM values (user changed context in conversation).
2. Else if sidebar has values β use sidebar values.
3. Else if LLM extracted values β use those.
"""
# Concise one-line summary; full dataclass dump moved to DEBUG.
logger.info(
"π§ FILTER BUILDING: context: district=%s year=%s source=%s entity=%s "
"needs_followup=%s needs_metadata_lookup=%s",
context.extracted_district, context.extracted_year,
context.extracted_source, context.extracted_entity_type,
context.needs_follow_up, context.needs_metadata_lookup,
)
logger.debug(f"π§ FILTER BUILDING: full context = {context}")
filters = {}
anchored: set = set()
ui = context.ui_filters or {}
if ui.get("filenames"):
filters["filenames"] = ui["filenames"]
anchored.add("filenames")
logger.info(f"π§ FILTER BUILDING: Using filename filter: {filters}")
return filters, anchored
# --- sources ---
source_from_ui = bool(ui.get("sources"))
llm_overrides_source = self._llm_overrides_ui(context.has_source, context.extracted_source, ui.get("sources"))
if llm_overrides_source:
logger.info(f"π§ FILTER BUILDING: LLM source overrides sidebar ({ui.get('sources')} β {context.extracted_source})")
filters["sources"] = [context.extracted_source] if not isinstance(context.extracted_source, list) else context.extracted_source
anchored.add("sources")
source_from_ui = False
elif source_from_ui:
filters["sources"] = ui["sources"]
anchored.add("sources")
elif context.extracted_source and context.extracted_source != "ALL":
filters["sources"] = [context.extracted_source] if not isinstance(context.extracted_source, list) else context.extracted_source
if context.has_source:
anchored.add("sources")
# --- year ---
llm_overrides_year = self._llm_overrides_ui(context.has_year, context.extracted_year, ui.get("years"))
if llm_overrides_year:
logger.info(f"π§ FILTER BUILDING: LLM year overrides sidebar ({ui.get('years')} β {context.extracted_year})")
filters["year"] = [context.extracted_year] if not isinstance(context.extracted_year, list) else context.extracted_year
anchored.add("year")
elif ui.get("years"):
filters["year"] = ui["years"]
anchored.add("year")
elif context.extracted_year and context.extracted_year != "ALL":
filters["year"] = [context.extracted_year] if not isinstance(context.extracted_year, list) else context.extracted_year
if context.has_year:
anchored.add("year")
# --- district ---
llm_overrides_district = self._llm_overrides_ui(context.has_district, context.extracted_district, ui.get("districts"))
if llm_overrides_district:
logger.info(f"π§ FILTER BUILDING: LLM district overrides sidebar ({ui.get('districts')} β {context.extracted_district})")
if isinstance(context.extracted_district, list):
normalized = [self._normalize_district_name(d) for d in context.extracted_district]
filters["district"] = [d for d in normalized if d]
else:
normalized = self._normalize_district_name(context.extracted_district)
if normalized:
filters["district"] = [normalized]
anchored.add("district")
elif ui.get("districts"):
filters["district"] = [d.title() for d in ui['districts']]
anchored.add("district")
elif context.extracted_district and context.extracted_district != "ALL":
if isinstance(context.extracted_district, list):
normalized = [self._normalize_district_name(d) for d in context.extracted_district]
filters["district"] = [d for d in normalized if d]
else:
normalized = self._normalize_district_name(context.extracted_district)
if normalized:
filters["district"] = [normalized]
if context.has_district:
anchored.add("district")
# --- entity_type ---
llm_overrides_entity = self._llm_overrides_ui(context.has_entity_type, context.extracted_entity_type, ui.get("entity_types"))
if llm_overrides_entity:
logger.info(f"π§ FILTER BUILDING: LLM entity_type overrides sidebar ({ui.get('entity_types')} β {context.extracted_entity_type})")
filters["entity_type"] = [context.extracted_entity_type] if not isinstance(context.extracted_entity_type, list) else context.extracted_entity_type
anchored.add("entity_type")
elif ui.get("entity_types"):
if llm_overrides_source and not context.has_entity_type:
logger.info(f"π§ FILTER BUILDING: Dropping stale UI entity_type={ui['entity_types']} β LLM changed source and did not re-select entity_type")
else:
filters["entity_type"] = ui["entity_types"]
anchored.add("entity_type")
elif context.extracted_entity_type:
filters["entity_type"] = [context.extracted_entity_type] if not isinstance(context.extracted_entity_type, list) else context.extracted_entity_type
# Normalize source values against whitelist (fixes case mismatches like "And" vs "and")
if "sources" in filters:
filters["sources"] = [self._normalize_source_name(s) for s in filters["sources"]]
# District takes priority over source: when district is present and
# source was NOT explicitly requested by the user, drop source to
# avoid losing documents (e.g. VFM audits in a district).
has_district = bool(filters.get("district"))
user_explicitly_said_source = context.has_source or source_from_ui
if has_district and not user_explicitly_said_source and "sources" in filters:
logger.info(f"π§ FILTER BUILDING: Dropping auto-inferred source={filters['sources']} β district is more specific")
filters.pop("sources")
anchored.discard("sources")
filters = self._validate_filter_values(filters)
logger.info(f"π§ FILTER BUILDING: Final filters: {filters} | anchored={anchored}")
return filters, anchored
@abstractmethod
def _generate_conversational_response(self, query: str, documents: List[Any], rag_answer: str, messages: List[Any], filters: Dict[str, Any] = None, *, resolution_notes: str = None) -> str:
"""Generate conversational response - must be implemented by subclasses"""
pass
@abstractmethod
def _generate_conversational_response_without_docs(self, query: str, messages: List[Any]) -> str:
"""Generate response without documents - must be implemented by subclasses"""
pass
def chat(self, user_input: str, conversation_id: str = "default") -> Dict[str, Any]:
"""Entry point called by app.py for every user message.
Loads the prior conversation from disk (or starts fresh), appends the
new user message, runs the LangGraph state machine end-to-end through
all relevant agent nodes (main, optionally resolver, RAG, response),
appends the assistant response back to the conversation, and saves
the updated history to disk.
Args:
user_input: the user's text message
conversation_id: persistent identifier for this conversation;
used to load/save the chat history JSON file. Default
``"default"`` is used by the test scripts; production passes
a UUID generated per Streamlit session.
Returns:
Dict with keys: ``response`` (the assistant's reply text),
``rag_filters``, ``rag_query``, ``retrieved_documents``,
``agent_logs`` (debug trace), ``relaxation_notes``, ``gap_follow_up``.
"""
"""Main chat interface"""
logger.info(f"π¬ MULTI-AGENT CHAT: Processing '{user_input[:50]}...'")
# Load conversation
conversation_file = self.conversations_dir / f"{conversation_id}.json"
conversation = self._load_conversation(conversation_file)
# Add user message
conversation["messages"].append(HumanMessage(content=user_input))
# Prepare state
state = MultiAgentState(
conversation_id=conversation_id,
messages=conversation["messages"],
current_query=user_input,
query_context=None,
rag_query=None,
rag_filters=None,
anchored_filter_keys=None,
retrieved_documents=None,
final_response=None,
agent_logs=[],
conversation_context=conversation.get("context", {}),
session_start_time=conversation["session_start_time"],
last_ai_message_time=conversation["last_ai_message_time"],
resolution_result=None,
resolution_attempted=False,
relaxation_notes=None,
gap_follow_up=None,
)
# Run multi-agent graph.
# Pass conversation_id through as LangSmith thread_id so multi-turn
# conversations group into a single Thread in the LangSmith UI
# instead of appearing as N unrelated Traces. Also tag the run with
# the conversation_id for grep-friendly filtering. Harmless when
# LangSmith tracing is off.
#
# `recursion_limit` is env-driven (default 8 in production) so a
# routing bug or unexpected agent loop fails fast instead of
# burning ~100 LLM calls before hitting LangGraph's default 25.
# A healthy turn never needs more than ~5 nodes; 8 leaves
# headroom for the resolverβmain bounce-back. The bottom catch
# turns the otherwise-fatal `GraphRecursionError` into the same
# service-unavailable message the quota path produces.
import os
from langgraph.errors import GraphRecursionError
try:
recursion_limit = int(os.getenv("LANGGRAPH_RECURSION_LIMIT", "8"))
except ValueError:
recursion_limit = 8
try:
final_state = self.graph.invoke(
state,
config={
"configurable": {"thread_id": conversation_id},
"metadata": {"conversation_id": conversation_id},
"run_name": f"chat[{conversation_id[:12]}]",
"recursion_limit": recursion_limit,
},
)
except GraphRecursionError as exc:
# The graph hit `recursion_limit` without producing a
# `final_response`. This is the safety net for any future
# bug (or unforeseen quota-detection miss). Use the
# centralised handler to produce the same user-visible
# message + structured incident log as the quota path.
self._handle_service_unavailable(
state, incident_type="recursion_limit",
details=f"LangGraph hit recursion_limit={recursion_limit} "
f"without producing a final response. Underlying "
f"error: {exc}",
last_agent="graph", error_obj=exc,
)
final_state = state
# Add AI response to conversation
if final_state["final_response"]:
conversation["messages"].append(AIMessage(content=final_state["final_response"]))
# Update conversation
conversation["last_ai_message_time"] = final_state["last_ai_message_time"]
conversation["context"] = final_state["conversation_context"]
# Save conversation
self._save_conversation(conversation_file, conversation)
return {
'response': final_state["final_response"],
'rag_result': {
'sources': final_state["retrieved_documents"] or [],
'answer': final_state["final_response"]
},
'agent_logs': final_state["agent_logs"],
'actual_rag_query': final_state.get("rag_query", ""),
'applied_filters': final_state.get("rag_filters") or {},
'relaxation_notes': final_state.get("relaxation_notes") or [],
'gap_follow_up': final_state.get("gap_follow_up"),
}
"""
Base Multi-Agent Chatbot - Abstract base class with sophisticated query analysis
This module extracts the core multi-agent logic from MultiAgentRAGChatbot:
- Sophisticated LLM-based query analysis
- Filter extraction and validation
- Query rewriting
- Conversation management
- Main agent, RAG agent, Response agent logic
Subclasses only need to implement:
- _perform_retrieval(): The actual retrieval mechanism (text-based RAG vs visual search)
"""
import re
import json
import time
import logging
import traceback
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Any, Optional
from abc import ABC, abstractmethod
from langgraph.graph import StateGraph, END
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
from src.llm.adapters import get_llm_client
from src.config.paths import PROJECT_DIR, CONVERSATIONS_DIR
from src.config.loader import load_config
from .state import _LLMResponse, LLMWrapper, QueryContext, MultiAgentState
from .metadata import _MetadataMixin
from .agent_filtering import _FiltersMixin
from .conversation_history import _ConversationHistoryMixin
from .prompts import build_query_analysis_prompt, build_query_rewriting_prompt
from ..llm.adapters import QuotaExhaustedError
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class BaseMultiAgentChatbot(_MetadataMixin, _FiltersMixin, _ConversationHistoryMixin, ABC):
"""
Abstract base class for multi-agent chatbots.
Provides the multi-agent orchestration:
- LLM-based query analysis
- Filter extraction and validation
- Query rewriting
- Main agent, RAG agent, Response agent
Composed mixins:
- :class:`_MetadataMixin` - corpus-metadata bootstrap and district
name normalisation (see ``src/agents/metadata.py``).
- :class:`_FiltersMixin` - Qdrant filter construction,
pre/post validation, value normalisation (see ``src/agents/agent_filtering.py``).
- :class:`_ConversationHistoryMixin` - per-conversation_id JSON disk
persistence of chat messages (see ``src/agents/conversation_history.py``).
Subclasses only need to implement:
- :meth:`_perform_retrieval` - the actual retrieval mechanism.
"""
def __init__(self, config_path: str = "src/config/settings.yaml"):
"""Initialize the base multi-agent chatbot"""
self.config = load_config(config_path)
reader_config = self.config.get("reader", {})
default_type = reader_config.get("default_type", "INF_PROVIDERS")
provider_name = default_type.lower()
self.llm_adapter = get_llm_client(provider_name, self.config)
# Tier 2: strong model for query analysis
try:
if "OPENAI_STRONG" in reader_config:
self.llm_strong_adapter = get_llm_client("openai_strong", self.config)
logger.info("π§ Strong model loaded for query analysis")
else:
self.llm_strong_adapter = self.llm_adapter
logger.info("βΉοΈ No OPENAI_STRONG config β using default model for all calls")
except Exception as e:
logger.warning(f"β οΈ Could not load strong model, falling back to default: {e}")
self.llm_strong_adapter = self.llm_adapter
# Tier 3: response model for final answer generation (falls back to strong)
try:
if "OPENAI_RESPONSE" in reader_config:
self.llm_response_adapter = get_llm_client("openai_response", self.config)
logger.info("π Response model loaded for final answer generation")
else:
self.llm_response_adapter = self.llm_strong_adapter
logger.info("βΉοΈ No OPENAI_RESPONSE config β using strong model for response generation")
except Exception as e:
logger.warning(f"β οΈ Could not load response model, falling back to strong: {e}")
self.llm_response_adapter = self.llm_strong_adapter
self.llm = LLMWrapper(self.llm_adapter)