File size: 7,753 Bytes
481dfe6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
"""

LangGraph node functions for the Agentic RAG pipeline.

Each node receives AgentState and returns a partial state update.

"""
import json
import logging

from langchain_core.documents import Document
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
from langchain_openai import ChatOpenAI

from app.agent.state import AgentState
from app.agent.prompts import (
    SYSTEM_PROMPT,
    INTENT_CLASSIFICATION_PROMPT,
    RELEVANCE_GRADING_PROMPT,
    HALLUCINATION_CHECK_PROMPT,
    QUERY_REWRITE_PROMPT,
    GENERATION_PROMPT,
)
from app.retrieval.retriever import retrieve_and_rerank, format_sources
from app.config import settings

logger = logging.getLogger(__name__)


def _get_llm(temperature: float = 0.0) -> ChatOpenAI:
    return ChatOpenAI(
        model=settings.llm_model,
        api_key=settings.openai_api_key,
        base_url=settings.openai_api_base,
        temperature=temperature,
        default_headers={
            "HTTP-Referer": "https://acpc.gujarat.gov.in",
            "X-Title": "ACPC Chatbot",
        },
    )


def classify_intent(state: AgentState) -> dict:
    """Node: Classify whether the query is ACPC-related, off-topic, or injection."""
    query = state["query"]
    llm = _get_llm(temperature=0.0)
    prompt = INTENT_CLASSIFICATION_PROMPT.format(query=query)
    response = llm.invoke([HumanMessage(content=prompt)])
    classification = response.content.strip().upper()

    if classification not in ("ACPC_RELATED", "OFF_TOPIC", "INJECTION"):
        # Default to ACPC_RELATED if response is unexpected
        classification = "ACPC_RELATED"

    logger.info("Intent classification: %s for query: %s", classification, query[:80])

    if classification in ("OFF_TOPIC", "INJECTION"):
        return {"route": "fallback"}
    return {"route": "retrieve"}


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 grade_documents(state: AgentState) -> dict:
    """Node: Grade each retrieved document for relevance to the query."""
    query = state["query"]
    documents = state["retrieved_documents"]

    if not documents:
        return {"relevant_documents": [], "confidence": 0.0}

    llm = _get_llm(temperature=0.0)
    relevant = []

    for doc in documents:
        prompt = RELEVANCE_GRADING_PROMPT.format(
            document=doc.page_content[:1000],
            question=query,
        )
        try:
            response = llm.invoke([HumanMessage(content=prompt)])
            result = json.loads(response.content.strip())
            if result.get("relevant") == "yes":
                relevant.append(doc)
        except (json.JSONDecodeError, Exception) as e:
            logger.warning("Grading error for doc: %s", e)
            # On error, include the document (fail open for retrieval)
            relevant.append(doc)

    confidence = len(relevant) / len(documents) if documents else 0.0
    logger.info("Grading complete: %d/%d relevant (confidence=%.2f)", len(relevant), len(documents), confidence)
    return {"relevant_documents": relevant, "confidence": confidence}


def rewrite_query(state: AgentState) -> dict:
    """Node: Rewrite the query for better retrieval and increment retry count."""
    original_query = state["query"]
    llm = _get_llm(temperature=0.3)
    prompt = QUERY_REWRITE_PROMPT.format(query=original_query)
    response = llm.invoke([HumanMessage(content=prompt)])
    rewritten = response.content.strip()
    retry_count = state.get("retry_count", 0) + 1
    logger.info("Query rewritten (retry %d): '%s' -> '%s'", retry_count, original_query[:60], rewritten[:60])
    return {"query": rewritten, "retry_count": retry_count}


def generate(state: AgentState) -> dict:
    """Node: Generate an answer from relevant documents using gpt-4o."""
    query = state["query"]
    relevant_docs = state["relevant_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)]
    # Add conversation history (excluding the current user message, already in query)
    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)
    logger.info("Generation complete (%d chars, %d sources)", len(generation), len(sources))
    return {"generation": generation, "sources": sources}


def check_hallucination(state: AgentState) -> dict:
    """Node: Verify that the generated answer is grounded in the retrieved context."""
    generation = state["generation"]
    relevant_docs = state["relevant_documents"]

    context = "\n\n".join(doc.page_content[:800] for doc in relevant_docs)
    prompt = HALLUCINATION_CHECK_PROMPT.format(documents=context, answer=generation)

    llm = _get_llm(temperature=0.0)
    try:
        response = llm.invoke([HumanMessage(content=prompt)])
        result = json.loads(response.content.strip())
        is_grounded = result.get("grounded", True)
    except (json.JSONDecodeError, Exception) as e:
        logger.warning("Hallucination check error: %s — defaulting to grounded=True", e)
        is_grounded = True

    if is_grounded:
        logger.info("Hallucination check passed")
        return {"route": "grounded"}
    else:
        logger.warning("Hallucination check FAILED — routing to fallback")
        return {"route": "not_grounded"}


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

def route_after_classify(state: AgentState) -> str:
    return state.get("route", "retrieve")


def route_after_grade(state: AgentState) -> str:
    relevant = state.get("relevant_documents", [])
    retry_count = state.get("retry_count", 0)
    confidence = state.get("confidence", 0.0)

    if relevant and confidence >= settings.confidence_threshold:
        return "generate"
    elif retry_count < settings.max_retrieval_retries:
        return "rewrite"
    else:
        return "fallback"


def route_after_hallucination(state: AgentState) -> str:
    return "respond" if state.get("route") == "grounded" else "fallback"