Update app.py
Browse files
app.py
CHANGED
@@ -6,17 +6,16 @@ from smolagents import ToolCallingAgent, tool
|
|
6 |
from duckduckgo_search import DDGS
|
7 |
import math
|
8 |
import re
|
9 |
-
from datetime import datetime
|
10 |
-
import time
|
11 |
|
12 |
-
# ---
|
13 |
@tool
|
14 |
-
def
|
15 |
-
"""
|
16 |
|
17 |
Args:
|
18 |
query: The search query string.
|
19 |
-
|
20 |
Returns:
|
21 |
A formatted string with search results.
|
22 |
"""
|
@@ -31,45 +30,40 @@ def duck_search(query: str) -> str:
|
|
31 |
return f"Search error: {str(e)}"
|
32 |
|
33 |
@tool
|
34 |
-
def
|
35 |
"""Evaluates mathematical expressions.
|
36 |
|
37 |
Args:
|
38 |
expression: The math expression to evaluate.
|
39 |
-
|
40 |
Returns:
|
41 |
-
The result as a string.
|
42 |
"""
|
43 |
try:
|
44 |
# Safe evaluation environment
|
45 |
-
safe_dict = {k: v for k, v in math.__dict__.items()
|
|
|
46 |
safe_dict.update({
|
47 |
'__builtins__': None,
|
48 |
'abs': abs,
|
49 |
-
'round': round
|
50 |
-
'min': min,
|
51 |
-
'max': max
|
52 |
})
|
53 |
-
|
54 |
-
# Handle percentage expressions
|
55 |
-
if '%' in expression:
|
56 |
-
expression = expression.replace('%', '/100')
|
57 |
-
|
58 |
result = eval(expression, {'__builtins__': None}, safe_dict)
|
59 |
return str(result)
|
60 |
except Exception as e:
|
61 |
return f"Calculation error: {str(e)}"
|
62 |
|
63 |
-
# ---
|
64 |
class GAIAAgent:
|
65 |
def __init__(self):
|
|
|
66 |
try:
|
67 |
self.agent = ToolCallingAgent(
|
68 |
-
name="
|
69 |
description="Agent for GAIA benchmark tasks",
|
70 |
-
tools=[
|
71 |
-
model="gpt-3.5-turbo",
|
72 |
-
planning_interval=
|
73 |
)
|
74 |
print("✅ Agent initialized successfully")
|
75 |
except Exception as e:
|
@@ -79,77 +73,59 @@ class GAIAAgent:
|
|
79 |
def __call__(self, question: str) -> str:
|
80 |
"""Process a question with proper error handling."""
|
81 |
try:
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
# Run the agent
|
86 |
response = self.agent.run(question)
|
87 |
|
88 |
-
#
|
89 |
-
if
|
90 |
-
return "
|
91 |
-
|
92 |
-
return str(response)[:1000] # Limit response length
|
93 |
-
|
94 |
except Exception as e:
|
95 |
print(f"⚠️ Processing error: {str(e)}")
|
96 |
return f"Error processing question: {str(e)}"
|
97 |
|
98 |
-
# ---
|
99 |
-
def
|
100 |
if not profile:
|
101 |
-
return "Please login to Hugging Face
|
102 |
|
103 |
try:
|
104 |
agent = GAIAAgent()
|
105 |
-
except Exception as e:
|
106 |
-
return f"Agent initialization failed: {str(e)}", None
|
107 |
-
|
108 |
-
try:
|
109 |
response = requests.get(
|
110 |
"https://agents-course-unit4-scoring.hf.space/questions",
|
111 |
-
timeout=
|
112 |
)
|
113 |
questions = response.json()
|
|
|
114 |
if not questions:
|
115 |
-
return "No questions received
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
results = []
|
120 |
-
answers = []
|
121 |
-
|
122 |
-
for item in questions[:20]: # Process first 20 questions for testing
|
123 |
-
task_id = item.get("task_id")
|
124 |
-
question = item.get("question")
|
125 |
|
126 |
-
|
127 |
-
|
|
|
128 |
|
129 |
-
|
|
|
|
|
130 |
answer = agent(question)
|
131 |
answers.append({
|
132 |
"task_id": task_id,
|
133 |
-
"submitted_answer": answer
|
134 |
})
|
135 |
results.append({
|
136 |
"Task ID": task_id,
|
137 |
"Question": question[:100],
|
138 |
"Answer": answer[:200]
|
139 |
})
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
"submitted_answer": f"Error: {str(e)}"
|
144 |
-
})
|
145 |
-
results.append({
|
146 |
-
"Task ID": task_id,
|
147 |
-
"Question": question[:100],
|
148 |
-
"Answer": f"Error: {str(e)}"
|
149 |
-
})
|
150 |
-
|
151 |
-
try:
|
152 |
-
response = requests.post(
|
153 |
"https://agents-course-unit4-scoring.hf.space/submit",
|
154 |
json={
|
155 |
"username": profile.username,
|
@@ -158,27 +134,28 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
158 |
},
|
159 |
timeout=60
|
160 |
)
|
161 |
-
data =
|
|
|
162 |
return (
|
163 |
f"Submitted {len(answers)} answers\n"
|
164 |
f"Score: {data.get('score', 'N/A')}%\n"
|
165 |
-
f"Correct: {data.get('correct_count', 0)}/{
|
166 |
-
f"Message: {data.get('message', '')}",
|
167 |
pd.DataFrame(results)
|
168 |
)
|
|
|
169 |
except Exception as e:
|
170 |
-
return f"
|
171 |
|
172 |
# --- Gradio Interface ---
|
173 |
with gr.Blocks() as demo:
|
174 |
-
gr.Markdown("# GAIA Agent")
|
175 |
gr.LoginButton()
|
176 |
-
submit_btn = gr.Button("Run
|
177 |
output = gr.Textbox(label="Results")
|
178 |
table = gr.DataFrame(label="Details")
|
179 |
|
180 |
submit_btn.click(
|
181 |
-
fn=
|
182 |
outputs=[output, table]
|
183 |
)
|
184 |
|
|
|
6 |
from duckduckgo_search import DDGS
|
7 |
import math
|
8 |
import re
|
9 |
+
from datetime import datetime
|
|
|
10 |
|
11 |
+
# --- Tools with Proper Docstrings ---
|
12 |
@tool
|
13 |
+
def web_search(query: str) -> str:
|
14 |
+
"""Performs a web search using DuckDuckGo.
|
15 |
|
16 |
Args:
|
17 |
query: The search query string.
|
18 |
+
|
19 |
Returns:
|
20 |
A formatted string with search results.
|
21 |
"""
|
|
|
30 |
return f"Search error: {str(e)}"
|
31 |
|
32 |
@tool
|
33 |
+
def calculate(expression: str) -> str:
|
34 |
"""Evaluates mathematical expressions.
|
35 |
|
36 |
Args:
|
37 |
expression: The math expression to evaluate.
|
38 |
+
|
39 |
Returns:
|
40 |
+
The result as a string or error message.
|
41 |
"""
|
42 |
try:
|
43 |
# Safe evaluation environment
|
44 |
+
safe_dict = {k: v for k, v in math.__dict__.items()
|
45 |
+
if not k.startswith("__")}
|
46 |
safe_dict.update({
|
47 |
'__builtins__': None,
|
48 |
'abs': abs,
|
49 |
+
'round': round
|
|
|
|
|
50 |
})
|
|
|
|
|
|
|
|
|
|
|
51 |
result = eval(expression, {'__builtins__': None}, safe_dict)
|
52 |
return str(result)
|
53 |
except Exception as e:
|
54 |
return f"Calculation error: {str(e)}"
|
55 |
|
56 |
+
# --- Robust Agent Class ---
|
57 |
class GAIAAgent:
|
58 |
def __init__(self):
|
59 |
+
"""Initialize the agent with proper error handling."""
|
60 |
try:
|
61 |
self.agent = ToolCallingAgent(
|
62 |
+
name="GAIA_Submission_Agent",
|
63 |
description="Agent for GAIA benchmark tasks",
|
64 |
+
tools=[web_search, calculate],
|
65 |
+
model="gpt-3.5-turbo",
|
66 |
+
planning_interval=3 # Changed from max_iterations
|
67 |
)
|
68 |
print("✅ Agent initialized successfully")
|
69 |
except Exception as e:
|
|
|
73 |
def __call__(self, question: str) -> str:
|
74 |
"""Process a question with proper error handling."""
|
75 |
try:
|
76 |
+
if not question or not isinstance(question, str):
|
77 |
+
return "Invalid question format"
|
78 |
+
|
79 |
# Run the agent
|
80 |
response = self.agent.run(question)
|
81 |
|
82 |
+
# Ensure we return a string
|
83 |
+
if response is None:
|
84 |
+
return "No response generated"
|
85 |
+
return str(response)
|
|
|
|
|
86 |
except Exception as e:
|
87 |
print(f"⚠️ Processing error: {str(e)}")
|
88 |
return f"Error processing question: {str(e)}"
|
89 |
|
90 |
+
# --- Submission Logic ---
|
91 |
+
def submit_answers(profile: gr.OAuthProfile | None):
|
92 |
if not profile:
|
93 |
+
return "Please login to Hugging Face", None
|
94 |
|
95 |
try:
|
96 |
agent = GAIAAgent()
|
|
|
|
|
|
|
|
|
97 |
response = requests.get(
|
98 |
"https://agents-course-unit4-scoring.hf.space/questions",
|
99 |
+
timeout=20
|
100 |
)
|
101 |
questions = response.json()
|
102 |
+
|
103 |
if not questions:
|
104 |
+
return "No questions received", None
|
105 |
+
|
106 |
+
answers = []
|
107 |
+
results = []
|
|
|
|
|
|
|
|
|
|
|
|
|
108 |
|
109 |
+
for item in questions[:15]: # Process first 15 for testing
|
110 |
+
task_id = item.get("task_id")
|
111 |
+
question = item.get("question")
|
112 |
|
113 |
+
if not task_id or not question:
|
114 |
+
continue
|
115 |
+
|
116 |
answer = agent(question)
|
117 |
answers.append({
|
118 |
"task_id": task_id,
|
119 |
+
"submitted_answer": answer[:1000] # Limit answer length
|
120 |
})
|
121 |
results.append({
|
122 |
"Task ID": task_id,
|
123 |
"Question": question[:100],
|
124 |
"Answer": answer[:200]
|
125 |
})
|
126 |
+
|
127 |
+
# Submit answers
|
128 |
+
submit_response = requests.post(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
129 |
"https://agents-course-unit4-scoring.hf.space/submit",
|
130 |
json={
|
131 |
"username": profile.username,
|
|
|
134 |
},
|
135 |
timeout=60
|
136 |
)
|
137 |
+
data = submit_response.json()
|
138 |
+
|
139 |
return (
|
140 |
f"Submitted {len(answers)} answers\n"
|
141 |
f"Score: {data.get('score', 'N/A')}%\n"
|
142 |
+
f"Correct: {data.get('correct_count', 0)}/{len(answers)}",
|
|
|
143 |
pd.DataFrame(results)
|
144 |
)
|
145 |
+
|
146 |
except Exception as e:
|
147 |
+
return f"Error: {str(e)}", None
|
148 |
|
149 |
# --- Gradio Interface ---
|
150 |
with gr.Blocks() as demo:
|
151 |
+
gr.Markdown("# GAIA Submission Agent")
|
152 |
gr.LoginButton()
|
153 |
+
submit_btn = gr.Button("Run Evaluation", variant="primary")
|
154 |
output = gr.Textbox(label="Results")
|
155 |
table = gr.DataFrame(label="Details")
|
156 |
|
157 |
submit_btn.click(
|
158 |
+
fn=submit_answers,
|
159 |
outputs=[output, table]
|
160 |
)
|
161 |
|