acpcchatbotadmin's picture
Upload 40 files
481dfe6 verified
Raw History Blame Contribute Delete
2.51 kB
"""
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