Spaces:
Sleeping
Sleeping
Create agent.py
Browse files
agent.py
ADDED
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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_openai import ChatOpenAI
|
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 |
+
|
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 |
+
|
116 |
+
# load the system prompt from the file
|
117 |
+
with open("system_prompt.txt", "r", encoding="utf-8") as f:
|
118 |
+
system_prompt = f.read()
|
119 |
+
|
120 |
+
# System message
|
121 |
+
sys_msg = SystemMessage(content=system_prompt)
|
122 |
+
|
123 |
+
# build a retriever
|
124 |
+
|
125 |
+
|
126 |
+
|
127 |
+
tools = [
|
128 |
+
multiply,
|
129 |
+
add,
|
130 |
+
subtract,
|
131 |
+
divide,
|
132 |
+
modulus,
|
133 |
+
wiki_search,
|
134 |
+
web_search,
|
135 |
+
arvix_search,
|
136 |
+
]
|
137 |
+
|
138 |
+
# Build graph function
|
139 |
+
def build_graph(provider: str = "groq"):
|
140 |
+
"""Build the graph"""
|
141 |
+
# Load environment variables from .env file
|
142 |
+
if provider == "google":
|
143 |
+
# Google Gemini
|
144 |
+
llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
|
145 |
+
elif provider == "test":
|
146 |
+
llm = ChatOpenAI(api_key=os.environ.get("TEST_API_KEY"), base_url="https://api.chatanywhere.tech")
|
147 |
+
else:
|
148 |
+
raise ValueError("Invalid provider. Choose 'google', 'groq' or 'huggingface'.")
|
149 |
+
# Bind tools to LLM
|
150 |
+
llm_with_tools = llm.bind_tools(tools)
|
151 |
+
|
152 |
+
# Node
|
153 |
+
def assistant(state: MessagesState):
|
154 |
+
"""Assistant node"""
|
155 |
+
return {"messages": [llm_with_tools.invoke(state["messages"])]}
|
156 |
+
|
157 |
+
|
158 |
+
builder = StateGraph(MessagesState)
|
159 |
+
builder.add_node("assistant", assistant)
|
160 |
+
builder.add_node("tools", ToolNode(tools))
|
161 |
+
builder.add_edge(START, "assistant")
|
162 |
+
builder.add_conditional_edges(
|
163 |
+
"assistant",
|
164 |
+
tools_condition,
|
165 |
+
)
|
166 |
+
builder.add_edge("tools", "assistant")
|
167 |
+
|
168 |
+
# Compile graph
|
169 |
+
return builder.compile()
|
170 |
+
|
171 |
+
# test
|
172 |
+
if __name__ == "__main__":
|
173 |
+
question = "When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect?"
|
174 |
+
# Build the graph
|
175 |
+
graph = build_graph(provider="test")
|
176 |
+
# Run the graph
|
177 |
+
messages = [HumanMessage(content=question)]
|
178 |
+
messages = graph.invoke({"messages": messages})
|
179 |
+
for m in messages["messages"]:
|
180 |
+
m.pretty_print()
|