Spaces:
Starting
Starting
initial commit
Browse files- agents.py +182 -0
- app.py +10 -3
- requirements.txt +19 -1
- system_prompt.txt +5 -0
agents.py
ADDED
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.agents import initialize_agent, Tool
|
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 |
+
|
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 |
+
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 |
+
Args:
|
43 |
+
a: first int
|
44 |
+
b: second int
|
45 |
+
"""
|
46 |
+
return a - b
|
47 |
+
|
48 |
+
@tool
|
49 |
+
def divide(a: int, b: int) -> int:
|
50 |
+
"""Divide two numbers.
|
51 |
+
Args:
|
52 |
+
a: first int
|
53 |
+
b: second int
|
54 |
+
"""
|
55 |
+
if b == 0:
|
56 |
+
raise ValueError("Cannot divide by zero.")
|
57 |
+
return a / b
|
58 |
+
|
59 |
+
@tool
|
60 |
+
def modulus(a: int, b: int) -> int:
|
61 |
+
"""Get the modulus of two numbers.
|
62 |
+
Args:
|
63 |
+
a: first int
|
64 |
+
b: second int
|
65 |
+
"""
|
66 |
+
return a % b
|
67 |
+
|
68 |
+
@tool
|
69 |
+
def wiki_search(query: str) -> str:
|
70 |
+
"""Search Wikipedia for a query and return maximum 2 results.
|
71 |
+
Args:
|
72 |
+
query: The search query."""
|
73 |
+
search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
|
74 |
+
formatted_search_docs = "\n\n---\n\n".join(
|
75 |
+
[
|
76 |
+
f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
|
77 |
+
for doc in search_docs
|
78 |
+
])
|
79 |
+
return {"wiki_results": formatted_search_docs}
|
80 |
+
|
81 |
+
@tool
|
82 |
+
def web_search(query: str) -> str:
|
83 |
+
"""Search Tavily for a query and return maximum 3 results.
|
84 |
+
Args:
|
85 |
+
query: The search query."""
|
86 |
+
search_docs = TavilySearchResults(max_results=3).invoke(query=query)
|
87 |
+
formatted_search_docs = "\n\n---\n\n".join(
|
88 |
+
[
|
89 |
+
f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
|
90 |
+
for doc in search_docs
|
91 |
+
])
|
92 |
+
return {"web_results": formatted_search_docs}
|
93 |
+
|
94 |
+
@tool
|
95 |
+
def arvix_search(query: str) -> str:
|
96 |
+
"""Search Arxiv for a query and return maximum 3 result.
|
97 |
+
Args:
|
98 |
+
query: The search query."""
|
99 |
+
search_docs = ArxivLoader(query=query, load_max_docs=3).load()
|
100 |
+
formatted_search_docs = "\n\n---\n\n".join(
|
101 |
+
[
|
102 |
+
f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
|
103 |
+
for doc in search_docs
|
104 |
+
])
|
105 |
+
return {"arvix_results": formatted_search_docs}
|
106 |
+
|
107 |
+
|
108 |
+
|
109 |
+
# load the system prompt from the file
|
110 |
+
with open("system_prompt.txt", "r", encoding="utf-8") as f:
|
111 |
+
system_prompt = f.read()
|
112 |
+
|
113 |
+
# System message
|
114 |
+
sys_msg = SystemMessage(content=system_prompt)
|
115 |
+
|
116 |
+
# build a retriever
|
117 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2") # dim=768
|
118 |
+
supabase: Client = create_client(
|
119 |
+
os.environ.get("SUPABASE_URL"),
|
120 |
+
os.environ.get("SUPABASE_SERVICE_KEY"))
|
121 |
+
vector_store = SupabaseVectorStore(
|
122 |
+
client=supabase,
|
123 |
+
embedding= embeddings,
|
124 |
+
table_name="documents",
|
125 |
+
query_name="match_documents_langchain",
|
126 |
+
)
|
127 |
+
create_retriever_tool = create_retriever_tool(
|
128 |
+
retriever=vector_store.as_retriever(),
|
129 |
+
name="Question Search",
|
130 |
+
description="A tool to retrieve similar questions from a vector store.",
|
131 |
+
)
|
132 |
+
|
133 |
+
|
134 |
+
|
135 |
+
tools = [
|
136 |
+
multiply,
|
137 |
+
add,
|
138 |
+
subtract,
|
139 |
+
divide,
|
140 |
+
modulus,
|
141 |
+
wiki_search,
|
142 |
+
web_search,
|
143 |
+
arvix_search,
|
144 |
+
]
|
145 |
+
|
146 |
+
# Build graph function
|
147 |
+
def build_graph(provider: str = "groq"):
|
148 |
+
"""Build the graph"""
|
149 |
+
|
150 |
+
# Google Gemini
|
151 |
+
llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
|
152 |
+
|
153 |
+
# Bind tools to LLM
|
154 |
+
llm_with_tools = llm.bind_tools(tools)
|
155 |
+
|
156 |
+
# Node
|
157 |
+
def assistant(state: MessagesState):
|
158 |
+
"""Assistant node"""
|
159 |
+
return {"messages": [llm_with_tools.invoke(state["messages"])]}
|
160 |
+
|
161 |
+
def retriever(state: MessagesState):
|
162 |
+
"""Retriever node"""
|
163 |
+
similar_question = vector_store.similarity_search(state["messages"][0].content)
|
164 |
+
example_msg = HumanMessage(
|
165 |
+
content=f"Here I provide a similar question and answer for reference: \n\n{similar_question[0].page_content}",
|
166 |
+
)
|
167 |
+
return {"messages": [sys_msg] + state["messages"] + [example_msg]}
|
168 |
+
|
169 |
+
builder = StateGraph(MessagesState)
|
170 |
+
builder.add_node("retriever", retriever)
|
171 |
+
builder.add_node("assistant", assistant)
|
172 |
+
builder.add_node("tools", ToolNode(tools))
|
173 |
+
builder.add_edge(START, "retriever")
|
174 |
+
builder.add_edge("retriever", "assistant")
|
175 |
+
builder.add_conditional_edges(
|
176 |
+
"assistant",
|
177 |
+
tools_condition,
|
178 |
+
)
|
179 |
+
builder.add_edge("tools", "assistant")
|
180 |
+
|
181 |
+
# Compile graph
|
182 |
+
return builder.compile()
|
app.py
CHANGED
@@ -3,6 +3,8 @@ import gradio as gr
|
|
3 |
import requests
|
4 |
import inspect
|
5 |
import pandas as pd
|
|
|
|
|
6 |
|
7 |
# (Keep Constants as is)
|
8 |
# --- Constants ---
|
@@ -11,13 +13,18 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
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 |
-
|
19 |
-
|
20 |
-
|
|
|
|
|
21 |
|
22 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
23 |
"""
|
|
|
3 |
import requests
|
4 |
import inspect
|
5 |
import pandas as pd
|
6 |
+
from langchain_core.messages import HumanMessage
|
7 |
+
from agents import build_graph
|
8 |
|
9 |
# (Keep Constants as is)
|
10 |
# --- Constants ---
|
|
|
13 |
# --- Basic Agent Definition ---
|
14 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
15 |
class BasicAgent:
|
16 |
+
"""A langgraph agent."""
|
17 |
def __init__(self):
|
18 |
print("BasicAgent initialized.")
|
19 |
+
self.graph = build_graph()
|
20 |
+
|
21 |
def __call__(self, question: str) -> str:
|
22 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
23 |
+
# Wrap the question in a HumanMessage from langchain_core
|
24 |
+
messages = [HumanMessage(content=question)]
|
25 |
+
messages = self.graph.invoke({"messages": messages})
|
26 |
+
answer = messages['messages'][-1].content
|
27 |
+
return answer[14:]
|
28 |
|
29 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
30 |
"""
|
requirements.txt
CHANGED
@@ -1,2 +1,20 @@
|
|
1 |
gradio
|
2 |
-
requests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
gradio
|
2 |
+
requests
|
3 |
+
langchain
|
4 |
+
langchain-community
|
5 |
+
langchain-core
|
6 |
+
langchain-google-genai
|
7 |
+
langchain-huggingface
|
8 |
+
langchain-tavily
|
9 |
+
langchain-chroma
|
10 |
+
langgraph
|
11 |
+
huggingface_hub
|
12 |
+
supabase
|
13 |
+
arxiv
|
14 |
+
pymupdf
|
15 |
+
wikipedia
|
16 |
+
pgvector
|
17 |
+
python-dotenv
|
18 |
+
pandas
|
19 |
+
sentence-transformers
|
20 |
+
langchain-tools
|
system_prompt.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
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.
|