surya07 commited on
Commit
a0be6a7
·
verified ·
1 Parent(s): 7b7c7c0

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +261 -204
agent.py CHANGED
@@ -1,222 +1,279 @@
1
  import os
 
 
2
  from dotenv import load_dotenv
3
  from langgraph.graph import START, StateGraph, MessagesState
4
  from langgraph.prebuilt import tools_condition
5
  from langgraph.prebuilt import ToolNode
6
- from langchain_google_genai import ChatGoogleGenerativeAI
7
- from langchain_groq import ChatGroq
8
  from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint, HuggingFaceEmbeddings
9
  from langchain_community.tools.tavily_search import TavilySearchResults
10
- from langchain_community.document_loaders import WikipediaLoader
11
- from langchain_community.document_loaders import ArxivLoader
12
- from langchain_community.vectorstores import SupabaseVectorStore
13
  from langchain_core.messages import SystemMessage, HumanMessage
14
  from langchain_core.tools import tool
15
  from langchain.tools.retriever import create_retriever_tool
16
- from supabase.client import Client, create_client
 
 
 
17
 
18
  load_dotenv()
19
 
 
 
 
 
 
 
 
 
 
20
  @tool
21
- def multiply(a: int, b: int) -> int:
22
- """Multiply two numbers.
23
- Args:
24
- a: first int
25
- b: second int
26
- """
27
- return a * b
28
-
29
- @tool
30
- def add(a: int, b: int) -> int:
31
- """Add two numbers.
32
-
33
- Args:
34
- a: first int
35
- b: second int
36
- """
37
- return a + b
38
-
39
- @tool
40
- def subtract(a: int, b: int) -> int:
41
- """Subtract two numbers.
42
-
43
- Args:
44
- a: first int
45
- b: second int
46
- """
47
- return a - b
48
-
49
- @tool
50
- def divide(a: int, b: int) -> int:
51
- """Divide two numbers.
52
-
53
- Args:
54
- a: first int
55
- b: second int
56
- """
57
- if b == 0:
58
- raise ValueError("Cannot divide by zero.")
59
- return a / b
60
-
61
- @tool
62
- def modulus(a: int, b: int) -> int:
63
- """Get the modulus of two numbers.
64
-
65
- Args:
66
- a: first int
67
- b: second int
68
- """
69
- return a % b
70
-
71
- @tool
72
- def wiki_search(query: str) -> str:
73
- """Search Wikipedia for a query and return maximum 2 results.
74
-
75
- Args:
76
- query: The search query."""
77
- search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
78
- formatted_search_docs = "\n\n---\n\n".join(
79
- [
80
- f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
81
- for doc in search_docs
82
- ])
83
- return {"wiki_results": formatted_search_docs}
84
-
85
- @tool
86
- def web_search(query: str) -> str:
87
- """Search Tavily for a query and return maximum 3 results.
88
-
89
- Args:
90
- query: The search query."""
91
- search_docs = TavilySearchResults(max_results=3).invoke(query=query)
92
- formatted_search_docs = "\n\n---\n\n".join(
93
- [
94
- f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
95
- for doc in search_docs
96
- ])
97
- return {"web_results": formatted_search_docs}
98
-
99
- @tool
100
- def arvix_search(query: str) -> str:
101
- """Search Arxiv for a query and return maximum 3 result.
102
-
103
- Args:
104
- query: The search query."""
105
- search_docs = ArxivLoader(query=query, load_max_docs=3).load()
106
- formatted_search_docs = "\n\n---\n\n".join(
107
- [
108
- f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
109
- for doc in search_docs
110
- ])
111
- return {"arvix_results": formatted_search_docs}
112
-
113
-
114
-
115
- # load the system prompt from the file
116
- with open("system_prompt.txt", "r", encoding="utf-8") as f:
117
- system_prompt = f.read()
118
-
119
- # System message
120
- sys_msg = SystemMessage(content=system_prompt)
121
-
122
- # build a retriever
123
- embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2") # dim=768
124
- supabase: Client = create_client(
125
- os.environ.get("SUPABASE_URL"),
126
- os.environ.get("SUPABASE_SERVICE_KEY"))
127
- vector_store = SupabaseVectorStore(
128
- client=supabase,
129
- embedding= embeddings,
130
- table_name="documents",
131
- query_name="match_documents_langchain",
132
- )
133
- create_retriever_tool = create_retriever_tool(
134
- retriever=vector_store.as_retriever(),
135
- name="Question Search",
136
- description="A tool to retrieve similar questions from a vector store.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  )
138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
 
 
 
 
 
 
 
140
 
141
- tools = [
142
- multiply,
143
- add,
144
- subtract,
145
- divide,
146
- modulus,
147
- wiki_search,
148
- web_search,
149
- arvix_search,
150
- ]
151
-
152
- # Build graph function
153
- def build_graph(provider: str = "google"):
154
- """Build the graph"""
155
- # Load environment variables from .env file
156
- if provider == "google":
157
- # Google Gemini
158
- llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
159
- elif provider == "groq":
160
- # Groq https://console.groq.com/docs/models
161
- llm = ChatGroq(model="qwen-qwq-32b", temperature=0) # optional : qwen-qwq-32b gemma2-9b-it
162
- elif provider == "huggingface":
163
- # TODO: Add huggingface endpoint
164
- llm = ChatHuggingFace(
165
- llm=HuggingFaceEndpoint(
166
- url="https://api-inference.huggingface.co/models/Meta-DeepLearning/llama-2-7b-chat-hf",
167
- temperature=0,
168
- ),
169
- )
170
- else:
171
- raise ValueError("Invalid provider. Choose 'google', 'groq' or 'huggingface'.")
172
- # Bind tools to LLM
173
- llm_with_tools = llm.bind_tools(tools)
174
-
175
- # Node
176
- def assistant(state: MessagesState):
177
- """Assistant node"""
178
- return {"messages": [llm_with_tools.invoke(state["messages"])]}
179
-
180
- # def retriever(state: MessagesState):
181
- # """Retriever node"""
182
- # similar_question = vector_store.similarity_search(state["messages"][0].content)
183
- #example_msg = HumanMessage(
184
- # content=f"Here I provide a similar question and answer for reference: \n\n{similar_question[0].page_content}",
185
- # )
186
- # return {"messages": [sys_msg] + state["messages"] + [example_msg]}
187
-
188
- from langchain_core.messages import AIMessage
189
-
190
- def retriever(state: MessagesState):
191
- query = state["messages"][-1].content
192
- similar_doc = vector_store.similarity_search(query, k=1)[0]
193
-
194
- content = similar_doc.page_content
195
- if "Final answer :" in content:
196
- answer = content.split("Final answer :")[-1].strip()
197
- else:
198
- answer = content.strip()
199
-
200
- return {"messages": [AIMessage(content=answer)]}
201
-
202
- # builder = StateGraph(MessagesState)
203
- #builder.add_node("retriever", retriever)
204
- #builder.add_node("assistant", assistant)
205
- #builder.add_node("tools", ToolNode(tools))
206
- #builder.add_edge(START, "retriever")
207
- #builder.add_edge("retriever", "assistant")
208
- #builder.add_conditional_edges(
209
- # "assistant",
210
- # tools_condition,
211
- #)
212
- #builder.add_edge("tools", "assistant")
213
-
214
- builder = StateGraph(MessagesState)
215
- builder.add_node("retriever", retriever)
216
-
217
- # Retriever ist Start und Endpunkt
218
- builder.set_entry_point("retriever")
219
- builder.set_finish_point("retriever")
220
-
221
- # Compile graph
222
- return builder.compile()
 
1
  import os
2
+ import certifi
3
+ os.environ['REQUESTS_CA_BUNDLE'] = certifi.where()
4
  from dotenv import load_dotenv
5
  from langgraph.graph import START, StateGraph, MessagesState
6
  from langgraph.prebuilt import tools_condition
7
  from langgraph.prebuilt import ToolNode
 
 
8
  from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint, HuggingFaceEmbeddings
9
  from langchain_community.tools.tavily_search import TavilySearchResults
10
+ from langchain_community.document_loaders import WikipediaLoader, ArxivLoader
11
+ from langchain_community.vectorstores import Chroma
 
12
  from langchain_core.messages import SystemMessage, HumanMessage
13
  from langchain_core.tools import tool
14
  from langchain.tools.retriever import create_retriever_tool
15
+ from langchain_core.documents import Document
16
+ from langchain_community.embeddings import HuggingFaceEmbeddings
17
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
18
+ from langchain_groq import ChatGroq
19
 
20
  load_dotenv()
21
 
22
+
23
+ # ---------------- CONFIGURATION ----------------
24
+ # Change this to any valid Hugging Face model endpoint (e.g., meta-llama/Llama-3-8b-chat-hf)
25
+ HF_MODEL_NAME = os.getenv("LLAMA_MODEL_NAME", "meta-llama/Meta-Llama-3-8B-Instruct")
26
+ HF_API_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")
27
+ HF_MODEL_URL = f"https://api-inference.huggingface.co/models/{HF_MODEL_NAME}"
28
+ # Use the OpenAI-compatible inference endpoint
29
+ HF_OPENAI_URL = "https://api-inference.huggingface.co/openai"
30
+ # ---------------- UTILITY TOOLS ----------------
31
  @tool
32
+ def multiply_numbers(x: int, y: int) -> int:
33
+ """Multiply two integers and return the result."""
34
+ return x * y
35
+
36
+ @tool
37
+ def add_numbers(x: int, y: int) -> int:
38
+ """Add two integers and return the sum."""
39
+ return x + y
40
+
41
+ @tool
42
+ def subtract_numbers(x: int, y: int) -> int:
43
+ """Subtract the second integer from the first and return the result."""
44
+ return x - y
45
+
46
+ @tool
47
+ def divide_numbers(x: int, y: int) -> float:
48
+ """Divide the first number by the second and return the result. Raises an error on division by zero."""
49
+ if y == 0:
50
+ raise ValueError("Division by zero is not allowed.")
51
+ return x / y
52
+
53
+ @tool
54
+ def modulus_numbers(x: int, y: int) -> int:
55
+ """Return the remainder when the first number is divided by the second."""
56
+ return x % y
57
+
58
+ @tool
59
+ def power_numbers(base: float, exponent: float) -> float:
60
+ """Raise the base to the power of exponent and return the result."""
61
+ return base ** exponent
62
+
63
+ @tool
64
+ def root_number(value: float, n: float) -> float:
65
+ """Compute the nth root of a value and return the result."""
66
+ return value ** (1 / n)
67
+
68
+ @tool
69
+ def wiki_lookup(query: str) -> str:
70
+ """Search Wikipedia for the query and return up to 2 summarized documents."""
71
+ docs = WikipediaLoader(query=query, load_max_docs=2).load()
72
+ return "\n\n---\n\n".join(
73
+ f'<Document source="{d.metadata["source"]}" page="{d.metadata.get("page", "")}"/>{d.page_content}</Document>' for d in docs
74
+ )
75
+
76
+ @tool
77
+ def web_lookup(query: str) -> str:
78
+ """Search the web using Tavily and return up to 3 summarized results."""
79
+ docs = TavilySearchResults(max_results=3).invoke(query=query)
80
+ return "\n\n---\n\n".join(
81
+ f'<Document source="{d.metadata["source"]}" page="{d.metadata.get("page", "")}"/>{d.page_content}</Document>' for d in docs
82
+ )
83
+
84
+ @tool
85
+ def arxiv_lookup(query: str) -> str:
86
+ """Search arXiv for the query and return summaries of up to 3 papers."""
87
+ docs = ArxivLoader(query=query, load_max_docs=3).load()
88
+ return "\n\n---\n\n".join(
89
+ f'<Document source="{d.metadata["source"]}" page="{d.metadata.get("page", "")}"/>{d.page_content[:800]}</Document>' for d in docs
90
+ )
91
+ @tool
92
+ def add_numbers(x: int, y: int) -> int:
93
+ """Add two integers and return the sum."""
94
+ return x + y
95
+
96
+ @tool
97
+ def subtract_numbers(x: int, y: int) -> int:
98
+ """Subtract the second integer from the first and return the result."""
99
+ return x - y
100
+
101
+ @tool
102
+ def divide_numbers(x: int, y: int) -> float:
103
+ """Divide the first number by the second and return the result. Raises an error on division by zero."""
104
+ if y == 0:
105
+ raise ValueError("Division by zero is not allowed.")
106
+ return x / y
107
+
108
+ @tool
109
+ def modulus_numbers(x: int, y: int) -> int:
110
+ """Return the remainder when the first number is divided by the second."""
111
+ return x % y
112
+
113
+ @tool
114
+ def power_numbers(base: float, exponent: float) -> float:
115
+ """Raise the base to the power of exponent and return the result."""
116
+ return base ** exponent
117
+
118
+ @tool
119
+ def root_number(value: float, n: float) -> float:
120
+ """Compute the nth root of a value and return the result."""
121
+ return value ** (1 / n)
122
+
123
+ @tool
124
+ def wiki_lookup(query: str) -> str:
125
+ """Search Wikipedia for the query and return up to 2 summarized documents."""
126
+ docs = WikipediaLoader(query=query, load_max_docs=2).load()
127
+ return "\n\n---\n\n".join(
128
+ f'<Document source="{d.metadata["source"]}" page="{d.metadata.get("page", "")}"/>{d.page_content}</Document>' for d in docs
129
+ )
130
+
131
+ @tool
132
+ def web_lookup(query: str) -> str:
133
+ """Search the web using Tavily and return up to 3 summarized results."""
134
+ docs = TavilySearchResults(max_results=3).invoke(query=query)
135
+ return "\n\n---\n\n".join(
136
+ f'<Document source="{d.metadata["source"]}" page="{d.metadata.get("page", "")}"/>{d.page_content}</Document>' for d in docs
137
+ )
138
+
139
+ @tool
140
+ def arxiv_lookup(query: str) -> str:
141
+ """Search arXiv for the query and return summaries of up to 3 papers."""
142
+ docs = ArxivLoader(query=query, load_max_docs=3).load()
143
+ return "\n\n---\n\n".join(
144
+ f'<Document source="{d.metadata["source"]}" page="{d.metadata.get("page", "")}"/>{d.page_content[:800]}</Document>' for d in docs
145
+ )
146
+
147
+ # # ---------------- SETUP LOCAL VECTORSTORE ----------------
148
+ # embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
149
+ # text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)
150
+ # sample_docs = [Document(page_content="St. Thomas Aquinas was a medieval Catholic priest and philosopher.", metadata={"source": "wiki", "page": "St. Thomas Aquinas"})]
151
+ # split_docs = text_splitter.split_documents(sample_docs)
152
+ # vector_db = Chroma.from_documents(documents=split_docs, embedding=embedding_model)
153
+ # retriever_tool = create_retriever_tool(
154
+ # retriever=vector_db.as_retriever(),
155
+ # name="SimilarQuestionFinder",
156
+ # description="Retrieve similar questions and examples from vector DB."
157
+ # )
158
+
159
+ # # ---------------- SYSTEM PROMPT ----------------
160
+ # with open("system_prompt.txt", "r", encoding="utf-8") as f:
161
+ # system_content = f.read()
162
+ # system_message = SystemMessage(content=system_content)
163
+
164
+ # # ---------------- BUILD STATE GRAPH ----------------
165
+ # def construct_agent_graph():
166
+ # llama_llm = ChatHuggingFace(
167
+ # llm=HuggingFaceEndpoint(
168
+ # endpoint_url=HF_OPENAI_URL,
169
+ # temperature=0
170
+ # )
171
+ # ).bind_tools([
172
+ # multiply_numbers,
173
+ # add_numbers,
174
+ # subtract_numbers,
175
+ # divide_numbers,
176
+ # modulus_numbers,
177
+ # power_numbers,
178
+ # root_number,
179
+ # wiki_lookup,
180
+ # web_lookup,
181
+ # arxiv_lookup,
182
+ # retriever_tool,
183
+ # ])
184
+
185
+ # def retrieve_node(state: MessagesState):
186
+ # similar = vector_db.similarity_search(state["messages"][0].content)
187
+ # hint = HumanMessage(content=f"Reference example:\n{similar[0].page_content}" if similar else "")
188
+ # return {"messages": [system_message] + state["messages"] + [hint]}
189
+
190
+ # def respond_node(state: MessagesState):
191
+ # return {"messages": [llama_llm.invoke(state["messages"]) ]}
192
+
193
+ # graph_builder = StateGraph(MessagesState)
194
+ # graph_builder.add_node("find_similar", retrieve_node)
195
+ # graph_builder.add_node("generate_answer", respond_node)
196
+ # graph_builder.add_node("tool_executor", ToolNode([]))
197
+
198
+ # graph_builder.add_edge(START, "find_similar")
199
+ # graph_builder.add_edge("find_similar", "generate_answer")
200
+ # graph_builder.add_conditional_edges(
201
+ # "generate_answer",
202
+ # tools_condition,
203
+ # {"tools": "tool_executor", "default": "generate_answer"}
204
+ # )
205
+ # graph_builder.add_edge("tool_executor", "generate_answer")
206
+
207
+ # return graph_builder.compile()
208
+
209
+ # # ---------------- RUN EXAMPLE ----------------
210
+ # if __name__ == "__main__":
211
+ # sample_q = "When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect?"
212
+ # agent = construct_agent_graph()
213
+ # msgs = [HumanMessage(content=sample_q)]
214
+ # out = agent.invoke({"messages": msgs})
215
+ # for m in out["messages"]:
216
+ # m.pretty_print()
217
+
218
+ # ---------------- EMBEDDINGS & VECTOR DB ----------------
219
+ embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
220
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)
221
+ sample_docs = [Document(page_content="Sample doc.", metadata={"source":"wiki"})]
222
+ split_docs = text_splitter.split_documents(sample_docs)
223
+ vector_db = Chroma.from_documents(documents=split_docs, embedding=embedding_model)
224
+ retriever_tool = create_retriever_tool(
225
+ retriever=vector_db.as_retriever(),
226
+ name="SimilarQuestionFinder",
227
+ description="Retrieve similar questions and examples from vector DB."
228
  )
229
 
230
+ all_tools = [multiply_numbers, add_numbers, subtract_numbers, divide_numbers,
231
+ modulus_numbers, power_numbers, root_number,
232
+ wiki_lookup, web_lookup, arxiv_lookup, retriever_tool]
233
+
234
+ # ---------------- SYSTEM PROMPT ----------------
235
+ with open("system_prompt.txt", "r", encoding="utf-8") as f:
236
+ system_content = f.read()
237
+ system_message = SystemMessage(content=system_content)
238
+ # ---------------- BUILD GRAPH ----------------
239
+ def construct_agent_graph():
240
+ llama_llm = ChatGroq(
241
+ model="qwen-qwq-32b",
242
+ api_key=os.environ["GROQ_API_KEY"],
243
+ temperature=0,
244
+ )
245
+
246
+ def retrieve_node(state: MessagesState):
247
+ msgs = [system_message] + state["messages"]
248
+ similar = vector_db.similarity_search(state["messages"][0].content)
249
+ if similar:
250
+ msgs.append(HumanMessage(content=f"Reference example:\n{similar[0].page_content}"))
251
+ return {"messages": msgs}
252
+
253
+ def respond_node(state: MessagesState):
254
+ return {"messages": [llama_llm.invoke(state["messages"])]}
255
+
256
+ graph = StateGraph(MessagesState)
257
+ graph.add_node("find_similar", retrieve_node)
258
+ graph.add_node("generate_answer", respond_node)
259
+ graph.add_node("tool_executor", ToolNode(tools=all_tools))
260
+
261
+ graph.add_edge(START, "find_similar")
262
+ graph.add_edge("find_similar", "generate_answer")
263
+ graph.add_conditional_edges(
264
+ "generate_answer",
265
+ tools_condition,
266
+ {"tools": "tool_executor", "__end__": "__end__"}
267
+ )
268
+ graph.add_edge("tool_executor", "generate_answer")
269
+
270
+ return graph.compile()
271
 
272
+ # ---------------- RUN EXAMPLE ----------------
273
+ if __name__ == "__main__":
274
+ agent = construct_agent_graph()
275
+ sample_q = "When was St. Thomas Aquinas added to that page?"
276
+ out = agent.invoke({"messages": [HumanMessage(content=sample_q)]})
277
+ for m in out["messages"]:
278
+ m.pretty_print()
279