agents-course / app.py
laiking's picture
update
498d072
import os
import gradio as gr
import requests
import pandas as pd
# My imports
import re
import json
import warnings
import mwclient
from llama_index.core.tools import FunctionTool
from llama_index.llms.openrouter import OpenRouter
from llama_index.core.agent.workflow import ReActAgent
from llama_index.readers.web import BeautifulSoupWebReader
from llama_index.tools.tavily_research import TavilyToolSpec
from llama_index.core.llms import ChatMessage
from llama_index.core.tools.ondemand_loader_tool import OnDemandLoaderTool
from pydantic.warnings import PydanticDeprecatedSince20, PydanticDeprecatedSince211
# Get environment variables for local testing
file_path = os.path.dirname(os.path.abspath(__file__))
environment_file = os.path.join(file_path, ".env")
if os.path.exists(environment_file): # Load environment variables from .env file
from dotenv import load_dotenv
load_dotenv(environment_file)
# Disable pydantic deprecation warnings
warnings.filterwarnings("ignore", category=PydanticDeprecatedSince20)
warnings.filterwarnings("ignore", category=PydanticDeprecatedSince211)
# (Keep Constants as is)
# --- Constants ---
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
# --- Basic Agent Definition ---
nemotron_super = OpenRouter(model="nvidia/llama-3.3-nemotron-super-49b-v1:free") # advanced reasoning, conversational interactions, retrieval-augmented generation (RAG), and tool-calling tasks
# --- Tools ---
def get_page(page_query:str):
"""Send a query to wikipedia and return the text of the page found if it is found, else return an empty string."""
site = mwclient.Site('en.wikipedia.org')
page = site.pages[page_query]
if not page.exists:
return "Page not found."
return page.text()
def reverse_string(s: str) -> str:
"""Reverse a string."""
return s[::-1]
async def reverse_string_async(s: str) -> str:
"""Asynchronous version of reverse_string."""
return s[::-1]
wiki_page_tool = FunctionTool.from_defaults(
get_page,
name="WikipediaTool",
description="Get the text of a Wikipedia page by its title. If the page does not exist, return 'Page not found.'",
)
reverse_string_tool = FunctionTool.from_defaults(
reverse_string,
name="ReverseStringTool",
description="Reverse a string and return it.",
async_fn=reverse_string_async
)
tavily_tools = TavilyToolSpec(
api_key=os.getenv("TAVILY_API_KEY"),
).to_tool_list()
web_page_reader_tool = OnDemandLoaderTool.from_defaults(
BeautifulSoupWebReader(),
name="WebPageReaderTool",
description="A tool for reading web pages. Provide a URL to read the content of the page.",
)
tools = [
wiki_page_tool,
reverse_string_tool,
web_page_reader_tool,
] + tavily_tools
GAIA_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string."""
def extract_final_answer(response_text: str) -> str:
"""Extract the final answer from agent response text."""
if not response_text:
return "ERROR: Empty response"
# Try multiple patterns to extract final answer
patterns = [
r'(?:final\s+)?answer\s*:\s*(.*?)(?:\n|$)',
r'answer\s*:\s*(.*?)(?:\n|$)',
r'final\s*:\s*(.*?)(?:\n|$)',
]
for pattern in patterns:
match = re.search(pattern, response_text, re.IGNORECASE | re.DOTALL)
if match:
answer = match.group(1).strip()
# Clean up the answer
answer = re.sub(r'\s+', ' ', answer) # Normalize whitespace
answer = answer.replace('```', '').strip() # Remove code blocks
if answer and len(answer) < 500: # Reasonable length check
return answer
# Fallback: return last line if no pattern matches
lines = response_text.strip().split('\n')
if lines:
last_line = lines[-1].strip()
if last_line and len(last_line) < 200:
return last_line
return "No clear final answer found"
async 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
submit_url = f"{api_url}/submit"
# 1. Instantiate Agent ( modify this part to create your agent)
try:
agent = ReActAgent(
name="Gaia Agent",
description="General AI assistant",
llm=nemotron_super,
tools=tools,
system_prompt="detailed thinking off",
max_iterations=10,
verbose=True,
)
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 ( usefull for others so please keep it public)
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
print(agent_code)
# 2. Fetch Questions
data_path = os.path.join(file_path, "data", "gaia-tasks.json")
with open(data_path,"r") as f:
try:
questions_data = json.load(f)
except json.JSONDecodeError as e:
print(f"Error loading questions data: {e}")
return "Error loading questions data. Please check the JSON format.", 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")
file_name = item.get("file_name", "")
if not task_id or question_text is None:
print(f"Skipping item with missing task_id or question: {item}")
continue
try:
prompt = f"{GAIA_PROMPT}\nQuestion: {question_text}"
message = ChatMessage(role="user",content=prompt) # TODO: handle files/multimodal inputs
agent_answer = await agent.run(user_msg=message)
# Parsing agents answer
pattern = r'(?:final\s+)?answer\s*:\s*(.*)'
match = re.search(pattern, agent_answer.response.blocks[-1].text, re.IGNORECASE)
submitted_answer = match.group(1) if match else "No final answer found"
# Prepare the payload for submission
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. Prepare Submission
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
print(status_update)
# 5. Submit
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
try:
response = requests.post(submit_url, json=submission_data, timeout=60)
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/A')}% "
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
f"Message: {result_data.get('message', 'No message received.')}"
)
print("Submission successful.")
results_df = pd.DataFrame(results_log)
return final_status, results_df
except requests.exceptions.HTTPError as e:
error_detail = f"Server responded with status {e.response.status_code}."
try:
error_json = e.response.json()
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
except requests.exceptions.JSONDecodeError:
error_detail += f" Response: {e.response.text[:500]}"
status_message = f"Submission Failed: {error_detail}"
print(status_message)
results_df = pd.DataFrame(results_log)
return status_message, results_df
except requests.exceptions.Timeout:
status_message = "Submission Failed: The request timed out."
print(status_message)
results_df = pd.DataFrame(results_log)
return status_message, results_df
except requests.exceptions.RequestException as e:
status_message = f"Submission Failed: Network error - {e}"
print(status_message)
results_df = pd.DataFrame(results_log)
return status_message, results_df
except Exception as e:
status_message = f"An unexpected error occurred during submission: {e}"
print(status_message)
results_df = pd.DataFrame(results_log)
return status_message, results_df
# --- Build Gradio Interface using Blocks ---
with gr.Blocks() as demo:
gr.Markdown("# Basic Agent Evaluation Runner")
gr.Markdown(
"""
**Instructions:**
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
---
**Disclaimers:**
Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
"""
)
gr.LoginButton()
run_button = gr.Button("Run Evaluation & Submit All Answers")
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
# Removed max_rows=10 from DataFrame constructor
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
run_button.click(
fn=run_and_submit_all,
outputs=[status_output, results_table]
)
if __name__ == "__main__":
print("\n" + "-"*30 + " App Starting " + "-"*30)
# Check for SPACE_HOST and SPACE_ID at startup for information
space_host_startup = os.getenv("SPACE_HOST")
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
if space_host_startup:
print(f"✅ SPACE_HOST found: {space_host_startup}")
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
else:
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
if space_id_startup: # Print repo URLs if SPACE_ID is found
print(f"✅ SPACE_ID found: {space_id_startup}")
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
else:
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
print("-"*(60 + len(" App Starting ")) + "\n")
print("Launching Gradio Interface for Basic Agent Evaluation...")
demo.launch(debug=True, share=False)