Stoic-2910 commited on
Commit
169d4d5
·
verified ·
1 Parent(s): 8548f1c

Delete app

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. app/__init__.py +0 -0
  2. app/__pycache__/__init__.cpython-312.pyc +0 -0
  3. app/__pycache__/__init__.cpython-313.pyc +0 -0
  4. app/__pycache__/__init__.cpython-314.pyc +0 -0
  5. app/__pycache__/config.cpython-312.pyc +0 -0
  6. app/__pycache__/config.cpython-313.pyc +0 -0
  7. app/__pycache__/main.cpython-312.pyc +0 -0
  8. app/__pycache__/main.cpython-313.pyc +0 -0
  9. app/agent/__init__.py +0 -0
  10. app/agent/__pycache__/__init__.cpython-312.pyc +0 -0
  11. app/agent/__pycache__/__init__.cpython-313.pyc +0 -0
  12. app/agent/__pycache__/graph.cpython-312.pyc +0 -0
  13. app/agent/__pycache__/graph.cpython-313.pyc +0 -0
  14. app/agent/__pycache__/graph.cpython-314.pyc +0 -0
  15. app/agent/__pycache__/nodes.cpython-312.pyc +0 -0
  16. app/agent/__pycache__/nodes.cpython-313.pyc +0 -0
  17. app/agent/__pycache__/nodes.cpython-314.pyc +0 -0
  18. app/agent/__pycache__/prompts.cpython-312.pyc +0 -0
  19. app/agent/__pycache__/prompts.cpython-313.pyc +0 -0
  20. app/agent/__pycache__/state.cpython-312.pyc +0 -0
  21. app/agent/__pycache__/state.cpython-313.pyc +0 -0
  22. app/agent/graph.py +0 -49
  23. app/agent/nodes.py +0 -118
  24. app/agent/prompts.py +0 -33
  25. app/agent/state.py +0 -26
  26. app/config.py +0 -89
  27. app/dependencies.py +0 -7
  28. app/guardrails/__init__.py +0 -13
  29. app/guardrails/__pycache__/__init__.cpython-312.pyc +0 -0
  30. app/guardrails/__pycache__/__init__.cpython-313.pyc +0 -0
  31. app/guardrails/__pycache__/__init__.cpython-314.pyc +0 -0
  32. app/guardrails/__pycache__/hallucination_checker.cpython-312.pyc +0 -0
  33. app/guardrails/__pycache__/hallucination_checker.cpython-313.pyc +0 -0
  34. app/guardrails/__pycache__/hallucination_checker.cpython-314.pyc +0 -0
  35. app/guardrails/__pycache__/intent_classifier.cpython-312.pyc +0 -0
  36. app/guardrails/__pycache__/intent_classifier.cpython-313.pyc +0 -0
  37. app/guardrails/__pycache__/intent_classifier.cpython-314.pyc +0 -0
  38. app/guardrails/__pycache__/relevance_grader.cpython-312.pyc +0 -0
  39. app/guardrails/__pycache__/relevance_grader.cpython-313.pyc +0 -0
  40. app/guardrails/__pycache__/relevance_grader.cpython-314.pyc +0 -0
  41. app/guardrails/intent_classifier.py +0 -80
  42. app/main.py +0 -67
  43. app/memory/__init__.py +0 -0
  44. app/memory/__pycache__/__init__.cpython-312.pyc +0 -0
  45. app/memory/__pycache__/__init__.cpython-313.pyc +0 -0
  46. app/memory/__pycache__/conversation_buffer.cpython-312.pyc +0 -0
  47. app/memory/__pycache__/conversation_buffer.cpython-313.pyc +0 -0
  48. app/memory/__pycache__/session_store.cpython-312.pyc +0 -0
  49. app/memory/__pycache__/session_store.cpython-313.pyc +0 -0
  50. app/memory/conversation_buffer.py +0 -61
app/__init__.py DELETED
File without changes
app/__pycache__/__init__.cpython-312.pyc DELETED
Binary file (178 Bytes)
 
app/__pycache__/__init__.cpython-313.pyc DELETED
Binary file (178 Bytes)
 
app/__pycache__/__init__.cpython-314.pyc DELETED
Binary file (180 Bytes)
 
app/__pycache__/config.cpython-312.pyc DELETED
Binary file (4.33 kB)
 
app/__pycache__/config.cpython-313.pyc DELETED
Binary file (4.16 kB)
 
app/__pycache__/main.cpython-312.pyc DELETED
Binary file (2.73 kB)
 
app/__pycache__/main.cpython-313.pyc DELETED
Binary file (2.74 kB)
 
app/agent/__init__.py DELETED
File without changes
app/agent/__pycache__/__init__.cpython-312.pyc DELETED
Binary file (184 Bytes)
 
app/agent/__pycache__/__init__.cpython-313.pyc DELETED
Binary file (184 Bytes)
 
app/agent/__pycache__/graph.cpython-312.pyc DELETED
Binary file (1.67 kB)
 
app/agent/__pycache__/graph.cpython-313.pyc DELETED
Binary file (2.71 kB)
 
app/agent/__pycache__/graph.cpython-314.pyc DELETED
Binary file (2.39 kB)
 
app/agent/__pycache__/nodes.cpython-312.pyc DELETED
Binary file (5.2 kB)
 
app/agent/__pycache__/nodes.cpython-313.pyc DELETED
Binary file (8.2 kB)
 
app/agent/__pycache__/nodes.cpython-314.pyc DELETED
Binary file (9.72 kB)
 
app/agent/__pycache__/prompts.cpython-312.pyc DELETED
Binary file (2 kB)
 
app/agent/__pycache__/prompts.cpython-313.pyc DELETED
Binary file (5.52 kB)
 
app/agent/__pycache__/state.cpython-312.pyc DELETED
Binary file (1.01 kB)
 
app/agent/__pycache__/state.cpython-313.pyc DELETED
Binary file (1.07 kB)
 
app/agent/graph.py DELETED
@@ -1,49 +0,0 @@
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 DELETED
@@ -1,118 +0,0 @@
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 DELETED
@@ -1,33 +0,0 @@
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 DELETED
@@ -1,26 +0,0 @@
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 DELETED
@@ -1,89 +0,0 @@
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 DELETED
@@ -1,7 +0,0 @@
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 DELETED
@@ -1,13 +0,0 @@
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 DELETED
Binary file (528 Bytes)
 
app/guardrails/__pycache__/__init__.cpython-313.pyc DELETED
Binary file (686 Bytes)
 
app/guardrails/__pycache__/__init__.cpython-314.pyc DELETED
Binary file (617 Bytes)
 
app/guardrails/__pycache__/hallucination_checker.cpython-312.pyc DELETED
Binary file (3.81 kB)
 
app/guardrails/__pycache__/hallucination_checker.cpython-313.pyc DELETED
Binary file (3.87 kB)
 
app/guardrails/__pycache__/hallucination_checker.cpython-314.pyc DELETED
Binary file (4.07 kB)
 
app/guardrails/__pycache__/intent_classifier.cpython-312.pyc DELETED
Binary file (2.85 kB)
 
app/guardrails/__pycache__/intent_classifier.cpython-313.pyc DELETED
Binary file (2.74 kB)
 
app/guardrails/__pycache__/intent_classifier.cpython-314.pyc DELETED
Binary file (2.9 kB)
 
app/guardrails/__pycache__/relevance_grader.cpython-312.pyc DELETED
Binary file (3.87 kB)
 
app/guardrails/__pycache__/relevance_grader.cpython-313.pyc DELETED
Binary file (3.88 kB)
 
app/guardrails/__pycache__/relevance_grader.cpython-314.pyc DELETED
Binary file (3.39 kB)
 
app/guardrails/intent_classifier.py DELETED
@@ -1,80 +0,0 @@
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 DELETED
@@ -1,67 +0,0 @@
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 DELETED
File without changes
app/memory/__pycache__/__init__.cpython-312.pyc DELETED
Binary file (185 Bytes)
 
app/memory/__pycache__/__init__.cpython-313.pyc DELETED
Binary file (185 Bytes)
 
app/memory/__pycache__/conversation_buffer.cpython-312.pyc DELETED
Binary file (4.11 kB)
 
app/memory/__pycache__/conversation_buffer.cpython-313.pyc DELETED
Binary file (4.05 kB)
 
app/memory/__pycache__/session_store.cpython-312.pyc DELETED
Binary file (3.58 kB)
 
app/memory/__pycache__/session_store.cpython-313.pyc DELETED
Binary file (3.62 kB)
 
app/memory/conversation_buffer.py DELETED
@@ -1,61 +0,0 @@
1
- from datetime import datetime, timezone
2
- from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, SystemMessage
3
- from app.utils.token_counter import count_messages_tokens
4
- from app.config import settings
5
-
6
-
7
- class ConversationBuffer:
8
- """Sliding window conversation buffer with token-based trimming."""
9
-
10
- def __init__(self):
11
- self.messages: list[BaseMessage] = []
12
- self.last_accessed: datetime = datetime.now(timezone.utc)
13
-
14
- def add_user_message(self, content: str) -> None:
15
- self.messages.append(HumanMessage(content=content))
16
- self._trim()
17
- self.last_accessed = datetime.now(timezone.utc)
18
-
19
- def add_ai_message(self, content: str) -> None:
20
- self.messages.append(AIMessage(content=content))
21
- self._trim()
22
- self.last_accessed = datetime.utcnow()
23
-
24
- def get_messages(self, max_tokens: int | None = None) -> list[BaseMessage]:
25
- """Return messages, token-trimmed to max_tokens (default from settings)."""
26
- self.last_accessed = datetime.now(timezone.utc)
27
- limit = max_tokens or settings.max_context_tokens
28
- return self._token_trim(self.messages.copy(), limit)
29
-
30
- def _trim(self) -> None:
31
- """Apply sliding window: keep last MAX_CONVERSATION_MESSAGES."""
32
- max_msgs = settings.max_conversation_messages
33
- if len(self.messages) > max_msgs:
34
- self.messages = self.messages[-max_msgs:]
35
-
36
- def _token_trim(self, messages: list[BaseMessage], max_tokens: int) -> list[BaseMessage]:
37
- """
38
- Trim oldest messages (excluding last user message) until total tokens <= max_tokens.
39
- Always preserves the most recent user message.
40
- """
41
- if not messages:
42
- return messages
43
-
44
- total = count_messages_tokens(messages)
45
- if total <= max_tokens:
46
- return messages
47
-
48
- # Always keep the last message (current user query)
49
- last = messages[-1]
50
- trimable = messages[:-1]
51
-
52
- while trimable and count_messages_tokens(trimable) + count_messages_tokens([last]) > max_tokens:
53
- trimable.pop(0)
54
-
55
- return trimable + [last]
56
-
57
- def clear(self) -> None:
58
- self.messages = []
59
-
60
- def __len__(self) -> int:
61
- return len(self.messages)