Update app.py
Browse files
app.py
CHANGED
@@ -2,152 +2,133 @@ import os
|
|
2 |
import gradio as gr
|
3 |
import requests
|
4 |
import pandas as pd
|
5 |
-
from smolagents import ToolCallingAgent
|
|
|
6 |
from duckduckgo_search import DDGS
|
7 |
-
import
|
8 |
-
import openai
|
9 |
|
10 |
-
# --- Tools ---
|
11 |
-
@tool
|
12 |
-
def duck_search(query: str) -> str:
|
13 |
-
"""
|
14 |
-
Searches the web using DuckDuckGo and returns a short summary.
|
15 |
-
|
16 |
-
Args:
|
17 |
-
query: The search query string.
|
18 |
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
return "\n\n".join(summaries) if summaries else "No results found."
|
27 |
-
except Exception as e:
|
28 |
-
return f"Search error: {e}"
|
29 |
-
|
30 |
-
@tool
|
31 |
-
def calculator(expression: str) -> str:
|
32 |
-
"""
|
33 |
-
Evaluates basic math expressions using math module.
|
34 |
-
|
35 |
-
Args:
|
36 |
-
expression: A math expression as a string.
|
37 |
|
38 |
-
Returns:
|
39 |
-
The result or an error message.
|
40 |
-
"""
|
41 |
-
try:
|
42 |
-
result = eval(expression, {"__builtins__": {}}, math.__dict__)
|
43 |
-
return str(result)
|
44 |
-
except Exception as e:
|
45 |
-
return f"Calculation error: {e}"
|
46 |
|
47 |
-
#
|
48 |
-
class
|
49 |
def __init__(self):
|
50 |
self.agent = ToolCallingAgent(
|
51 |
name="GAIAWebToolAgent",
|
52 |
description="An agent using DuckDuckGo and calculator tools.",
|
53 |
tools=[duck_search, calculator],
|
54 |
-
model="gpt-3.5-turbo"
|
55 |
-
planning_interval=5,
|
56 |
)
|
57 |
-
print("β
Agent initialized.")
|
58 |
|
59 |
def __call__(self, question: str) -> str:
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
|
|
68 |
)
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
return f"Error: {e}"
|
73 |
|
74 |
-
|
|
|
75 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
76 |
|
77 |
-
# --- Evaluation & Submission ---
|
78 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
79 |
space_id = os.getenv("SPACE_ID")
|
|
|
|
|
|
|
|
|
80 |
if profile:
|
81 |
username = profile.username
|
82 |
-
print(f"
|
83 |
else:
|
84 |
return "Please login to Hugging Face.", None
|
85 |
|
86 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
87 |
-
questions_url = f"{DEFAULT_API_URL}/questions"
|
88 |
-
submit_url = f"{DEFAULT_API_URL}/submit"
|
89 |
-
|
90 |
try:
|
91 |
-
agent =
|
92 |
except Exception as e:
|
93 |
return f"Agent initialization error: {e}", None
|
94 |
|
|
|
|
|
95 |
try:
|
96 |
response = requests.get(questions_url, timeout=15)
|
97 |
response.raise_for_status()
|
98 |
-
|
99 |
-
if not questions:
|
100 |
-
return "No questions received.", None
|
101 |
except Exception as e:
|
102 |
-
return f"
|
103 |
|
104 |
-
results_log = []
|
105 |
answers_payload = []
|
|
|
106 |
|
107 |
-
for item in
|
108 |
task_id = item.get("task_id")
|
109 |
question = item.get("question")
|
110 |
if not task_id or not question:
|
111 |
continue
|
112 |
try:
|
113 |
answer = agent(question)
|
114 |
-
results_log.append({"Task ID": task_id, "Question": question, "Submitted Answer": answer})
|
115 |
answers_payload.append({"task_id": task_id, "submitted_answer": answer})
|
|
|
116 |
except Exception as e:
|
117 |
-
|
118 |
-
results_log.append({"Task ID": task_id, "Question": question, "Submitted Answer": error_msg})
|
119 |
|
120 |
if not answers_payload:
|
121 |
-
return "No answers
|
|
|
|
|
|
|
|
|
|
|
|
|
122 |
|
123 |
try:
|
124 |
-
response = requests.post(submit_url, json=
|
125 |
-
"username": username.strip(),
|
126 |
-
"agent_code": agent_code,
|
127 |
-
"answers": answers_payload
|
128 |
-
}, timeout=60)
|
129 |
response.raise_for_status()
|
130 |
-
|
131 |
-
|
132 |
f"β
Submission Successful!\n"
|
133 |
-
f"User: {
|
134 |
-
f"Score: {
|
135 |
-
f"({
|
136 |
-
f"Message: {
|
137 |
)
|
138 |
-
return
|
139 |
except Exception as e:
|
140 |
-
return f"
|
141 |
|
142 |
-
|
|
|
143 |
with gr.Blocks() as demo:
|
144 |
-
gr.Markdown("
|
|
|
|
|
|
|
|
|
|
|
|
|
145 |
gr.LoginButton()
|
146 |
-
|
147 |
-
|
148 |
-
|
|
|
|
|
149 |
|
150 |
-
run_btn.click(fn=run_and_submit_all, outputs=[status_box, result_table])
|
151 |
|
152 |
if __name__ == "__main__":
|
153 |
-
|
|
|
|
2 |
import gradio as gr
|
3 |
import requests
|
4 |
import pandas as pd
|
5 |
+
from smolagents import ToolCallingAgent
|
6 |
+
from smolagents.tools.calculator import calculator
|
7 |
from duckduckgo_search import DDGS
|
8 |
+
from smolagents.schema import Tool
|
|
|
9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
+
# Define a DuckDuckGo tool
|
12 |
+
@Tool
|
13 |
+
def duck_search(query: str) -> str:
|
14 |
+
"""Searches the web using DuckDuckGo for the given query and returns the top results."""
|
15 |
+
with DDGS() as ddgs:
|
16 |
+
results = ddgs.text(query, max_results=3)
|
17 |
+
return "\n".join([r["body"] for r in results])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
+
# Custom Agent class
|
21 |
+
class GAIAAgent:
|
22 |
def __init__(self):
|
23 |
self.agent = ToolCallingAgent(
|
24 |
name="GAIAWebToolAgent",
|
25 |
description="An agent using DuckDuckGo and calculator tools.",
|
26 |
tools=[duck_search, calculator],
|
27 |
+
model="gpt-3.5-turbo"
|
|
|
28 |
)
|
|
|
29 |
|
30 |
def __call__(self, question: str) -> str:
|
31 |
+
print(f"π Question: {question}")
|
32 |
+
try:
|
33 |
+
return self.agent.run(
|
34 |
+
question,
|
35 |
+
step_limit=5,
|
36 |
+
system_prompt=(
|
37 |
+
"You are a helpful reasoning agent. You can answer questions using search and calculation tools. "
|
38 |
+
"Be concise and accurate. Think step by step when needed. Use DuckDuckGo for recent or factual queries."
|
39 |
+
)
|
40 |
)
|
41 |
+
except Exception as e:
|
42 |
+
print(f"β Agent error: {e}")
|
43 |
+
return f"Error: {e}"
|
|
|
44 |
|
45 |
+
|
46 |
+
# Evaluation and submission code (Hugging Face GAIA integration)
|
47 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
48 |
|
|
|
49 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
50 |
space_id = os.getenv("SPACE_ID")
|
51 |
+
api_url = DEFAULT_API_URL
|
52 |
+
questions_url = f"{api_url}/questions"
|
53 |
+
submit_url = f"{api_url}/submit"
|
54 |
+
|
55 |
if profile:
|
56 |
username = profile.username
|
57 |
+
print(f"User: {username}")
|
58 |
else:
|
59 |
return "Please login to Hugging Face.", None
|
60 |
|
|
|
|
|
|
|
|
|
61 |
try:
|
62 |
+
agent = GAIAAgent()
|
63 |
except Exception as e:
|
64 |
return f"Agent initialization error: {e}", None
|
65 |
|
66 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
67 |
+
|
68 |
try:
|
69 |
response = requests.get(questions_url, timeout=15)
|
70 |
response.raise_for_status()
|
71 |
+
questions_data = response.json()
|
|
|
|
|
72 |
except Exception as e:
|
73 |
+
return f"Error fetching questions: {e}", None
|
74 |
|
|
|
75 |
answers_payload = []
|
76 |
+
results_log = []
|
77 |
|
78 |
+
for item in questions_data:
|
79 |
task_id = item.get("task_id")
|
80 |
question = item.get("question")
|
81 |
if not task_id or not question:
|
82 |
continue
|
83 |
try:
|
84 |
answer = agent(question)
|
|
|
85 |
answers_payload.append({"task_id": task_id, "submitted_answer": answer})
|
86 |
+
results_log.append({"Task ID": task_id, "Question": question, "Submitted Answer": answer})
|
87 |
except Exception as e:
|
88 |
+
results_log.append({"Task ID": task_id, "Question": question, "Submitted Answer": f"Error: {e}"})
|
|
|
89 |
|
90 |
if not answers_payload:
|
91 |
+
return "No answers generated.", pd.DataFrame(results_log)
|
92 |
+
|
93 |
+
submission_data = {
|
94 |
+
"username": username,
|
95 |
+
"agent_code": agent_code,
|
96 |
+
"answers": answers_payload
|
97 |
+
}
|
98 |
|
99 |
try:
|
100 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
|
|
|
|
|
|
|
|
101 |
response.raise_for_status()
|
102 |
+
result_data = response.json()
|
103 |
+
final_status = (
|
104 |
f"β
Submission Successful!\n"
|
105 |
+
f"User: {result_data.get('username')}\n"
|
106 |
+
f"Score: {result_data.get('score')}% "
|
107 |
+
f"({result_data.get('correct_count')}/{result_data.get('total_attempted')})\n"
|
108 |
+
f"Message: {result_data.get('message', '')}"
|
109 |
)
|
110 |
+
return final_status, pd.DataFrame(results_log)
|
111 |
except Exception as e:
|
112 |
+
return f"Submission error: {e}", pd.DataFrame(results_log)
|
113 |
|
114 |
+
|
115 |
+
# Gradio UI
|
116 |
with gr.Blocks() as demo:
|
117 |
+
gr.Markdown("## π GAIA Agent with Web Search & Calculator Tools")
|
118 |
+
gr.Markdown(
|
119 |
+
"1. Log in with your Hugging Face account.\n"
|
120 |
+
"2. Click the button to evaluate the agent on GAIA questions.\n"
|
121 |
+
"3. Results and score will appear below."
|
122 |
+
)
|
123 |
+
|
124 |
gr.LoginButton()
|
125 |
+
run_button = gr.Button("π Run & Submit to GAIA")
|
126 |
+
status_output = gr.Textbox(label="Status", lines=5)
|
127 |
+
results_table = gr.DataFrame(label="Results")
|
128 |
+
|
129 |
+
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
130 |
|
|
|
131 |
|
132 |
if __name__ == "__main__":
|
133 |
+
print("π Launching app...")
|
134 |
+
demo.launch()
|