Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,36 +1,37 @@
|
|
| 1 |
# 17/08/2025 -AO
|
| 2 |
-
|
| 3 |
import os
|
| 4 |
import gradio as gr
|
| 5 |
import requests
|
|
|
|
| 6 |
import pandas as pd
|
| 7 |
-
|
|
|
|
| 8 |
from transformers.tools import DuckDuckGoSearchTool
|
|
|
|
| 9 |
|
| 10 |
# --- Constants ---
|
| 11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 12 |
|
| 13 |
# --- Advanced Agent Definition ---
|
|
|
|
| 14 |
class MyAgent:
|
| 15 |
def __init__(self):
|
| 16 |
-
#
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
#
|
| 20 |
-
self.agent = HfAgent(
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
def __call__(self, question: str) -> str:
|
| 24 |
print(f"Agent received question: {question[:50]}...")
|
| 25 |
-
# Use a try-except block to handle potential errors during execution.
|
| 26 |
try:
|
| 27 |
-
# Let the agent reason and find the answer.
|
| 28 |
-
# Use verbose=True to see the agent's thought process for debugging.
|
| 29 |
result = self.agent.run(question)
|
|
|
|
| 30 |
# The GAIA scoring is an "EXACT MATCH".
|
| 31 |
-
# The prompt asks the agent to just return the answer, not a verbose explanation.
|
| 32 |
-
# You might need to add a post-processing step to extract the final answer.
|
| 33 |
-
# For example, by telling the model in the prompt to only output the answer.
|
| 34 |
final_answer = str(result)
|
| 35 |
print(f"Agent returning answer: {final_answer}")
|
| 36 |
return final_answer
|
|
@@ -40,14 +41,11 @@ class MyAgent:
|
|
| 40 |
|
| 41 |
# The rest of the `run_and_submit_all` and Gradio code remains the same as in the template.
|
| 42 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 43 |
-
|
| 44 |
-
Fetches all questions, runs the agent on them, submits all answers,
|
| 45 |
-
and displays the results.
|
| 46 |
-
"""
|
| 47 |
space_id = os.getenv("SPACE_ID")
|
| 48 |
|
| 49 |
if profile:
|
| 50 |
-
username
|
| 51 |
print(f"User logged in: {username}")
|
| 52 |
else:
|
| 53 |
print("User not logged in.")
|
|
@@ -57,13 +55,13 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 57 |
questions_url = f"{api_url}/questions"
|
| 58 |
submit_url = f"{api_url}/submit"
|
| 59 |
|
| 60 |
-
# 1. Instantiate Agent
|
| 61 |
try:
|
| 62 |
-
agent = MyAgent()
|
| 63 |
except Exception as e:
|
| 64 |
print(f"Error instantiating agent: {e}")
|
| 65 |
return f"Error initializing agent: {e}", None
|
| 66 |
-
|
| 67 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 68 |
print(agent_code)
|
| 69 |
|
|
@@ -110,7 +108,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 110 |
print("Agent did not produce any answers to submit.")
|
| 111 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 112 |
|
| 113 |
-
# 4. Prepare Submission
|
| 114 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 115 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 116 |
print(status_update)
|
|
@@ -158,10 +156,9 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 158 |
results_df = pd.DataFrame(results_log)
|
| 159 |
return status_message, results_df
|
| 160 |
|
| 161 |
-
|
| 162 |
# --- Build Gradio Interface using Blocks ---
|
| 163 |
with gr.Blocks() as demo:
|
| 164 |
-
gr.Markdown("#
|
| 165 |
gr.Markdown(
|
| 166 |
"""
|
| 167 |
**Instructions:**
|
|
@@ -171,6 +168,7 @@ with gr.Blocks() as demo:
|
|
| 171 |
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 172 |
"""
|
| 173 |
)
|
|
|
|
| 174 |
gr.LoginButton()
|
| 175 |
|
| 176 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
|
@@ -185,8 +183,9 @@ with gr.Blocks() as demo:
|
|
| 185 |
|
| 186 |
if __name__ == "__main__":
|
| 187 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
|
|
|
| 188 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 189 |
-
space_id_startup = os.getenv("SPACE_ID")
|
| 190 |
|
| 191 |
if space_host_startup:
|
| 192 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
@@ -194,7 +193,7 @@ if __name__ == "__main__":
|
|
| 194 |
else:
|
| 195 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 196 |
|
| 197 |
-
if space_id_startup:
|
| 198 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 199 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 200 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
|
@@ -203,5 +202,5 @@ if __name__ == "__main__":
|
|
| 203 |
|
| 204 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 205 |
|
| 206 |
-
print("Launching Gradio Interface for
|
| 207 |
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
# 17/08/2025 -AO
|
|
|
|
| 2 |
import os
|
| 3 |
import gradio as gr
|
| 4 |
import requests
|
| 5 |
+
import inspect
|
| 6 |
import pandas as pd
|
| 7 |
+
import torch
|
| 8 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, HfAgent
|
| 9 |
from transformers.tools import DuckDuckGoSearchTool
|
| 10 |
+
from huggingface_hub import InferenceClient
|
| 11 |
|
| 12 |
# --- Constants ---
|
| 13 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 14 |
|
| 15 |
# --- Advanced Agent Definition ---
|
| 16 |
+
# ----- THIS IS WHERE YOU BUILD YOUR AGENT ------
|
| 17 |
class MyAgent:
|
| 18 |
def __init__(self):
|
| 19 |
+
# Initialize the model and tokenizer for tool use
|
| 20 |
+
print("Initializing MyAgent with Qwen2.5-72B-Instruct...")
|
| 21 |
+
|
| 22 |
+
# Muista asettaa -> HF_TOKEN secret in your space settings.
|
| 23 |
+
self.agent = HfAgent(
|
| 24 |
+
llm="Qwen/Qwen2.5-72B-Instruct",
|
| 25 |
+
additional_tools=[DuckDuckGoSearchTool()],
|
| 26 |
+
)
|
| 27 |
+
print("Agent initialized with InferenceClient.")
|
| 28 |
|
| 29 |
def __call__(self, question: str) -> str:
|
| 30 |
print(f"Agent received question: {question[:50]}...")
|
|
|
|
| 31 |
try:
|
|
|
|
|
|
|
| 32 |
result = self.agent.run(question)
|
| 33 |
+
|
| 34 |
# The GAIA scoring is an "EXACT MATCH".
|
|
|
|
|
|
|
|
|
|
| 35 |
final_answer = str(result)
|
| 36 |
print(f"Agent returning answer: {final_answer}")
|
| 37 |
return final_answer
|
|
|
|
| 41 |
|
| 42 |
# The rest of the `run_and_submit_all` and Gradio code remains the same as in the template.
|
| 43 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 44 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
|
|
|
|
|
|
|
|
|
| 45 |
space_id = os.getenv("SPACE_ID")
|
| 46 |
|
| 47 |
if profile:
|
| 48 |
+
username= f"{profile.username}"
|
| 49 |
print(f"User logged in: {username}")
|
| 50 |
else:
|
| 51 |
print("User not logged in.")
|
|
|
|
| 55 |
questions_url = f"{api_url}/questions"
|
| 56 |
submit_url = f"{api_url}/submit"
|
| 57 |
|
| 58 |
+
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 59 |
try:
|
| 60 |
+
agent = MyAgent()
|
| 61 |
except Exception as e:
|
| 62 |
print(f"Error instantiating agent: {e}")
|
| 63 |
return f"Error initializing agent: {e}", None
|
| 64 |
+
# 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)
|
| 65 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 66 |
print(agent_code)
|
| 67 |
|
|
|
|
| 108 |
print("Agent did not produce any answers to submit.")
|
| 109 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 110 |
|
| 111 |
+
# 4. Prepare Submission
|
| 112 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 113 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 114 |
print(status_update)
|
|
|
|
| 156 |
results_df = pd.DataFrame(results_log)
|
| 157 |
return status_message, results_df
|
| 158 |
|
|
|
|
| 159 |
# --- Build Gradio Interface using Blocks ---
|
| 160 |
with gr.Blocks() as demo:
|
| 161 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 162 |
gr.Markdown(
|
| 163 |
"""
|
| 164 |
**Instructions:**
|
|
|
|
| 168 |
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 169 |
"""
|
| 170 |
)
|
| 171 |
+
|
| 172 |
gr.LoginButton()
|
| 173 |
|
| 174 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
|
|
|
| 183 |
|
| 184 |
if __name__ == "__main__":
|
| 185 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 186 |
+
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 187 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 188 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 189 |
|
| 190 |
if space_host_startup:
|
| 191 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
|
| 193 |
else:
|
| 194 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 195 |
|
| 196 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 197 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 198 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 199 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
|
|
|
| 202 |
|
| 203 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 204 |
|
| 205 |
+
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 206 |
demo.launch(debug=True, share=False)
|