Update app.py
Browse files
app.py
CHANGED
|
@@ -3,253 +3,72 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
import time
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
# --- Constants ---
|
| 8 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 9 |
-
|
|
|
|
| 10 |
class GeminiAgent:
|
| 11 |
def __init__(self):
|
| 12 |
-
api_key = os.getenv("GEMINI_API_KEY")
|
| 13 |
if not api_key:
|
| 14 |
raise ValueError("GEMINI_API_KEY not set")
|
| 15 |
|
| 16 |
-
|
| 17 |
-
self.
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
print(f"GeminiAgent received question: {question[:50]}...")
|
| 23 |
-
|
| 24 |
-
prompt = f"""
|
| 25 |
-
You are solving GAIA benchmark questions.
|
| 26 |
-
https://huggingface.co/datasets/gaia-benchmark/GAIA
|
| 27 |
-
search for thedataset in the df provided and provide exact answer for the exact question. also
|
| 28 |
-
the answer for question mentioning studio is 3.
|
| 29 |
-
STRICT RULES:
|
| 30 |
-
- Return ONLY the final answer
|
| 31 |
-
- No explanation
|
| 32 |
-
- No sentences
|
| 33 |
-
- No labels like "Final Answer"
|
| 34 |
-
- No punctuation at the end
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
|
| 42 |
-
{question}
|
| 43 |
-
"""
|
| 44 |
|
|
|
|
|
|
|
|
|
|
| 45 |
try:
|
| 46 |
-
time.sleep(
|
| 47 |
-
|
| 48 |
-
response = self.
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
],
|
| 53 |
-
temperature=0
|
| 54 |
-
)
|
| 55 |
-
|
| 56 |
-
answer = response.choices[0].message.content.strip()
|
| 57 |
-
|
| 58 |
-
# 🔥 CLEANING (this is what boosts score)
|
| 59 |
-
answer = answer.replace("Final Answer:", "")
|
| 60 |
-
answer = answer.replace("Answer:", "")
|
| 61 |
-
answer = answer.strip()
|
| 62 |
-
|
| 63 |
-
# keep only first line
|
| 64 |
-
answer = answer.split("\n")[0]
|
| 65 |
-
|
| 66 |
-
# remove trailing dot (but keep decimals)
|
| 67 |
-
if answer.endswith(".") and not answer.replace(".", "", 1).isdigit():
|
| 68 |
-
answer = answer[:-1]
|
| 69 |
-
|
| 70 |
-
# normalize spaces
|
| 71 |
-
answer = " ".join(answer.split())
|
| 72 |
-
|
| 73 |
if not answer:
|
| 74 |
answer = "0"
|
| 75 |
-
|
| 76 |
return answer
|
| 77 |
|
| 78 |
except Exception as e:
|
| 79 |
-
print("
|
| 80 |
-
return f"Error occurred: {e}"
|
| 81 |
-
|
| 82 |
-
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 83 |
-
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 84 |
-
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 85 |
-
|
| 86 |
-
if profile:
|
| 87 |
-
username = f"{profile.username}"
|
| 88 |
-
print(f"User logged in: {username}")
|
| 89 |
-
else:
|
| 90 |
-
print("User not logged in.")
|
| 91 |
-
return "Please Login to Hugging Face with the button.", None
|
| 92 |
-
|
| 93 |
-
api_url = DEFAULT_API_URL
|
| 94 |
-
questions_url = f"{api_url}/questions"
|
| 95 |
-
submit_url = f"{api_url}/submit"
|
| 96 |
-
|
| 97 |
-
# 1. Instantiate Gemini Agent
|
| 98 |
-
try:
|
| 99 |
-
agent = GeminiAgent()
|
| 100 |
-
except Exception as e:
|
| 101 |
-
print(f"Error instantiating agent: {e}")
|
| 102 |
-
return f"Error initializing agent: {e}", None
|
| 103 |
-
|
| 104 |
-
# In the case of an app running as a hugging Face space, this link points toward your codebase
|
| 105 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 106 |
-
print(agent_code)
|
| 107 |
-
|
| 108 |
-
# 2. Fetch Questions
|
| 109 |
-
print(f"Fetching questions from: {questions_url}")
|
| 110 |
-
try:
|
| 111 |
-
response = requests.get(questions_url, timeout=15)
|
| 112 |
-
response.raise_for_status()
|
| 113 |
-
questions_data = response.json()
|
| 114 |
-
if not questions_data:
|
| 115 |
-
print("Fetched questions list is empty.")
|
| 116 |
-
return "Fetched questions list is empty or invalid format.", None
|
| 117 |
-
print(f"Fetched {len(questions_data)} questions.")
|
| 118 |
-
except requests.exceptions.RequestException as e:
|
| 119 |
-
print(f"Error fetching questions: {e}")
|
| 120 |
-
return f"Error fetching questions: {e}", None
|
| 121 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 122 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 123 |
-
print(f"Response text: {response.text[:500]}")
|
| 124 |
-
return f"Error decoding server response for questions: {e}", None
|
| 125 |
-
except Exception as e:
|
| 126 |
-
print(f"An unexpected error occurred fetching questions: {e}")
|
| 127 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 128 |
-
|
| 129 |
-
# 3. Run your Agent
|
| 130 |
-
results_log = []
|
| 131 |
-
answers_payload = []
|
| 132 |
-
print(f"Running agent on {len(questions_data)} questions...")
|
| 133 |
-
for item in questions_data:
|
| 134 |
-
task_id = item.get("task_id")
|
| 135 |
-
question_text = item.get("question")
|
| 136 |
-
if not task_id or question_text is None:
|
| 137 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
| 138 |
-
continue
|
| 139 |
-
try:
|
| 140 |
-
submitted_answer = agent(question_text)
|
| 141 |
-
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 142 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 143 |
-
except Exception as e:
|
| 144 |
-
print(f"Error running agent on task {task_id}: {e}")
|
| 145 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 146 |
-
|
| 147 |
-
if not answers_payload:
|
| 148 |
-
print("Agent did not produce any answers to submit.")
|
| 149 |
-
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 150 |
-
|
| 151 |
-
# 4. Prepare Submission
|
| 152 |
-
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 153 |
-
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 154 |
-
print(status_update)
|
| 155 |
-
|
| 156 |
-
# 5. Submit
|
| 157 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 158 |
-
try:
|
| 159 |
-
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 160 |
-
response.raise_for_status()
|
| 161 |
-
result_data = response.json()
|
| 162 |
-
final_status = (
|
| 163 |
-
f"Submission Successful!\n"
|
| 164 |
-
f"User: {result_data.get('username')}\n"
|
| 165 |
-
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 166 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 167 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
| 168 |
-
)
|
| 169 |
-
print("Submission successful.")
|
| 170 |
-
results_df = pd.DataFrame(results_log)
|
| 171 |
-
return final_status, results_df
|
| 172 |
-
except requests.exceptions.HTTPError as e:
|
| 173 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
| 174 |
-
try:
|
| 175 |
-
error_json = e.response.json()
|
| 176 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 177 |
-
except requests.exceptions.JSONDecodeError:
|
| 178 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
| 179 |
-
status_message = f"Submission Failed: {error_detail}"
|
| 180 |
-
print(status_message)
|
| 181 |
-
results_df = pd.DataFrame(results_log)
|
| 182 |
-
return status_message, results_df
|
| 183 |
-
except requests.exceptions.Timeout:
|
| 184 |
-
status_message = "Submission Failed: The request timed out."
|
| 185 |
-
print(status_message)
|
| 186 |
-
results_df = pd.DataFrame(results_log)
|
| 187 |
-
return status_message, results_df
|
| 188 |
-
except requests.exceptions.RequestException as e:
|
| 189 |
-
status_message = f"Submission Failed: Network error - {e}"
|
| 190 |
-
print(status_message)
|
| 191 |
-
results_df = pd.DataFrame(results_log)
|
| 192 |
-
return status_message, results_df
|
| 193 |
-
except Exception as e:
|
| 194 |
-
status_message = f"An unexpected error occurred during submission: {e}"
|
| 195 |
-
print(status_message)
|
| 196 |
-
results_df = pd.DataFrame(results_log)
|
| 197 |
-
return status_message, results_df
|
| 198 |
-
|
| 199 |
-
# --- Build Gradio Interface using Blocks ---
|
| 200 |
-
with gr.Blocks() as demo:
|
| 201 |
-
gr.Markdown("# Gemini Agent Evaluation Runner")
|
| 202 |
-
gr.Markdown(
|
| 203 |
-
"""
|
| 204 |
-
**Instructions:**
|
| 205 |
-
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 206 |
-
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 207 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 208 |
-
---
|
| 209 |
-
**Disclaimers:**
|
| 210 |
-
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).
|
| 211 |
-
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.
|
| 212 |
-
"""
|
| 213 |
-
)
|
| 214 |
-
|
| 215 |
-
gr.LoginButton()
|
| 216 |
-
|
| 217 |
-
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 218 |
-
|
| 219 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 220 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 221 |
-
|
| 222 |
-
run_button.click(
|
| 223 |
-
fn=run_and_submit_all,
|
| 224 |
-
outputs=[status_output, results_table]
|
| 225 |
-
)
|
| 226 |
-
|
| 227 |
-
if __name__ == "__main__":
|
| 228 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 229 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 230 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
| 231 |
-
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 232 |
-
gemini_key = os.getenv("GEMINI_API_KEY")
|
| 233 |
-
|
| 234 |
-
if space_host_startup:
|
| 235 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 236 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 237 |
-
else:
|
| 238 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 239 |
-
|
| 240 |
-
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 241 |
-
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 242 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 243 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 244 |
-
else:
|
| 245 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 246 |
-
|
| 247 |
-
if gemini_key:
|
| 248 |
-
print("✅ GEMINI_API_KEY found.")
|
| 249 |
-
else:
|
| 250 |
-
print("⚠️ WARNING: GEMINI_API_KEY environment variable not set. The agent will fail to initialize.")
|
| 251 |
-
|
| 252 |
-
print("-" * (60 + len(" App Starting ")) + "\n")
|
| 253 |
-
|
| 254 |
-
print("Launching Gradio Interface for Gemini Agent Evaluation...")
|
| 255 |
-
demo.launch(debug=True, share=False)
|
|
|
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
import time
|
| 6 |
+
|
| 7 |
+
# --- New Imports for Tool-Calling Agent ---
|
| 8 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 9 |
+
from langchain_community.tools import DuckDuckGoSearchRun
|
| 10 |
+
from langchain.agents import AgentExecutor, create_tool_calling_agent
|
| 11 |
+
from langchain_core.prompts import ChatPromptTemplate
|
| 12 |
+
|
| 13 |
# --- Constants ---
|
| 14 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 15 |
+
|
| 16 |
+
# --- Refactored Gemini Agent Definition ---
|
| 17 |
class GeminiAgent:
|
| 18 |
def __init__(self):
|
| 19 |
+
api_key = os.getenv("GEMINI_API_KEY")
|
| 20 |
if not api_key:
|
| 21 |
raise ValueError("GEMINI_API_KEY not set")
|
| 22 |
|
| 23 |
+
# Initialize Gemini 2.5 Flash for fast, accurate tool calling
|
| 24 |
+
self.llm = ChatGoogleGenerativeAI(
|
| 25 |
+
model="gemini-2.5-flash",
|
| 26 |
+
temperature=0,
|
| 27 |
+
google_api_key=api_key
|
| 28 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
+
# Equip the agent with Web Search
|
| 31 |
+
self.search_tool = DuckDuckGoSearchRun()
|
| 32 |
+
self.tools = [self.search_tool]
|
| 33 |
+
|
| 34 |
+
# Define the Agentic Prompt
|
| 35 |
+
prompt = ChatPromptTemplate.from_messages([
|
| 36 |
+
("system", """You are an expert assistant for the GAIA benchmark.
|
| 37 |
+
You must use your tools to find accurate, up-to-date information before answering.
|
| 38 |
+
Do not guess. If you need to perform math, search for the formula or calculation.
|
| 39 |
+
Provide ONLY a short, factual answer (e.g., a specific number, name, or exact phrase).
|
| 40 |
+
No explanations, just the direct answer."""),
|
| 41 |
+
("human", "{input}"),
|
| 42 |
+
("placeholder", "{agent_scratchpad}"),
|
| 43 |
+
])
|
| 44 |
+
|
| 45 |
+
# Create the Tool Calling Agent and Executor
|
| 46 |
+
self.agent = create_tool_calling_agent(self.llm, self.tools, prompt)
|
| 47 |
+
self.agent_executor = AgentExecutor(
|
| 48 |
+
agent=self.agent,
|
| 49 |
+
tools=self.tools,
|
| 50 |
+
verbose=True, # Set to False to reduce logs
|
| 51 |
+
max_iterations=5, # Prevent infinite loops
|
| 52 |
+
handle_parsing_errors=True
|
| 53 |
+
)
|
| 54 |
|
| 55 |
+
print("Gemini Tool-Calling Agent initialized with Gemini 2.5 Flash")
|
|
|
|
|
|
|
| 56 |
|
| 57 |
+
def __call__(self, question: str) -> str:
|
| 58 |
+
print(f"Agent processing question: {question[:50]}...")
|
| 59 |
+
|
| 60 |
try:
|
| 61 |
+
# We no longer need time.sleep(6) because Gemini 2.5 Flash handles rate limits better,
|
| 62 |
+
# and the agent executor handles the pacing of tool calls natively.
|
| 63 |
+
response = self.agent_executor.invoke({"input": question})
|
| 64 |
+
|
| 65 |
+
answer = response.get("output", "").strip()
|
| 66 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
if not answer:
|
| 68 |
answer = "0"
|
| 69 |
+
|
| 70 |
return answer
|
| 71 |
|
| 72 |
except Exception as e:
|
| 73 |
+
print("Agent execution error:", e)
|
| 74 |
+
return f"Error occurred: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|