welcometoFightclub's picture
Upload 42 files
abd4a7f verified
Raw History Blame Contribute Delete
4.97 kB
"""
LangGraph node functions for the Agentic RAG pipeline.
Each node receives AgentState and returns a partial state update.
Guardrail logic (relevance grading, hallucination checking) lives in app/guardrails/ β€”
nodes here are thin wrappers that call those modules.
"""
import logging
import re
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.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__)
def _append_mandatory_citations(answer: str, sources: list[dict]) -> str:
"""Guarantee clickable inline citations and no trailing reference block."""
if not sources:
return answer
normalized = (answer or "").strip()
if not normalized:
normalized = "Based on the available information."
# Remove any generated reference section from the tail.
normalized = re.sub(
r"\n\s*(?:##\s*)?References\b[\s\S]*$",
"",
normalized,
flags=re.IGNORECASE,
).strip()
source_urls: dict[int, str] = {}
for idx, source in enumerate(sources, start=1):
source_urls[idx] = source.get("url", "") or "https://acpc.gujarat.gov.in/assets/uploads/media-uploader/BE"
# Convert plain [n] citations to clickable markdown links [n](url).
def _replace_plain_citation(match: re.Match[str]) -> str:
citation_number = int(match.group(1))
citation_url = source_urls.get(citation_number) or source_urls[1]
return f"[{citation_number}]({citation_url})"
normalized = re.sub(r"\[(\d+)\](?!\()", _replace_plain_citation, normalized)
# Ensure at least one inline citation exists.
if not re.search(r"\[\d+\]\([^\)]+\)", normalized):
normalized = f"{normalized} [1]({source_urls[1]})"
return normalized
# ──────────────────────────────────────────────
# Core pipeline nodes
# ──────────────────────────────────────────────
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 = retrieve_and_rerank(query)
logger.info("Retrieved %d documents", len(documents))
return {"retrieved_documents": documents}
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.1)
response = llm.invoke(messages)
generation = response.content.strip()
sources = format_sources(relevant_docs)
generation = _append_mandatory_citations(generation, sources)
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)]}