Update app.py
Browse files
app.py
CHANGED
|
@@ -5,110 +5,149 @@ import pandas as pd
|
|
| 5 |
import math
|
| 6 |
|
| 7 |
from smolagents import ToolCallingAgent, tool
|
| 8 |
-
from smolagents.models import OpenAIServerModel
|
| 9 |
from duckduckgo_search import DDGS
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
# --- Tools ---
|
| 12 |
@tool
|
| 13 |
def web_search(query: str) -> str:
|
| 14 |
-
"""
|
| 15 |
-
Perform a web search using DuckDuckGo.
|
| 16 |
|
| 17 |
Args:
|
| 18 |
-
query
|
| 19 |
|
| 20 |
Returns:
|
| 21 |
-
|
| 22 |
"""
|
| 23 |
try:
|
| 24 |
with DDGS() as ddgs:
|
| 25 |
results = ddgs.text(query, max_results=3)
|
|
|
|
|
|
|
| 26 |
return "\n\n".join(
|
| 27 |
-
f"Title: {r['title']}\
|
| 28 |
for r in results
|
| 29 |
-
)
|
| 30 |
except Exception as e:
|
| 31 |
return f"Search error: {str(e)}"
|
| 32 |
|
| 33 |
-
|
| 34 |
@tool
|
| 35 |
def calculate(expression: str) -> str:
|
| 36 |
-
"""
|
| 37 |
-
Evaluate a mathematical expression safely.
|
| 38 |
|
| 39 |
Args:
|
| 40 |
-
expression
|
| 41 |
|
| 42 |
Returns:
|
| 43 |
-
|
| 44 |
"""
|
| 45 |
try:
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
result = eval(expression, {"__builtins__": None}, safe_dict)
|
| 49 |
return str(result)
|
| 50 |
except Exception as e:
|
| 51 |
return f"Calculation error: {str(e)}"
|
| 52 |
|
| 53 |
-
#
|
|
|
|
|
|
|
|
|
|
| 54 |
class GAIAAgent:
|
| 55 |
def __init__(self):
|
| 56 |
-
self.
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
tools=[web_search, calculate],
|
| 66 |
-
model=client.chat.completions # callable, no kwargs
|
| 67 |
-
)
|
| 68 |
-
print("β
Agent initialized successfully")
|
| 69 |
-
except Exception as e:
|
| 70 |
-
raise RuntimeError(f"Agent init failed: {str(e)}")
|
| 71 |
|
| 72 |
def __call__(self, question: str) -> str:
|
| 73 |
try:
|
| 74 |
-
response = self.agent.run(question)
|
| 75 |
-
return str(response)
|
| 76 |
except Exception as e:
|
| 77 |
-
return f"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
-
|
| 80 |
-
def submit_answers(profile: gr.OAuthProfile | None):
|
| 81 |
if not profile:
|
| 82 |
-
return "Please
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
questions = resp.json() or []
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
-
|
| 96 |
-
"username": profile.username,
|
| 97 |
-
"agent_code": f"https://huggingface.co/spaces/{os.getenv('SPACE_ID')}",
|
| 98 |
-
"answers": answers
|
| 99 |
-
}, timeout=60)
|
| 100 |
-
data = post.json()
|
| 101 |
|
| 102 |
-
|
| 103 |
-
|
|
|
|
| 104 |
|
| 105 |
with gr.Blocks() as demo:
|
| 106 |
-
gr.Markdown("# GAIA Agent")
|
|
|
|
| 107 |
gr.LoginButton()
|
| 108 |
-
|
| 109 |
-
status = gr.Textbox(label="
|
| 110 |
-
|
| 111 |
-
|
|
|
|
| 112 |
|
| 113 |
if __name__ == "__main__":
|
| 114 |
demo.launch()
|
|
|
|
| 5 |
import math
|
| 6 |
|
| 7 |
from smolagents import ToolCallingAgent, tool
|
|
|
|
| 8 |
from duckduckgo_search import DDGS
|
| 9 |
+
from openai import OpenAI
|
| 10 |
+
|
| 11 |
+
# Load OpenAI API key
|
| 12 |
+
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
| 13 |
+
|
| 14 |
+
# ------------------------
|
| 15 |
+
# Define Tools
|
| 16 |
+
# ------------------------
|
| 17 |
|
|
|
|
| 18 |
@tool
|
| 19 |
def web_search(query: str) -> str:
|
| 20 |
+
"""Search the web using DuckDuckGo.
|
|
|
|
| 21 |
|
| 22 |
Args:
|
| 23 |
+
query: The search query to look up.
|
| 24 |
|
| 25 |
Returns:
|
| 26 |
+
A summary of the top web results.
|
| 27 |
"""
|
| 28 |
try:
|
| 29 |
with DDGS() as ddgs:
|
| 30 |
results = ddgs.text(query, max_results=3)
|
| 31 |
+
if not results:
|
| 32 |
+
return "No results found."
|
| 33 |
return "\n\n".join(
|
| 34 |
+
f"Title: {r['title']}\nSnippet: {r['body']}\nURL: {r['href']}"
|
| 35 |
for r in results
|
| 36 |
+
)
|
| 37 |
except Exception as e:
|
| 38 |
return f"Search error: {str(e)}"
|
| 39 |
|
|
|
|
| 40 |
@tool
|
| 41 |
def calculate(expression: str) -> str:
|
| 42 |
+
"""Evaluate a mathematical expression.
|
|
|
|
| 43 |
|
| 44 |
Args:
|
| 45 |
+
expression: The math expression to evaluate (e.g. '2 + 3 * 5').
|
| 46 |
|
| 47 |
Returns:
|
| 48 |
+
Result of the calculation.
|
| 49 |
"""
|
| 50 |
try:
|
| 51 |
+
safe_math = {k: v for k, v in math.__dict__.items() if not k.startswith("__")}
|
| 52 |
+
result = eval(expression, {"__builtins__": None}, safe_math)
|
|
|
|
| 53 |
return str(result)
|
| 54 |
except Exception as e:
|
| 55 |
return f"Calculation error: {str(e)}"
|
| 56 |
|
| 57 |
+
# ------------------------
|
| 58 |
+
# Define Agent
|
| 59 |
+
# ------------------------
|
| 60 |
+
|
| 61 |
class GAIAAgent:
|
| 62 |
def __init__(self):
|
| 63 |
+
self.agent = ToolCallingAgent(
|
| 64 |
+
name="GAIA Agent",
|
| 65 |
+
description="""You are an AI assistant that answers questions using tools:
|
| 66 |
+
- Use 'web_search' for looking up facts and recent information.
|
| 67 |
+
- Use 'calculate' for evaluating math expressions.
|
| 68 |
+
Be accurate and concise.""",
|
| 69 |
+
tools=[web_search, calculate],
|
| 70 |
+
model=client.chat.completions
|
| 71 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
def __call__(self, question: str) -> str:
|
| 74 |
try:
|
| 75 |
+
response = self.agent.run(question)
|
| 76 |
+
return str(response)
|
| 77 |
except Exception as e:
|
| 78 |
+
return f"Agent error: {str(e)}"
|
| 79 |
+
|
| 80 |
+
# ------------------------
|
| 81 |
+
# Gradio App Logic
|
| 82 |
+
# ------------------------
|
| 83 |
|
| 84 |
+
def run_agent_and_submit(profile: gr.OAuthProfile | None):
|
|
|
|
| 85 |
if not profile:
|
| 86 |
+
return "β οΈ Please log in to Hugging Face.", None
|
| 87 |
+
|
| 88 |
+
try:
|
| 89 |
+
agent = GAIAAgent()
|
| 90 |
+
response = requests.get("https://agents-course-unit4-scoring.hf.space/questions", timeout=20)
|
| 91 |
+
questions = response.json()
|
| 92 |
+
except Exception as e:
|
| 93 |
+
return f"β Error fetching questions: {e}", None
|
| 94 |
|
| 95 |
+
results = []
|
| 96 |
+
answers = []
|
|
|
|
| 97 |
|
| 98 |
+
for q in questions:
|
| 99 |
+
task_id = q.get("task_id")
|
| 100 |
+
question_text = q.get("question")
|
| 101 |
+
if not task_id or not question_text:
|
| 102 |
+
continue
|
| 103 |
+
try:
|
| 104 |
+
answer = agent(question_text)
|
| 105 |
+
except Exception as e:
|
| 106 |
+
answer = f"Agent error: {e}"
|
| 107 |
+
|
| 108 |
+
answers.append({
|
| 109 |
+
"task_id": task_id,
|
| 110 |
+
"submitted_answer": answer[:1000]
|
| 111 |
+
})
|
| 112 |
+
results.append({
|
| 113 |
+
"Task ID": task_id,
|
| 114 |
+
"Question": question_text,
|
| 115 |
+
"Answer": answer
|
| 116 |
+
})
|
| 117 |
+
|
| 118 |
+
# Submit answers
|
| 119 |
+
try:
|
| 120 |
+
submit_url = "https://agents-course-unit4-scoring.hf.space/submit"
|
| 121 |
+
payload = {
|
| 122 |
+
"username": profile.username,
|
| 123 |
+
"agent_code": f"https://huggingface.co/spaces/{os.getenv('SPACE_ID')}/tree/main",
|
| 124 |
+
"answers": answers
|
| 125 |
+
}
|
| 126 |
+
submit_resp = requests.post(submit_url, json=payload, timeout=60)
|
| 127 |
+
result_data = submit_resp.json()
|
| 128 |
+
summary = (
|
| 129 |
+
f"β
Submitted {len(answers)} answers\n"
|
| 130 |
+
f"π Score: {result_data.get('score', 'N/A')}%\n"
|
| 131 |
+
f"βοΈ Correct: {result_data.get('correct_count', '?')}/{len(answers)}"
|
| 132 |
+
)
|
| 133 |
+
except Exception as e:
|
| 134 |
+
summary = f"β Submission error: {e}"
|
| 135 |
|
| 136 |
+
return summary, pd.DataFrame(results)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
+
# ------------------------
|
| 139 |
+
# Gradio Interface
|
| 140 |
+
# ------------------------
|
| 141 |
|
| 142 |
with gr.Blocks() as demo:
|
| 143 |
+
gr.Markdown("# π€ GAIA Tool Agent")
|
| 144 |
+
gr.Markdown("This agent answers GAIA benchmark questions using tool-calling with search and math.")
|
| 145 |
gr.LoginButton()
|
| 146 |
+
run_btn = gr.Button("π Run Agent & Submit")
|
| 147 |
+
status = gr.Textbox(label="Status", lines=4)
|
| 148 |
+
results_df = gr.DataFrame(label="Results")
|
| 149 |
+
|
| 150 |
+
run_btn.click(fn=run_agent_and_submit, outputs=[status, results_df])
|
| 151 |
|
| 152 |
if __name__ == "__main__":
|
| 153 |
demo.launch()
|