Update app.py
Browse files
app.py
CHANGED
@@ -5,10 +5,8 @@ import pandas as pd
|
|
5 |
from smolagents import ToolCallingAgent, tool
|
6 |
from duckduckgo_search import DDGS
|
7 |
import math
|
8 |
-
import re
|
9 |
-
from datetime import datetime
|
10 |
|
11 |
-
# --- Tools
|
12 |
@tool
|
13 |
def web_search(query: str) -> str:
|
14 |
"""Performs a web search using DuckDuckGo.
|
@@ -17,7 +15,7 @@ def web_search(query: str) -> str:
|
|
17 |
query: The search query string.
|
18 |
|
19 |
Returns:
|
20 |
-
A formatted string with search results.
|
21 |
"""
|
22 |
try:
|
23 |
with DDGS() as ddgs:
|
@@ -31,7 +29,7 @@ def web_search(query: str) -> str:
|
|
31 |
|
32 |
@tool
|
33 |
def calculate(expression: str) -> str:
|
34 |
-
"""Evaluates mathematical expressions.
|
35 |
|
36 |
Args:
|
37 |
expression: The math expression to evaluate.
|
@@ -40,54 +38,48 @@ def calculate(expression: str) -> str:
|
|
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 |
-
|
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 |
-
# ---
|
57 |
class GAIAAgent:
|
58 |
def __init__(self):
|
59 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
try:
|
61 |
self.agent = ToolCallingAgent(
|
62 |
-
name="
|
63 |
-
description=
|
64 |
tools=[web_search, calculate],
|
65 |
model="gpt-3.5-turbo",
|
66 |
-
planning_interval=3
|
67 |
)
|
68 |
-
print("✅ Agent initialized successfully")
|
69 |
except Exception as e:
|
70 |
-
|
71 |
-
raise
|
72 |
|
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 |
-
|
88 |
-
return f"Error processing question: {str(e)}"
|
89 |
|
90 |
-
# ---
|
91 |
def submit_answers(profile: gr.OAuthProfile | None):
|
92 |
if not profile:
|
93 |
return "Please login to Hugging Face", None
|
@@ -98,25 +90,19 @@ def submit_answers(profile: gr.OAuthProfile | None):
|
|
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]
|
120 |
})
|
121 |
results.append({
|
122 |
"Task ID": task_id,
|
@@ -146,18 +132,14 @@ def submit_answers(profile: gr.OAuthProfile | None):
|
|
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
|
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 |
|
162 |
if __name__ == "__main__":
|
163 |
demo.launch()
|
|
|
5 |
from smolagents import ToolCallingAgent, tool
|
6 |
from duckduckgo_search import DDGS
|
7 |
import math
|
|
|
|
|
8 |
|
9 |
+
# --- Tools ---
|
10 |
@tool
|
11 |
def web_search(query: str) -> str:
|
12 |
"""Performs a web search using DuckDuckGo.
|
|
|
15 |
query: The search query string.
|
16 |
|
17 |
Returns:
|
18 |
+
A formatted string with search results or error message.
|
19 |
"""
|
20 |
try:
|
21 |
with DDGS() as ddgs:
|
|
|
29 |
|
30 |
@tool
|
31 |
def calculate(expression: str) -> str:
|
32 |
+
"""Evaluates mathematical expressions safely.
|
33 |
|
34 |
Args:
|
35 |
expression: The math expression to evaluate.
|
|
|
38 |
The result as a string or error message.
|
39 |
"""
|
40 |
try:
|
|
|
41 |
safe_dict = {k: v for k, v in math.__dict__.items()
|
42 |
if not k.startswith("__")}
|
43 |
+
safe_dict.update({'__builtins__': None, 'abs': abs, 'round': round})
|
44 |
+
return str(eval(expression, {'__builtins__': None}, safe_dict))
|
|
|
|
|
|
|
|
|
|
|
45 |
except Exception as e:
|
46 |
return f"Calculation error: {str(e)}"
|
47 |
|
48 |
+
# --- Agent with System Prompt ---
|
49 |
class GAIAAgent:
|
50 |
def __init__(self):
|
51 |
+
self.system_prompt = """You are an AI assistant designed to answer questions accurately using these tools:
|
52 |
+
|
53 |
+
1. web_search - For finding current information
|
54 |
+
2. calculate - For mathematical calculations
|
55 |
+
|
56 |
+
Guidelines:
|
57 |
+
- For factual questions, always use web_search
|
58 |
+
- For math problems, use calculate
|
59 |
+
- Be concise but thorough
|
60 |
+
- Verify information when possible
|
61 |
+
- If unsure, say so rather than guessing"""
|
62 |
+
|
63 |
try:
|
64 |
self.agent = ToolCallingAgent(
|
65 |
+
name="GAIA_Agent",
|
66 |
+
description=self.system_prompt,
|
67 |
tools=[web_search, calculate],
|
68 |
model="gpt-3.5-turbo",
|
69 |
+
planning_interval=3
|
70 |
)
|
|
|
71 |
except Exception as e:
|
72 |
+
raise RuntimeError(f"Agent initialization failed: {str(e)}")
|
|
|
73 |
|
74 |
def __call__(self, question: str) -> str:
|
75 |
"""Process a question with proper error handling."""
|
76 |
try:
|
|
|
|
|
|
|
|
|
77 |
response = self.agent.run(question)
|
78 |
+
return str(response) if response else "No answer generated"
|
|
|
|
|
|
|
|
|
79 |
except Exception as e:
|
80 |
+
return f"Error: {str(e)}"
|
|
|
81 |
|
82 |
+
# --- Gradio Interface ---
|
83 |
def submit_answers(profile: gr.OAuthProfile | None):
|
84 |
if not profile:
|
85 |
return "Please login to Hugging Face", None
|
|
|
90 |
"https://agents-course-unit4-scoring.hf.space/questions",
|
91 |
timeout=20
|
92 |
)
|
93 |
+
questions = response.json() or []
|
94 |
|
|
|
|
|
|
|
95 |
answers = []
|
96 |
results = []
|
97 |
|
98 |
for item in questions[:15]: # Process first 15 for testing
|
99 |
+
task_id = item.get("task_id", "")
|
100 |
+
question = item.get("question", "")
|
101 |
|
|
|
|
|
|
|
102 |
answer = agent(question)
|
103 |
answers.append({
|
104 |
"task_id": task_id,
|
105 |
+
"submitted_answer": answer[:1000]
|
106 |
})
|
107 |
results.append({
|
108 |
"Task ID": task_id,
|
|
|
132 |
except Exception as e:
|
133 |
return f"Error: {str(e)}", None
|
134 |
|
|
|
135 |
with gr.Blocks() as demo:
|
136 |
+
gr.Markdown("# GAIA Agent")
|
137 |
gr.LoginButton()
|
138 |
submit_btn = gr.Button("Run Evaluation", variant="primary")
|
139 |
output = gr.Textbox(label="Results")
|
140 |
table = gr.DataFrame(label="Details")
|
141 |
|
142 |
+
submit_btn.click(submit_answers, outputs=[output, table])
|
|
|
|
|
|
|
143 |
|
144 |
if __name__ == "__main__":
|
145 |
demo.launch()
|