navihs's picture
Update app.py
a5338e9 verified
Raw History Blame
4.68 kB
import os
import gradio as gr
import requests
import pandas as pd
from smolagents import (
CodeAgent,
DuckDuckGoSearchTool,
InferenceClientModel
)
# --------------------------------------------------
# Constants
# --------------------------------------------------
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
# --------------------------------------------------
# Agent
# --------------------------------------------------
class BasicAgent:
def __init__(self):
print("Initializing Agent...")
self.model = InferenceClientModel()
self.agent = CodeAgent(
tools=[
DuckDuckGoSearchTool()
],
model=self.model,
add_base_tools=True,
planning_interval=3
)
print("✅ Agent Ready")
def __call__(self, question: str) -> str:
prompt = f"""
You are solving a GAIA benchmark question.
IMPORTANT:
- Solve the question correctly.
- Use search tools when necessary.
- Use calculations when necessary.
- Think carefully.
VERY IMPORTANT:
Return ONLY the final answer.
Do NOT provide:
- explanations
- reasoning
- markdown
- bullet points
- "FINAL ANSWER:"
- "The answer is"
- "Answer:"
- extra text
Question:
{question}
"""
try:
result = self.agent.run(prompt)
answer = str(result).strip()
answer = answer.replace("FINAL ANSWER:", "")
answer = answer.replace("Final Answer:", "")
answer = answer.replace("Answer:", "")
answer = answer.replace("The answer is", "")
answer = answer.strip()
print("=" * 80)
print("QUESTION:")
print(question)
print()
print("ANSWER:")
print(answer)
print("=" * 80)
return answer
except Exception as e:
print(f"Agent Error: {e}")
return ""
# --------------------------------------------------
# Submission Logic
# --------------------------------------------------
def run_and_submit_all(profile: gr.OAuthProfile | None):
space_id = os.getenv("SPACE_ID")
if profile:
username = profile.username
print(f"User logged in: {username}")
else:
return "Please login to Hugging Face first.", None
api_url = DEFAULT_API_URL
questions_url = f"{api_url}/questions"
submit_url = f"{api_url}/submit"
try:
agent = BasicAgent()
except Exception as e:
return f"Agent initialization error: {e}", None
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
try:
response = requests.get(
questions_url,
timeout=30
)
response.raise_for_status()
questions_data = response.json()
print(f"Fetched {len(questions_data)} questions")
except Exception as e:
return f"Question fetch failed: {e}", None
answers_payload = []
results_log = []
for item in questions_data:
task_id = item.get("task_id")
question_text = item.get("question")
if not task_id or question_text is None:
continue
try:
print(f"TASK ID: {task_id}")
print(f"QUESTION: {question_text}")
submitted_answer = agent(question_text)
print(f"SUBMITTED: {submitted_answer}")
answers_payload.append(
{
"task_id": task_id,
"submitted_answer": submitted_answer
}
)
results_log.append(
{
"Task ID": task_id,
"Question": question_text,
"Submitted Answer": submitted_answer
}
)
except Exception as e:
print(f"Task Error {task_id}: {e}")
results_log.append(
{
"Task ID": task_id,
"Question": question_text,
"Submitted Answer": f"ERROR: {e}"
}
)
submission_data = {
"username": username,
"agent_code": agent_code,
"answers": answers_payload
}
try:
response = requests.post(
submit_url,
json=submission_data,
timeout=300
)
response.raise_for_status()
result_data = response.json()
final_status = (
f"Submission Successful!\n"
f"User: {result_data.get('username')}\n"
f"Overall Score: {result_data.get('score')}%\n"