arijit121 commited on
Commit
42e0e51
Β·
1 Parent(s): 70b536e
Files changed (1) hide show
  1. level_3_agent.py +209 -0
level_3_agent.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LangGraph Agent for Level 1, 2, 3 Reasoning Tasks"""
2
+ import os
3
+ from dotenv import load_dotenv
4
+ from langgraph.graph import START, StateGraph, MessagesState
5
+ from langgraph.prebuilt import tools_condition
6
+ from langgraph.prebuilt import ToolNode
7
+ from langchain_google_genai import ChatGoogleGenerativeAI
8
+ from langchain_groq import ChatGroq
9
+ from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint, HuggingFaceEmbeddings
10
+ from langchain_community.tools.tavily_search import TavilySearchResults
11
+ from langchain_community.document_loaders import WikipediaLoader
12
+ from langchain_community.document_loaders import ArxivLoader
13
+ from langchain_community.vectorstores import SupabaseVectorStore
14
+ from langchain_core.messages import SystemMessage
15
+ from langchain_core.tools import tool
16
+ from langchain.tools.retriever import create_retriever_tool
17
+ from supabase.client import Client, create_client
18
+
19
+ load_dotenv()
20
+
21
+ @tool
22
+ def multiply(a: int, b: int) -> int:
23
+ """Multiply two numbers.
24
+ Args:
25
+ a: first int
26
+ b: second int
27
+ """
28
+ return a * b
29
+
30
+ @tool
31
+ def add(a: int, b: int) -> int:
32
+ """Add two numbers.
33
+
34
+ Args:
35
+ a: first int
36
+ b: second int
37
+ """
38
+ return a + b
39
+
40
+ @tool
41
+ def subtract(a: int, b: int) -> int:
42
+ """Subtract two numbers.
43
+
44
+ Args:
45
+ a: first int
46
+ b: second int
47
+ """
48
+ return a - b
49
+
50
+ @tool
51
+ def divide(a: int, b: int) -> int:
52
+ """Divide two numbers.
53
+
54
+ Args:
55
+ a: first int
56
+ b: second int
57
+ """
58
+ if b == 0:
59
+ raise ValueError("Cannot divide by zero.")
60
+ return a / b
61
+
62
+ @tool
63
+ def modulus(a: int, b: int) -> int:
64
+ """Get the modulus of two numbers.
65
+
66
+ Args:
67
+ a: first int
68
+ b: second int
69
+ """
70
+ return a % b
71
+
72
+ @tool
73
+ def wiki_search(query: str) -> str:
74
+ """Search Wikipedia for a query and return maximum 2 results.
75
+
76
+ Args:
77
+ query: The search query."""
78
+ search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
79
+ formatted_search_docs = "\n\n---\n\n".join(
80
+ [
81
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
82
+ for doc in search_docs
83
+ ])
84
+ return {"wiki_results": formatted_search_docs}
85
+
86
+ @tool
87
+ def web_search(query: str) -> str:
88
+ """Search Tavily for a query and return maximum 3 results.
89
+
90
+ Args:
91
+ query: The search query."""
92
+ search_docs = TavilySearchResults(max_results=3).invoke(query=query)
93
+ formatted_search_docs = "\n\n---\n\n".join(
94
+ [
95
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
96
+ for doc in search_docs
97
+ ])
98
+ return {"web_results": formatted_search_docs}
99
+
100
+ @tool
101
+ def arvix_search(query: str) -> str:
102
+ """Search Arxiv for a query and return maximum 3 result.
103
+
104
+ Args:
105
+ query: The search query."""
106
+ search_docs = ArxivLoader(query=query, load_max_docs=3).load()
107
+ formatted_search_docs = "\n\n---\n\n".join(
108
+ [
109
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
110
+ for doc in search_docs
111
+ ])
112
+ return {"arvix_results": formatted_search_docs}
113
+
114
+
115
+ # Load the system prompt
116
+ # Assuming we are in model09, the path to system_prompt is RobotPai/system_prompt.txt
117
+ prompt_path = os.path.join(os.path.dirname(__file__), "RobotPai", "system_prompt.txt")
118
+ try:
119
+ with open(prompt_path, "r", encoding="utf-8") as f:
120
+ system_prompt = f.read()
121
+ except FileNotFoundError:
122
+ system_prompt = (
123
+ "You are a helpful assistant tasked with answering questions using a set of tools.\n\n"
124
+ "Your final answer must strictly follow this format:\n"
125
+ "FINAL ANSWER: [ANSWER]\n\n"
126
+ "Only write the answer in that exact format. Do not explain anything. Do not include any other text.\n\n"
127
+ "If you are provided with a similar question and its final answer, and the current question is **exactly the same**, then simply return the same final answer without using any tools.\n\n"
128
+ "Only use tools if the current question is different from the similar one.\n\n"
129
+ "Examples:\n"
130
+ "- FINAL ANSWER: FunkMonk\n"
131
+ "- FINAL ANSWER: Paris\n"
132
+ "- FINAL ANSWER: 128\n\n"
133
+ "If you do not follow this format exactly, your response will be considered incorrect."
134
+ )
135
+
136
+ sys_msg = SystemMessage(content=system_prompt)
137
+
138
+ # Build a retriever
139
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2") # dim=768
140
+ supabase: Client = create_client(
141
+ os.environ.get("SUPABASE_URL", ""),
142
+ os.environ.get("SUPABASE_SERVICE_KEY", "")
143
+ )
144
+ vector_store = SupabaseVectorStore(
145
+ client=supabase,
146
+ embedding=embeddings,
147
+ table_name="documents",
148
+ query_name="match_documents_langchain",
149
+ )
150
+
151
+ question_search_tool = create_retriever_tool(
152
+ retriever=vector_store.as_retriever(),
153
+ name="question_search",
154
+ description="A tool to retrieve similar questions from a vector store.",
155
+ )
156
+
157
+ tools = [
158
+ multiply,
159
+ add,
160
+ subtract,
161
+ divide,
162
+ modulus,
163
+ wiki_search,
164
+ web_search,
165
+ arvix_search,
166
+ question_search_tool,
167
+ ]
168
+
169
+ def build_graph(provider: str = "google"):
170
+ """Build the ReAct graph for Level 1, 2, 3 tasks"""
171
+ if provider == "google":
172
+ llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
173
+ elif provider == "groq":
174
+ llm = ChatGroq(model="qwen-qwq-32b", temperature=0)
175
+ elif provider == "huggingface":
176
+ llm = ChatHuggingFace(
177
+ llm=HuggingFaceEndpoint(
178
+ url="https://api-inference.huggingface.co/models/Meta-DeepLearning/llama-2-7b-chat-hf",
179
+ temperature=0,
180
+ ),
181
+ )
182
+ else:
183
+ raise ValueError("Invalid provider. Choose 'google', 'groq' or 'huggingface'.")
184
+
185
+ llm_with_tools = llm.bind_tools(tools)
186
+
187
+ def assistant(state: MessagesState):
188
+ """Assistant node that dynamically thinks and uses tools"""
189
+ # We prepend the system message so the LLM respects the strict output constraints
190
+ return {"messages": [llm_with_tools.invoke([sys_msg] + state["messages"])]}
191
+
192
+ builder = StateGraph(MessagesState)
193
+ builder.add_node("assistant", assistant)
194
+ builder.add_node("tools", ToolNode(tools))
195
+
196
+ # Setup the ReAct loop
197
+ builder.add_edge(START, "assistant")
198
+ builder.add_conditional_edges(
199
+ "assistant",
200
+ tools_condition, # Routes to "tools" if there are tool calls, otherwise "END"
201
+ )
202
+ builder.add_edge("tools", "assistant")
203
+
204
+ return builder.compile()
205
+
206
+ if __name__ == "__main__":
207
+ # Little test to show it compiles and works
208
+ graph = build_graph()
209
+ print("Level 1-3 Agent successfully built!")