""" 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"