Spaces:
Sleeping
Sleeping
shaukat39
commited on
Commit
·
f4de580
1
Parent(s):
81917a3
adding files
Browse files- agent.py +134 -0
- requirements.txt +18 -1
- system_prompt.txt +33 -0
agent.py
ADDED
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
19 |
+
load_dotenv()
|
20 |
+
|
21 |
+
# ------------------ Arithmetic Tools ------------------
|
22 |
+
@tool
|
23 |
+
def multiply(a: int, b: int) -> str:
|
24 |
+
return str(a * b)
|
25 |
+
|
26 |
+
@tool
|
27 |
+
def add(a: int, b: int) -> str:
|
28 |
+
return str(a + b)
|
29 |
+
|
30 |
+
@tool
|
31 |
+
def subtract(a: int, b: int) -> str:
|
32 |
+
return str(a - b)
|
33 |
+
|
34 |
+
@tool
|
35 |
+
def divide(a: int, b: int) -> str:
|
36 |
+
if b == 0:
|
37 |
+
return "Error: Cannot divide by zero."
|
38 |
+
return str(a / b)
|
39 |
+
|
40 |
+
@tool
|
41 |
+
def modulus(a: int, b: int) -> str:
|
42 |
+
return str(a % b)
|
43 |
+
|
44 |
+
# ------------------ Retrieval Tools ------------------
|
45 |
+
@tool
|
46 |
+
def wiki_search(query: str) -> str:
|
47 |
+
docs = WikipediaLoader(query=query, load_max_docs=2).load()
|
48 |
+
return "\n\n---\n\n".join(doc.page_content for doc in docs)
|
49 |
+
|
50 |
+
@tool
|
51 |
+
def web_search(query: str) -> str:
|
52 |
+
docs = TavilySearchResults(max_results=3).invoke(query)
|
53 |
+
return "\n\n---\n\n".join(doc.page_content for doc in docs)
|
54 |
+
|
55 |
+
@tool
|
56 |
+
def arvix_search(query: str) -> str:
|
57 |
+
docs = ArxivLoader(query=query, load_max_docs=3).load()
|
58 |
+
return "\n\n---\n\n".join(doc.page_content[:1000] for doc in docs)
|
59 |
+
|
60 |
+
# ------------------ System Setup ------------------
|
61 |
+
with open("system_prompt.txt", "r", encoding="utf-8") as f:
|
62 |
+
system_prompt = f.read()
|
63 |
+
sys_msg = SystemMessage(content=system_prompt)
|
64 |
+
|
65 |
+
# Vector Store Retrieval
|
66 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
|
67 |
+
supabase: Client = create_client(
|
68 |
+
os.environ["SUPABASE_URL"],
|
69 |
+
os.environ["SUPABASE_SERVICE_KEY"]
|
70 |
+
)
|
71 |
+
vector_store = SupabaseVectorStore(
|
72 |
+
client=supabase,
|
73 |
+
embedding=embeddings,
|
74 |
+
table_name="documents",
|
75 |
+
query_name="match_documents_langchain"
|
76 |
+
)
|
77 |
+
|
78 |
+
retriever_tool = create_retriever_tool(
|
79 |
+
retriever=vector_store.as_retriever(),
|
80 |
+
name="Question Search",
|
81 |
+
description="Retrieve similar questions from vector DB."
|
82 |
+
)
|
83 |
+
|
84 |
+
tools = [multiply, add, subtract, divide, modulus, wiki_search, web_search, arvix_search]
|
85 |
+
|
86 |
+
# ------------------ Build Agent Graph ------------------
|
87 |
+
def build_graph(provider: str = "groq"):
|
88 |
+
if provider == "google":
|
89 |
+
llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
|
90 |
+
elif provider == "groq":
|
91 |
+
llm = ChatGroq(model="qwen-qwq-32b", temperature=0)
|
92 |
+
elif provider == "huggingface":
|
93 |
+
llm = ChatHuggingFace(
|
94 |
+
llm=HuggingFaceEndpoint(
|
95 |
+
url="https://api-inference.huggingface.co/models/Meta-DeepLearning/llama-2-7b-chat-hf",
|
96 |
+
temperature=0
|
97 |
+
)
|
98 |
+
)
|
99 |
+
else:
|
100 |
+
raise ValueError("Invalid provider.")
|
101 |
+
|
102 |
+
llm_with_tools = llm.bind_tools(tools)
|
103 |
+
|
104 |
+
def retriever(state: MessagesState):
|
105 |
+
similar = vector_store.similarity_search(state["messages"][0].content)
|
106 |
+
example_msg = HumanMessage(
|
107 |
+
content=f"Here’s a similar QA pair for grounding:\n\n{similar[0].page_content}"
|
108 |
+
)
|
109 |
+
return {"messages": [sys_msg] + state["messages"] + [example_msg]}
|
110 |
+
|
111 |
+
def assistant(state: MessagesState):
|
112 |
+
result = llm_with_tools.invoke(state["messages"])
|
113 |
+
# Extract only the raw string answer
|
114 |
+
final_response = result.content
|
115 |
+
return {"messages": [HumanMessage(content=final_response.strip())]}
|
116 |
+
|
117 |
+
builder = StateGraph(MessagesState)
|
118 |
+
builder.add_node("retriever", retriever)
|
119 |
+
builder.add_node("assistant", assistant)
|
120 |
+
builder.add_node("tools", ToolNode(tools))
|
121 |
+
builder.add_edge(START, "retriever")
|
122 |
+
builder.add_edge("retriever", "assistant")
|
123 |
+
builder.add_conditional_edges("assistant", tools_condition)
|
124 |
+
builder.add_edge("tools", "assistant")
|
125 |
+
|
126 |
+
return builder.compile()
|
127 |
+
|
128 |
+
# ------------------ Local Test Harness ------------------
|
129 |
+
if __name__ == "__main__":
|
130 |
+
graph = build_graph(provider="groq")
|
131 |
+
question = "When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect?"
|
132 |
+
messages = [HumanMessage(content=question)]
|
133 |
+
result = graph.invoke({"messages": messages})
|
134 |
+
print(result["messages"][-1].content)
|
requirements.txt
CHANGED
@@ -1,2 +1,19 @@
|
|
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-groq
|
9 |
+
langchain-tavily
|
10 |
+
langchain-chroma
|
11 |
+
langgraph
|
12 |
+
huggingface_hub
|
13 |
+
supabase
|
14 |
+
arxiv
|
15 |
+
pymupdf
|
16 |
+
wikipedia
|
17 |
+
pgvector
|
18 |
+
python-dotenv
|
19 |
+
sentence-transformers
|
system_prompt.txt
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
You are a helpful assistant tasked with answering questions using a set of tools.
|
2 |
+
|
3 |
+
You will receive one question at a time. Think step-by-step, use any relevant tools, and reason carefully before providing your final response.
|
4 |
+
|
5 |
+
When you're ready to answer, respond using the following exact format:
|
6 |
+
|
7 |
+
FINAL ANSWER: [YOUR FINAL ANSWER]
|
8 |
+
|
9 |
+
Your answer must follow these strict formatting rules:
|
10 |
+
|
11 |
+
If the answer is a number:
|
12 |
+
|
13 |
+
Do not include commas.
|
14 |
+
|
15 |
+
Do not include units (e.g., %, $, cm) unless the question explicitly asks for them.
|
16 |
+
|
17 |
+
If the answer is a string:
|
18 |
+
|
19 |
+
Avoid using articles (a, an, the).
|
20 |
+
|
21 |
+
Do not abbreviate (e.g., write "New York City", not "NYC").
|
22 |
+
|
23 |
+
Write all digits as words unless the question says otherwise.
|
24 |
+
|
25 |
+
If the answer is a comma-separated list:
|
26 |
+
|
27 |
+
Apply the above rules for each element based on its type (number or string).
|
28 |
+
|
29 |
+
Do not use brackets, bullet points, or extra formatting.
|
30 |
+
|
31 |
+
Always begin your final response with exactly: FINAL ANSWER:
|
32 |
+
|
33 |
+
Do not include anything else after that line—no thoughts, no commentary. Only the formatted answer.
|