Spaces:
Sleeping
Sleeping
Update agent.py
Browse files
agent.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
from pathlib import Path
|
| 3 |
from typing import Optional, Union
|
| 4 |
|
|
@@ -19,25 +20,21 @@ from smolagents.tools import Tool
|
|
| 19 |
# Load environment variables
|
| 20 |
load_dotenv()
|
| 21 |
|
| 22 |
-
|
| 23 |
-
import os
|
| 24 |
-
|
| 25 |
model = LiteLLMModel(
|
| 26 |
-
model_id="gemini/gemini-2.5-flash-preview-09-2025",
|
| 27 |
api_key=os.getenv("GEMINI_API_KEY"),
|
| 28 |
)
|
| 29 |
|
| 30 |
|
| 31 |
-
|
| 32 |
class ExcelToTextTool(Tool):
|
| 33 |
"""Render an Excel worksheet as a Markdown table."""
|
| 34 |
-
|
| 35 |
name = "excel_to_text"
|
| 36 |
description = (
|
| 37 |
"Read an Excel file and return a Markdown table of the requested sheet. "
|
| 38 |
"Accepts either the sheet name or a zero-based index (as a string)."
|
| 39 |
)
|
| 40 |
-
|
| 41 |
inputs = {
|
| 42 |
"excel_path": {
|
| 43 |
"type": "string",
|
|
@@ -52,37 +49,36 @@ class ExcelToTextTool(Tool):
|
|
| 52 |
"nullable": True,
|
| 53 |
},
|
| 54 |
}
|
| 55 |
-
|
| 56 |
output_type = "string"
|
| 57 |
|
| 58 |
def forward(self, excel_path: str, sheet_name: Optional[str] = None) -> str:
|
| 59 |
"""Load the Excel file and return the sheet as a Markdown table."""
|
| 60 |
file_path = Path(excel_path).expanduser().resolve()
|
|
|
|
| 61 |
if not file_path.is_file():
|
| 62 |
return f"Error: Excel file not found at {file_path}"
|
| 63 |
-
|
| 64 |
try:
|
| 65 |
sheet: Union[str, int] = (
|
| 66 |
int(sheet_name) if sheet_name and sheet_name.isdigit() else sheet_name or 0
|
| 67 |
)
|
| 68 |
-
|
| 69 |
df = pd.read_excel(file_path, sheet_name=sheet)
|
| 70 |
-
|
| 71 |
if hasattr(df, "to_markdown"):
|
| 72 |
return df.to_markdown(index=False)
|
| 73 |
-
|
| 74 |
return tabulate(df, headers="keys", tablefmt="github", showindex=False)
|
| 75 |
-
|
| 76 |
except Exception as e:
|
| 77 |
return f"Error reading Excel file: {e}"
|
| 78 |
|
| 79 |
|
| 80 |
class GaiaAgent:
|
| 81 |
-
"""An agent capable of using tools to answer general questions."""
|
| 82 |
-
|
| 83 |
def __init__(self):
|
| 84 |
print("✅ GaiaAgent initialized with tools.")
|
| 85 |
-
|
| 86 |
tools = [
|
| 87 |
DuckDuckGoSearchTool(),
|
| 88 |
WikipediaSearchTool(),
|
|
@@ -90,21 +86,37 @@ class GaiaAgent:
|
|
| 90 |
PythonInterpreterTool(),
|
| 91 |
FinalAnswerTool(),
|
| 92 |
]
|
| 93 |
-
|
| 94 |
self.agent = CodeAgent(
|
| 95 |
model=model,
|
| 96 |
tools=tools,
|
| 97 |
add_base_tools=True,
|
| 98 |
additional_authorized_imports=["pandas", "numpy", "csv", "subprocess"],
|
| 99 |
)
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
def __call__(self, task_id: str, question: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
print(f"🔹 Agent received task_id='{task_id}' | question='{question[:50]}...'")
|
|
|
|
| 103 |
try:
|
| 104 |
answer = self.agent.run(question)
|
| 105 |
if not answer:
|
| 106 |
answer = "⚠️ Sorry, I could not generate a valid response."
|
| 107 |
except Exception as e:
|
| 108 |
answer = f"⚠️ Agent failed with error: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
print(f"🔹 Agent returning answer: {answer}")
|
| 110 |
-
return answer
|
|
|
|
| 1 |
import os
|
| 2 |
+
import time
|
| 3 |
from pathlib import Path
|
| 4 |
from typing import Optional, Union
|
| 5 |
|
|
|
|
| 20 |
# Load environment variables
|
| 21 |
load_dotenv()
|
| 22 |
|
| 23 |
+
# Initialize the model
|
|
|
|
|
|
|
| 24 |
model = LiteLLMModel(
|
| 25 |
+
model_id="gemini/gemini-2.5-flash-preview-09-2025",
|
| 26 |
api_key=os.getenv("GEMINI_API_KEY"),
|
| 27 |
)
|
| 28 |
|
| 29 |
|
|
|
|
| 30 |
class ExcelToTextTool(Tool):
|
| 31 |
"""Render an Excel worksheet as a Markdown table."""
|
| 32 |
+
|
| 33 |
name = "excel_to_text"
|
| 34 |
description = (
|
| 35 |
"Read an Excel file and return a Markdown table of the requested sheet. "
|
| 36 |
"Accepts either the sheet name or a zero-based index (as a string)."
|
| 37 |
)
|
|
|
|
| 38 |
inputs = {
|
| 39 |
"excel_path": {
|
| 40 |
"type": "string",
|
|
|
|
| 49 |
"nullable": True,
|
| 50 |
},
|
| 51 |
}
|
|
|
|
| 52 |
output_type = "string"
|
| 53 |
|
| 54 |
def forward(self, excel_path: str, sheet_name: Optional[str] = None) -> str:
|
| 55 |
"""Load the Excel file and return the sheet as a Markdown table."""
|
| 56 |
file_path = Path(excel_path).expanduser().resolve()
|
| 57 |
+
|
| 58 |
if not file_path.is_file():
|
| 59 |
return f"Error: Excel file not found at {file_path}"
|
| 60 |
+
|
| 61 |
try:
|
| 62 |
sheet: Union[str, int] = (
|
| 63 |
int(sheet_name) if sheet_name and sheet_name.isdigit() else sheet_name or 0
|
| 64 |
)
|
|
|
|
| 65 |
df = pd.read_excel(file_path, sheet_name=sheet)
|
| 66 |
+
|
| 67 |
if hasattr(df, "to_markdown"):
|
| 68 |
return df.to_markdown(index=False)
|
| 69 |
+
|
| 70 |
return tabulate(df, headers="keys", tablefmt="github", showindex=False)
|
| 71 |
+
|
| 72 |
except Exception as e:
|
| 73 |
return f"Error reading Excel file: {e}"
|
| 74 |
|
| 75 |
|
| 76 |
class GaiaAgent:
|
| 77 |
+
"""An agent capable of using tools to answer general questions with rate limiting."""
|
| 78 |
+
|
| 79 |
def __init__(self):
|
| 80 |
print("✅ GaiaAgent initialized with tools.")
|
| 81 |
+
|
| 82 |
tools = [
|
| 83 |
DuckDuckGoSearchTool(),
|
| 84 |
WikipediaSearchTool(),
|
|
|
|
| 86 |
PythonInterpreterTool(),
|
| 87 |
FinalAnswerTool(),
|
| 88 |
]
|
| 89 |
+
|
| 90 |
self.agent = CodeAgent(
|
| 91 |
model=model,
|
| 92 |
tools=tools,
|
| 93 |
add_base_tools=True,
|
| 94 |
additional_authorized_imports=["pandas", "numpy", "csv", "subprocess"],
|
| 95 |
)
|
| 96 |
+
|
| 97 |
+
# Rate limiting configuration
|
| 98 |
+
self.last_call_time = 0
|
| 99 |
+
self.min_delay = 6 # 6 seconds between calls (10 per minute = 6s spacing)
|
| 100 |
+
|
| 101 |
def __call__(self, task_id: str, question: str) -> str:
|
| 102 |
+
# Apply rate limiting
|
| 103 |
+
elapsed = time.time() - self.last_call_time
|
| 104 |
+
if elapsed < self.min_delay:
|
| 105 |
+
wait_time = self.min_delay - elapsed
|
| 106 |
+
print(f"⏳ Rate limiting: waiting {wait_time:.1f}s...")
|
| 107 |
+
time.sleep(wait_time)
|
| 108 |
+
|
| 109 |
print(f"🔹 Agent received task_id='{task_id}' | question='{question[:50]}...'")
|
| 110 |
+
|
| 111 |
try:
|
| 112 |
answer = self.agent.run(question)
|
| 113 |
if not answer:
|
| 114 |
answer = "⚠️ Sorry, I could not generate a valid response."
|
| 115 |
except Exception as e:
|
| 116 |
answer = f"⚠️ Agent failed with error: {e}"
|
| 117 |
+
|
| 118 |
+
# Update last call time
|
| 119 |
+
self.last_call_time = time.time()
|
| 120 |
+
|
| 121 |
print(f"🔹 Agent returning answer: {answer}")
|
| 122 |
+
return answer
|