foleymon's picture
Gemini grounded search tool + direct-answer fallback; drop DuckDuckGo
edde1df
Raw History Blame Contribute Delete
15.7 kB
import os
import re
import gradio as gr
import requests
import inspect
import pandas as pd
import spaces
from smolagents import CodeAgent, LiteLLMModel, VisitWebpageTool, tool
# (Keep Constants as is)
# --- Constants ---
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
# --- ZeroGPU: the Space needs at least one @spaces.GPU function to start ---
@spaces.GPU(duration=120)
def _zero_gpu_keepalive():
return "ok"
# --- Gemini with Google Search grounding ---
# DuckDuckGo rate-limits requests coming from HF Spaces ("No results found"),
# so web search goes through Gemini's built-in Google Search grounding instead.
GEMINI_MODEL = "gemini-3.8-flash"
GEMINI_URL = f"https://generativelanguage.googleapis.com/v1beta/models/{GEMINI_MODEL}:generateContent"
def gemini_grounded(prompt: str, timeout: int = 90) -> str:
"""Ask Gemini a question with Google Search grounding and return its text."""
resp = requests.post(
GEMINI_URL,
headers={"x-goog-api-key": os.getenv("GEMINI_API_KEY", ""), "Content-Type": "application/json"},
json={"contents": [{"parts": [{"text": prompt}]}], "tools": [{"google_search": {}}]},
timeout=timeout,
)
resp.raise_for_status()
parts = resp.json()["candidates"][0]["content"]["parts"]
return "".join(p.get("text", "") for p in parts).strip()
@tool
def google_search(query: str) -> str:
"""Search the web with Google (via Gemini grounding) and return a factual summary with key details.
Args:
query: The search query or factual question to look up.
"""
try:
return gemini_grounded(
"Search the web and give a factual, detailed answer with specific names, numbers and dates. "
"Query: " + query
)[:6000]
except Exception as e:
return f"Search failed: {e}"
# --- Extra tools for the GAIA agent ---
@tool
def search_wikipedia(query: str) -> str:
"""Search English Wikipedia for a topic and return a short summary of the best matching article.
Args:
query: The topic or question to look up on Wikipedia.
"""""
try:
search_url = "https://en.wikipedia.org/w/api.php"
params = {"action": "query", "list": "search", "srsearch": query, "srlimit": 3, "format": "json"}
headers = {"User-Agent": "GAIA-agent-course/1.0"}
resp = requests.get(search_url, params=params, headers=headers, timeout=20)
resp.raise_for_status()
results = resp.json().get("query", {}).get("search", [])
if not results:
return "No Wikipedia article found."
title = results[0]["title"]
summary_url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + requests.utils.quote(title)
summary_resp = requests.get(summary_url, headers=headers, timeout=20)
summary_resp.raise_for_status()
data = summary_resp.json()
text = data.get("extract", "")
if text:
return f"Wikipedia article '{title}': {text}"
return f"Wikipedia article found: {title} (no summary available)."
except Exception as e:
return f"Wikipedia search failed: {e}"
@tool
def read_file(path: str) -> str:
"""Read a local file and return its contents as text. Supports .txt, .py, .md, .csv and .json files and .xlsx spreadsheets (returned as a table). Use this to inspect files attached to a task.
Args:
path: The local file path to read.
"""""
try:
if path.lower().endswith(".xlsx"):
df = pd.read_excel(path)
return df.to_string(index=False)
if path.lower().endswith((".mp3", ".wav", ".png", ".jpg", ".jpeg")):
return f"The file {path} is an audio or image file and cannot be read as text with the available tools."
with open(path, "r", encoding="utf-8", errors="replace") as f:
content = f.read()
if len(content) > 8000:
return content[:8000]
return content
except Exception as e:
return f"Could not read file {path}: {e}"
@tool
def get_youtube_transcript(video_url: str) -> str:
"""Fetch the transcript (subtitles) of a YouTube video, given its URL or video ID.
Args:
video_url: The full YouTube video URL or the video ID.
"""""
try:
from youtube_transcript_api import YouTubeTranscriptApi
match = re.search(r"(?:v=|youtu\.be/|shorts/)([A-Za-z0-9_-]{11})", video_url)
video_id = match.group(1) if match else video_url.strip()
try:
transcript = YouTubeTranscriptApi().fetch(video_id)
lines = [entry.text for entry in transcript]
except Exception:
transcript = YouTubeTranscriptApi.get_transcript(video_id)
lines = [entry["text"] for entry in transcript]
text = " ".join(lines)
if len(text) > 8000:
return text[:8000]
return text
except Exception as e:
return f"Could not fetch YouTube transcript: {e}"
# --- Basic Agent Definition ---
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
class BasicAgent:
def __init__(self):
# Gemini via LiteLLM. gemini-2.5-flash and gemini-2.0-flash are retired
# for this key (Google returns 404), so use the current flash model.
model = LiteLLMModel(
model_id=f"gemini/{GEMINI_MODEL}",
api_key=os.getenv("GEMINI_API_KEY"),
)
self.agent = CodeAgent(
tools=[google_search, VisitWebpageTool(), search_wikipedia, read_file, get_youtube_transcript],
model=model,
max_steps=12,
)
print("BasicAgent initialized.")
def __call__(self, question: str) -> str:
print(f"Agent received question (first 50 chars): {question[:50]}...")
prompt = (
question
+ "\n\nUse your tools to research the question and verify the facts before answering. "
"When you know the answer, finish with exactly one line in this format: FINAL ANSWER: <your answer> "
"Do not add anything after that line."
)
try:
result = self.agent.run(prompt)
except Exception as e:
print(f"Agent run failed: {e}")
result = None
answer = self._clean(result)
if self._is_junk(answer):
print(f"Agent answer unusable ({answer!r}); using grounded fallback.")
try:
answer = self._clean(gemini_grounded(
question
+ "\n\nResearch this carefully, then reply with ONLY the final answer on the last line as "
"'FINAL ANSWER: <answer>'. The answer must be a number, a few words, or a comma-separated list, "
"with no units or explanation unless the question asks for them."
))
except Exception as e:
print(f"Fallback failed: {e}")
print(f"Agent returning answer: {answer}")
return answer
@staticmethod
def _clean(result) -> str:
"""Pull the text after the last 'FINAL ANSWER:' and keep its first line."""
answer = "" if result is None else str(result).strip()
if "FINAL ANSWER:" in answer:
answer = answer.split("FINAL ANSWER:")[-1].strip()
return answer.split("\n")[0].strip().strip("*").strip()
@staticmethod
def _is_junk(answer: str) -> bool:
"""True for empty answers or obvious leftovers like 'None', 'Thought:' or '{answer}'."""
low = answer.lower()
return (not answer or low in ("none", "null", "thought:") or "{answer}" in low
or low.startswith("thought") or len(answer) > 200)
def run_and_submit_all(profile: gr.OAuthProfile | None):
"""
Fetches all questions, runs the BasicAgent on them, submits all answers,
and displays the results.
"""""
# --- Determine HF Space Runtime URL and Repo URL ---
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
if profile:
username = f"{profile.username}"
print(f"User logged in: {username}")
else:
print("User not logged in.")
return "Please Login to Hugging Face with the button.", None
api_url = DEFAULT_API_URL
questions_url = f"{api_url}/questions"
submit_url = f"{api_url}/submit"
# 1. Instantiate Agent ( modify this part to create your agent)
try:
agent = BasicAgent()
except Exception as e:
print(f"Error instantiating agent: {e}")
return f"Error initializing agent: {e}", None
# In the case of an app running as a hugging Face space, this link points toward your codebase ( use the SPACE_ID environment variable if you don't want to hardcode it)
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
print(agent_code)
# 2. Fetch Questions
print(f"Fetching questions from: {questions_url}")
try:
response = requests.get(questions_url, timeout=15)
response.raise_for_status()
questions_data = response.json()
if not questions_data:
print("Fetched questions list is empty.")
return "Fetched questions list is empty or invalid format.", None
print(f"Fetched {len(questions_data)} questions.")
except requests.exceptions.RequestException as e:
print(f"Error fetching questions: {e}")
return f"Error fetching questions: {e}", None
except requests.exceptions.JSONDecodeError as e:
print(f"Error decoding JSON response of questions: {e}")
return f"Error decoding JSON response of questions: {e}", None
except Exception as e:
print(f"Unexpected error fetching questions: {e}")
return f"Unexpected error fetching questions: {e}", None
# 3. Run your Agent
results_log = []
answers_payload = []
print(f"Running agent on {len(questions_data)} questions...")
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:
print(f"Skipping item with missing task_id or question: {item}")
continue
try:
# Download the file attached to this task, if any, so the agent can inspect it
file_name = item.get("file_name") or ""
question_for_agent = question_text
if file_name:
try:
file_url = f"{api_url}/files/{task_id}"
file_response = requests.get(file_url, timeout=60)
file_response.raise_for_status()
local_path = os.path.join("/tmp", file_name)
with open(local_path, "wb") as f:
f.write(file_response.content)
question_for_agent = (
question_text
+ f"\n\nAn attached file for this task was downloaded to: {local_path}. Use the read_file tool to inspect it if it helps answer the question."
)
except Exception as fe:
print(f"Could not download file for task {task_id}: {fe}")
submitted_answer = agent(question_for_agent)
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"Error running agent on task {task_id}: {e}")
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
if not answers_payload:
print("Agent did not produce any answers to submit.")
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
# 4. Submit Answers
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
try:
payload = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
response = requests.post(submit_url, json=payload, timeout=60)
response.raise_for_status()
result_data = response.json()
except requests.exceptions.HTTPError as e:
error_detail = f"HTTP Error: {e}"
try:
error_json = response.json()
error_detail += f" | Server response: {error_json}"
except Exception:
error_detail += f" | Server raw response: {response.text[:500]}"
print(error_detail)
return error_detail, pd.DataFrame(results_log)
except requests.exceptions.RequestException as e:
print(f"Error submitting answers: {e}")
return f"Error submitting answers: {e}", pd.DataFrame(results_log)
except requests.exceptions.JSONDecodeError as e:
print(f"Error decoding JSON response of submission: {e}")
return f"Error decoding JSON response of submission: {e}", pd.DataFrame(results_log)
except Exception as e:
print(f"Unexpected error submitting answers: {e}")
return f"Unexpected error submitting answers: {e}", pd.DataFrame(results_log)
# 5. Format Submission Results
try:
status_message = (
f"Submission Successful!\n"
f"User: {result_data.get('username')}\n"
f"Score: {result_data.get('score')} ({result_data.get('correct_count')}/{result_data.get('total_attempted')} correct)\n"
f"Message: {result_data.get('message')}"
)
print(status_message)
return status_message, pd.DataFrame(results_log)
except Exception as e:
print(f"Error formatting submission results: {e}")
return f"Submission worked but formatting failed: {e}\nRaw data: {result_data}", pd.DataFrame(results_log)
# --- Build the Gradio UI ---
with gr.Blocks() as demo:
gr.Markdown("# Basic Agent Evaluation Runner")
gr.Markdown(
"""
**Instructions:**
1. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
2. Click 'Run Evaluation & Submit All Answers' to fetch the 20 GAIA level-1 questions, run the agent on them, submit the answers, and see the score.
---
**Disclaimer:**
Running the evaluation can take quite some time (this is the time for the agent to answer all 20 questions). Please be patient.
"""""
)
# --- OAuth ---
gr.LoginButton()
# --- Interactive Components ---
run_button = gr.Button("Run Evaluation & Submit All Answers")
status_output = gr.Textbox(label="Status Message", lines=5, interactive=False)
results_dataframe = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
# --- UI Events ---
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_dataframe])
# --- Launch the App ---
if __name__ == "__main__":
space_host = os.getenv("SPACE_HOST")
space_id = os.getenv("SPACE_ID")
if space_host:
print(f"SPACE_HOST found: {space_host}")
print(f"SPACE_ID='{space_id}'")
else:
print("SPACE_HOST environment variable not found (running locally?).")
print("SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
launch_kwargs = {"debug": True, "share": False}
if space_host:
launch_kwargs["server_name"] = "0.0.0.0"
launch_kwargs["server_port"] = 7860
demo.launch(**launch_kwargs)