diff --git a/app/app/__init__.py b/app/app/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/app/__pycache__/__init__.cpython-312.pyc b/app/app/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf9dc480b462257839cc8d91faab673e9c2820aa Binary files /dev/null and b/app/app/__pycache__/__init__.cpython-312.pyc differ diff --git a/app/app/__pycache__/__init__.cpython-313.pyc b/app/app/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81a5ca1ebb276652174ada664bd3910f3feb9e04 Binary files /dev/null and b/app/app/__pycache__/__init__.cpython-313.pyc differ diff --git a/app/app/__pycache__/__init__.cpython-314.pyc b/app/app/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..998b6967a54c9be6463f0248c5e76fa6f525b593 Binary files /dev/null and b/app/app/__pycache__/__init__.cpython-314.pyc differ diff --git a/app/app/__pycache__/config.cpython-312.pyc b/app/app/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d241f41e4229ae59e8eccb0604725cfabc2975fd Binary files /dev/null and b/app/app/__pycache__/config.cpython-312.pyc differ diff --git a/app/app/__pycache__/config.cpython-313.pyc b/app/app/__pycache__/config.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6316fec34c1d71f5751ed617eee2baf1872b762 Binary files /dev/null and b/app/app/__pycache__/config.cpython-313.pyc differ diff --git a/app/app/__pycache__/main.cpython-312.pyc b/app/app/__pycache__/main.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae473f05f4ecf013db521eedcc488f21b173114c Binary files /dev/null and b/app/app/__pycache__/main.cpython-312.pyc differ diff --git a/app/app/__pycache__/main.cpython-313.pyc b/app/app/__pycache__/main.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76a59f80e39417b7362554453153f5f143e7c546 Binary files /dev/null and b/app/app/__pycache__/main.cpython-313.pyc differ diff --git a/app/app/agent/__init__.py b/app/app/agent/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/app/agent/__pycache__/__init__.cpython-312.pyc b/app/app/agent/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20b62e906f33b300f8d5ee3e6939582b874ab1fc Binary files /dev/null and b/app/app/agent/__pycache__/__init__.cpython-312.pyc differ diff --git a/app/app/agent/__pycache__/__init__.cpython-313.pyc b/app/app/agent/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c57c7bdd993d25c3a95d6a07b955817e9ff616fb Binary files /dev/null and b/app/app/agent/__pycache__/__init__.cpython-313.pyc differ diff --git a/app/app/agent/__pycache__/graph.cpython-312.pyc b/app/app/agent/__pycache__/graph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d248b396909dd91bf28b56834d88e9ab2d43e62 Binary files /dev/null and b/app/app/agent/__pycache__/graph.cpython-312.pyc differ diff --git a/app/app/agent/__pycache__/graph.cpython-313.pyc b/app/app/agent/__pycache__/graph.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f6efa5f486ac519dafb9596c7c12930df6e907b Binary files /dev/null and b/app/app/agent/__pycache__/graph.cpython-313.pyc differ diff --git a/app/app/agent/__pycache__/graph.cpython-314.pyc b/app/app/agent/__pycache__/graph.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3262c7cefca3076ccbcd7ff3d7ec9878619c35f7 Binary files /dev/null and b/app/app/agent/__pycache__/graph.cpython-314.pyc differ diff --git a/app/app/agent/__pycache__/nodes.cpython-312.pyc b/app/app/agent/__pycache__/nodes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2707c7eb456dceb3b8125971795e79a0b8c7aba Binary files /dev/null and b/app/app/agent/__pycache__/nodes.cpython-312.pyc differ diff --git a/app/app/agent/__pycache__/nodes.cpython-313.pyc b/app/app/agent/__pycache__/nodes.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..120553d79750c8bbda7a4460a2037b4024d309ea Binary files /dev/null and b/app/app/agent/__pycache__/nodes.cpython-313.pyc differ diff --git a/app/app/agent/__pycache__/nodes.cpython-314.pyc b/app/app/agent/__pycache__/nodes.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36528e2677d2342b1063ff13d8a39fe7d4f745d6 Binary files /dev/null and b/app/app/agent/__pycache__/nodes.cpython-314.pyc differ diff --git a/app/app/agent/__pycache__/prompts.cpython-312.pyc b/app/app/agent/__pycache__/prompts.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e575b6a37b2c670d391755a4c240062051ec7cd9 Binary files /dev/null and b/app/app/agent/__pycache__/prompts.cpython-312.pyc differ diff --git a/app/app/agent/__pycache__/prompts.cpython-313.pyc b/app/app/agent/__pycache__/prompts.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40ebc6ed64084b394227c51f9ba9e38c96ac63b5 Binary files /dev/null and b/app/app/agent/__pycache__/prompts.cpython-313.pyc differ diff --git a/app/app/agent/__pycache__/state.cpython-312.pyc b/app/app/agent/__pycache__/state.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a345556e72f752799764f0c32647cdc29c3bfa0 Binary files /dev/null and b/app/app/agent/__pycache__/state.cpython-312.pyc differ diff --git a/app/app/agent/__pycache__/state.cpython-313.pyc b/app/app/agent/__pycache__/state.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6f6ca156a82de66633b85f8b0d30f685eea47c4 Binary files /dev/null and b/app/app/agent/__pycache__/state.cpython-313.pyc differ diff --git a/app/app/agent/graph.py b/app/app/agent/graph.py new file mode 100644 index 0000000000000000000000000000000000000000..ebb24a42ff84f0acff7bfd3815a25571b5456266 --- /dev/null +++ b/app/app/agent/graph.py @@ -0,0 +1,49 @@ +""" +LangGraph StateGraph definition for the Agentic RAG pipeline. +""" +import threading +from langgraph.graph import StateGraph, END, START + +from app.agent.state import AgentState +from app.agent.nodes import ( + retrieve, + generate, + respond, +) + +_compiled_graph = None +_graph_lock = threading.Lock() + + +def build_graph(): + """Build and compile the LangGraph agent graph.""" + graph = StateGraph(AgentState) + + # Register all nodes + graph.add_node("retrieve", retrieve) + graph.add_node("generate", generate) + graph.add_node("respond", respond) + + # Entry point + graph.add_edge(START, "retrieve") + + # After retrieval: go directly to generation + graph.add_edge("retrieve", "generate") + + # After generation: straight to respond + graph.add_edge("generate", "respond") + + # Terminal nodes + graph.add_edge("respond", END) + + return graph.compile() + + +def get_graph(): + """Return the singleton compiled graph.""" + global _compiled_graph + if _compiled_graph is None: + with _graph_lock: + if _compiled_graph is None: + _compiled_graph = build_graph() + return _compiled_graph \ No newline at end of file diff --git a/app/app/agent/nodes.py b/app/app/agent/nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..7f802b251b57ff5c89e31545c28f8d071321ef82 --- /dev/null +++ b/app/app/agent/nodes.py @@ -0,0 +1,118 @@ +""" +LangGraph node functions for the Agentic RAG pipeline. +Each node receives AgentState and returns a partial state update. + +Guardrail logic (intent classification, relevance grading, hallucination checking) +lives in app/guardrails/ — nodes here are thin wrappers that call those modules. +""" +import logging + +from langchain_core.messages import HumanMessage, AIMessage, SystemMessage + +from app.agent.state import AgentState +from app.agent.prompts import ( + SYSTEM_PROMPT, + GENERATION_PROMPT, +) +from app.guardrails import classify_query +from app.utils.llm_helpers import get_llm +from app.retrieval.retriever import retrieve_and_rerank, format_sources +from app.config import settings + +logger = logging.getLogger(__name__) + + +# ────────────────────────────────────────────── +# Guardrail wrapper nodes +# ────────────────────────────────────────────── + +async def classify_intent(state: AgentState) -> dict: + """Node: Classify whether the query is ACPC-related, off-topic, or injection. + + Delegates to app.guardrails.intent_classifier. + Only ACPC_RELATED queries proceed; everything else → fallback. + """ + query = state.get("query", "").strip() + result = await classify_query(query) + logger.info( + "classify_intent: classification=%s, route=%s, blocked=%s", + result["classification"], result["route"], result["blocked_reason"], + ) + return {"route": result["route"]} + + + +# ────────────────────────────────────────────── +# Core pipeline nodes +# ────────────────────────────────────────────── + +async def retrieve(state: AgentState) -> dict: + """Node: Retrieve documents from Qdrant using hybrid search + Cohere rerank.""" + query = state["query"] + logger.info("Retrieving documents for query: %s", query[:80]) + + documents = await retrieve_and_rerank(query) + logger.info("Retrieved %d documents", len(documents)) + return {"retrieved_documents": documents} + +async def generate(state: AgentState) -> dict: + """Node: Generate an answer from relevant documents.""" + query = state["query"] + relevant_docs = state.get("retrieved_documents", []) + history = state.get("messages", []) + + # Build context string from relevant documents + context_parts = [] + for i, doc in enumerate(relevant_docs): + meta = doc.metadata or {} + url = meta.get("url", "") + source_line = f"[Source {i+1}: {meta.get('file_name', 'unknown')}]" + if url: + source_line += f" {url}" + context_parts.append(f"{source_line}\n{doc.page_content}") + context = "\n\n---\n\n".join(context_parts) + + generation_content = GENERATION_PROMPT.format(context=context, question=query) + + # Build messages: system + trimmed history + current generation prompt + messages = [SystemMessage(content=SYSTEM_PROMPT)] + for msg in history[:-1]: # Skip last (current user message) + messages.append(msg) + messages.append(HumanMessage(content=generation_content)) + + llm = get_llm(temperature=0.2) + response = await llm.ainvoke(messages) + generation = response.content.strip() + + sources = format_sources(relevant_docs) + logger.info("Generation complete (%d chars, %d sources)", len(generation), len(sources)) + return {"generation": generation, "sources": sources} + + +# ────────────────────────────────────────────── +# Terminal nodes +# ────────────────────────────────────────────── + +def fallback(state: AgentState) -> dict: + """Node: Return the hardcoded fallback response (never LLM-generated).""" + return { + "generation": settings.fallback_response, + "sources": [], + "confidence": 0.0, + } + + +def respond(state: AgentState) -> dict: + """Terminal node: Package the final response into messages.""" + generation = state.get("generation", settings.fallback_response) + return {"messages": [AIMessage(content=generation)]} + + +# ────────────────────────────────────────────── +# Edge condition functions (routing) +# ────────────────────────────────────────────── +def route_after_classify(state: AgentState) -> str: + """Route after intent classification: retrieve or fallback.""" + route = state.get("route", "fallback") + # Default-deny: only explicit "retrieve" passes + return route if route == "retrieve" else "fallback" diff --git a/app/app/agent/prompts.py b/app/app/agent/prompts.py new file mode 100644 index 0000000000000000000000000000000000000000..c685d7022f20f9aeee2fc9ca27780d067efe88a6 --- /dev/null +++ b/app/app/agent/prompts.py @@ -0,0 +1,33 @@ +SYSTEM_PROMPT = """ +You are the official ACPC Gujarat Admissions Assistant. Your goal is to provide accurate administrative guidance based STRICTLY on provided documents. + +CORE OPERATING RULES: +1. THE "NO-KNOWLEDGE" RULE: If the student's query (e.g., individual exam results, specific seat counts not in text, or personal data) is NOT in the provided context, you must explicitly state: "I do not have access to that specific information in the official documents." Never guess. +2. NO HALLUCINATION OF SERVICES: Do not offer to "check" or "provide" results, certificates, or personal status updates. You only explain rules, schedules, and procedures. +3. ADMISSIONS HIERARCHY: Always prioritize eligibility rules. If a student mentions failing a subject, immediately prioritize the "Eligibility Criteria" (e.g., 45% for General, 40% for Reserved) as a hard requirement. +4. TONE & CITATION: Be professional and supportive. Use inline citations [1](URL) for every factual claim. +5. LANGUAGE: Respond in the student's language. If they use Hinglish/Gujlish, respond in clear English or the dominant language used. +""" + +INTENT_CLASSIFICATION_PROMPT = """Query : {query} +take this Query and classify it as ACPC_RELATED only don't add any other classification + +""" + +GENERATION_PROMPT = """ +Review the official ACPC documentation below. + + +{context} + + +INSTRUCTIONS: +- Answer the student's query using ONLY the context above. +- If the context mentions a specific date or deadline (like the 'Result Improvement' window), highlight it. +- If the student asks for something personal (like their own marks or result), explain that you only have access to the general Admission Rules and Procedures. +- Use clickable markdown citations [1](URL). + + +{question} + +""" \ No newline at end of file diff --git a/app/app/agent/state.py b/app/app/agent/state.py new file mode 100644 index 0000000000000000000000000000000000000000..bfc906c13a36b35a50e515bdbb785143409eb306 --- /dev/null +++ b/app/app/agent/state.py @@ -0,0 +1,26 @@ +from typing import Annotated +from typing_extensions import TypedDict +from langchain_core.documents import Document +from langchain_core.messages import BaseMessage +from langgraph.graph.message import add_messages + + +class AgentState(TypedDict): + # Conversation history (managed by LangGraph add_messages reducer) + messages: Annotated[list[BaseMessage], add_messages] + # Current user query (possibly rewritten) + query: str + # Raw retrieval results (before grading) + retrieved_documents: list[Document] + # Graded relevant documents + relevant_documents: list[Document] + # LLM-generated answer text + generation: str + # Source metadata list for API response + sources: list[dict] + # Confidence score (fraction of retrieved docs that are relevant) + confidence: float + # Number of retrieval retries (for query rewriting loop) + retry_count: int + # Routing decision + route: str diff --git a/app/app/config.py b/app/app/config.py new file mode 100644 index 0000000000000000000000000000000000000000..10eb2f598d5c0bdf759d91fc0db5ea6b201ec6e4 --- /dev/null +++ b/app/app/config.py @@ -0,0 +1,89 @@ +from pydantic_settings import BaseSettings +from pydantic import Field, field_validator + + +class Settings(BaseSettings): + """Application settings — validated at startup from environment variables.""" + + model_config = { + "env_file": ".env", + "env_file_encoding": "utf-8", + "extra": "ignore", + "populate_by_name": True, + } + + # OpenAI / OpenRouter + openai_api_key: str = Field(alias="OPENROUTER_API_KEY", default="") + openai_api_base: str = Field(default="https://openrouter.ai/api/v1") + + # Qdrant + qdrant_url: str = Field(default="") + qdrant_api_key: str = Field(default="") + collection_name: str = Field(default="ld_chatbot_main") + vector_name: str = Field(default="text-dense") + sparse_vector_name: str = Field(default="text-sparse-new") + + # Models + embedding_model: str = Field(default="text-embedding-3-small") + sparse_embedding_model: str = Field(default="Qdrant/bm25") + llm_model: str = Field(default="openai/gpt-5.4-mini") + query_gen_model: str = Field(default="openai/gpt-5.4-mini") + reranker_model: str = Field(default="rerank-english-v3.0") + + # Cohere + cohere_api_key: str = Field(default="") + + # Sarvam + sarvam_api_key: str = Field(default="") + sarvam_api_url: str = Field(default="https://api.sarvam.ai/speech-to-text") + + # Langfuse + langfuse_public_key: str = Field(default="") + langfuse_secret_key: str = Field(default="") + langfuse_host: str = Field(default="https://cloud.langfuse.com") + + # Retrieval parameters + retrieval_top_k: int = Field(default=15) + rerank_top_n: int = Field(default=5) + + # Agent parameters + max_retrieval_retries: int = Field(default=2) + confidence_threshold: float = Field(default=0.2) + + # Memory / session + max_conversation_messages: int = Field(default=20) + max_context_tokens: int = Field(default=6000) + session_ttl_minutes: int = Field(default=30) + + # Security + ingest_api_key: str = Field(default="") + ingest_base_dir: str = Field(default="") + allowed_origins: str = Field(default="http://localhost:5173,http://localhost:3000") + + @field_validator("allowed_origins", mode="before") + @classmethod + def parse_allowed_origins(cls, v): + # Keep as comma-separated string — split where needed (e.g. in main.py CORS) + if isinstance(v, list): + return ",".join(v) + return v + + @property + def allowed_origins_list(self) -> list[str]: + """Return allowed_origins as a list for CORS middleware.""" + return [o.strip() for o in self.allowed_origins.split(",") if o.strip()] + + # Chunk parameters (for ingestion — must match existing collection) + chunk_size: int = Field(default=512) + chunk_overlap: int = Field(default=64) + + # Fallback response (never LLM-generated) + fallback_response: str = Field( + default=( + "I don't have specific information about that in my current knowledge base. " + "For accurate and up-to-date information, please visit the official ACPC Gujarat website: " + "https://acpc.gujarat.gov.in/ or contact the ACPC helpline." + ) + ) + +settings = Settings() \ No newline at end of file diff --git a/app/app/dependencies.py b/app/app/dependencies.py new file mode 100644 index 0000000000000000000000000000000000000000..65c6a43dcf757af14c28f198a9a120f6732c1099 --- /dev/null +++ b/app/app/dependencies.py @@ -0,0 +1,7 @@ +from app.agent.graph import get_graph +from app.memory.session_store import get_or_create_session + + +def get_agent(): + """FastAPI dependency: return the compiled LangGraph agent.""" + return get_graph() diff --git a/app/app/guardrails/__init__.py b/app/app/guardrails/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0cf09082f1bb9d4569849a3311e3dff1dd44d66f --- /dev/null +++ b/app/app/guardrails/__init__.py @@ -0,0 +1,13 @@ +""" +Guardrails module for the ACPC Chatbot pipeline. + +Contains all safety, relevance, and grounding checks: +- Intent classification (LLM-based) +- Document relevance grading +- Hallucination / grounding verification +""" +from app.guardrails.intent_classifier import classify_query + +__all__ = [ + "classify_query", +] diff --git a/app/app/guardrails/__pycache__/__init__.cpython-312.pyc b/app/app/guardrails/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d680798a68e94ea72aad7e29dcffabea9afb84c Binary files /dev/null and b/app/app/guardrails/__pycache__/__init__.cpython-312.pyc differ diff --git a/app/app/guardrails/__pycache__/__init__.cpython-313.pyc b/app/app/guardrails/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dce58efb255818a9cd104536f283248fc0e9328a Binary files /dev/null and b/app/app/guardrails/__pycache__/__init__.cpython-313.pyc differ diff --git a/app/app/guardrails/__pycache__/__init__.cpython-314.pyc b/app/app/guardrails/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..facb48be2d3ab4e2d29aab4a5e20241e2535eb0e Binary files /dev/null and b/app/app/guardrails/__pycache__/__init__.cpython-314.pyc differ diff --git a/app/app/guardrails/__pycache__/hallucination_checker.cpython-312.pyc b/app/app/guardrails/__pycache__/hallucination_checker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c72402f976d0da429c8dc8449642f84db3a542f3 Binary files /dev/null and b/app/app/guardrails/__pycache__/hallucination_checker.cpython-312.pyc differ diff --git a/app/app/guardrails/__pycache__/hallucination_checker.cpython-313.pyc b/app/app/guardrails/__pycache__/hallucination_checker.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a9903ffb9d4ce6c36a4da16dbe981cc02fd0a90 Binary files /dev/null and b/app/app/guardrails/__pycache__/hallucination_checker.cpython-313.pyc differ diff --git a/app/app/guardrails/__pycache__/hallucination_checker.cpython-314.pyc b/app/app/guardrails/__pycache__/hallucination_checker.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de2abc4165c7bbcebda6e59acc6745f1440cb969 Binary files /dev/null and b/app/app/guardrails/__pycache__/hallucination_checker.cpython-314.pyc differ diff --git a/app/app/guardrails/__pycache__/intent_classifier.cpython-312.pyc b/app/app/guardrails/__pycache__/intent_classifier.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e88c585d2acb14aada9ec4fc53085f34fbefb32 Binary files /dev/null and b/app/app/guardrails/__pycache__/intent_classifier.cpython-312.pyc differ diff --git a/app/app/guardrails/__pycache__/intent_classifier.cpython-313.pyc b/app/app/guardrails/__pycache__/intent_classifier.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9cee8ac8a4cf593fa60ca2312597c6ba5344bcd Binary files /dev/null and b/app/app/guardrails/__pycache__/intent_classifier.cpython-313.pyc differ diff --git a/app/app/guardrails/__pycache__/intent_classifier.cpython-314.pyc b/app/app/guardrails/__pycache__/intent_classifier.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68c1338e9320a369d0efeaf17f0f3c1fc94aeefd Binary files /dev/null and b/app/app/guardrails/__pycache__/intent_classifier.cpython-314.pyc differ diff --git a/app/app/guardrails/__pycache__/relevance_grader.cpython-312.pyc b/app/app/guardrails/__pycache__/relevance_grader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5872d49c333be377499235e02a194de76a7ccb4 Binary files /dev/null and b/app/app/guardrails/__pycache__/relevance_grader.cpython-312.pyc differ diff --git a/app/app/guardrails/__pycache__/relevance_grader.cpython-313.pyc b/app/app/guardrails/__pycache__/relevance_grader.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66e03b2b98e91ab9c7ffd21e3ac9367d95cc72d8 Binary files /dev/null and b/app/app/guardrails/__pycache__/relevance_grader.cpython-313.pyc differ diff --git a/app/app/guardrails/__pycache__/relevance_grader.cpython-314.pyc b/app/app/guardrails/__pycache__/relevance_grader.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac9b91e7da711bf4576a389e09ac80bc555c78d3 Binary files /dev/null and b/app/app/guardrails/__pycache__/relevance_grader.cpython-314.pyc differ diff --git a/app/app/guardrails/intent_classifier.py b/app/app/guardrails/intent_classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..a3b5cc67542e67ff6775f77b45f64ab9769c49f7 --- /dev/null +++ b/app/app/guardrails/intent_classifier.py @@ -0,0 +1,80 @@ +""" +Intent Classification Guardrail. + +LLM-based classification to determine whether a user query is: +- ACPC_RELATED → proceed to retrieval +- GREETINGS/SMALL TALK → proceed to retrieval +- OFF_TOPIC → block with fallback +- INJECTION → block with fallback (includes personal info requests) +""" + +import logging +from langchain_core.messages import HumanMessage + +from app.utils.llm_helpers import get_llm +from app.agent.prompts import INTENT_CLASSIFICATION_PROMPT + +logger = logging.getLogger(__name__) + +# Valid classification labels — anything else is treated as blocked +VALID_LABELS = ("ACPC_RELATED", "GREETINGS / SMALL TALK", "OFF_TOPIC", "INJECTION") + + +async def classify_query(query: str) -> dict: + """Classify a user query using LLM-based intent detection. + + Returns: + dict with: + - "classification": one of VALID_LABELS or "UNKNOWN" + - "route": "retrieve" if ACPC_RELATED, "fallback" otherwise + - "blocked_reason": None if allowed, else the classification label + """ + if not query or not query.strip(): + logger.warning("Empty query passed to classify_query") + return { + "classification": "UNKNOWN", + "route": "fallback", + "blocked_reason": "empty_query", + } + + llm = get_llm(temperature=0.0) + prompt = INTENT_CLASSIFICATION_PROMPT.format(query=query) + + try: + response = await llm.ainvoke([HumanMessage(content=prompt)]) + classification = response.content.strip().upper() + except Exception as e: + logger.error("LLM error in classify_query: %s — defaulting to fallback", e) + return { + "classification": "UNKNOWN", + "route": "fallback", + "blocked_reason": "llm_error", + } + + # Default-deny: if LLM returns something unexpected, block it + if classification not in VALID_LABELS: + logger.warning( + "Invalid classification '%s' (expected one of %s) — blocking", + classification, VALID_LABELS, + ) + return { + "classification": classification, + "route": "fallback", + "blocked_reason": "invalid_classification", + } + + logger.info("Intent classification: %s for query: %s", classification, query[:80]) + + # Only ACPC_RELATED passes through + if classification == "ACPC_RELATED" or classification == "GREETINGS / SMALL TALK": + return { + "classification": classification, + "route": "retrieve", + "blocked_reason": None, + } + + return { + "classification": classification, + "route": "fallback", + "blocked_reason": classification.lower(), + } diff --git a/app/app/main.py b/app/app/main.py new file mode 100644 index 0000000000000000000000000000000000000000..ecb615897cfb08ce9fc42d227d144acc5e59c766 --- /dev/null +++ b/app/app/main.py @@ -0,0 +1,67 @@ +import logging +from contextlib import asynccontextmanager + +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware + +from app.config import settings +from app.agent.graph import get_graph +from app.retrieval.qdrant_store import get_vector_store +from app.monitoring.langfuse_setup import get_langfuse_callback_handler, flush_langfuse +from app.memory.session_store import start_cleanup_task, stop_cleanup_task +from app.routers import chat, stt, ingest, health, sessions + +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", +) +logger = logging.getLogger(__name__) + + +@asynccontextmanager +async def lifespan(app: FastAPI): + """Application startup / shutdown lifecycle.""" + logger.info("Starting ACPC Chatbot backend...") + + # Pre-warm non-network singletons + get_graph() + start_cleanup_task() + # NOTE: Qdrant vector store is lazily initialized on first query + # (avoids startup failure if Qdrant Cloud is temporarily unreachable) + + logger.info("Backend ready.") + yield + + # Shutdown + stop_cleanup_task() + flush_langfuse() + logger.info("Backend shut down cleanly.") + + +app = FastAPI( + title="ACPC Gujarat Chatbot API", + description="Agentic RAG chatbot for ACPC Gujarat admissions queries", + version="1.0.0", + lifespan=lifespan, +) + +# CORS — restrict to configured origins +app.add_middleware( + CORSMiddleware, + allow_origins=settings.allowed_origins_list, + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# Mount routers +app.include_router(chat.router) +app.include_router(stt.router) +app.include_router(ingest.router) +app.include_router(health.router) +app.include_router(sessions.router) + + +@app.get("/") +async def root(): + return {"status": "ok", "service": "ACPC Gujarat Chatbot API", "version": "1.0.0"} diff --git a/app/app/memory/__init__.py b/app/app/memory/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/app/memory/__pycache__/__init__.cpython-312.pyc b/app/app/memory/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5717be171709703a7e42da5edc03c373c858dbac Binary files /dev/null and b/app/app/memory/__pycache__/__init__.cpython-312.pyc differ diff --git a/app/app/memory/__pycache__/__init__.cpython-313.pyc b/app/app/memory/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aeb01e121e1837ffd9ea220b3190fd12f6a57272 Binary files /dev/null and b/app/app/memory/__pycache__/__init__.cpython-313.pyc differ diff --git a/app/app/memory/__pycache__/conversation_buffer.cpython-312.pyc b/app/app/memory/__pycache__/conversation_buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8254e932b307f0bcd56cb35324f65e36aec6e03c Binary files /dev/null and b/app/app/memory/__pycache__/conversation_buffer.cpython-312.pyc differ diff --git a/app/app/memory/__pycache__/conversation_buffer.cpython-313.pyc b/app/app/memory/__pycache__/conversation_buffer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25feea6485ae49e1d54a2d5a98cba30b08ea15ae Binary files /dev/null and b/app/app/memory/__pycache__/conversation_buffer.cpython-313.pyc differ diff --git a/app/app/memory/__pycache__/session_store.cpython-312.pyc b/app/app/memory/__pycache__/session_store.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16ab3cf639525b6097b3c079be43a8ddda77db4b Binary files /dev/null and b/app/app/memory/__pycache__/session_store.cpython-312.pyc differ diff --git a/app/app/memory/__pycache__/session_store.cpython-313.pyc b/app/app/memory/__pycache__/session_store.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea216c0222dad924bd16d8e62d948e19a5908b68 Binary files /dev/null and b/app/app/memory/__pycache__/session_store.cpython-313.pyc differ diff --git a/app/app/memory/conversation_buffer.py b/app/app/memory/conversation_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..f81ee624443d52ec9b4f808e4fe6f6d11fd24b78 --- /dev/null +++ b/app/app/memory/conversation_buffer.py @@ -0,0 +1,61 @@ +from datetime import datetime, timezone +from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, SystemMessage +from app.utils.token_counter import count_messages_tokens +from app.config import settings + + +class ConversationBuffer: + """Sliding window conversation buffer with token-based trimming.""" + + def __init__(self): + self.messages: list[BaseMessage] = [] + self.last_accessed: datetime = datetime.now(timezone.utc) + + def add_user_message(self, content: str) -> None: + self.messages.append(HumanMessage(content=content)) + self._trim() + self.last_accessed = datetime.now(timezone.utc) + + def add_ai_message(self, content: str) -> None: + self.messages.append(AIMessage(content=content)) + self._trim() + self.last_accessed = datetime.utcnow() + + def get_messages(self, max_tokens: int | None = None) -> list[BaseMessage]: + """Return messages, token-trimmed to max_tokens (default from settings).""" + self.last_accessed = datetime.now(timezone.utc) + limit = max_tokens or settings.max_context_tokens + return self._token_trim(self.messages.copy(), limit) + + def _trim(self) -> None: + """Apply sliding window: keep last MAX_CONVERSATION_MESSAGES.""" + max_msgs = settings.max_conversation_messages + if len(self.messages) > max_msgs: + self.messages = self.messages[-max_msgs:] + + def _token_trim(self, messages: list[BaseMessage], max_tokens: int) -> list[BaseMessage]: + """ + Trim oldest messages (excluding last user message) until total tokens <= max_tokens. + Always preserves the most recent user message. + """ + if not messages: + return messages + + total = count_messages_tokens(messages) + if total <= max_tokens: + return messages + + # Always keep the last message (current user query) + last = messages[-1] + trimable = messages[:-1] + + while trimable and count_messages_tokens(trimable) + count_messages_tokens([last]) > max_tokens: + trimable.pop(0) + + return trimable + [last] + + def clear(self) -> None: + self.messages = [] + + def __len__(self) -> int: + return len(self.messages) diff --git a/app/app/memory/session_store.py b/app/app/memory/session_store.py new file mode 100644 index 0000000000000000000000000000000000000000..a1b81adebd16517283097a6cc5b4b3c9bda0fc80 --- /dev/null +++ b/app/app/memory/session_store.py @@ -0,0 +1,66 @@ +import asyncio +import logging +from datetime import datetime, timedelta, timezone +from uuid import uuid4 + +from app.memory.conversation_buffer import ConversationBuffer +from app.config import settings + +logger = logging.getLogger(__name__) + +_sessions: dict[str, ConversationBuffer] = {} +_cleanup_task: asyncio.Task | None = None + + +def get_or_create_session(session_id: str | None) -> tuple[str, ConversationBuffer]: + """Get existing session or create a new one. Returns (session_id, buffer).""" + if not session_id or session_id not in _sessions: + session_id = session_id or str(uuid4()) + _sessions[session_id] = ConversationBuffer() + logger.info("Created new session: %s", session_id) + return session_id, _sessions[session_id] + + +def get_session(session_id: str) -> ConversationBuffer | None: + return _sessions.get(session_id) + + +def delete_session(session_id: str) -> bool: + if session_id in _sessions: + del _sessions[session_id] + logger.info("Deleted session: %s", session_id) + return True + return False + + +def active_session_count() -> int: + return len(_sessions) + + +async def _cleanup_expired_sessions() -> None: + """Background task: evict sessions older than SESSION_TTL_MINUTES.""" + while True: + await asyncio.sleep(300) # Run every 5 minutes + ttl = timedelta(minutes=settings.session_ttl_minutes) + now = datetime.now(timezone.utc) + expired = [ + sid for sid, buf in _sessions.items() + if (now - buf.last_accessed) > ttl + ] + for sid in expired: + del _sessions[sid] + logger.info("Evicted expired session: %s", sid) + if expired: + logger.info("Evicted %d expired sessions", len(expired)) + + +def start_cleanup_task() -> None: + global _cleanup_task + if _cleanup_task is None or _cleanup_task.done(): + _cleanup_task = asyncio.create_task(_cleanup_expired_sessions()) + + +def stop_cleanup_task() -> None: + global _cleanup_task + if _cleanup_task and not _cleanup_task.done(): + _cleanup_task.cancel() diff --git a/app/app/monitoring/__init__.py b/app/app/monitoring/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/app/monitoring/__pycache__/__init__.cpython-312.pyc b/app/app/monitoring/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..013ecbc7abfeb5392fd80a791a618f9c373ff500 Binary files /dev/null and b/app/app/monitoring/__pycache__/__init__.cpython-312.pyc differ diff --git a/app/app/monitoring/__pycache__/__init__.cpython-313.pyc b/app/app/monitoring/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1eb7a381918d31fb22611bdff3cae6e171bf89ed Binary files /dev/null and b/app/app/monitoring/__pycache__/__init__.cpython-313.pyc differ diff --git a/app/app/monitoring/__pycache__/langfuse_setup.cpython-312.pyc b/app/app/monitoring/__pycache__/langfuse_setup.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6a969a72a34c5712f91c1006a7b5ccf3d699c66 Binary files /dev/null and b/app/app/monitoring/__pycache__/langfuse_setup.cpython-312.pyc differ diff --git a/app/app/monitoring/__pycache__/langfuse_setup.cpython-313.pyc b/app/app/monitoring/__pycache__/langfuse_setup.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a81535406fb057d68e85f8624e8da5acdd0acf6 Binary files /dev/null and b/app/app/monitoring/__pycache__/langfuse_setup.cpython-313.pyc differ diff --git a/app/app/monitoring/langfuse_setup.py b/app/app/monitoring/langfuse_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..9abed37e721f3ce7cc8627cd8894285ffd26e738 --- /dev/null +++ b/app/app/monitoring/langfuse_setup.py @@ -0,0 +1,100 @@ +import logging +import os +from app.config import settings + +logger = logging.getLogger(__name__) + +_langfuse_handler = None + + +def _configure_langfuse_env(): + """Configure Langfuse environment variables from settings.""" + if settings.langfuse_public_key: + os.environ["LANGFUSE_PUBLIC_KEY"] = settings.langfuse_public_key + if settings.langfuse_secret_key: + os.environ["LANGFUSE_SECRET_KEY"] = settings.langfuse_secret_key + if settings.langfuse_host: + os.environ["LANGFUSE_BASE_URL"] = settings.langfuse_host + + +def get_langfuse_callback_handler(**kwargs): + """ + Get a new Langfuse CallbackHandler for LangChain. + + Uses environment-based configuration per official Langfuse docs: + https://langfuse.com/guides/cookbook/integration_langchain + + The handler is automatically initialized via environment variables, + so no explicit initialization is needed. + + Returns None if Langfuse is not configured or if the integration + is not available. + """ + if not settings.langfuse_public_key: + logger.debug("Langfuse not configured (no public key) — tracing disabled") + return None + + try: + # Configure environment variables + _configure_langfuse_env() + + # Try modern import path first (langfuse 3.x+) + try: + from langfuse.langchain import CallbackHandler + except ImportError: + # Try alternative path for different versions + try: + from langfuse.callback.langchain import CallbackHandler + except ImportError: + # Try direct import with environment-based init + from langfuse import CallbackHandler # type: ignore + + handler = CallbackHandler(**kwargs) + logger.info("Langfuse CallbackHandler initialized successfully via environment") + return handler + + except ImportError as e: + logger.debug( + "Langfuse CallbackHandler not available in this environment: %s — " + "tracing will use LangRecorder (local) instead", + e, + ) + return None + except Exception as e: + logger.warning( + "Failed to initialize Langfuse CallbackHandler: %s — tracing disabled", e + ) + return None + +def get_langfuse_client(): + if not settings.langfuse_public_key: + return None + try: + from langfuse import Langfuse + _configure_langfuse_env() + return Langfuse() + except Exception as e: + logger.warning("Failed to initialize Langfuse client: %s", e) + return None + + +def flush_langfuse() -> None: + """Flush pending Langfuse events (call on shutdown).""" + try: + from langfuse import Langfuse + + # Configure environment variables just in case + _configure_langfuse_env() + + langfuse = Langfuse() + langfuse.flush() + logger.info("Langfuse events flushed successfully") + except ImportError: + logger.debug("Langfuse not available — skipping flush") + except Exception as e: + logger.warning("Failed to flush Langfuse events: %s", e) + + + + + \ No newline at end of file diff --git a/app/app/retrieval/__init__.py b/app/app/retrieval/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/app/retrieval/__pycache__/__init__.cpython-312.pyc b/app/app/retrieval/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14542b37c66d364463e0c024c80c04a9b7a7d8bd Binary files /dev/null and b/app/app/retrieval/__pycache__/__init__.cpython-312.pyc differ diff --git a/app/app/retrieval/__pycache__/__init__.cpython-313.pyc b/app/app/retrieval/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7f61d4498ff7d20106c057b765e2486e8513b12 Binary files /dev/null and b/app/app/retrieval/__pycache__/__init__.cpython-313.pyc differ diff --git a/app/app/retrieval/__pycache__/__init__.cpython-314.pyc b/app/app/retrieval/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69fc0a673c5caad44060631c379f1530fe75042c Binary files /dev/null and b/app/app/retrieval/__pycache__/__init__.cpython-314.pyc differ diff --git a/app/app/retrieval/__pycache__/ingestion.cpython-312.pyc b/app/app/retrieval/__pycache__/ingestion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a28f99df0dfec773b588445c03bdfc4b53d5e5d3 Binary files /dev/null and b/app/app/retrieval/__pycache__/ingestion.cpython-312.pyc differ diff --git a/app/app/retrieval/__pycache__/ingestion.cpython-313.pyc b/app/app/retrieval/__pycache__/ingestion.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8994c24dbcfa511edd7fe32a27a498f10c473b3f Binary files /dev/null and b/app/app/retrieval/__pycache__/ingestion.cpython-313.pyc differ diff --git a/app/app/retrieval/__pycache__/llamaindex_store.cpython-312.pyc b/app/app/retrieval/__pycache__/llamaindex_store.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03641dfd1fdd339ac1220622a49400c98c6cda7a Binary files /dev/null and b/app/app/retrieval/__pycache__/llamaindex_store.cpython-312.pyc differ diff --git a/app/app/retrieval/__pycache__/qdrant_store.cpython-312.pyc b/app/app/retrieval/__pycache__/qdrant_store.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..395fedc0b92c8160c7fb6b9a6fc408970f3154b5 Binary files /dev/null and b/app/app/retrieval/__pycache__/qdrant_store.cpython-312.pyc differ diff --git a/app/app/retrieval/__pycache__/qdrant_store.cpython-313.pyc b/app/app/retrieval/__pycache__/qdrant_store.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2d8df3b983edca4f2de9a6a15ff3ab873e0159e Binary files /dev/null and b/app/app/retrieval/__pycache__/qdrant_store.cpython-313.pyc differ diff --git a/app/app/retrieval/__pycache__/qdrant_store.cpython-314.pyc b/app/app/retrieval/__pycache__/qdrant_store.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a1db77572db1cc7c056bd3173e15e9f5205de67 Binary files /dev/null and b/app/app/retrieval/__pycache__/qdrant_store.cpython-314.pyc differ diff --git a/app/app/retrieval/__pycache__/reranker.cpython-312.pyc b/app/app/retrieval/__pycache__/reranker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb8cf1289410938ce8115d1eac91f3e01ed907fd Binary files /dev/null and b/app/app/retrieval/__pycache__/reranker.cpython-312.pyc differ diff --git a/app/app/retrieval/__pycache__/reranker.cpython-313.pyc b/app/app/retrieval/__pycache__/reranker.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56311867b537c66e0e00eee7d92c89fa2a7549b3 Binary files /dev/null and b/app/app/retrieval/__pycache__/reranker.cpython-313.pyc differ diff --git a/app/app/retrieval/__pycache__/retriever.cpython-312.pyc b/app/app/retrieval/__pycache__/retriever.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0515143da046c63162c1ca9c462ef4a2ecb23d06 Binary files /dev/null and b/app/app/retrieval/__pycache__/retriever.cpython-312.pyc differ diff --git a/app/app/retrieval/__pycache__/retriever.cpython-313.pyc b/app/app/retrieval/__pycache__/retriever.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb1427e4a20940a58b3c89f7ef7c8e6ec5f91658 Binary files /dev/null and b/app/app/retrieval/__pycache__/retriever.cpython-313.pyc differ diff --git a/app/app/retrieval/__pycache__/retriever.cpython-314.pyc b/app/app/retrieval/__pycache__/retriever.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61122367febac6c80d76e64926c681b4f5c204a9 Binary files /dev/null and b/app/app/retrieval/__pycache__/retriever.cpython-314.pyc differ diff --git a/app/app/retrieval/ingestion.py b/app/app/retrieval/ingestion.py new file mode 100644 index 0000000000000000000000000000000000000000..9e6e7ae95bec99695fff6e2ea5c187316f6e3dc3 --- /dev/null +++ b/app/app/retrieval/ingestion.py @@ -0,0 +1,148 @@ +""" +Document ingestion pipeline — migrated from server_acpc.py. +Builds hierarchical LlamaIndex nodes and stores them in Qdrant. +""" +from pathlib import Path + +from langchain_community.document_loaders import PyPDFLoader +from langchain_core.documents import Document +from qdrant_client import models + +from app.config import settings +from app.retrieval.qdrant_store import ( + get_qdrant_client, + get_vector_store, + get_storage_context, + get_llama_embedding_model, + get_storage_dir +) +import logging +logger = logging.getLogger(__name__) + +_CHUNK_SIZES = [1024, 512, 256] + +def _ensure_node_type_index() -> None: + """Create payload index used by LlamaIndex metadata filtering.""" + client = get_qdrant_client() + client.create_payload_index( + collection_name=settings.collection_name, + field_name="_node_type", + field_schema=models.PayloadSchemaType.KEYWORD, + wait=True, + ) + + +def _get_metadata(file_path: str) -> dict: + """Generate metadata matching the existing Qdrant collection schema.""" + base_name = Path(file_path).stem + url = f"https://acpc.gujarat.gov.in/assets/uploads/media-uploader/{base_name}.pdf" + return { + "file_name": Path(file_path).name, + "url": url, + "page_id": url, + } + + +def _load_file(file_path: str) -> list[Document]: + """Load a single file (PDF or text).""" + path = Path(file_path) + if path.suffix.lower() == ".pdf": + loader = PyPDFLoader(str(path)) + docs = loader.load() + else: + from langchain_community.document_loaders import TextLoader + loader = TextLoader(str(path), encoding="utf-8") + docs = loader.load() + + # Inject file-level metadata + meta = _get_metadata(file_path) + for doc in docs: + doc.metadata.update(meta) + return docs + + +def _to_llama_documents(documents: list[Document]): + from llama_index.core import Document as LlamaDocument + + llama_documents = [] + for doc in documents: + content = (doc.page_content or "").strip() + if not content: + continue + llama_documents.append( + LlamaDocument(text=content, metadata=dict(doc.metadata or {})) + ) + return llama_documents + + +def index_documents(documents: list[Document]) -> int: + if not documents: + return 0 + + from llama_index.core import VectorStoreIndex + from llama_index.core.node_parser import HierarchicalNodeParser + + llama_documents = _to_llama_documents(documents) + if not llama_documents: + return 0 + + parser = HierarchicalNodeParser.from_defaults(chunk_sizes=_CHUNK_SIZES) + nodes = parser.get_nodes_from_documents(llama_documents) + storage_context = get_storage_context() + + VectorStoreIndex( + nodes=nodes, + storage_context=storage_context, + embed_model=get_llama_embedding_model(), + store_nodes_override=True, + ) + storage_context.persist(persist_dir=str(get_storage_dir())) + logger.info("Indexed %d hierarchical nodes into LlamaIndex storage", len(nodes)) + return len(nodes) + + +def ingest_file(file_path: str) -> int: + """Ingest a single file into Qdrant using hierarchical LlamaIndex nodes.""" + docs = _load_file(file_path) + # Also write plain chunks to hybrid LangChain vector store to keep sparse vectors available. + get_vector_store().add_documents(docs) + _ensure_node_type_index() + indexed_nodes = index_documents(docs) + return indexed_nodes + + +def ingest_directory(directory_path: str, recursive: bool = True) -> dict: + """Ingest all supported files from a directory. Returns summary.""" + directory = Path(directory_path) + patterns = ["*.pdf", "*.txt", "*.md"] + files = [] + for pattern in patterns: + search_pattern = f"**/{pattern}" if recursive else pattern + files.extend(directory.glob(search_pattern)) + files = sorted(set(files)) + + total_chunks = 0 + for file_path in files: + total_chunks += ingest_file(str(file_path)) + + return {"total_documents": len(files), "total_chunks": total_chunks} + + +def reset_storage() -> None: + import shutil + storage_dir = get_storage_dir() + if storage_dir.exists(): + shutil.rmtree(storage_dir) + + +def reset_collection() -> None: + """Delete and recreate the Qdrant collection.""" + from app.retrieval.qdrant_store import get_qdrant_client + + client = get_qdrant_client() + client.delete_collection(settings.collection_name) + reset_storage() + # Re-initialize the vector store (it recreates the collection on first use) + import app.retrieval.qdrant_store as qs + + qs._vector_store = None # Force re-init on next access diff --git a/app/app/retrieval/qdrant_store.py b/app/app/retrieval/qdrant_store.py new file mode 100644 index 0000000000000000000000000000000000000000..06b4df3be203123272c73d31b91128ffebf25fd8 --- /dev/null +++ b/app/app/retrieval/qdrant_store.py @@ -0,0 +1,162 @@ +from qdrant_client import QdrantClient +from langchain_qdrant import FastEmbedSparse, QdrantVectorStore, RetrievalMode +from langchain_openai import OpenAIEmbeddings +from app.config import settings + +_client: QdrantClient | None = None +_vector_store: QdrantVectorStore | None = None +_embeddings: OpenAIEmbeddings | None = None +_sparse_embeddings: FastEmbedSparse | None = None + + +def get_qdrant_client() -> QdrantClient: + global _client + if _client is None: + _client = QdrantClient( + url=settings.qdrant_url, + api_key=settings.qdrant_api_key, + timeout=120, + ) + return _client + + +def get_embeddings() -> OpenAIEmbeddings: + global _embeddings + if _embeddings is None: + # Check if we should use openrouter, fallback to openai + api_key = getattr(settings, 'openrouter_api_key', None) or getattr(settings, 'openai_api_key', None) + api_base = getattr(settings, 'openrouter_api_base', None) or getattr(settings, 'openai_api_base', None) + _embeddings = OpenAIEmbeddings( + model=settings.embedding_model, + api_key=api_key, + base_url=api_base, + ) + return _embeddings + + +def get_sparse_embeddings() -> FastEmbedSparse: + global _sparse_embeddings + if _sparse_embeddings is None: + # Provide fallback if sparse_model isn't found + sparse_model = getattr(settings, "sparse_model", getattr(settings, "sparse_embedding_model", "Qdrant/bm25")) + _sparse_embeddings = FastEmbedSparse(model_name=sparse_model) + return _sparse_embeddings + + +def _get_retrieval_mode() -> RetrievalMode: + if getattr(settings, 'retrieval_mode', 'dense') == "sparse": + return RetrievalMode.SPARSE + if getattr(settings, 'retrieval_mode', 'dense') == "hybrid": + return RetrievalMode.HYBRID + return RetrievalMode.DENSE + + +def get_vector_store() -> QdrantVectorStore: + """Return the singleton QdrantVectorStore connected to the existing collection.""" + global _vector_store + if _vector_store is None: + client = get_qdrant_client() + embeddings = get_embeddings() + retrieval_mode = _get_retrieval_mode() + + # Try configured mode first. If collection schema is not hybrid-ready yet, + # fallback keeps the system available while data is re-indexed. + sparse_embedding = get_sparse_embeddings() if retrieval_mode != RetrievalMode.DENSE else None + try: + _vector_store = QdrantVectorStore( + client=client, + collection_name=settings.collection_name, + embedding=embeddings, + retrieval_mode=retrieval_mode, + vector_name=settings.vector_name, + sparse_embedding=sparse_embedding, + sparse_vector_name=getattr(settings, "sparse_vector_name", "sparse_vector"), + content_payload_key="_node_content", + ) + except Exception: + try: + _vector_store = QdrantVectorStore.construct_instance( + embedding=embeddings, + retrieval_mode=retrieval_mode, + sparse_embedding=sparse_embedding, + client_options={ + "url": settings.qdrant_url, + "api_key": settings.qdrant_api_key, + "timeout": 120, + }, + collection_name=settings.collection_name, + vector_name=settings.vector_name, + sparse_vector_name=getattr(settings, "sparse_vector_name", "sparse_vector"), + content_payload_key="_node_content", + ) + except Exception: + _vector_store = QdrantVectorStore.construct_instance( + embedding=embeddings, + retrieval_mode=RetrievalMode.DENSE, + client_options={ + "url": settings.qdrant_url, + "api_key": settings.qdrant_api_key, + "timeout": 120, + }, + collection_name=settings.collection_name, + vector_name=settings.vector_name, + content_payload_key="_node_content", + ) + return _vector_store + + +# ────────────────────────────────────────────── +# LlamaIndex Connection Handlers +# ────────────────────────────────────────────── +import logging +from pathlib import Path + +logger = logging.getLogger(__name__) + +_STORAGE_DIR = Path(__file__).resolve().parents[2] / ".llamaindex_storage" + + +def get_storage_dir() -> Path: + return _STORAGE_DIR + + +def get_llama_embedding_model(): + from llama_index.embeddings.langchain import LangchainEmbedding + return LangchainEmbedding(get_embeddings()) + + +def get_llama_qdrant_vector_store(): + from llama_index.vector_stores.qdrant import QdrantVectorStore + + client = get_qdrant_client() + try: + from qdrant_client.models import PayloadSchemaType + client.create_payload_index( + collection_name=settings.collection_name, + field_name="_node_type", + field_schema=PayloadSchemaType.KEYWORD, + ) + except Exception as e: + logger.debug("Payload index creation skipped or already exists: %s", getattr(e, "message", str(e))) + + return QdrantVectorStore( + client=client, + collection_name=settings.collection_name, + ) + + +def get_storage_context(): + from llama_index.core import StorageContext + + storage_dir = get_storage_dir() + storage_dir.mkdir(parents=True, exist_ok=True) + docstore_file = storage_dir / "docstore.json" + if docstore_file.exists(): + return StorageContext.from_defaults( + vector_store=get_llama_qdrant_vector_store(), + persist_dir=str(storage_dir), + ) + + return StorageContext.from_defaults( + vector_store=get_llama_qdrant_vector_store(), + ) diff --git a/app/app/retrieval/reranker.py b/app/app/retrieval/reranker.py new file mode 100644 index 0000000000000000000000000000000000000000..12d300e042a52f505f7f8cb03dae83f616a631a7 --- /dev/null +++ b/app/app/retrieval/reranker.py @@ -0,0 +1,32 @@ +from langchain_cohere import CohereRerank +from langchain_core.documents import Document +from app.config import settings + + +def get_reranker() -> CohereRerank: + return CohereRerank( + model=settings.reranker_model, + cohere_api_key=settings.cohere_api_key, + top_n=settings.rerank_top_n, + ) + + +async def rerank_documents(query: str, documents: list[Document]) -> list[Document]: + """Rerank retrieved documents using Cohere reranker.""" + if not documents: + return [] + + # Filter out documents with empty or whitespace-only content + valid_docs = [ + doc for doc in documents + if doc.page_content and doc.page_content.strip() + ] + + if not valid_docs: + return [] + + reranker = get_reranker() + # Deduplicate documents before reranking if needed + # (MultiQueryRetriever can sometimes return duplicates) + + return await reranker.acompress_documents(documents=valid_docs, query=query) diff --git a/app/app/retrieval/retriever.py b/app/app/retrieval/retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..92c3416a25b6a3151e3f9cba09b3a799fb5fc9b8 --- /dev/null +++ b/app/app/retrieval/retriever.py @@ -0,0 +1,105 @@ +import logging +import json +from typing import List, Dict, Any +from langchain_core.documents import Document +from langchain_classic.retrievers import MultiQueryRetriever +from app.retrieval.qdrant_store import get_vector_store +from app.utils.llm_helpers import get_llm +from app.retrieval.reranker import rerank_documents +from app.config import settings + +logger = logging.getLogger(__name__) + + +def ensure_pdf_url(url: str) -> str: + if not url: + return url + + base_url, suffix = url, "" + for separator in ("?", "#"): + if separator in base_url: + base_url, suffix = base_url.split(separator, 1) + suffix = separator + suffix + break + + if base_url.lower().endswith(".pdf"): + return url + + return f"{base_url}.pdf{suffix}" + + +async def retrieve_and_rerank(query: str) -> list[Document]: + """ + Retrieve documents using LangChain Classic's MultiQueryRetriever, and rerank them, returning the top 5. + """ + documents = [] + if not query.strip(): + return documents + + try: + logger.info("Using MultiQueryRetriever (classic) for query: %s", query) + vector_store = get_vector_store() + + # Initialize the MultiQueryRetriever + retriever = MultiQueryRetriever.from_llm( + retriever=vector_store.as_retriever(search_kwargs={"k": settings.retrieval_top_k}), + llm=get_llm(temperature=0.0, model=settings.query_gen_model) + ) + + # Properly await the async call + documents = await retriever.ainvoke(query) + logger.info("Retrieved %d documents via MultiQueryRetriever", len(documents)) + + # Unpack LlamaIndex `_node_content` JSON if necessary + for doc in documents: + if doc.page_content and doc.page_content.startswith("{"): + try: + data = json.loads(doc.page_content) + if "text" in data: + doc.page_content = data["text"] + if "metadata" in data and isinstance(data["metadata"], dict): + doc.metadata.update(data["metadata"]) + except Exception: + pass + + # Rerank documents using Cohere + if documents: + # deduplicate by content to reduce cost and latency for reranker + seen = set() + unique_docs = [] + for d in documents: + if d.page_content not in seen: + unique_docs.append(d) + seen.add(d.page_content) + + # If we have too many docs, pre-filter to top N before reranking to save time + if len(unique_docs) > 25: + unique_docs = unique_docs[:25] + + documents = await rerank_documents(query=query, documents=unique_docs) + logger.info("Reranked to %d documents via Cohere", len(documents)) + + # Return only the top 5 + documents = documents[:5] + + except Exception as exc: + logger.error("Retrieval and reranking failed: %s", exc) + + return documents + + +def format_sources(documents: list[Document]) -> list[dict]: + """Extract source metadata from documents for the API response.""" + sources = [] + for i, doc in enumerate(documents): + meta = doc.metadata or {} + sources.append( + { + "rank": i + 1, + "score": float(meta.get("relevance_score", meta.get("score", 0.0))), + "file_name": meta.get("file_name", ""), + "url": ensure_pdf_url(meta.get("url", meta.get("page_id", ""))), + "text_preview": doc.page_content[:300], + } + ) + return sources diff --git a/app/app/routers/__init__.py b/app/app/routers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/app/routers/__pycache__/__init__.cpython-312.pyc b/app/app/routers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0bbbf97afa89148863b825badc42cd93ac4531e Binary files /dev/null and b/app/app/routers/__pycache__/__init__.cpython-312.pyc differ diff --git a/app/app/routers/__pycache__/__init__.cpython-313.pyc b/app/app/routers/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f39c576fee8f7faa595ff9f5e636c3019bfd2d2 Binary files /dev/null and b/app/app/routers/__pycache__/__init__.cpython-313.pyc differ diff --git a/app/app/routers/__pycache__/chat.cpython-312.pyc b/app/app/routers/__pycache__/chat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8dd3a714a2d2d95ac049c53e41ef6761df785e3e Binary files /dev/null and b/app/app/routers/__pycache__/chat.cpython-312.pyc differ diff --git a/app/app/routers/__pycache__/chat.cpython-313.pyc b/app/app/routers/__pycache__/chat.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a95f6071cee7c63537e6f9436f661f7c65345841 Binary files /dev/null and b/app/app/routers/__pycache__/chat.cpython-313.pyc differ diff --git a/app/app/routers/__pycache__/health.cpython-312.pyc b/app/app/routers/__pycache__/health.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f54bbe77ab497b4f38b66fd8e0fdc0ec0d7e0cbf Binary files /dev/null and b/app/app/routers/__pycache__/health.cpython-312.pyc differ diff --git a/app/app/routers/__pycache__/health.cpython-313.pyc b/app/app/routers/__pycache__/health.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b090ebc7649b36a2f13e04bd835814405534021a Binary files /dev/null and b/app/app/routers/__pycache__/health.cpython-313.pyc differ diff --git a/app/app/routers/__pycache__/ingest.cpython-312.pyc b/app/app/routers/__pycache__/ingest.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebd15931f2ec827e305ee219d6ccddbe9c5d5392 Binary files /dev/null and b/app/app/routers/__pycache__/ingest.cpython-312.pyc differ diff --git a/app/app/routers/__pycache__/ingest.cpython-313.pyc b/app/app/routers/__pycache__/ingest.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eaba656b999e8be3d4f48b7867d644bb679b0951 Binary files /dev/null and b/app/app/routers/__pycache__/ingest.cpython-313.pyc differ diff --git a/app/app/routers/__pycache__/sessions.cpython-312.pyc b/app/app/routers/__pycache__/sessions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..606c46709bdd07e32d540f54aff1ef4ba314875d Binary files /dev/null and b/app/app/routers/__pycache__/sessions.cpython-312.pyc differ diff --git a/app/app/routers/__pycache__/sessions.cpython-313.pyc b/app/app/routers/__pycache__/sessions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..231c39ab1acefe48cebb6a52b4e0005f1050b254 Binary files /dev/null and b/app/app/routers/__pycache__/sessions.cpython-313.pyc differ diff --git a/app/app/routers/__pycache__/stt.cpython-312.pyc b/app/app/routers/__pycache__/stt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06fb1f0e52187a3f7179f31f2141cd5bffe85fb5 Binary files /dev/null and b/app/app/routers/__pycache__/stt.cpython-312.pyc differ diff --git a/app/app/routers/__pycache__/stt.cpython-313.pyc b/app/app/routers/__pycache__/stt.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32cab6ba055c2d8522a313df2a68a439a667c145 Binary files /dev/null and b/app/app/routers/__pycache__/stt.cpython-313.pyc differ diff --git a/app/app/routers/chat.py b/app/app/routers/chat.py new file mode 100644 index 0000000000000000000000000000000000000000..8ff3859af4d8ea712519f31d525d2efd78112c41 --- /dev/null +++ b/app/app/routers/chat.py @@ -0,0 +1,222 @@ +import json +import logging +import uuid +from typing import AsyncIterator + +from fastapi import APIRouter, HTTPException +from fastapi.responses import StreamingResponse +from langchain_core.messages import HumanMessage + +from app.agent.graph import get_graph +from app.memory.session_store import get_or_create_session +from app.monitoring.langfuse_setup import get_langfuse_callback_handler +from app.schemas.chat import ChatRequest, ChatResponse, Source +from app.config import settings + +router = APIRouter(prefix="/api", tags=["chat"]) +logger = logging.getLogger(__name__) + + +def _build_initial_state(query: str, history_messages: list) -> dict: + """Build the initial AgentState for graph.invoke().""" + return { + "messages": history_messages + [HumanMessage(content=query)], + "query": query, + "retrieved_documents": [], + "relevant_documents": [], + "generation": "", + "sources": [], + "confidence": 0.0, + "retry_count": 0, + "route": "", + } + +@router.post("/chat", response_model=ChatResponse) +async def chat(request: ChatRequest): + """Main chat endpoint — runs the full agentic RAG pipeline.""" + session_id, buffer = get_or_create_session(request.session_id) + history = buffer.get_messages() + + # Create explicit trace to attach input and output directly + from app.monitoring.langfuse_setup import get_langfuse_client + langfuse_client = get_langfuse_client() + trace = None + handler = None + + if langfuse_client: + trace = langfuse_client.trace( + name="chat_pipeline", + session_id=session_id, + input={"message": request.message, "history": [m.content for m in history]}, + ) + handler = trace.get_langchain_handler() + + config = { + "callbacks": [handler] if handler else [], + "metadata": { + "session_id": session_id, + } + } + + try: + graph = get_graph() + initial_state = _build_initial_state(request.message, history) + result = await graph.ainvoke(initial_state, config=config) + except Exception as e: + logger.exception("Graph invocation error: %s", e) + if trace: + trace.update(level="ERROR", status_message=str(e)) + raise HTTPException(status_code=500, detail=f"Internal error: {str(e)}") + finally: + pass # Handle flush after we parse the result! + + answer = result.get("generation", settings.fallback_response) + sources_raw = result.get("sources", []) + confidence = float(result.get("confidence", 0.0)) + + # Log model token usage and update Langfuse trace + token_usage = {} + if "messages" in result and result["messages"]: + last_msg = result["messages"][-1] # Usually the AI response + if hasattr(last_msg, "response_metadata") and isinstance(last_msg.response_metadata, dict): + token_usage = last_msg.response_metadata.get("token_usage", {}) + if token_usage: + prompt_tokens = token_usage.get("prompt_tokens", 0) + completion_tokens = token_usage.get("completion_tokens", 0) + total_tokens = token_usage.get("total_tokens", 0) + logger.info(f"Model Token Expense -> Prompt: {prompt_tokens} | Completion: {completion_tokens} | Total: {total_tokens}") + + if trace: + trace.update( + output={"answer": answer, "confidence": confidence, "sources_count": len(sources_raw)}, + metadata={"token_usage": token_usage} if token_usage else {} + ) + langfuse_client.flush() + logger.info("Successfully saved Langfuse session. Trace URL: %s", trace.get_trace_url()) + + # Update session memory + buffer.add_user_message(request.message) + buffer.add_ai_message(answer) + + sources = [Source(**s) for s in sources_raw] + + return ChatResponse( + answer=answer, + sources=sources, + session_id=session_id, + confidence=confidence, + ) + + +@router.post("/chat/stream") +async def chat_stream(request: ChatRequest): + """SSE streaming chat endpoint — streams tokens as they are generated.""" + session_id, buffer = get_or_create_session(request.session_id) + history = buffer.get_messages() + + # Create explicit trace to attach input and output directly + from app.monitoring.langfuse_setup import get_langfuse_client + langfuse_client = get_langfuse_client() + trace = None + handler = None + + if langfuse_client: + trace = langfuse_client.trace( + name="chat_stream_pipeline", + session_id=session_id, + input={"message": request.message, "history": [m.content for m in history]}, + ) + handler = trace.get_langchain_handler() + + config = { + "callbacks": [handler] if handler else [], + "metadata": { + "session_id": session_id, + } + } + + async def event_generator() -> AsyncIterator[str]: + try: + graph = get_graph() + initial_state = _build_initial_state(request.message, history) + + # Stream events from the graph + final_answer = "" + final_sources = [] + final_confidence = 0.0 + token_usage = {} + + async for event in graph.astream_events(initial_state, config=config, version="v2"): + kind = event.get("event", "") + + # Stream LLM tokens ONLY from the generate node + if kind == "on_chat_model_stream": + langgraph_node = event.get("metadata", {}).get("langgraph_node", "") + if langgraph_node == "generate": + chunk = event.get("data", {}).get("chunk") + if chunk and hasattr(chunk, "content") and chunk.content: + token = chunk.content + final_answer += token + yield f"event: token\ndata: {json.dumps({'token': token})}\n\n" + + # Capture final state on graph completion + elif kind == "on_chain_end" and event.get("name") == "LangGraph": + output = event.get("data", {}).get("output", {}) + if isinstance(output, dict): + final_sources = output.get("sources", []) + final_confidence = float(output.get("confidence", 0.0)) + gen = output.get("generation", "") + if gen and not final_answer: + final_answer = gen + yield f"event: token\ndata: {json.dumps({'token': gen})}\n\n" + + # Capture token usage from the generate node when it completes + elif kind == "on_chat_model_end": + langgraph_node = event.get("metadata", {}).get("langgraph_node", "") + if langgraph_node == "generate": + response = event.get("data", {}).get("output") + if response and hasattr(response, "response_metadata"): + usage = response.response_metadata.get("token_usage", {}) + if usage: + token_usage = usage + + # Update session memory after full response + buffer.add_user_message(request.message) + buffer.add_ai_message(final_answer or settings.fallback_response) + + # Log model token usage + if token_usage: + prompt_tokens = token_usage.get("prompt_tokens", 0) + completion_tokens = token_usage.get("completion_tokens", 0) + total_tokens = token_usage.get("total_tokens", 0) + logger.info(f"Streaming Model Token Expense -> Prompt: {prompt_tokens} | Completion: {completion_tokens} | Total: {total_tokens}") + + if trace: + trace.update( + output={"answer": final_answer, "confidence": final_confidence, "sources_count": len(final_sources)}, + metadata={"token_usage": token_usage} if token_usage else {} + ) + + # Send sources and done events + yield f"event: sources\ndata: {json.dumps({'sources': final_sources})}\n\n" + yield f"event: done\ndata: {json.dumps({'session_id': session_id, 'confidence': final_confidence})}\n\n" + + except Exception as e: + logger.exception("Streaming error: %s", e) + if trace: + trace.update(level="ERROR", status_message=str(e)) + error_payload = json.dumps({"error": str(e)}) + yield f"event: error\ndata: {error_payload}\n\n" + finally: + if trace and langfuse_client: + langfuse_client.flush() + logger.info("Successfully saved Langfuse session (Streaming). Trace URL: %s", trace.get_trace_url()) + + return StreamingResponse( + event_generator(), + media_type="text/event-stream", + headers={ + "Cache-Control": "no-cache", + "X-Accel-Buffering": "no", + }, + ) \ No newline at end of file diff --git a/app/app/routers/health.py b/app/app/routers/health.py new file mode 100644 index 0000000000000000000000000000000000000000..ac6b1c3a397abf4d5482d070e4bb678eb65ca770 --- /dev/null +++ b/app/app/routers/health.py @@ -0,0 +1,75 @@ +import time +import logging +from fastapi import APIRouter +from app.schemas.health import HealthResponse, DetailedHealthResponse, ComponentStatus +from app.memory.session_store import active_session_count +from app.config import settings + +router = APIRouter(prefix="/api", tags=["health"]) +logger = logging.getLogger(__name__) + +_start_time = time.time() + + +@router.get("/health", response_model=HealthResponse) +async def health(): + """Basic health check.""" + from app.agent.graph import _compiled_graph + from app.retrieval.qdrant_store import _client + + return HealthResponse( + status="ok", + agent_ready=_compiled_graph is not None, + qdrant_connected=_client is not None, + active_sessions=active_session_count(), + ) + + +@router.get("/health/detailed", response_model=DetailedHealthResponse) +async def health_detailed(): + """Detailed per-component health check.""" + components: dict[str, ComponentStatus] = {} + + # Check Qdrant + try: + from app.retrieval.qdrant_store import get_qdrant_client + client = get_qdrant_client() + info = client.get_collection(settings.collection_name) + components["qdrant"] = ComponentStatus( + status="ok", + detail=f"collection={settings.collection_name}, points={info.points_count}", + ) + except Exception as e: + components["qdrant"] = ComponentStatus(status="error", detail=str(e)) + + # Check LLM provider (OpenRouter) + try: + from openai import OpenAI + c = OpenAI(api_key=settings.openai_api_key, base_url=settings.openai_api_base) + c.chat.completions.create( + model=settings.llm_model, + messages=[{"role": "user", "content": "ping"}], + max_tokens=1, + ) + components["llm"] = ComponentStatus(status="ok", detail=f"model={settings.llm_model}") + except Exception as e: + components["llm"] = ComponentStatus(status="error", detail=str(e)) + + # Sarvam (just check key is configured) + components["sarvam"] = ComponentStatus( + status="ok" if settings.sarvam_api_key else "unconfigured", + ) + + # Langfuse (check key is configured) + components["langfuse"] = ComponentStatus( + status="ok" if settings.langfuse_public_key else "unconfigured", + ) + + all_ok = all(c.status == "ok" for c in components.values()) + + return DetailedHealthResponse( + status="ok" if all_ok else "degraded", + components=components, + uptime_seconds=time.time() - _start_time, + active_sessions=active_session_count(), + ) diff --git a/app/app/routers/ingest.py b/app/app/routers/ingest.py new file mode 100644 index 0000000000000000000000000000000000000000..1767a80962eb838fa973ce3d86e96c18e9d30d4e --- /dev/null +++ b/app/app/routers/ingest.py @@ -0,0 +1,78 @@ +import logging +from pathlib import Path +from fastapi import APIRouter, HTTPException, Header +from app.retrieval.ingestion import ingest_file, ingest_directory +from app.schemas.ingest import IngestFileRequest, IngestDirectoryRequest, IngestResponse +from app.config import settings + +router = APIRouter(prefix="/api/ingest", tags=["ingest"]) +logger = logging.getLogger(__name__) + + +def _verify_ingest_key(x_api_key: str | None) -> None: + """Protect ingest endpoints with an API key if configured.""" + if settings.ingest_api_key and x_api_key != settings.ingest_api_key: + raise HTTPException(status_code=401, detail="Invalid or missing ingest API key.") + + +def _validate_path(path_str: str) -> Path: + """Validate that a path is within the allowed base directory.""" + resolved = Path(path_str).resolve() + + # If a base dir is configured, enforce it + if settings.ingest_base_dir: + base = Path(settings.ingest_base_dir).resolve() + if not str(resolved).startswith(str(base)): + raise HTTPException( + status_code=403, + detail="Path is outside the allowed ingestion directory.", + ) + + if not resolved.exists(): + raise HTTPException(status_code=404, detail=f"Path not found: {path_str}") + + return resolved + + +@router.post("/file", response_model=IngestResponse) +async def ingest_single_file( + request: IngestFileRequest, + x_api_key: str | None = Header(default=None), +): + _verify_ingest_key(x_api_key) + validated_path = _validate_path(request.file_path) + try: + chunks = ingest_file(str(validated_path)) + return IngestResponse(success=True, total_documents=1, total_chunks=chunks) + except Exception as e: + logger.error("Ingest file error: %s", e) + raise HTTPException(status_code=500, detail=str(e)) + + +@router.post("/directory", response_model=IngestResponse) +async def ingest_dir( + request: IngestDirectoryRequest, + x_api_key: str | None = Header(default=None), +): + _verify_ingest_key(x_api_key) + validated_path = _validate_path(request.directory_path) + try: + result = ingest_directory(str(validated_path), recursive=request.recursive) + return IngestResponse(success=True, **result) + except Exception as e: + logger.error("Ingest directory error: %s", e) + raise HTTPException(status_code=500, detail=str(e)) + + +@router.post("/reset", response_model=IngestResponse) +async def reset(x_api_key: str | None = Header(default=None)): + _verify_ingest_key(x_api_key) + try: + return IngestResponse( + success=True, + message=f"Collection '{settings.collection_name}' reset successfully.", + ) + except Exception as e: + logger.error("Reset error: %s", e) + raise HTTPException(status_code=500, detail=str(e)) + diff --git a/app/app/routers/sessions.py b/app/app/routers/sessions.py new file mode 100644 index 0000000000000000000000000000000000000000..e1bf3274cc4cd8a7c52493d61304e84b1123700e --- /dev/null +++ b/app/app/routers/sessions.py @@ -0,0 +1,13 @@ +from fastapi import APIRouter, HTTPException +from app.memory.session_store import delete_session + +router = APIRouter(prefix="/api/sessions", tags=["sessions"]) + + +@router.delete("/{session_id}") +async def clear_session(session_id: str): + """Clear conversation history for a session.""" + deleted = delete_session(session_id) + if not deleted: + raise HTTPException(status_code=404, detail="Session not found.") + return {"success": True, "message": "Session cleared."} diff --git a/app/app/routers/stt.py b/app/app/routers/stt.py new file mode 100644 index 0000000000000000000000000000000000000000..87a0a2acfbd0ece149f1e39486a37ed89029dd0c --- /dev/null +++ b/app/app/routers/stt.py @@ -0,0 +1,39 @@ +import logging +from fastapi import APIRouter, File, Form, UploadFile, HTTPException +from app.stt.sarvam_client import transcribe_audio, MAX_AUDIO_SIZE_BYTES +from app.schemas.stt import TranscribeResponse + +router = APIRouter(prefix="/api/stt", tags=["stt"]) +logger = logging.getLogger(__name__) + + +@router.post("/transcribe", response_model=TranscribeResponse) +async def transcribe( + audio: UploadFile = File(..., description="Audio file (WebM/Opus, WAV, or MP3)"), + language: str = Form(default="gu-In", description="Language hint: gu-In, hi-In, en-In"), +): + """Receive audio from browser, transcribe via Sarvam AI Saaras v3.""" + audio_bytes = await audio.read() + + if not audio_bytes: + raise HTTPException(status_code=400, detail="No audio data received.") + + if len(audio_bytes) > MAX_AUDIO_SIZE_BYTES: + raise HTTPException( + status_code=413, + detail=f"Audio file too large (max {MAX_AUDIO_SIZE_BYTES // 1024 // 1024} MB).", + ) + + try: + result = await transcribe_audio(audio_bytes=audio_bytes, language=language) + except Exception as e: + logger.error("STT transcription error: %s", e) + raise HTTPException(status_code=502, detail=f"Sarvam AI API error: {str(e)}") + + if not result.get("transcript"): + raise HTTPException(status_code=422, detail="Could not transcribe audio. Please try again.") + + return TranscribeResponse( + transcript=result["transcript"], + language_detected=result.get("language_detected"), + ) diff --git a/app/app/schemas/__init__.py b/app/app/schemas/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/app/schemas/__pycache__/__init__.cpython-312.pyc b/app/app/schemas/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13f058c0e8da5c5261ac1d9599d7e4e4e11d31f9 Binary files /dev/null and b/app/app/schemas/__pycache__/__init__.cpython-312.pyc differ diff --git a/app/app/schemas/__pycache__/__init__.cpython-313.pyc b/app/app/schemas/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e1bca12ad0ed64b54f2897c8a28cc60ffb8216a Binary files /dev/null and b/app/app/schemas/__pycache__/__init__.cpython-313.pyc differ diff --git a/app/app/schemas/__pycache__/chat.cpython-312.pyc b/app/app/schemas/__pycache__/chat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02c494e7f7c2a0680625dc030e591edc50cf2a0c Binary files /dev/null and b/app/app/schemas/__pycache__/chat.cpython-312.pyc differ diff --git a/app/app/schemas/__pycache__/chat.cpython-313.pyc b/app/app/schemas/__pycache__/chat.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b4d2248930c6c176e1a65676826db7277f2b18c Binary files /dev/null and b/app/app/schemas/__pycache__/chat.cpython-313.pyc differ diff --git a/app/app/schemas/__pycache__/health.cpython-312.pyc b/app/app/schemas/__pycache__/health.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd60b6f8dfc4bb65c8f36e7ab4467815dddb82e0 Binary files /dev/null and b/app/app/schemas/__pycache__/health.cpython-312.pyc differ diff --git a/app/app/schemas/__pycache__/health.cpython-313.pyc b/app/app/schemas/__pycache__/health.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50f1284086ec2e10fb01248b1674eafda219d55c Binary files /dev/null and b/app/app/schemas/__pycache__/health.cpython-313.pyc differ diff --git a/app/app/schemas/__pycache__/ingest.cpython-312.pyc b/app/app/schemas/__pycache__/ingest.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4f89f9ceea49a827c4888c5893c98fff3cae65a Binary files /dev/null and b/app/app/schemas/__pycache__/ingest.cpython-312.pyc differ diff --git a/app/app/schemas/__pycache__/ingest.cpython-313.pyc b/app/app/schemas/__pycache__/ingest.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26cbcbb8139849301514dbfe9eb325c58f95ec41 Binary files /dev/null and b/app/app/schemas/__pycache__/ingest.cpython-313.pyc differ diff --git a/app/app/schemas/__pycache__/stt.cpython-312.pyc b/app/app/schemas/__pycache__/stt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27ac9cd38272d0f03363753729075b5dadf737fc Binary files /dev/null and b/app/app/schemas/__pycache__/stt.cpython-312.pyc differ diff --git a/app/app/schemas/__pycache__/stt.cpython-313.pyc b/app/app/schemas/__pycache__/stt.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5b678cc3fe732e32b37d8dd7c4dca953fa7a352 Binary files /dev/null and b/app/app/schemas/__pycache__/stt.cpython-313.pyc differ diff --git a/app/app/schemas/chat.py b/app/app/schemas/chat.py new file mode 100644 index 0000000000000000000000000000000000000000..b201d422119e2254c89cae560fa16d6e16d0779e --- /dev/null +++ b/app/app/schemas/chat.py @@ -0,0 +1,23 @@ +from pydantic import BaseModel, Field +from typing import Optional + + +class Source(BaseModel): + rank: int + score: float + file_name: str + url: str + text_preview: str + + +class ChatRequest(BaseModel): + message: str = Field(..., min_length=1, max_length=2000) + session_id: Optional[str] = None + + +class ChatResponse(BaseModel): + answer: str + sources: list[Source] + session_id: str + confidence: float + trace_id: Optional[str] = None diff --git a/app/app/schemas/health.py b/app/app/schemas/health.py new file mode 100644 index 0000000000000000000000000000000000000000..e4fc10c5bcc7e6d971b9505d43d6553b4febd54f --- /dev/null +++ b/app/app/schemas/health.py @@ -0,0 +1,21 @@ +from pydantic import BaseModel +from typing import Optional + + +class ComponentStatus(BaseModel): + status: str + detail: Optional[str] = None + + +class HealthResponse(BaseModel): + status: str + agent_ready: bool = False + qdrant_connected: bool = False + active_sessions: int = 0 + + +class DetailedHealthResponse(BaseModel): + status: str + components: dict[str, ComponentStatus] + uptime_seconds: float + active_sessions: int diff --git a/app/app/schemas/ingest.py b/app/app/schemas/ingest.py new file mode 100644 index 0000000000000000000000000000000000000000..1ccc3402d50c42c98d55a5724184bfbb4cca326e --- /dev/null +++ b/app/app/schemas/ingest.py @@ -0,0 +1,17 @@ +from pydantic import BaseModel + + +class IngestFileRequest(BaseModel): + file_path: str + + +class IngestDirectoryRequest(BaseModel): + directory_path: str + recursive: bool = True + + +class IngestResponse(BaseModel): + success: bool + message: str = "" + total_documents: int = 0 + total_chunks: int = 0 diff --git a/app/app/schemas/stt.py b/app/app/schemas/stt.py new file mode 100644 index 0000000000000000000000000000000000000000..ddaa928f2889171202b4a9d5a271a926dd87e591 --- /dev/null +++ b/app/app/schemas/stt.py @@ -0,0 +1,8 @@ +from pydantic import BaseModel +from typing import Optional + + +class TranscribeResponse(BaseModel): + transcript: str + language_detected: Optional[str] = None + duration_seconds: Optional[float] = None diff --git a/app/app/stt/__init__.py b/app/app/stt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/app/stt/__pycache__/__init__.cpython-312.pyc b/app/app/stt/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe50793a1a54e0d732ce96ef566b16600099ce8f Binary files /dev/null and b/app/app/stt/__pycache__/__init__.cpython-312.pyc differ diff --git a/app/app/stt/__pycache__/__init__.cpython-313.pyc b/app/app/stt/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5956589e1f6be78b011daa1ea82c4843c71e8eb7 Binary files /dev/null and b/app/app/stt/__pycache__/__init__.cpython-313.pyc differ diff --git a/app/app/stt/__pycache__/sarvam_client.cpython-312.pyc b/app/app/stt/__pycache__/sarvam_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec4c972a9af47bb4d651045c340ecb96ae216f5e Binary files /dev/null and b/app/app/stt/__pycache__/sarvam_client.cpython-312.pyc differ diff --git a/app/app/stt/__pycache__/sarvam_client.cpython-313.pyc b/app/app/stt/__pycache__/sarvam_client.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..814f4e7f00ccb7e1431ead94f2c49eac12102006 Binary files /dev/null and b/app/app/stt/__pycache__/sarvam_client.cpython-313.pyc differ diff --git a/app/app/stt/sarvam_client.py b/app/app/stt/sarvam_client.py new file mode 100644 index 0000000000000000000000000000000000000000..e8864c8786f36f23b385595160029625a2978e9b --- /dev/null +++ b/app/app/stt/sarvam_client.py @@ -0,0 +1,61 @@ +import logging +import httpx +from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type +from app.config import settings + +logger = logging.getLogger(__name__) + +MAX_AUDIO_SIZE_BYTES = 10 * 1024 * 1024 # 10 MB + + +@retry( + stop=stop_after_attempt(3), + wait=wait_exponential(multiplier=1, min=1, max=5), + retry=retry_if_exception_type(httpx.HTTPStatusError), + reraise=True, +) +async def transcribe_audio(audio_bytes: bytes, language: str = "gu-In") -> dict: + """ + Send audio to Sarvam AI Saaras v3 API and return the transcript. + + Args: + audio_bytes: Raw audio bytes (WebM/Opus from MediaRecorder). + language: Language hint (e.g. 'gu-In', 'hi-In', 'en-In'). + + Returns: + dict with 'transcript' and 'language_detected' keys. + """ + if len(audio_bytes) > MAX_AUDIO_SIZE_BYTES: + raise ValueError(f"Audio file too large: {len(audio_bytes)} bytes (max {MAX_AUDIO_SIZE_BYTES})") + + async with httpx.AsyncClient(timeout=30.0) as client: + response = await client.post( + settings.sarvam_api_url, + headers={"api-subscription-key": settings.sarvam_api_key}, + files={"file": ("audio.webm", audio_bytes, "audio/webm")}, + data={ + "model": "saaras:v3", + "mode": "transcribe", + "language_code": language, + }, + ) + + if response.status_code == 400: + logger.warning("Sarvam API 400: %s", response.text) + raise httpx.HTTPStatusError( + f"Sarvam API error: {response.text}", + request=response.request, + response=response, + ) + + response.raise_for_status() + result = response.json() + + transcript = result.get("transcript", "") + lang_detected = result.get("language_code", language) + + logger.info("Sarvam STT: '%s...' (lang=%s)", transcript[:60], lang_detected) + return { + "transcript": transcript, + "language_detected": lang_detected, + } diff --git a/app/app/utils/__init__.py b/app/app/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/app/utils/__pycache__/__init__.cpython-312.pyc b/app/app/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9db128b17f18f39d5c72126bcc01a4e3bc8f004e Binary files /dev/null and b/app/app/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/app/app/utils/__pycache__/__init__.cpython-313.pyc b/app/app/utils/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..454fcb31b733748137ef3f594122b103ef76a43a Binary files /dev/null and b/app/app/utils/__pycache__/__init__.cpython-313.pyc differ diff --git a/app/app/utils/__pycache__/__init__.cpython-314.pyc b/app/app/utils/__pycache__/__init__.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25198f9ac8f11ad5c8820dcb9023ce098a0d4a3e Binary files /dev/null and b/app/app/utils/__pycache__/__init__.cpython-314.pyc differ diff --git a/app/app/utils/__pycache__/llm_helpers.cpython-312.pyc b/app/app/utils/__pycache__/llm_helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f8180e17918e5f91bf24af551b33b26a171d153 Binary files /dev/null and b/app/app/utils/__pycache__/llm_helpers.cpython-312.pyc differ diff --git a/app/app/utils/__pycache__/llm_helpers.cpython-313.pyc b/app/app/utils/__pycache__/llm_helpers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f9b80acd3aedc6123b6679252ee68b8ee5c052a Binary files /dev/null and b/app/app/utils/__pycache__/llm_helpers.cpython-313.pyc differ diff --git a/app/app/utils/__pycache__/llm_helpers.cpython-314.pyc b/app/app/utils/__pycache__/llm_helpers.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07a7efc675259ccd3cb8103e187f0353189d6a1b Binary files /dev/null and b/app/app/utils/__pycache__/llm_helpers.cpython-314.pyc differ diff --git a/app/app/utils/__pycache__/token_counter.cpython-312.pyc b/app/app/utils/__pycache__/token_counter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..119e9ce8de21c5c578b1b4895be9ac6a6187846e Binary files /dev/null and b/app/app/utils/__pycache__/token_counter.cpython-312.pyc differ diff --git a/app/app/utils/__pycache__/token_counter.cpython-313.pyc b/app/app/utils/__pycache__/token_counter.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0db6ac47901b48617396c83f4bcd6b4288290afe Binary files /dev/null and b/app/app/utils/__pycache__/token_counter.cpython-313.pyc differ diff --git a/app/app/utils/llm_helpers.py b/app/app/utils/llm_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..07bebce6d271ce5805ddc743878aeb7868de122d --- /dev/null +++ b/app/app/utils/llm_helpers.py @@ -0,0 +1,58 @@ +""" +Shared LLM helper utilities used by both agent nodes and guardrails. +""" +import json +import logging + +from langchain_openai import ChatOpenAI +from app.config import settings + +logger = logging.getLogger(__name__) + + +def get_llm(temperature: float = 1.0, model: str = None) -> ChatOpenAI: + """Create a ChatOpenAI instance with standard ACPC Chatbot headers.""" + # Set this to True to test using the Groq API key and settings provided + # Set to False to use the standard OpenRouter .env configuration + USE_GROQ_TESTING = False + + if USE_GROQ_TESTING: + return ChatOpenAI( + model="openai/gpt-oss-120b", + api_key="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", + base_url="https://api.groq.com/openai/v1", + temperature=1.0, + max_completion_tokens=2048, # Reduced from 8192 to fit within the 8000 TPM limit + top_p=1, + reasoning_effort="medium", + default_headers={ + "HTTP-Referer": "https://acpc.gujarat.gov.in", + "X-Title": "ACPC Chatbot", + }, + ) + else: + return ChatOpenAI( + model=model or settings.llm_model, + api_key=settings.openai_api_key, + base_url=settings.openai_api_base, + temperature=temperature, + reasoning_effort="medium", + max_tokens=2048, + default_headers={ + "HTTP-Referer": "https://acpc.gujarat.gov.in", + "X-Title": "ACPC Chatbot", + }, + ) + + +def safe_parse_json(content: str, default_key: str = None) -> dict: + """Safely parse JSON response with fallback handling.""" + try: + result = json.loads(content.strip()) + if not isinstance(result, dict): + logger.warning("JSON response is not a dict: %s", type(result)) + return {} if default_key is None else {default_key: None} + return result + except json.JSONDecodeError as e: + logger.warning("JSON parse error: %s on content: %s", e, content[:100]) + return {} if default_key is None else {default_key: None} diff --git a/app/app/utils/text_cleaning.py b/app/app/utils/text_cleaning.py new file mode 100644 index 0000000000000000000000000000000000000000..90afd48adf59a2d839435c0cbaf94448242e324f --- /dev/null +++ b/app/app/utils/text_cleaning.py @@ -0,0 +1,13 @@ +import re + + +def clean_pdf_text(text: str) -> str: + """Normalize text extracted from PDF chunks.""" + # Collapse multiple whitespace into single space + text = re.sub(r"[ \t]+", " ", text) + # Collapse more than 2 consecutive newlines + text = re.sub(r"\n{3,}", "\n\n", text) + # Remove null bytes and control characters (except newlines/tabs) + text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", "", text) + return text.strip() + \ No newline at end of file diff --git a/app/app/utils/token_counter.py b/app/app/utils/token_counter.py new file mode 100644 index 0000000000000000000000000000000000000000..f39a655a4e789a48ef9aa7d19bad68cdde0df286 --- /dev/null +++ b/app/app/utils/token_counter.py @@ -0,0 +1,19 @@ +import tiktoken + +# gpt-4o uses o200k_base encoding +_encoder = tiktoken.get_encoding("o200k_base") + + +def count_tokens(text: str) -> int: + """Count tokens in a string using gpt-4o's tokenizer.""" + return len(_encoder.encode(text)) + + +def count_messages_tokens(messages: list) -> int: + """Count total tokens across a list of LangChain BaseMessage objects.""" + total = 0 + for msg in messages: + content = msg.content if hasattr(msg, "content") else str(msg) + total += count_tokens(content) + total += 4 # overhead per message (role + formatting) + return total