1. Architectural Purpose & Mental Model
In enterprise knowledge systems, dumping all company documents into a single monolithic vector store leads to retrieval pollution (e.g., searching for "late fees" retrieving internal academic probation policies instead of billing policies). Furthermore, simple conversational greetings (e.g., "Hello, how are you?") should not trigger expensive vector similarity searches across millions of documents.
The Solution: Adaptive RAG
An Adaptive RAG Router uses a fast, lightweight LLM classifier to determine user intent, dynamically routing the query:
- Academic Inquiries: Routed to an isolated Academic Regulations vector store.
- Fee & Financial Inquiries: Routed to an isolated Billing & Tuition vector store.
- General Chit-Chat: Bypasses vector retrieval completely, generating a direct response and saving API latency and compute costs.
2. Architecture Diagram
flowchart LR
START(["START"]) --> Q{"Query classifier"}
Q -- "academic" --> A["Academic RAG node<br/><small>academics_handbook.pdf</small>"]
Q -- "fee" --> F["Fee RAG node<br/><small>fee_structure.pdf</small>"]
Q -- "general" --> G["General chat node<br/><small>direct LLM, no vector search</small>"]
A --> END(["END"])
F --> END
G --> END
classDef term fill:#0e3b3a,stroke:#0e3b3a,color:#ffffff,font-weight:bold
classDef gate fill:#fdf1ec,stroke:#c9583a,color:#7a2e1a
classDef store fill:#f5f5f4,stroke:#57534e,color:#292524
classDef c0 fill:#d4ecea,stroke:#2a7a79,color:#0e3b3a
classDef c1 fill:#fbe5dc,stroke:#c9583a,color:#7a2e1a
classDef c2 fill:#e3f5ee,stroke:#4aa58a,color:#14463a
classDef c3 fill:#f6f4f0,stroke:#a7a29a,color:#3f3b35
classDef c4 fill:#eef7f7,stroke:#1a5c5b,color:#0e3b3a
class START term
class Q gate
class A c0
class F c1
class G c2
class END term+-----------------------------------------------------------------------------------------+
| ADAPTIVE CONDITIONAL RAG ROUTER |
+-----------------------------------------------------------------------------------------+
| |
| ┌───> [Academic RAG Node] (academics_handbook.pdf) ──┐ |
| │ │ |
| [START] ──> [Query Classifier] ┼───> [Fee RAG Node] (fee_structure.pdf) ───┼──>|
| │ │[END]
| └───> [General Chat Node] (Direct LLM, Zero Vector) ─┘ |
| |
+-----------------------------------------------------------------------------------------+
3. Node Responsibilities & Prompts
-
Classifier Prompt:
Forces the model to return strictly one of three discrete tokens:'academic','fee', or'general'. -
Domain Retrievers:
Two completely independent FAISS vector indexes loaded from separate PDF files: -
data/academics_handbook.pdf data/fee_structure.pdf- Program-Aware Generator Prompt:
Personalizes the extracted answer to the student's enrolled programme (e.g., B.Tech vs MBA).
4. Production Python Implementation (conditional_RAG.py)
Code · 143 lines01_conditional_rag.pyShow here
import os
from dotenv import load_dotenv
load_dotenv()
from typing import TypedDict
from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_mistralai import MistralAIEmbeddings
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import FAISS
from langgraph.graph import START, END, StateGraph
# 1. State Schema
class CollegeBotState(TypedDict):
query: str
programme: str
category: str
context: str
response: str
# 2. Model & Embedding Setup
model = init_chat_model("mistralai:mistral-small-2603")
embeddings = MistralAIEmbeddings(model="mistral-embed")
parser = StrOutputParser()
# 3. Helper: Build Independent Domain Vector Retrievers
def build_retriever(pdf_path: str):
loader = PyPDFLoader(pdf_path)
docs = loader.load()
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
chunks = splitter.split_documents(docs)
vector_store = FAISS.from_documents(chunks, embedding=embeddings)
return vector_store.as_retriever(search_kwargs={"k": 3})
# Ingest isolated knowledge bases
academic_retriever = build_retriever("data/academics_handbook.pdf")
fee_retriever = build_retriever("data/fee_structure.pdf")
# 4. Prompts
classifier_prompt = ChatPromptTemplate.from_messages([
("system", """You are a smart college front-desk classifier.
Classify the following query into EXACTLY ONE of these categories:
- 'academic': for attendance, exams, grading, credits, course structure, degree requirements.
- 'fee': for tuition, payment, refund, late charges, scholarships.
- 'general': for greetings, casual chit-chat, or general questions.
Return ONLY the single word in lowercase: 'academic', 'fee', or 'general'."""),
("human", "Query:\n{query}")
])
rag_response_prompt = ChatPromptTemplate.from_messages([
("system", """You are a helpful college assistant assisting a {programme} student.
Use the provided official context from college documents to answer accurately.
Highlight rules specific to {programme}. If not found in context, state so politely.
Official Context:
{context}"""),
("human", "{query}")
])
general_response_prompt = ChatPromptTemplate.from_messages([
("system", "You are a friendly college assistant chatting with a {programme} student. Answer politely using general knowledge."),
("human", "{query}")
])
# 5. Worker Nodes
def classify_node(state: CollegeBotState) -> dict:
chain = classifier_prompt | model | parser
category = chain.invoke({"query": state["query"]}).strip().lower()
return {"category": category}
def academic_rag_node(state: CollegeBotState) -> dict:
docs = academic_retriever.invoke(state["query"])
context_text = "\n\n".join([doc.page_content for doc in docs])
chain = rag_response_prompt | model | parser
reply = chain.invoke({
"programme": state["programme"],
"context": context_text,
"query": state["query"]
})
return {"context": context_text, "response": reply}
def fee_rag_node(state: CollegeBotState) -> dict:
docs = fee_retriever.invoke(state["query"])
context_text = "\n\n".join([doc.page_content for doc in docs])
chain = rag_response_prompt | model | parser
reply = chain.invoke({
"programme": state["programme"],
"context": context_text,
"query": state["query"]
})
return {"context": context_text, "response": reply}
def general_chat_node(state: CollegeBotState) -> dict:
chain = general_response_prompt | model | parser
reply = chain.invoke({
"programme": state["programme"],
"query": state["query"]
})
return {"response": reply, "context": "No documents retrieved (General Chat)"}
# 6. Routing Function
def route_query(state: CollegeBotState) -> str:
category = state.get("category", "general")
if category in ["academic", "fee"]:
return category
return "general"
# 7. Construct Graph
builder = StateGraph(CollegeBotState)
builder.add_node("classifier", classify_node)
builder.add_node("academic", academic_rag_node)
builder.add_node("fee", fee_rag_node)
builder.add_node("general", general_chat_node)
builder.add_edge(START, "classifier")
builder.add_conditional_edges(
"classifier",
route_query,
{
"academic": "academic",
"fee": "fee",
"general": "general"
}
)
builder.add_edge("academic", END)
builder.add_edge("fee", END)
builder.add_edge("general", END)
app = builder.compile()
# 8. Execution Demo
test_query = "What is the penalty if I pay my tuition fee 2 weeks late?"
result = app.invoke({
"query": test_query,
"programme": "B.Tech Computer Science"
})
print(f"Detected Category: [bold yellow]{result['category']}[/bold yellow]")
print(f"AI Response:\n{result['response']}")
5. Key Takeaways
- Zero Vector Overhead for Chit-Chat: General greetings bypass vector retrieval, saving latency and vector database query costs.
- Segregated Knowledge Silos: Domain-specific PDFs live in isolated vector stores, preventing cross-domain retrieval hallucination.
- Contextual Personalization: User metadata (
programme: B.Tech) is passed to the generation prompt alongside retrieved context to give tailored student guidance.
01_conditional_rag.py01_conditional_rag.py · 181 linesShow code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | from dotenv import load_dotenv load_dotenv() from langchain.chat_models import init_chat_model from langchain_core.prompts import ChatPromptTemplate from langchain_mistralai import MistralAIEmbeddings from langchain_community.document_loaders import PyPDFLoader from langchain_text_splitters import RecursiveCharacterTextSplitter from langchain_community.vectorstores import FAISS from langchain.chat_models import init_chat_model from typing import TypedDict , Annotated from langgraph.graph.message import add_messages from langchain_core.output_parsers import StrOutputParser from langgraph.graph import START , END , StateGraph embeddings = MistralAIEmbeddings(model ="mistral-embed") parser = StrOutputParser() """One retriever per PDF: load -> split -> FAISS -> as_retriever (k=4)""" def build_retriver(pdf_path : str): loader = PyPDFLoader(pdf_path) docs = loader.load() splitter = RecursiveCharacterTextSplitter(chunk_size = 500 , chunk_overlap=50) chunks = splitter.split_documents(docs) vectorStore = FAISS.from_documents(chunks,embedding=embeddings) return vectorStore.as_retriever(search_kwargs={"k":4}) acedemic_retriever = build_retriver("data/academics_handbook.pdf") fee_retriever = build_retriver("data/fee_structure.pdf") model = init_chat_model("mistralai:open-mistral-nemo") classifier_prompt = ChatPromptTemplate.from_messages([ ("system", """You are a smart college front-desk classifier. Classify the following student query into EXACTLY ONE of these categories: - 'academic': for attendance, exams, grading, credits, promotion, course structure, degree requirements. - 'fee': for tuition, payment, refund, late charges, scholarships, or money-related topics. - 'general': for greetings, casual chit-chat, or general questions not related to college rules/fees. Return ONLY the single word in lowercase: 'academic', 'fee', or 'general'."""), ("human", "Query:\n{query}") ]) rag_response_prompt = ChatPromptTemplate.from_messages([ ("system", """You are a helpful college assistant assisting a {programme} student. Use the provided official context from college documents to answer the student's question accurately. If the context mentions specific figures or rules for different programmes, highlight the one relevant to {programme}. If the answer is not found in the context, politely state that you could not find the information in the official documents. Official Context: {context}"""), ("human", "{query}") ]) general_response_prompt = ChatPromptTemplate.from_messages([ ("system", "You are a friendly, welcoming college assistant chatting with a {programme} student. Answer their question politely using your general knowledge."), ("human", "{query}") ]) class State(TypedDict): programme :str message :Annotated[list,add_messages] query_type: str retrieved_context : str def classifier_node(state:State)->dict: """Classifies user query using ChatPromptTemplate & LLM.""" last_user_message = state["message"][-1].content chain = classifier_prompt | model | parser category = chain.invoke({"query":last_user_message}).strip().lower() if "academic" in category: detected = "academic" elif "fee" in category: detected = "fee" else: detected="general" return {"query_type":detected} def academic_rag_node(state:State)->dict: """Retrieves relevant chunks from the Academics Handbook.""" last_user_messsage = state["message"][-1].content docs = acedemic_retriever.invoke(last_user_messsage) context_text = "\n\n".join([doc.page_content for doc in docs]) return {"retrieved_context":context_text} def fee_rag_node(state: State) -> dict: """Retrieves relevant chunks from the Fee Structure PDF.""" last_user_message = state["message"][-1].content docs = fee_retriever.invoke(last_user_message) context_text = "\n\n".join([doc.page_content for doc in docs]) return {"retrieved_context": context_text} def general_node(state: State) -> dict: """Bypasses vector search completely.""" return {"retrieved_context": "NO_RETRIEVAL_NEEDED"} def response_node(state:State)->dict: """Generates personalized final response using ChatPromptTemplates.""" last_user_message = state["message"][-1].content programme = state.get("programme","student") context = state["retrieved_context"] if context =="NO_RETRIEVAL_NEEDED": chain = general_response_prompt | model |parser ai_reply = chain.invoke({ "programme":programme, "query":last_user_message }) else: chain = rag_response_prompt | model |parser ai_reply = chain.invoke({ "programme":programme, "context":context, "query":last_user_message }) return {"message":[("ai",ai_reply)]} """Router: reads the state, returns the NAME of the next node""" def route_query(state:State) -> str: """Traffic officer: routes to academic_rag, fee_rag, or general.""" if state["query_type"] == "academic": return "academic_rag" elif state["query_type"] == "fee": return "fee_rag" else: return "general" workflow = StateGraph(State) workflow.add_node("classifier", classifier_node) workflow.add_node("academic_rag", academic_rag_node) workflow.add_node("fee_rag", fee_rag_node) workflow.add_node("general", general_node) workflow.add_node("response", response_node) # Add Edges workflow.add_edge(START, "classifier") # Conditional Edge (Branching) workflow.add_conditional_edges("classifier", route_query) # Fan-in to Response Node workflow.add_edge("academic_rag", "response") workflow.add_edge("fee_rag", "response") workflow.add_edge("general", "response") # Exit workflow.add_edge("response", END) # Compile the Graph App app = workflow.compile() #Interactive Terminal Runner if __name__ == "__main__": print("\n 🎓 Welcome to the University AI Assistant!\n") print("Select your Programme:") print("1. BCA") print("2. BBA") print("3. B.Com (H)") choice = input("\nEnter 1, 2, or 3: ").strip() programme_map = {"1": "BCA", "2": "BBA", "3": "B.Com (H)"} student_programme = programme_map.get(choice, "BCA") print(f"\nProfile Set: {student_programme} Student.\n") while True: user_query = input("\n[You]: ") if user_query.lower() in ["exit", "quit", "q"]: break result = app.invoke({ "programme": student_programme, "message": [("human", user_query)] }) ai_message = result["message"][-1].content print(f"\n Ai :{ai_message}") |
02_conditional_rag_memory.py02_conditional_rag_memory.py · 179 linesShow code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | from dotenv import load_dotenv load_dotenv() from langchain.chat_models import init_chat_model from langchain_core.prompts import ChatPromptTemplate , MessagesPlaceholder from langchain_mistralai import MistralAIEmbeddings from langchain_community.vectorstores import FAISS from langchain_text_splitters import RecursiveCharacterTextSplitter from langchain_core.output_parsers import StrOutputParser from langgraph.graph.message import add_messages from langgraph.graph import START , END , StateGraph from typing import Annotated , TypedDict from langchain_community.document_loaders import PyPDFLoader from langgraph.checkpoint.memory import MemorySaver embeddings = MistralAIEmbeddings(model ="mistral-embed") parser = StrOutputParser() model = init_chat_model("mistralai:open-mistral-nemo") def build_vectorstore(pdf_path:str): """loads PDF , splits into chunks , and returns the raw FAISS vectorstore""" loader=PyPDFLoader(pdf_path) docs = loader.load() splitter = RecursiveCharacterTextSplitter(chunk_size=500,chunk_overlap = 50) chunks = splitter.split_documents(docs) return FAISS.from_documents(documents=chunks , embedding=embeddings) academic_db = build_vectorstore("data/academics_handbook.pdf") fee_db = build_vectorstore("data/fee_structure.pdf") classifier_prompt = ChatPromptTemplate.from_messages([ ("system",""" Classify the student message into EXACTLY ONE category: - 'academic': attendance, exams, grading, credits, syllabus, degree rules. - 'fee': tuition, payment, refund, late fees, scholarships. - 'general': greetings, introductions, casual chat, or personal questions. Return ONLY one word in lowercase: academic, fee, or general. """), ("human","{query}") ]) rag_response_prompt = ChatPromptTemplate.from_messages([ ("system", """You are a helpful college assistant assisting a {programme} student. Use the official context below to answer accurately. Highlight details for {programme}. If not found in context, politely say it's not in the documents. Context: {context}"""), MessagesPlaceholder(variable_name="messages") ]) general_response_prompt = ChatPromptTemplate.from_messages([ ("system", "You are a friendly college assistant for a {programme} student. Chat warmly and answer politely."), MessagesPlaceholder(variable_name="messages") ]) class State(TypedDict): programme :str messages:Annotated[list,add_messages] query_type: str retrieved_context:str def classifier_node(state:State) -> dict: """Classifies the latest user message.""" last_message = state["messages"][-1].content chain = classifier_prompt | model | parser category = chain.invoke({"query":last_message}).strip().lower() if "academic" in category: detected = "academic" elif "fee" in category: detected = "fee" else: detected = "general" return {"query_type":detected} def academic_rag_node(state:State) -> dict: """Direct similarity search on academic database.""" last_message = state["messages"][-1].content docs = academic_db.similarity_search(query=last_message,k=4) context_text = "\n\n".join([doc.page_content for doc in docs]) return {"retrieved_context":context_text} def fee_rag_node(state: State) -> dict: """Direct similarity search on fee database.""" last_message = state["messages"][-1].content docs = fee_db.similarity_search(query=last_message, k=4) context_text = "\n\n".join([doc.page_content for doc in docs]) return {"retrieved_context": context_text} def general_node(state: State) -> dict: """Bypasses database search for greetings and casual talk.""" return {"retrieved_context": "NO_RETRIEVAL_NEEDED"} def response_node(state:State) -> dict: """Generates final answer and appends to message history.""" programme= state.get("programme","BCA") context = state["retrieved_context"] if context =="NO_RETRIEVAL_NEEDED": chain = general_response_prompt|model|parser ai_reply = chain.invoke({"programme":programme, "messages":state["messages"]}) else: chain = rag_response_prompt | model | parser ai_reply = chain.invoke({ "programme":programme, "context":context, "messages":state["messages"] }) return {"messages":[("ai",ai_reply)]} def router_query(state:State)->str: if state["query_type"] =="academic": return "academic_rag" elif state["query_type"] =="fee": return "fee_rag" else: return "general" workflow = StateGraph(State) workflow.add_node("classifier",classifier_node) workflow.add_node("academic_rag",academic_rag_node) workflow.add_node("fee_rag",fee_rag_node) workflow.add_node("general",general_node) workflow.add_node("response",response_node) workflow.add_edge(START ,"classifier") workflow.add_conditional_edges("classifier",router_query) workflow.add_edge("academic_rag","response") workflow.add_edge("fee_rag","response") workflow.add_edge("general","response") workflow.add_edge("response",END) """Same routing graph as the conditional topic + MemorySaver: follow-up questions now work""" memory = MemorySaver() app = workflow.compile(checkpointer=memory) student_progamme = "BCA" config = {"configurable":{"thread_id":"dhruv_session_1"}} print("College Assistant Ready! (Type 'exit' to quit)\n") while True: user_input = input("You: ").strip() if user_input.lower() in ["exit" , "quit"]: break result = app.invoke({ "programme" : student_progamme, "messages":[("human",user_input)] },config=config) print(f'Ai:{result["messages"][-1].content}\n') |