Update app.py
Browse files
app.py
CHANGED
@@ -3,7 +3,7 @@ import gradio as gr
|
|
3 |
import requests
|
4 |
import pandas as pd
|
5 |
from smolagents import ToolCallingAgent, tool
|
6 |
-
import
|
7 |
import math
|
8 |
|
9 |
# --- Constants ---
|
@@ -12,11 +12,19 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
12 |
# --- Tools ---
|
13 |
@tool
|
14 |
def duck_search(query: str) -> str:
|
15 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
try:
|
17 |
-
results =
|
18 |
if results:
|
19 |
-
return "\n".join([f"{r['title']}: {r['body']}" for r in results])
|
20 |
else:
|
21 |
return "No results found."
|
22 |
except Exception as e:
|
@@ -24,131 +32,138 @@ def duck_search(query: str) -> str:
|
|
24 |
|
25 |
@tool
|
26 |
def calculator(expression: str) -> str:
|
27 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
try:
|
29 |
result = eval(expression, {"__builtins__": {}}, math.__dict__)
|
30 |
return str(result)
|
31 |
except Exception as e:
|
32 |
return f"Calculation error: {e}"
|
33 |
|
34 |
-
# --- Agent
|
35 |
class WebSearchAgent:
|
36 |
def __init__(self):
|
37 |
self.agent = ToolCallingAgent(
|
38 |
name="GAIAWebToolAgent",
|
39 |
-
description="
|
40 |
tools=[duck_search, calculator],
|
41 |
step_limit=5,
|
42 |
-
system_prompt=
|
|
|
|
|
|
|
43 |
)
|
44 |
-
print("β
|
45 |
|
46 |
def __call__(self, question: str) -> str:
|
47 |
-
print(f"π
|
48 |
try:
|
49 |
return self.agent.run(question)
|
50 |
except Exception as e:
|
51 |
-
print(f"β
|
52 |
return f"Error: {e}"
|
53 |
|
54 |
-
# ---
|
55 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
56 |
space_id = os.getenv("SPACE_ID")
|
57 |
if profile:
|
58 |
username = profile.username
|
59 |
-
print(f"User
|
60 |
else:
|
61 |
-
return "Please login to Hugging Face
|
62 |
|
63 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
64 |
-
|
65 |
-
|
66 |
-
submit_url = f"{api_url}/submit"
|
67 |
|
68 |
try:
|
69 |
agent = WebSearchAgent()
|
70 |
except Exception as e:
|
71 |
-
return f"Agent
|
72 |
|
73 |
try:
|
74 |
print("π₯ Fetching questions...")
|
75 |
response = requests.get(questions_url, timeout=15)
|
76 |
response.raise_for_status()
|
77 |
-
|
78 |
-
if not
|
79 |
-
return "
|
80 |
-
print(f"β
|
81 |
except Exception as e:
|
82 |
-
return f"
|
83 |
|
84 |
-
answers_payload = []
|
85 |
results_log = []
|
86 |
-
|
87 |
-
|
|
|
88 |
task_id = item.get("task_id")
|
89 |
-
|
90 |
-
if not task_id or not
|
91 |
continue
|
92 |
try:
|
93 |
-
|
94 |
-
answers_payload.append({
|
95 |
-
"task_id": task_id,
|
96 |
-
"submitted_answer": submitted_answer
|
97 |
-
})
|
98 |
results_log.append({
|
99 |
"Task ID": task_id,
|
100 |
-
"Question":
|
101 |
-
"Submitted Answer":
|
|
|
|
|
|
|
|
|
102 |
})
|
103 |
except Exception as e:
|
104 |
error_msg = f"Agent error: {e}"
|
105 |
-
print(error_msg)
|
106 |
results_log.append({
|
107 |
"Task ID": task_id,
|
108 |
-
"Question":
|
109 |
"Submitted Answer": error_msg
|
110 |
})
|
111 |
|
112 |
if not answers_payload:
|
113 |
-
return "No answers
|
114 |
|
115 |
print("π€ Submitting answers...")
|
116 |
-
submission_data = {
|
117 |
-
"username": username.strip(),
|
118 |
-
"agent_code": agent_code,
|
119 |
-
"answers": answers_payload
|
120 |
-
}
|
121 |
-
|
122 |
try:
|
123 |
-
response = requests.post(submit_url, json=
|
|
|
|
|
|
|
|
|
124 |
response.raise_for_status()
|
125 |
result = response.json()
|
126 |
-
|
127 |
f"β
Submission Successful!\n"
|
128 |
f"User: {result.get('username')}\n"
|
129 |
f"Score: {result.get('score', 'N/A')}% "
|
130 |
f"({result.get('correct_count', '?')}/{result.get('total_attempted', '?')} correct)\n"
|
131 |
-
f"Message: {result.get('message', 'No message
|
132 |
)
|
133 |
-
return
|
134 |
except Exception as e:
|
135 |
-
return f"Submission
|
136 |
|
137 |
# --- Gradio UI ---
|
138 |
with gr.Blocks() as demo:
|
139 |
-
gr.Markdown("#
|
140 |
gr.Markdown("""
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
""")
|
145 |
gr.LoginButton()
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
|
150 |
-
|
151 |
|
152 |
if __name__ == "__main__":
|
153 |
-
print("
|
154 |
-
demo.launch(debug=True, share=False)
|
|
|
3 |
import requests
|
4 |
import pandas as pd
|
5 |
from smolagents import ToolCallingAgent, tool
|
6 |
+
from duckduckgo_search import ddg
|
7 |
import math
|
8 |
|
9 |
# --- Constants ---
|
|
|
12 |
# --- Tools ---
|
13 |
@tool
|
14 |
def duck_search(query: str) -> str:
|
15 |
+
"""
|
16 |
+
Searches the web using DuckDuckGo and returns a short summary.
|
17 |
+
|
18 |
+
Args:
|
19 |
+
query: The search query string.
|
20 |
+
|
21 |
+
Returns:
|
22 |
+
A string summarizing the top search results.
|
23 |
+
"""
|
24 |
try:
|
25 |
+
results = ddg(query, max_results=3)
|
26 |
if results:
|
27 |
+
return "\n\n".join([f"{r['title']}: {r['body']}" for r in results])
|
28 |
else:
|
29 |
return "No results found."
|
30 |
except Exception as e:
|
|
|
32 |
|
33 |
@tool
|
34 |
def calculator(expression: str) -> str:
|
35 |
+
"""
|
36 |
+
Safely evaluates math expressions using Python's math module.
|
37 |
+
|
38 |
+
Args:
|
39 |
+
expression: A valid math expression as a string (e.g., 'sqrt(16) + 10').
|
40 |
+
|
41 |
+
Returns:
|
42 |
+
The result of the evaluated expression or an error message.
|
43 |
+
"""
|
44 |
try:
|
45 |
result = eval(expression, {"__builtins__": {}}, math.__dict__)
|
46 |
return str(result)
|
47 |
except Exception as e:
|
48 |
return f"Calculation error: {e}"
|
49 |
|
50 |
+
# --- Agent Wrapper ---
|
51 |
class WebSearchAgent:
|
52 |
def __init__(self):
|
53 |
self.agent = ToolCallingAgent(
|
54 |
name="GAIAWebToolAgent",
|
55 |
+
description="Agent that answers questions using web search and calculator tools.",
|
56 |
tools=[duck_search, calculator],
|
57 |
step_limit=5,
|
58 |
+
system_prompt=(
|
59 |
+
"You're a helpful reasoning agent. Use available tools like web search "
|
60 |
+
"and calculator to answer the user's question accurately and concisely."
|
61 |
+
),
|
62 |
)
|
63 |
+
print("β
Agent initialized.")
|
64 |
|
65 |
def __call__(self, question: str) -> str:
|
66 |
+
print(f"π Question: {question}")
|
67 |
try:
|
68 |
return self.agent.run(question)
|
69 |
except Exception as e:
|
70 |
+
print(f"β Agent error: {e}")
|
71 |
return f"Error: {e}"
|
72 |
|
73 |
+
# --- Evaluation and Submission ---
|
74 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
75 |
space_id = os.getenv("SPACE_ID")
|
76 |
if profile:
|
77 |
username = profile.username
|
78 |
+
print(f"π€ User: {username}")
|
79 |
else:
|
80 |
+
return "Please login to Hugging Face.", None
|
81 |
|
82 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
83 |
+
questions_url = f"{DEFAULT_API_URL}/questions"
|
84 |
+
submit_url = f"{DEFAULT_API_URL}/submit"
|
|
|
85 |
|
86 |
try:
|
87 |
agent = WebSearchAgent()
|
88 |
except Exception as e:
|
89 |
+
return f"Agent initialization error: {e}", None
|
90 |
|
91 |
try:
|
92 |
print("π₯ Fetching questions...")
|
93 |
response = requests.get(questions_url, timeout=15)
|
94 |
response.raise_for_status()
|
95 |
+
questions = response.json()
|
96 |
+
if not questions:
|
97 |
+
return "No questions received.", None
|
98 |
+
print(f"β
Retrieved {len(questions)} questions.")
|
99 |
except Exception as e:
|
100 |
+
return f"Failed to fetch questions: {e}", None
|
101 |
|
|
|
102 |
results_log = []
|
103 |
+
answers_payload = []
|
104 |
+
|
105 |
+
for item in questions:
|
106 |
task_id = item.get("task_id")
|
107 |
+
question = item.get("question")
|
108 |
+
if not task_id or not question:
|
109 |
continue
|
110 |
try:
|
111 |
+
answer = agent(question)
|
|
|
|
|
|
|
|
|
112 |
results_log.append({
|
113 |
"Task ID": task_id,
|
114 |
+
"Question": question,
|
115 |
+
"Submitted Answer": answer
|
116 |
+
})
|
117 |
+
answers_payload.append({
|
118 |
+
"task_id": task_id,
|
119 |
+
"submitted_answer": answer
|
120 |
})
|
121 |
except Exception as e:
|
122 |
error_msg = f"Agent error: {e}"
|
|
|
123 |
results_log.append({
|
124 |
"Task ID": task_id,
|
125 |
+
"Question": question,
|
126 |
"Submitted Answer": error_msg
|
127 |
})
|
128 |
|
129 |
if not answers_payload:
|
130 |
+
return "No answers were generated.", pd.DataFrame(results_log)
|
131 |
|
132 |
print("π€ Submitting answers...")
|
|
|
|
|
|
|
|
|
|
|
|
|
133 |
try:
|
134 |
+
response = requests.post(submit_url, json={
|
135 |
+
"username": username.strip(),
|
136 |
+
"agent_code": agent_code,
|
137 |
+
"answers": answers_payload
|
138 |
+
}, timeout=60)
|
139 |
response.raise_for_status()
|
140 |
result = response.json()
|
141 |
+
status = (
|
142 |
f"β
Submission Successful!\n"
|
143 |
f"User: {result.get('username')}\n"
|
144 |
f"Score: {result.get('score', 'N/A')}% "
|
145 |
f"({result.get('correct_count', '?')}/{result.get('total_attempted', '?')} correct)\n"
|
146 |
+
f"Message: {result.get('message', 'No message')}"
|
147 |
)
|
148 |
+
return status, pd.DataFrame(results_log)
|
149 |
except Exception as e:
|
150 |
+
return f"β Submission failed: {e}", pd.DataFrame(results_log)
|
151 |
|
152 |
# --- Gradio UI ---
|
153 |
with gr.Blocks() as demo:
|
154 |
+
gr.Markdown("# π€ GAIA Agent with Web Search & Calculator Tools")
|
155 |
gr.Markdown("""
|
156 |
+
- β
Log in to your Hugging Face account
|
157 |
+
- π Click the button to run and submit your agent
|
158 |
+
- π§ Agent uses DuckDuckGo search + calculator
|
159 |
""")
|
160 |
gr.LoginButton()
|
161 |
+
run_btn = gr.Button("Run Evaluation & Submit All Answers")
|
162 |
+
status_box = gr.Textbox(label="Status", lines=5)
|
163 |
+
result_table = gr.DataFrame(label="Agent Answers")
|
164 |
|
165 |
+
run_btn.click(fn=run_and_submit_all, outputs=[status_box, result_table])
|
166 |
|
167 |
if __name__ == "__main__":
|
168 |
+
print("π Starting Gradio App...")
|
169 |
+
demo.launch(debug=True, share=False)
|