File size: 5,005 Bytes
d8ff68d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6dea0d
d8ff68d
 
 
 
 
 
f6dea0d
d8ff68d
 
 
 
 
 
 
 
 
 
 
 
f6dea0d
d8ff68d
 
 
 
f6dea0d
d8ff68d
 
 
f6dea0d
d8ff68d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6dea0d
d8ff68d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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"