-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
92 lines (71 loc) 路 2.55 KB
/
Copy pathmain.py
File metadata and controls
92 lines (71 loc) 路 2.55 KB
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
import os
from dotenv import load_dotenv
from langgraph.graph import StateGraph, START, END
from langchain_core.messages import HumanMessage, AIMessage
from state import AgentState
from nodes import retrieve, grade_documents, generate, web_search
def create_rag_graph() -> StateGraph:
"""Create the Agentic RAG StateGraph with self-correction loop."""
# Initialize the graph
workflow = StateGraph(AgentState)
# Add nodes
workflow.add_node("retrieve", retrieve)
workflow.add_node("grade_documents", grade_documents)
workflow.add_node("generate", generate)
workflow.add_node("web_search", web_search)
# Add edges
workflow.add_edge(START, "retrieve")
workflow.add_edge("retrieve", "grade_documents")
# Conditional edge for self-correction loop
def decide_next_step(state: AgentState) -> str:
"""Determine next step based on document relevance."""
# If web search was already performed, go to generation to prevent infinite loop
if state.get("web_search_performed", False):
return "generate"
if state.get("is_relevant", False):
return "generate"
else:
return "web_search"
workflow.add_conditional_edges(
"grade_documents",
decide_next_step,
{
"generate": "generate",
"web_search": "web_search"
}
)
# Complete the loop
workflow.add_edge("web_search", "retrieve")
workflow.add_edge("generate", END)
return workflow.compile()
def main():
"""Main function to run the Agentic RAG system."""
# Load environment variables
load_dotenv()
# Verify Google API key is available
if not os.getenv("GOOGLE_API_KEY"):
raise ValueError("GOOGLE_API_KEY environment variable is not set")
# Create the graph
app = create_rag_graph()
# Example usage
print("Agentic RAG System with Self-Correction Loop")
print("=" * 50)
# Initial state with a user question
initial_state = {
"messages": [
HumanMessage(content="Tell me about TechFlow AI's RAG architecture")
],
"documents": [],
"is_relevant": False,
"web_search_performed": False
}
# Run the graph
result = app.invoke(initial_state)
# Print the final answer
print("\nFinal Answer:")
print("-" * 20)
for message in result["messages"]:
if isinstance(message, AIMessage):
print(message.content)
if __name__ == "__main__":
main()