Upload 131 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .dockerignore +22 -0
- Dockerfile +39 -0
- app/__init__.py +0 -0
- app/__pycache__/__init__.cpython-312.pyc +0 -0
- app/__pycache__/__init__.cpython-313.pyc +0 -0
- app/__pycache__/__init__.cpython-314.pyc +0 -0
- app/__pycache__/config.cpython-312.pyc +0 -0
- app/__pycache__/config.cpython-313.pyc +0 -0
- app/__pycache__/main.cpython-312.pyc +0 -0
- app/__pycache__/main.cpython-313.pyc +0 -0
- app/agent/__init__.py +0 -0
- app/agent/__pycache__/__init__.cpython-312.pyc +0 -0
- app/agent/__pycache__/__init__.cpython-313.pyc +0 -0
- app/agent/__pycache__/graph.cpython-312.pyc +0 -0
- app/agent/__pycache__/graph.cpython-313.pyc +0 -0
- app/agent/__pycache__/graph.cpython-314.pyc +0 -0
- app/agent/__pycache__/nodes.cpython-312.pyc +0 -0
- app/agent/__pycache__/nodes.cpython-313.pyc +0 -0
- app/agent/__pycache__/nodes.cpython-314.pyc +0 -0
- app/agent/__pycache__/prompts.cpython-312.pyc +0 -0
- app/agent/__pycache__/prompts.cpython-313.pyc +0 -0
- app/agent/__pycache__/state.cpython-312.pyc +0 -0
- app/agent/__pycache__/state.cpython-313.pyc +0 -0
- app/agent/graph.py +49 -0
- app/agent/nodes.py +118 -0
- app/agent/prompts.py +33 -0
- app/agent/state.py +26 -0
- app/config.py +89 -0
- app/dependencies.py +7 -0
- app/guardrails/__init__.py +13 -0
- app/guardrails/__pycache__/__init__.cpython-312.pyc +0 -0
- app/guardrails/__pycache__/__init__.cpython-313.pyc +0 -0
- app/guardrails/__pycache__/__init__.cpython-314.pyc +0 -0
- app/guardrails/__pycache__/hallucination_checker.cpython-312.pyc +0 -0
- app/guardrails/__pycache__/hallucination_checker.cpython-313.pyc +0 -0
- app/guardrails/__pycache__/hallucination_checker.cpython-314.pyc +0 -0
- app/guardrails/__pycache__/intent_classifier.cpython-312.pyc +0 -0
- app/guardrails/__pycache__/intent_classifier.cpython-313.pyc +0 -0
- app/guardrails/__pycache__/intent_classifier.cpython-314.pyc +0 -0
- app/guardrails/__pycache__/relevance_grader.cpython-312.pyc +0 -0
- app/guardrails/__pycache__/relevance_grader.cpython-313.pyc +0 -0
- app/guardrails/__pycache__/relevance_grader.cpython-314.pyc +0 -0
- app/guardrails/intent_classifier.py +80 -0
- app/main.py +67 -0
- app/memory/__init__.py +0 -0
- app/memory/__pycache__/__init__.cpython-312.pyc +0 -0
- app/memory/__pycache__/__init__.cpython-313.pyc +0 -0
- app/memory/__pycache__/conversation_buffer.cpython-312.pyc +0 -0
- app/memory/__pycache__/conversation_buffer.cpython-313.pyc +0 -0
- app/memory/__pycache__/session_store.cpython-312.pyc +0 -0
.dockerignore
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.venv
|
| 2 |
+
__pycache__
|
| 3 |
+
*.pyc
|
| 4 |
+
*.pyo
|
| 5 |
+
*.pyd
|
| 6 |
+
.Python
|
| 7 |
+
env/
|
| 8 |
+
venv/
|
| 9 |
+
ENV/
|
| 10 |
+
env.bak/
|
| 11 |
+
venv.bak/
|
| 12 |
+
.env
|
| 13 |
+
.git
|
| 14 |
+
.gitignore
|
| 15 |
+
.llamaindex_storage
|
| 16 |
+
evaluation/
|
| 17 |
+
tests/
|
| 18 |
+
payload.json
|
| 19 |
+
Dockerfile
|
| 20 |
+
.dockerignore
|
| 21 |
+
uv.lock
|
| 22 |
+
pyproject.toml
|
Dockerfile
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Stage 1: Build dependencies
|
| 2 |
+
FROM ghcr.io/astral-sh/uv:python3.11-slim AS builder
|
| 3 |
+
|
| 4 |
+
# Enable bytecode compilation and use copy instead of hardlinks
|
| 5 |
+
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
|
| 6 |
+
|
| 7 |
+
WORKDIR /app
|
| 8 |
+
|
| 9 |
+
# Copy configuration files
|
| 10 |
+
COPY pyproject.toml uv.lock ./
|
| 11 |
+
|
| 12 |
+
# Install dependencies into a virtual environment
|
| 13 |
+
RUN uv sync --frozen --no-dev
|
| 14 |
+
|
| 15 |
+
# Stage 2: Runtime
|
| 16 |
+
FROM python:3.11-slim AS runtime
|
| 17 |
+
|
| 18 |
+
WORKDIR /app
|
| 19 |
+
|
| 20 |
+
# Copy the virtual environment from the builder
|
| 21 |
+
COPY --from=builder /app/.venv /app/.venv
|
| 22 |
+
|
| 23 |
+
# Ensure the virtual environment is in the PATH
|
| 24 |
+
ENV PATH="/app/.venv/bin:$PATH"
|
| 25 |
+
|
| 26 |
+
# Create non-root user for security
|
| 27 |
+
# Hugging Face Spaces uses UID 1000
|
| 28 |
+
RUN useradd -m -u 1000 appuser
|
| 29 |
+
|
| 30 |
+
# Copy application code
|
| 31 |
+
COPY app/ ./app/
|
| 32 |
+
|
| 33 |
+
# Switch to non-root user
|
| 34 |
+
USER appuser
|
| 35 |
+
|
| 36 |
+
EXPOSE 7860
|
| 37 |
+
|
| 38 |
+
# Run the application using uvicorn from the virtual environment
|
| 39 |
+
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "2"]
|
app/__init__.py
ADDED
|
File without changes
|
app/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (178 Bytes). View file
|
|
|
app/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (178 Bytes). View file
|
|
|
app/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (180 Bytes). View file
|
|
|
app/__pycache__/config.cpython-312.pyc
ADDED
|
Binary file (4.33 kB). View file
|
|
|
app/__pycache__/config.cpython-313.pyc
ADDED
|
Binary file (4.16 kB). View file
|
|
|
app/__pycache__/main.cpython-312.pyc
ADDED
|
Binary file (2.73 kB). View file
|
|
|
app/__pycache__/main.cpython-313.pyc
ADDED
|
Binary file (2.74 kB). View file
|
|
|
app/agent/__init__.py
ADDED
|
File without changes
|
app/agent/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (184 Bytes). View file
|
|
|
app/agent/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (184 Bytes). View file
|
|
|
app/agent/__pycache__/graph.cpython-312.pyc
ADDED
|
Binary file (1.67 kB). View file
|
|
|
app/agent/__pycache__/graph.cpython-313.pyc
ADDED
|
Binary file (2.71 kB). View file
|
|
|
app/agent/__pycache__/graph.cpython-314.pyc
ADDED
|
Binary file (2.39 kB). View file
|
|
|
app/agent/__pycache__/nodes.cpython-312.pyc
ADDED
|
Binary file (5.2 kB). View file
|
|
|
app/agent/__pycache__/nodes.cpython-313.pyc
ADDED
|
Binary file (8.2 kB). View file
|
|
|
app/agent/__pycache__/nodes.cpython-314.pyc
ADDED
|
Binary file (9.72 kB). View file
|
|
|
app/agent/__pycache__/prompts.cpython-312.pyc
ADDED
|
Binary file (2 kB). View file
|
|
|
app/agent/__pycache__/prompts.cpython-313.pyc
ADDED
|
Binary file (5.52 kB). View file
|
|
|
app/agent/__pycache__/state.cpython-312.pyc
ADDED
|
Binary file (1.01 kB). View file
|
|
|
app/agent/__pycache__/state.cpython-313.pyc
ADDED
|
Binary file (1.07 kB). View file
|
|
|
app/agent/graph.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
LangGraph StateGraph definition for the Agentic RAG pipeline.
|
| 3 |
+
"""
|
| 4 |
+
import threading
|
| 5 |
+
from langgraph.graph import StateGraph, END, START
|
| 6 |
+
|
| 7 |
+
from app.agent.state import AgentState
|
| 8 |
+
from app.agent.nodes import (
|
| 9 |
+
retrieve,
|
| 10 |
+
generate,
|
| 11 |
+
respond,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
_compiled_graph = None
|
| 15 |
+
_graph_lock = threading.Lock()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def build_graph():
|
| 19 |
+
"""Build and compile the LangGraph agent graph."""
|
| 20 |
+
graph = StateGraph(AgentState)
|
| 21 |
+
|
| 22 |
+
# Register all nodes
|
| 23 |
+
graph.add_node("retrieve", retrieve)
|
| 24 |
+
graph.add_node("generate", generate)
|
| 25 |
+
graph.add_node("respond", respond)
|
| 26 |
+
|
| 27 |
+
# Entry point
|
| 28 |
+
graph.add_edge(START, "retrieve")
|
| 29 |
+
|
| 30 |
+
# After retrieval: go directly to generation
|
| 31 |
+
graph.add_edge("retrieve", "generate")
|
| 32 |
+
|
| 33 |
+
# After generation: straight to respond
|
| 34 |
+
graph.add_edge("generate", "respond")
|
| 35 |
+
|
| 36 |
+
# Terminal nodes
|
| 37 |
+
graph.add_edge("respond", END)
|
| 38 |
+
|
| 39 |
+
return graph.compile()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def get_graph():
|
| 43 |
+
"""Return the singleton compiled graph."""
|
| 44 |
+
global _compiled_graph
|
| 45 |
+
if _compiled_graph is None:
|
| 46 |
+
with _graph_lock:
|
| 47 |
+
if _compiled_graph is None:
|
| 48 |
+
_compiled_graph = build_graph()
|
| 49 |
+
return _compiled_graph
|
app/agent/nodes.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
LangGraph node functions for the Agentic RAG pipeline.
|
| 3 |
+
Each node receives AgentState and returns a partial state update.
|
| 4 |
+
|
| 5 |
+
Guardrail logic (intent classification, relevance grading, hallucination checking)
|
| 6 |
+
lives in app/guardrails/ — nodes here are thin wrappers that call those modules.
|
| 7 |
+
"""
|
| 8 |
+
import logging
|
| 9 |
+
|
| 10 |
+
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
|
| 11 |
+
|
| 12 |
+
from app.agent.state import AgentState
|
| 13 |
+
from app.agent.prompts import (
|
| 14 |
+
SYSTEM_PROMPT,
|
| 15 |
+
GENERATION_PROMPT,
|
| 16 |
+
)
|
| 17 |
+
from app.guardrails import classify_query
|
| 18 |
+
from app.utils.llm_helpers import get_llm
|
| 19 |
+
from app.retrieval.retriever import retrieve_and_rerank, format_sources
|
| 20 |
+
from app.config import settings
|
| 21 |
+
|
| 22 |
+
logger = logging.getLogger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# ──────────────────────────────────────────────
|
| 26 |
+
# Guardrail wrapper nodes
|
| 27 |
+
# ──────────────────────────────────────────────
|
| 28 |
+
|
| 29 |
+
def classify_intent(state: AgentState) -> dict:
|
| 30 |
+
"""Node: Classify whether the query is ACPC-related, off-topic, or injection.
|
| 31 |
+
|
| 32 |
+
Delegates to app.guardrails.intent_classifier.
|
| 33 |
+
Only ACPC_RELATED queries proceed; everything else → fallback.
|
| 34 |
+
"""
|
| 35 |
+
query = state.get("query", "").strip()
|
| 36 |
+
result = classify_query(query)
|
| 37 |
+
logger.info(
|
| 38 |
+
"classify_intent: classification=%s, route=%s, blocked=%s",
|
| 39 |
+
result["classification"], result["route"], result["blocked_reason"],
|
| 40 |
+
)
|
| 41 |
+
return {"route": result["route"]}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# ──────────────────────────────────────────────
|
| 46 |
+
# Core pipeline nodes
|
| 47 |
+
# ──────────────────────────────────────────────
|
| 48 |
+
|
| 49 |
+
def retrieve(state: AgentState) -> dict:
|
| 50 |
+
"""Node: Retrieve documents from Qdrant using hybrid search + Cohere rerank."""
|
| 51 |
+
query = state["query"]
|
| 52 |
+
logger.info("Retrieving documents for query: %s", query[:80])
|
| 53 |
+
|
| 54 |
+
documents = retrieve_and_rerank(query)
|
| 55 |
+
logger.info("Retrieved %d documents", len(documents))
|
| 56 |
+
return {"retrieved_documents": documents}
|
| 57 |
+
|
| 58 |
+
def generate(state: AgentState) -> dict:
|
| 59 |
+
"""Node: Generate an answer from relevant documents."""
|
| 60 |
+
query = state["query"]
|
| 61 |
+
relevant_docs = state.get("retrieved_documents", [])
|
| 62 |
+
history = state.get("messages", [])
|
| 63 |
+
|
| 64 |
+
# Build context string from relevant documents
|
| 65 |
+
context_parts = []
|
| 66 |
+
for i, doc in enumerate(relevant_docs):
|
| 67 |
+
meta = doc.metadata or {}
|
| 68 |
+
url = meta.get("url", "")
|
| 69 |
+
source_line = f"[Source {i+1}: {meta.get('file_name', 'unknown')}]"
|
| 70 |
+
if url:
|
| 71 |
+
source_line += f" {url}"
|
| 72 |
+
context_parts.append(f"{source_line}\n{doc.page_content}")
|
| 73 |
+
context = "\n\n---\n\n".join(context_parts)
|
| 74 |
+
|
| 75 |
+
generation_content = GENERATION_PROMPT.format(context=context, question=query)
|
| 76 |
+
|
| 77 |
+
# Build messages: system + trimmed history + current generation prompt
|
| 78 |
+
messages = [SystemMessage(content=SYSTEM_PROMPT)]
|
| 79 |
+
for msg in history[:-1]: # Skip last (current user message)
|
| 80 |
+
messages.append(msg)
|
| 81 |
+
messages.append(HumanMessage(content=generation_content))
|
| 82 |
+
|
| 83 |
+
llm = get_llm(temperature=0.2)
|
| 84 |
+
response = llm.invoke(messages)
|
| 85 |
+
generation = response.content.strip()
|
| 86 |
+
|
| 87 |
+
sources = format_sources(relevant_docs)
|
| 88 |
+
logger.info("Generation complete (%d chars, %d sources)", len(generation), len(sources))
|
| 89 |
+
return {"generation": generation, "sources": sources}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# ──────────────────────────────────────────────
|
| 93 |
+
# Terminal nodes
|
| 94 |
+
# ──────────────────────────────────────────────
|
| 95 |
+
|
| 96 |
+
def fallback(state: AgentState) -> dict:
|
| 97 |
+
"""Node: Return the hardcoded fallback response (never LLM-generated)."""
|
| 98 |
+
return {
|
| 99 |
+
"generation": settings.fallback_response,
|
| 100 |
+
"sources": [],
|
| 101 |
+
"confidence": 0.0,
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def respond(state: AgentState) -> dict:
|
| 106 |
+
"""Terminal node: Package the final response into messages."""
|
| 107 |
+
generation = state.get("generation", settings.fallback_response)
|
| 108 |
+
return {"messages": [AIMessage(content=generation)]}
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
# ──────────────────────────────────────────────
|
| 112 |
+
# Edge condition functions (routing)
|
| 113 |
+
# ──────────────────────────────────────────────
|
| 114 |
+
def route_after_classify(state: AgentState) -> str:
|
| 115 |
+
"""Route after intent classification: retrieve or fallback."""
|
| 116 |
+
route = state.get("route", "fallback")
|
| 117 |
+
# Default-deny: only explicit "retrieve" passes
|
| 118 |
+
return route if route == "retrieve" else "fallback"
|
app/agent/prompts.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
SYSTEM_PROMPT = """
|
| 2 |
+
You are the official ACPC Gujarat Admissions Assistant. Your goal is to provide accurate administrative guidance based STRICTLY on provided documents.
|
| 3 |
+
|
| 4 |
+
CORE OPERATING RULES:
|
| 5 |
+
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.
|
| 6 |
+
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.
|
| 7 |
+
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.
|
| 8 |
+
4. TONE & CITATION: Be professional and supportive. Use inline citations [1](URL) for every factual claim.
|
| 9 |
+
5. LANGUAGE: Respond in the student's language. If they use Hinglish/Gujlish, respond in clear English or the dominant language used.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
INTENT_CLASSIFICATION_PROMPT = """Query : {query}
|
| 13 |
+
take this Query and classify it as ACPC_RELATED only don't add any other classification
|
| 14 |
+
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
GENERATION_PROMPT = """
|
| 18 |
+
Review the official ACPC documentation below.
|
| 19 |
+
|
| 20 |
+
<context>
|
| 21 |
+
{context}
|
| 22 |
+
</context>
|
| 23 |
+
|
| 24 |
+
INSTRUCTIONS:
|
| 25 |
+
- Answer the student's query using ONLY the context above.
|
| 26 |
+
- If the context mentions a specific date or deadline (like the 'Result Improvement' window), highlight it.
|
| 27 |
+
- 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.
|
| 28 |
+
- Use clickable markdown citations [1](URL).
|
| 29 |
+
|
| 30 |
+
<student_query>
|
| 31 |
+
{question}
|
| 32 |
+
</student_query>
|
| 33 |
+
"""
|
app/agent/state.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Annotated
|
| 2 |
+
from typing_extensions import TypedDict
|
| 3 |
+
from langchain_core.documents import Document
|
| 4 |
+
from langchain_core.messages import BaseMessage
|
| 5 |
+
from langgraph.graph.message import add_messages
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class AgentState(TypedDict):
|
| 9 |
+
# Conversation history (managed by LangGraph add_messages reducer)
|
| 10 |
+
messages: Annotated[list[BaseMessage], add_messages]
|
| 11 |
+
# Current user query (possibly rewritten)
|
| 12 |
+
query: str
|
| 13 |
+
# Raw retrieval results (before grading)
|
| 14 |
+
retrieved_documents: list[Document]
|
| 15 |
+
# Graded relevant documents
|
| 16 |
+
relevant_documents: list[Document]
|
| 17 |
+
# LLM-generated answer text
|
| 18 |
+
generation: str
|
| 19 |
+
# Source metadata list for API response
|
| 20 |
+
sources: list[dict]
|
| 21 |
+
# Confidence score (fraction of retrieved docs that are relevant)
|
| 22 |
+
confidence: float
|
| 23 |
+
# Number of retrieval retries (for query rewriting loop)
|
| 24 |
+
retry_count: int
|
| 25 |
+
# Routing decision
|
| 26 |
+
route: str
|
app/config.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pydantic_settings import BaseSettings
|
| 2 |
+
from pydantic import Field, field_validator
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class Settings(BaseSettings):
|
| 6 |
+
"""Application settings — validated at startup from environment variables."""
|
| 7 |
+
|
| 8 |
+
model_config = {
|
| 9 |
+
"env_file": ".env",
|
| 10 |
+
"env_file_encoding": "utf-8",
|
| 11 |
+
"extra": "ignore",
|
| 12 |
+
"populate_by_name": True,
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
# OpenAI / OpenRouter
|
| 16 |
+
openai_api_key: str = Field(alias="OPENROUTER_API_KEY", default="")
|
| 17 |
+
openai_api_base: str = Field(default="https://openrouter.ai/api/v1")
|
| 18 |
+
|
| 19 |
+
# Qdrant
|
| 20 |
+
qdrant_url: str = Field(default="")
|
| 21 |
+
qdrant_api_key: str = Field(default="")
|
| 22 |
+
collection_name: str = Field(default="ld_chatbot_main")
|
| 23 |
+
vector_name: str = Field(default="text-dense")
|
| 24 |
+
sparse_vector_name: str = Field(default="text-sparse-new")
|
| 25 |
+
|
| 26 |
+
# Models
|
| 27 |
+
embedding_model: str = Field(default="text-embedding-3-small")
|
| 28 |
+
sparse_embedding_model: str = Field(default="Qdrant/bm25")
|
| 29 |
+
llm_model: str = Field(default="openai/gpt-5.4-mini")
|
| 30 |
+
query_gen_model: str = Field(default="openai/gpt-5.4-mini")
|
| 31 |
+
reranker_model: str = Field(default="rerank-english-v3.0")
|
| 32 |
+
|
| 33 |
+
# Cohere
|
| 34 |
+
cohere_api_key: str = Field(default="")
|
| 35 |
+
|
| 36 |
+
# Sarvam
|
| 37 |
+
sarvam_api_key: str = Field(default="")
|
| 38 |
+
sarvam_api_url: str = Field(default="https://api.sarvam.ai/speech-to-text")
|
| 39 |
+
|
| 40 |
+
# Langfuse
|
| 41 |
+
langfuse_public_key: str = Field(default="")
|
| 42 |
+
langfuse_secret_key: str = Field(default="")
|
| 43 |
+
langfuse_host: str = Field(default="https://cloud.langfuse.com")
|
| 44 |
+
|
| 45 |
+
# Retrieval parameters
|
| 46 |
+
retrieval_top_k: int = Field(default=15)
|
| 47 |
+
rerank_top_n: int = Field(default=5)
|
| 48 |
+
|
| 49 |
+
# Agent parameters
|
| 50 |
+
max_retrieval_retries: int = Field(default=2)
|
| 51 |
+
confidence_threshold: float = Field(default=0.2)
|
| 52 |
+
|
| 53 |
+
# Memory / session
|
| 54 |
+
max_conversation_messages: int = Field(default=20)
|
| 55 |
+
max_context_tokens: int = Field(default=6000)
|
| 56 |
+
session_ttl_minutes: int = Field(default=30)
|
| 57 |
+
|
| 58 |
+
# Security
|
| 59 |
+
ingest_api_key: str = Field(default="")
|
| 60 |
+
ingest_base_dir: str = Field(default="")
|
| 61 |
+
allowed_origins: str = Field(default="http://localhost:5173,http://localhost:3000")
|
| 62 |
+
|
| 63 |
+
@field_validator("allowed_origins", mode="before")
|
| 64 |
+
@classmethod
|
| 65 |
+
def parse_allowed_origins(cls, v):
|
| 66 |
+
# Keep as comma-separated string — split where needed (e.g. in main.py CORS)
|
| 67 |
+
if isinstance(v, list):
|
| 68 |
+
return ",".join(v)
|
| 69 |
+
return v
|
| 70 |
+
|
| 71 |
+
@property
|
| 72 |
+
def allowed_origins_list(self) -> list[str]:
|
| 73 |
+
"""Return allowed_origins as a list for CORS middleware."""
|
| 74 |
+
return [o.strip() for o in self.allowed_origins.split(",") if o.strip()]
|
| 75 |
+
|
| 76 |
+
# Chunk parameters (for ingestion — must match existing collection)
|
| 77 |
+
chunk_size: int = Field(default=512)
|
| 78 |
+
chunk_overlap: int = Field(default=64)
|
| 79 |
+
|
| 80 |
+
# Fallback response (never LLM-generated)
|
| 81 |
+
fallback_response: str = Field(
|
| 82 |
+
default=(
|
| 83 |
+
"I don't have specific information about that in my current knowledge base. "
|
| 84 |
+
"For accurate and up-to-date information, please visit the official ACPC Gujarat website: "
|
| 85 |
+
"https://acpc.gujarat.gov.in/ or contact the ACPC helpline."
|
| 86 |
+
)
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
settings = Settings()
|
app/dependencies.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from app.agent.graph import get_graph
|
| 2 |
+
from app.memory.session_store import get_or_create_session
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def get_agent():
|
| 6 |
+
"""FastAPI dependency: return the compiled LangGraph agent."""
|
| 7 |
+
return get_graph()
|
app/guardrails/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Guardrails module for the ACPC Chatbot pipeline.
|
| 3 |
+
|
| 4 |
+
Contains all safety, relevance, and grounding checks:
|
| 5 |
+
- Intent classification (LLM-based)
|
| 6 |
+
- Document relevance grading
|
| 7 |
+
- Hallucination / grounding verification
|
| 8 |
+
"""
|
| 9 |
+
from app.guardrails.intent_classifier import classify_query
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
"classify_query",
|
| 13 |
+
]
|
app/guardrails/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (528 Bytes). View file
|
|
|
app/guardrails/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (686 Bytes). View file
|
|
|
app/guardrails/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (617 Bytes). View file
|
|
|
app/guardrails/__pycache__/hallucination_checker.cpython-312.pyc
ADDED
|
Binary file (3.81 kB). View file
|
|
|
app/guardrails/__pycache__/hallucination_checker.cpython-313.pyc
ADDED
|
Binary file (3.87 kB). View file
|
|
|
app/guardrails/__pycache__/hallucination_checker.cpython-314.pyc
ADDED
|
Binary file (4.07 kB). View file
|
|
|
app/guardrails/__pycache__/intent_classifier.cpython-312.pyc
ADDED
|
Binary file (2.85 kB). View file
|
|
|
app/guardrails/__pycache__/intent_classifier.cpython-313.pyc
ADDED
|
Binary file (2.74 kB). View file
|
|
|
app/guardrails/__pycache__/intent_classifier.cpython-314.pyc
ADDED
|
Binary file (2.9 kB). View file
|
|
|
app/guardrails/__pycache__/relevance_grader.cpython-312.pyc
ADDED
|
Binary file (3.87 kB). View file
|
|
|
app/guardrails/__pycache__/relevance_grader.cpython-313.pyc
ADDED
|
Binary file (3.88 kB). View file
|
|
|
app/guardrails/__pycache__/relevance_grader.cpython-314.pyc
ADDED
|
Binary file (3.39 kB). View file
|
|
|
app/guardrails/intent_classifier.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Intent Classification Guardrail.
|
| 3 |
+
|
| 4 |
+
LLM-based classification to determine whether a user query is:
|
| 5 |
+
- ACPC_RELATED → proceed to retrieval
|
| 6 |
+
- GREETINGS/SMALL TALK → proceed to retrieval
|
| 7 |
+
- OFF_TOPIC → block with fallback
|
| 8 |
+
- INJECTION → block with fallback (includes personal info requests)
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import logging
|
| 12 |
+
from langchain_core.messages import HumanMessage
|
| 13 |
+
|
| 14 |
+
from app.utils.llm_helpers import get_llm
|
| 15 |
+
from app.agent.prompts import INTENT_CLASSIFICATION_PROMPT
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
# Valid classification labels — anything else is treated as blocked
|
| 20 |
+
VALID_LABELS = ("ACPC_RELATED", "GREETINGS / SMALL TALK", "OFF_TOPIC", "INJECTION")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def classify_query(query: str) -> dict:
|
| 24 |
+
"""Classify a user query using LLM-based intent detection.
|
| 25 |
+
|
| 26 |
+
Returns:
|
| 27 |
+
dict with:
|
| 28 |
+
- "classification": one of VALID_LABELS or "UNKNOWN"
|
| 29 |
+
- "route": "retrieve" if ACPC_RELATED, "fallback" otherwise
|
| 30 |
+
- "blocked_reason": None if allowed, else the classification label
|
| 31 |
+
"""
|
| 32 |
+
if not query or not query.strip():
|
| 33 |
+
logger.warning("Empty query passed to classify_query")
|
| 34 |
+
return {
|
| 35 |
+
"classification": "UNKNOWN",
|
| 36 |
+
"route": "fallback",
|
| 37 |
+
"blocked_reason": "empty_query",
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
llm = get_llm(temperature=0.0)
|
| 41 |
+
prompt = INTENT_CLASSIFICATION_PROMPT.format(query=query)
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
response = llm.invoke([HumanMessage(content=prompt)])
|
| 45 |
+
classification = response.content.strip().upper()
|
| 46 |
+
except Exception as e:
|
| 47 |
+
logger.error("LLM error in classify_query: %s — defaulting to fallback", e)
|
| 48 |
+
return {
|
| 49 |
+
"classification": "UNKNOWN",
|
| 50 |
+
"route": "fallback",
|
| 51 |
+
"blocked_reason": "llm_error",
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
# Default-deny: if LLM returns something unexpected, block it
|
| 55 |
+
if classification not in VALID_LABELS:
|
| 56 |
+
logger.warning(
|
| 57 |
+
"Invalid classification '%s' (expected one of %s) — blocking",
|
| 58 |
+
classification, VALID_LABELS,
|
| 59 |
+
)
|
| 60 |
+
return {
|
| 61 |
+
"classification": classification,
|
| 62 |
+
"route": "fallback",
|
| 63 |
+
"blocked_reason": "invalid_classification",
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
logger.info("Intent classification: %s for query: %s", classification, query[:80])
|
| 67 |
+
|
| 68 |
+
# Only ACPC_RELATED passes through
|
| 69 |
+
if classification == "ACPC_RELATED" or classification == "GREETINGS / SMALL TALK":
|
| 70 |
+
return {
|
| 71 |
+
"classification": classification,
|
| 72 |
+
"route": "retrieve",
|
| 73 |
+
"blocked_reason": None,
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
return {
|
| 77 |
+
"classification": classification,
|
| 78 |
+
"route": "fallback",
|
| 79 |
+
"blocked_reason": classification.lower(),
|
| 80 |
+
}
|
app/main.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from contextlib import asynccontextmanager
|
| 3 |
+
|
| 4 |
+
from fastapi import FastAPI
|
| 5 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
+
|
| 7 |
+
from app.config import settings
|
| 8 |
+
from app.agent.graph import get_graph
|
| 9 |
+
from app.retrieval.qdrant_store import get_vector_store
|
| 10 |
+
from app.monitoring.langfuse_setup import get_langfuse_callback_handler, flush_langfuse
|
| 11 |
+
from app.memory.session_store import start_cleanup_task, stop_cleanup_task
|
| 12 |
+
from app.routers import chat, stt, ingest, health, sessions
|
| 13 |
+
|
| 14 |
+
logging.basicConfig(
|
| 15 |
+
level=logging.INFO,
|
| 16 |
+
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
| 17 |
+
)
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@asynccontextmanager
|
| 22 |
+
async def lifespan(app: FastAPI):
|
| 23 |
+
"""Application startup / shutdown lifecycle."""
|
| 24 |
+
logger.info("Starting ACPC Chatbot backend...")
|
| 25 |
+
|
| 26 |
+
# Pre-warm non-network singletons
|
| 27 |
+
get_graph()
|
| 28 |
+
start_cleanup_task()
|
| 29 |
+
# NOTE: Qdrant vector store is lazily initialized on first query
|
| 30 |
+
# (avoids startup failure if Qdrant Cloud is temporarily unreachable)
|
| 31 |
+
|
| 32 |
+
logger.info("Backend ready.")
|
| 33 |
+
yield
|
| 34 |
+
|
| 35 |
+
# Shutdown
|
| 36 |
+
stop_cleanup_task()
|
| 37 |
+
flush_langfuse()
|
| 38 |
+
logger.info("Backend shut down cleanly.")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
app = FastAPI(
|
| 42 |
+
title="ACPC Gujarat Chatbot API",
|
| 43 |
+
description="Agentic RAG chatbot for ACPC Gujarat admissions queries",
|
| 44 |
+
version="1.0.0",
|
| 45 |
+
lifespan=lifespan,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
# CORS — restrict to configured origins
|
| 49 |
+
app.add_middleware(
|
| 50 |
+
CORSMiddleware,
|
| 51 |
+
allow_origins=settings.allowed_origins_list,
|
| 52 |
+
allow_credentials=True,
|
| 53 |
+
allow_methods=["*"],
|
| 54 |
+
allow_headers=["*"],
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
# Mount routers
|
| 58 |
+
app.include_router(chat.router)
|
| 59 |
+
app.include_router(stt.router)
|
| 60 |
+
app.include_router(ingest.router)
|
| 61 |
+
app.include_router(health.router)
|
| 62 |
+
app.include_router(sessions.router)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@app.get("/")
|
| 66 |
+
async def root():
|
| 67 |
+
return {"status": "ok", "service": "ACPC Gujarat Chatbot API", "version": "1.0.0"}
|
app/memory/__init__.py
ADDED
|
File without changes
|
app/memory/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (185 Bytes). View file
|
|
|
app/memory/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (185 Bytes). View file
|
|
|
app/memory/__pycache__/conversation_buffer.cpython-312.pyc
ADDED
|
Binary file (4.11 kB). View file
|
|
|
app/memory/__pycache__/conversation_buffer.cpython-313.pyc
ADDED
|
Binary file (4.05 kB). View file
|
|
|
app/memory/__pycache__/session_store.cpython-312.pyc
ADDED
|
Binary file (3.58 kB). View file
|
|
|