File size: 2,505 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 | """
LangGraph StateGraph definition for the Agentic RAG pipeline.
"""
from langgraph.graph import StateGraph, END, START
from app.agent.state import AgentState
from app.agent.nodes import (
classify_intent,
retrieve,
grade_documents,
rewrite_query,
generate,
check_hallucination,
fallback,
respond,
route_after_classify,
route_after_grade,
route_after_hallucination,
)
_compiled_graph = None
def build_graph():
"""Build and compile the LangGraph agent graph."""
graph = StateGraph(AgentState)
# Register all nodes
graph.add_node("classify_intent", classify_intent)
graph.add_node("retrieve", retrieve)
graph.add_node("grade_documents", grade_documents)
graph.add_node("rewrite_query", rewrite_query)
graph.add_node("generate", generate)
graph.add_node("check_hallucination", check_hallucination)
graph.add_node("fallback", fallback)
graph.add_node("respond", respond)
# Entry point
graph.add_edge(START, "classify_intent")
# After intent classification: either fallback or retrieve
graph.add_conditional_edges(
"classify_intent",
route_after_classify,
{
"retrieve": "retrieve",
"fallback": "fallback",
},
)
# After retrieval: always grade documents
graph.add_edge("retrieve", "grade_documents")
# After grading: generate, rewrite, or fallback
graph.add_conditional_edges(
"grade_documents",
route_after_grade,
{
"generate": "generate",
"rewrite": "rewrite_query",
"fallback": "fallback",
},
)
# After rewrite: go back to retrieve
graph.add_edge("rewrite_query", "retrieve")
# After generation: hallucination check
graph.add_edge("generate", "check_hallucination")
# After hallucination check: respond or fallback
graph.add_conditional_edges(
"check_hallucination",
route_after_hallucination,
{
"respond": "respond",
"fallback": "fallback",
},
)
# Terminal nodes
graph.add_edge("fallback", "respond")
graph.add_edge("respond", END)
return graph.compile()
def get_graph():
"""Return the singleton compiled graph."""
global _compiled_graph
if _compiled_graph is None:
_compiled_graph = build_graph()
return _compiled_graph
|