danhugo245 commited on
Commit
2b1c8b4
·
1 Parent(s): b386c24

FEAT: add agent

Browse files
Files changed (4) hide show
  1. agent.py +210 -0
  2. app.py +17 -4
  3. prompts.py +5 -0
  4. requirements.txt +2 -1
agent.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LangGraph Agent"""
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, HumanMessage
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
+ from prompts import system_prompt
19
+
20
+ load_dotenv()
21
+
22
+ @tool
23
+ def multiply(a: int, b: int) -> int:
24
+ """Multiply two numbers.
25
+
26
+ Args:
27
+ a: first int
28
+ b: second int
29
+ """
30
+ return a * b
31
+
32
+ @tool
33
+ def add(a: int, b: int) -> int:
34
+ """Add two numbers.
35
+
36
+ Args:
37
+ a: first int
38
+ b: second int
39
+ """
40
+ return a + b
41
+
42
+ @tool
43
+ def subtract(a: int, b: int) -> int:
44
+ """Subtract two numbers.
45
+
46
+ Args:
47
+ a: first int
48
+ b: second int
49
+ """
50
+ return a - b
51
+
52
+ @tool
53
+ def divide(a: int, b: int) -> int:
54
+ """Divide two numbers.
55
+
56
+ Args:
57
+ a: first int
58
+ b: second int
59
+ """
60
+ if b == 0:
61
+ raise ValueError("Cannot divide by zero.")
62
+ return a / b
63
+
64
+ @tool
65
+ def modulus(a: int, b: int) -> int:
66
+ """Get the modulus of two numbers.
67
+
68
+ Args:
69
+ a: first int
70
+ b: second int
71
+ """
72
+ return a % b
73
+
74
+ @tool
75
+ def wiki_search(query: str) -> str:
76
+ """Search Wikipedia for a query and return maximum 2 results.
77
+
78
+ Args:
79
+ query: The search query."""
80
+ search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
81
+ formatted_search_docs = "\n\n---\n\n".join(
82
+ [
83
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
84
+ for doc in search_docs
85
+ ])
86
+ return {"wiki_results": formatted_search_docs}
87
+
88
+ @tool
89
+ def web_search(query: str) -> str:
90
+ """Search Tavily for a query and return maximum 3 results.
91
+
92
+ Args:
93
+ query: The search query."""
94
+ search_docs = TavilySearchResults(max_results=3).invoke(query=query)
95
+ formatted_search_docs = "\n\n---\n\n".join(
96
+ [
97
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
98
+ for doc in search_docs
99
+ ])
100
+ return {"web_results": formatted_search_docs}
101
+
102
+ @tool
103
+ def arvix_search(query: str) -> str:
104
+ """Search Arxiv for a query and return maximum 3 result.
105
+
106
+ Args:
107
+ query: The search query."""
108
+ search_docs = ArxivLoader(query=query, load_max_docs=3).load()
109
+ formatted_search_docs = "\n\n---\n\n".join(
110
+ [
111
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
112
+ for doc in search_docs
113
+ ])
114
+ return {"arvix_results": formatted_search_docs}
115
+
116
+
117
+ # System message
118
+ sys_msg = SystemMessage(content=system_prompt)
119
+
120
+ # build a retriever
121
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2") # dim=768
122
+ supabase: Client = create_client(
123
+ os.environ.get("SUPABASE_URL"),
124
+ os.environ.get("SUPABASE_SERVICE_KEY"))
125
+ vector_store = SupabaseVectorStore(
126
+ client=supabase,
127
+ embedding= embeddings,
128
+ table_name="documents",
129
+ query_name="match_documents_langchain",
130
+ )
131
+ create_retriever_tool = create_retriever_tool(
132
+ retriever=vector_store.as_retriever(),
133
+ name="Question Search",
134
+ description="A tool to retrieve similar questions from a vector store.",
135
+ )
136
+
137
+
138
+
139
+ tools = [
140
+ multiply,
141
+ add,
142
+ subtract,
143
+ divide,
144
+ modulus,
145
+ wiki_search,
146
+ web_search,
147
+ arvix_search,
148
+ ]
149
+
150
+ # Build graph function
151
+ def build_graph(provider: str = "google"):
152
+ """Build the graph"""
153
+ # Load environment variables from .env file
154
+ if provider == "google":
155
+ # Google Gemini
156
+ llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
157
+ elif provider == "groq":
158
+ # Groq https://console.groq.com/docs/models
159
+ llm = ChatGroq(model="qwen-qwq-32b", temperature=0) # optional : qwen-qwq-32b gemma2-9b-it
160
+ elif provider == "huggingface":
161
+ # TODO: Add huggingface endpoint
162
+ llm = ChatHuggingFace(
163
+ llm=HuggingFaceEndpoint(
164
+ url="https://api-inference.huggingface.co/models/Meta-DeepLearning/llama-2-7b-chat-hf",
165
+ temperature=0,
166
+ ),
167
+ )
168
+ else:
169
+ raise ValueError("Invalid provider. Choose 'google', 'groq' or 'huggingface'.")
170
+ # Bind tools to LLM
171
+ llm_with_tools = llm.bind_tools(tools)
172
+
173
+ # Node
174
+ def assistant(state: MessagesState):
175
+ """Assistant node"""
176
+ return {"messages": [llm_with_tools.invoke(state["messages"])]}
177
+
178
+ def retriever(state: MessagesState):
179
+ """Retriever node"""
180
+ similar_question = vector_store.similarity_search(state["messages"][0].content)
181
+ example_msg = HumanMessage(
182
+ content=f"Here I provide a similar question and answer for reference: \n\n{similar_question[0].page_content}",
183
+ )
184
+ return {"messages": [sys_msg] + state["messages"] + [example_msg]}
185
+
186
+ builder = StateGraph(MessagesState)
187
+ builder.add_node("retriever", retriever)
188
+ builder.add_node("assistant", assistant)
189
+ builder.add_node("tools", ToolNode(tools))
190
+ builder.add_edge(START, "retriever")
191
+ builder.add_edge("retriever", "assistant")
192
+ builder.add_conditional_edges(
193
+ "assistant",
194
+ tools_condition,
195
+ )
196
+ builder.add_edge("tools", "assistant")
197
+
198
+ # Compile graph
199
+ return builder.compile()
200
+
201
+ # test
202
+ if __name__ == "__main__":
203
+ question = "When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect?"
204
+ # Build the graph
205
+ graph = build_graph(provider="groq")
206
+ # Run the graph
207
+ messages = [HumanMessage(content=question)]
208
+ messages = graph.invoke({"messages": messages})
209
+ for m in messages["messages"]:
210
+ m.pretty_print()
app.py CHANGED
@@ -1,8 +1,13 @@
 
1
  import os
 
2
  import gradio as gr
3
  import requests
4
- import inspect
5
  import pandas as pd
 
 
 
 
6
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
@@ -10,14 +15,22 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
  # --- Basic Agent Definition ---
12
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
 
 
13
  class BasicAgent:
 
14
  def __init__(self):
15
  print("BasicAgent initialized.")
 
 
16
  def __call__(self, question: str) -> str:
17
  print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
 
 
 
21
 
22
  def run_and_submit_all( profile: gr.OAuthProfile | None):
23
  """
 
1
+ """ Basic Agent Evaluation Runner"""
2
  import os
3
+ import inspect
4
  import gradio as gr
5
  import requests
 
6
  import pandas as pd
7
+ from langchain_core.messages import HumanMessage
8
+ from agent import build_graph
9
+
10
+
11
 
12
  # (Keep Constants as is)
13
  # --- Constants ---
 
15
 
16
  # --- Basic Agent Definition ---
17
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
18
+
19
+
20
  class BasicAgent:
21
+ """A langgraph agent."""
22
  def __init__(self):
23
  print("BasicAgent initialized.")
24
+ self.graph = build_graph()
25
+
26
  def __call__(self, question: str) -> str:
27
  print(f"Agent received question (first 50 chars): {question[:50]}...")
28
+ # Wrap the question in a HumanMessage from langchain_core
29
+ messages = [HumanMessage(content=question)]
30
+ messages = self.graph.invoke({"messages": messages})
31
+ answer = messages['messages'][-1].content
32
+ return answer[14:]
33
+
34
 
35
  def run_and_submit_all( profile: gr.OAuthProfile | None):
36
  """
prompts.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ system_prompt = """You are a helpful assistant tasked with answering questions using a set of tools.
2
+ Now, I will ask you a question. Report your thoughts, and finish your answer with the following template:
3
+ FINAL ANSWER: [YOUR FINAL ANSWER].
4
+ YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
5
+ Your answer should only start with "FINAL ANSWER: ", then follows with the answer."""
requirements.txt CHANGED
@@ -15,4 +15,5 @@ arxiv
15
  pymupdf
16
  wikipedia
17
  pgvector
18
- python-dotenv
 
 
15
  pymupdf
16
  wikipedia
17
  pgvector
18
+ python-dotenv
19
+ gradio[oauth]