File size: 1,327 Bytes
abd4a7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

LangGraph StateGraph definition for the Agentic RAG pipeline.

"""
import threading
from langgraph.graph import StateGraph, END, START

from app.agent.state import AgentState
from app.agent.nodes import (
    retrieve,
    generate,
    fallback,
    respond,
)

_compiled_graph = None
_graph_lock = threading.Lock()


def build_graph():
    """Build and compile the LangGraph agent graph."""
    graph = StateGraph(AgentState)

    # Register all nodes
    graph.add_node("retrieve", retrieve)
    graph.add_node("generate", generate)
    graph.add_node("fallback", fallback)
    graph.add_node("respond", respond)

    # Entry point: go straight to retrieval
    graph.add_edge(START, "retrieve")

    # After retrieval: go directly to generation
    graph.add_edge("retrieve", "generate")

    # After generation: straight to respond
    graph.add_edge("generate", "respond")

    # 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:
        with _graph_lock:
            if _compiled_graph is None:
                _compiled_graph = build_graph()
    return _compiled_graph