Spaces:
Runtime error
Runtime error
Create agent.py
Browse files
agent.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dotenv import load_dotenv
|
| 3 |
+
from langgraph.graph import START, StateGraph, MessagesState
|
| 4 |
+
from langgraph.prebuilt import ToolNode, tools_condition
|
| 5 |
+
from langchain_core.tools import tool
|
| 6 |
+
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
|
| 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, ArxivLoader
|
| 12 |
+
from langchain_community.vectorstores import SupabaseVectorStore
|
| 13 |
+
from langchain.tools.retriever import create_retriever_tool
|
| 14 |
+
from supabase.client import create_client
|
| 15 |
+
|
| 16 |
+
load_dotenv()
|
| 17 |
+
|
| 18 |
+
# --- System Prompt Loader ---
|
| 19 |
+
def load_system_prompt(path="system_prompt.txt") -> SystemMessage:
|
| 20 |
+
try:
|
| 21 |
+
with open(path, encoding="utf-8") as f:
|
| 22 |
+
return SystemMessage(content=f.read())
|
| 23 |
+
except FileNotFoundError:
|
| 24 |
+
return SystemMessage(content="You are a helpful assistant.")
|
| 25 |
+
|
| 26 |
+
sys_msg = load_system_prompt()
|
| 27 |
+
|
| 28 |
+
# --- Math Tools Factory ---
|
| 29 |
+
def math_tool(fn):
|
| 30 |
+
return tool(fn)
|
| 31 |
+
|
| 32 |
+
@math_tool
|
| 33 |
+
def add(a: int, b: int) -> int: return a + b
|
| 34 |
+
@math_tool
|
| 35 |
+
def subtract(a: int, b: int) -> int: return a - b
|
| 36 |
+
@math_tool
|
| 37 |
+
def multiply(a: int, b: int) -> int: return a * b
|
| 38 |
+
@math_tool
|
| 39 |
+
def divide(a: int, b: int) -> float:
|
| 40 |
+
if b == 0: raise ValueError("Cannot divide by zero.")
|
| 41 |
+
return a / b
|
| 42 |
+
|
| 43 |
+
@math_tool
|
| 44 |
+
def modulus(a: int, b: int) -> int: return a % b
|
| 45 |
+
|
| 46 |
+
# --- Document Formatting Helper ---
|
| 47 |
+
def format_docs(docs, key: str, max_chars: int = None) -> dict:
|
| 48 |
+
content = "\n\n---\n\n".join(
|
| 49 |
+
f'<Document source="{d.metadata.get("source","")}" page="{d.metadata.get("page","")}" />\n'
|
| 50 |
+
f'{d.page_content[:max_chars] if max_chars else d.page_content}\n</Document>'
|
| 51 |
+
for d in docs
|
| 52 |
+
)
|
| 53 |
+
return {key: content}
|
| 54 |
+
|
| 55 |
+
# --- Info Tools ---
|
| 56 |
+
@tool
|
| 57 |
+
def wiki_search(query: str) -> dict:
|
| 58 |
+
docs = WikipediaLoader(query=query, load_max_docs=2).load()
|
| 59 |
+
return format_docs(docs, "wiki_results")
|
| 60 |
+
|
| 61 |
+
@tool
|
| 62 |
+
def web_search(query: str) -> dict:
|
| 63 |
+
docs = TavilySearchResults(max_results=3).invoke(query=query)
|
| 64 |
+
return format_docs(docs, "web_results")
|
| 65 |
+
|
| 66 |
+
@tool
|
| 67 |
+
def arvix_search(query: str) -> dict:
|
| 68 |
+
docs = ArxivLoader(query=query, load_max_docs=3).load()
|
| 69 |
+
return format_docs(docs, "arvix_results", max_chars=1000)
|
| 70 |
+
|
| 71 |
+
# --- Vector Retriever Setup ---
|
| 72 |
+
def build_vector_retriever():
|
| 73 |
+
embed_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
|
| 74 |
+
supa = create_client(os.getenv("SUPABASE_URL"), os.getenv("SUPABASE_SERVICE_KEY"))
|
| 75 |
+
vs = SupabaseVectorStore(
|
| 76 |
+
client=supa,
|
| 77 |
+
embedding=embed_model,
|
| 78 |
+
table_name="documents",
|
| 79 |
+
query_name="match_documents_langchain"
|
| 80 |
+
)
|
| 81 |
+
return vs.as_retriever()
|
| 82 |
+
|
| 83 |
+
# --- LLM Factory ---
|
| 84 |
+
def get_llm(provider: str):
|
| 85 |
+
if provider == "google":
|
| 86 |
+
return ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
|
| 87 |
+
if provider == "groq":
|
| 88 |
+
return ChatGroq(model="qwen-qwq-32b", temperature=0)
|
| 89 |
+
if provider == "huggingface":
|
| 90 |
+
return ChatHuggingFace(llm=HuggingFaceEndpoint(
|
| 91 |
+
url="https://api-inference.huggingface.co/models/Meta-DeepLearning/llama-2-7b-chat-hf",
|
| 92 |
+
temperature=0))
|
| 93 |
+
raise ValueError(f"Unsupported provider: {provider}")
|
| 94 |
+
|
| 95 |
+
# --- Build Graph ---
|
| 96 |
+
def build_graph(provider: str = "google"):
|
| 97 |
+
# tools list
|
| 98 |
+
retriever = build_vector_retriever()
|
| 99 |
+
question_tool = create_retriever_tool(
|
| 100 |
+
retriever=retriever,
|
| 101 |
+
name="Question Search",
|
| 102 |
+
description="Retrieve similar Q&A from vector store"
|
| 103 |
+
)
|
| 104 |
+
tools = [
|
| 105 |
+
add, subtract, multiply, divide, modulus,
|
| 106 |
+
wiki_search, web_search, arvix_search,
|
| 107 |
+
question_tool
|
| 108 |
+
]
|
| 109 |
+
|
| 110 |
+
# LLM w/ tools
|
| 111 |
+
llm = get_llm(provider).bind_tools(tools)
|
| 112 |
+
|
| 113 |
+
# Nodes
|
| 114 |
+
def assistant(state: MessagesState):
|
| 115 |
+
msgs = [sys_msg] + state["messages"]
|
| 116 |
+
resp = llm.invoke({"messages": msgs})
|
| 117 |
+
return {"messages": [resp]}
|
| 118 |
+
|
| 119 |
+
def retriever_node(state: MessagesState):
|
| 120 |
+
query = state["messages"][-1].content
|
| 121 |
+
doc = retriever.similarity_search(query, k=1)[0]
|
| 122 |
+
text = doc.page_content
|
| 123 |
+
answer = text.split("Final answer :")[-1].strip() if "Final answer :" in text else text
|
| 124 |
+
return {"messages": [AIMessage(content=answer)]}
|
| 125 |
+
|
| 126 |
+
# Graph assembly
|
| 127 |
+
graph = StateGraph(MessagesState)
|
| 128 |
+
graph.add_node("retriever", retriever_node)
|
| 129 |
+
graph.add_node("assistant", assistant)
|
| 130 |
+
graph.add_node("tools", ToolNode(tools))
|
| 131 |
+
graph.add_edge(START, "retriever")
|
| 132 |
+
graph.add_edge("retriever", "assistant")
|
| 133 |
+
graph.add_conditional_edges("assistant", tools_condition)
|
| 134 |
+
graph.add_edge("tools", "assistant")
|
| 135 |
+
graph.set_entry_point("retriever")
|
| 136 |
+
graph.set_finish_point("assistant")
|
| 137 |
+
|
| 138 |
+
return graph.compile()
|