Spaces:
Runtime error
Runtime error
Update agent.py
Browse files
agent.py
CHANGED
|
@@ -1,7 +1,5 @@
|
|
| 1 |
import os
|
| 2 |
from dotenv import load_dotenv
|
| 3 |
-
from langchain.docstore.document import Document
|
| 4 |
-
from langchain_community.retrievers import BM25Retriever
|
| 5 |
from langchain.tools import Tool
|
| 6 |
from langchain.utilities import SerpAPIWrapper
|
| 7 |
from langgraph.graph.message import add_messages
|
|
@@ -10,44 +8,16 @@ from langgraph.prebuilt import ToolNode, tools_condition
|
|
| 10 |
from langchain_core.messages import AnyMessage, HumanMessage
|
| 11 |
from langchain_groq import ChatGroq
|
| 12 |
from typing import TypedDict, Annotated
|
| 13 |
-
import fitz # PyMuPDF
|
| 14 |
|
| 15 |
# Load environment variables
|
| 16 |
load_dotenv()
|
| 17 |
groq_api_key = os.getenv("GROQ_API_KEY")
|
| 18 |
serpapi_api_key = os.getenv("SERPAPI_API_KEY")
|
| 19 |
|
| 20 |
-
|
| 21 |
-
# --- PDF parsing ---
|
| 22 |
-
def parse_pdfs(uploaded_files):
|
| 23 |
-
pdf_docs = []
|
| 24 |
-
for uploaded_file in uploaded_files:
|
| 25 |
-
with fitz.open(stream=uploaded_file.read(), filetype="pdf") as doc:
|
| 26 |
-
text = ""
|
| 27 |
-
for page in doc:
|
| 28 |
-
text += page.get_text()
|
| 29 |
-
pdf_docs.append(Document(page_content=text, metadata={"source": uploaded_file.name}))
|
| 30 |
-
return pdf_docs
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
# --- BM25 Retrieval ---
|
| 34 |
-
def build_retriever(all_docs):
|
| 35 |
-
return BM25Retriever.from_documents(all_docs)
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
def extract_text(query: str, retriever):
|
| 39 |
-
results = retriever.invoke(query)
|
| 40 |
-
if results:
|
| 41 |
-
return "\n\n".join([doc.page_content for doc in results[:3]])
|
| 42 |
-
else:
|
| 43 |
-
return "لم يتم العثور على معلومات مطابقة في الملفات."
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
# --- Additional Tools ---
|
| 47 |
|
| 48 |
def calculator_tool_func(query: str):
|
| 49 |
try:
|
| 50 |
-
# أداة حساب بسيطة باستخدام eval (يمكن تطويرها لاحقًا)
|
| 51 |
result = str(eval(query, {"__builtins__": {}}))
|
| 52 |
return result
|
| 53 |
except Exception:
|
|
@@ -60,7 +30,6 @@ calculator_tool = Tool(
|
|
| 60 |
)
|
| 61 |
|
| 62 |
def weather_tool_func(location: str):
|
| 63 |
-
# يمكن ربطها ب API حقيقي للطقس لاحقًا
|
| 64 |
return f"حالة الطقس في {location}: مشمس، درجة الحرارة 25 درجة مئوية."
|
| 65 |
|
| 66 |
weather_tool = Tool(
|
|
@@ -69,33 +38,17 @@ weather_tool = Tool(
|
|
| 69 |
description="Provides weather information for a given location."
|
| 70 |
)
|
| 71 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
-
# ---
|
| 74 |
-
def create_ninu_agent(user_docs=None):
|
| 75 |
-
bm25_retriever = build_retriever(user_docs) if user_docs else None
|
| 76 |
-
|
| 77 |
-
def pdf_tool_func(q):
|
| 78 |
-
if bm25_retriever:
|
| 79 |
-
return extract_text(q, bm25_retriever)
|
| 80 |
-
else:
|
| 81 |
-
return "لا توجد ملفات PDF مرفوعة للبحث."
|
| 82 |
-
|
| 83 |
-
NINU_tool = Tool(
|
| 84 |
-
name="NINU_Lec_retriever",
|
| 85 |
-
func=pdf_tool_func,
|
| 86 |
-
description="Retrieves content from uploaded PDFs based on a query."
|
| 87 |
-
)
|
| 88 |
-
|
| 89 |
-
serpapi = SerpAPIWrapper(serpapi_api_key=serpapi_api_key)
|
| 90 |
-
SerpAPI_tool = Tool(
|
| 91 |
-
name="WebSearch",
|
| 92 |
-
func=serpapi.run,
|
| 93 |
-
description="Searches the web for recent information."
|
| 94 |
-
)
|
| 95 |
-
|
| 96 |
-
# دمج جميع التولز
|
| 97 |
-
tools = [NINU_tool, SerpAPI_tool, calculator_tool, weather_tool]
|
| 98 |
|
|
|
|
|
|
|
| 99 |
llm = ChatGroq(model="deepseek-r1-distill-llama-70b", groq_api_key=groq_api_key)
|
| 100 |
llm_with_tools = llm.bind_tools(tools)
|
| 101 |
|
|
@@ -111,27 +64,25 @@ def create_ninu_agent(user_docs=None):
|
|
| 111 |
builder.add_edge(START, "assistant")
|
| 112 |
builder.add_conditional_edges("assistant", tools_condition)
|
| 113 |
builder.add_edge("tools", "assistant")
|
|
|
|
| 114 |
return builder.compile()
|
| 115 |
|
|
|
|
| 116 |
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
agent = create_ninu_agent(user_docs)
|
| 120 |
|
| 121 |
conversation = []
|
| 122 |
|
| 123 |
intro_prompt = """
|
| 124 |
-
You are a general AI assistant with access to
|
| 125 |
-
1.
|
| 126 |
-
2.
|
| 127 |
-
3.
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
|
| 133 |
-
If you are asked for a number, don't use commas or units (like $, %, etc.) unless specified.
|
| 134 |
-
If you are asked for a string, avoid articles, abbreviations, and write digits in plain text unless specified.
|
| 135 |
"""
|
| 136 |
conversation.append(HumanMessage(content=intro_prompt))
|
| 137 |
conversation.append(HumanMessage(content=query))
|
|
@@ -139,6 +90,8 @@ If you are asked for a string, avoid articles, abbreviations, and write digits i
|
|
| 139 |
response = agent.invoke({"messages": conversation})
|
| 140 |
return response["messages"][-1].content
|
| 141 |
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
from dotenv import load_dotenv
|
|
|
|
|
|
|
| 3 |
from langchain.tools import Tool
|
| 4 |
from langchain.utilities import SerpAPIWrapper
|
| 5 |
from langgraph.graph.message import add_messages
|
|
|
|
| 8 |
from langchain_core.messages import AnyMessage, HumanMessage
|
| 9 |
from langchain_groq import ChatGroq
|
| 10 |
from typing import TypedDict, Annotated
|
|
|
|
| 11 |
|
| 12 |
# Load environment variables
|
| 13 |
load_dotenv()
|
| 14 |
groq_api_key = os.getenv("GROQ_API_KEY")
|
| 15 |
serpapi_api_key = os.getenv("SERPAPI_API_KEY")
|
| 16 |
|
| 17 |
+
# --- أدوات مساعدة ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
def calculator_tool_func(query: str):
|
| 20 |
try:
|
|
|
|
| 21 |
result = str(eval(query, {"__builtins__": {}}))
|
| 22 |
return result
|
| 23 |
except Exception:
|
|
|
|
| 30 |
)
|
| 31 |
|
| 32 |
def weather_tool_func(location: str):
|
|
|
|
| 33 |
return f"حالة الطقس في {location}: مشمس، درجة الحرارة 25 درجة مئوية."
|
| 34 |
|
| 35 |
weather_tool = Tool(
|
|
|
|
| 38 |
description="Provides weather information for a given location."
|
| 39 |
)
|
| 40 |
|
| 41 |
+
serpapi = SerpAPIWrapper(serpapi_api_key=serpapi_api_key)
|
| 42 |
+
SerpAPI_tool = Tool(
|
| 43 |
+
name="WebSearch",
|
| 44 |
+
func=serpapi.run,
|
| 45 |
+
description="Searches the web for recent information."
|
| 46 |
+
)
|
| 47 |
|
| 48 |
+
# --- بناء الوكيل ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
+
def create_search_only_agent():
|
| 51 |
+
tools = [SerpAPI_tool, calculator_tool, weather_tool]
|
| 52 |
llm = ChatGroq(model="deepseek-r1-distill-llama-70b", groq_api_key=groq_api_key)
|
| 53 |
llm_with_tools = llm.bind_tools(tools)
|
| 54 |
|
|
|
|
| 64 |
builder.add_edge(START, "assistant")
|
| 65 |
builder.add_conditional_edges("assistant", tools_condition)
|
| 66 |
builder.add_edge("tools", "assistant")
|
| 67 |
+
|
| 68 |
return builder.compile()
|
| 69 |
|
| 70 |
+
# --- دالة التفاعل ---
|
| 71 |
|
| 72 |
+
def run_search_agent(query):
|
| 73 |
+
agent = create_search_only_agent()
|
|
|
|
| 74 |
|
| 75 |
conversation = []
|
| 76 |
|
| 77 |
intro_prompt = """
|
| 78 |
+
You are a general AI assistant with access to the following tools:
|
| 79 |
+
1. WebSearch: to search for general or recent information from the internet.
|
| 80 |
+
2. Calculator: to perform arithmetic calculations.
|
| 81 |
+
3. Weather: to provide weather information.
|
| 82 |
+
Think step by step, and decide which tools to use to answer the query.
|
| 83 |
+
Respond with:
|
| 84 |
+
FINAL ANSWER: [your final answer]
|
| 85 |
+
Only include what the user asked for in the final answer.
|
|
|
|
|
|
|
|
|
|
| 86 |
"""
|
| 87 |
conversation.append(HumanMessage(content=intro_prompt))
|
| 88 |
conversation.append(HumanMessage(content=query))
|
|
|
|
| 90 |
response = agent.invoke({"messages": conversation})
|
| 91 |
return response["messages"][-1].content
|
| 92 |
|
| 93 |
+
# يمكن استخدام الدالة التالية لاختبار الوكيل
|
| 94 |
+
if __name__ == "__main__":
|
| 95 |
+
question = "ما هي عاصمة اليابان وكم عدد سكانها؟"
|
| 96 |
+
answer = run_search_agent(question)
|
| 97 |
+
print(answer)
|