Update app.py
#398
by Anil777K - opened
app.py
CHANGED
|
@@ -1,196 +1,254 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
-
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
| 11 |
-
|
| 12 |
-
# -----
|
|
|
|
|
|
|
| 13 |
class BasicAgent:
|
| 14 |
def __init__(self):
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def __call__(self, question: str) -> str:
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
if profile:
|
| 31 |
-
username= f"{profile.username}"
|
| 32 |
print(f"User logged in: {username}")
|
| 33 |
else:
|
| 34 |
-
|
| 35 |
-
return "Please Login to Hugging Face with the button.", None
|
| 36 |
|
| 37 |
api_url = DEFAULT_API_URL
|
|
|
|
| 38 |
questions_url = f"{api_url}/questions"
|
| 39 |
submit_url = f"{api_url}/submit"
|
| 40 |
|
| 41 |
-
#
|
|
|
|
|
|
|
| 42 |
try:
|
| 43 |
agent = BasicAgent()
|
|
|
|
| 44 |
except Exception as e:
|
| 45 |
-
print(f"Error instantiating agent: {e}")
|
| 46 |
return f"Error initializing agent: {e}", None
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
| 48 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
|
|
|
| 49 |
print(agent_code)
|
| 50 |
|
| 51 |
-
#
|
| 52 |
-
|
|
|
|
| 53 |
try:
|
| 54 |
-
response = requests.get(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
response.raise_for_status()
|
|
|
|
| 56 |
questions_data = response.json()
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
print(f"Fetched {len(questions_data)} questions.")
|
| 61 |
-
except requests.exceptions.RequestException as e:
|
| 62 |
-
print(f"Error fetching questions: {e}")
|
| 63 |
-
return f"Error fetching questions: {e}", None
|
| 64 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 65 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 66 |
-
print(f"Response text: {response.text[:500]}")
|
| 67 |
-
return f"Error decoding server response for questions: {e}", None
|
| 68 |
except Exception as e:
|
| 69 |
-
|
| 70 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 71 |
|
| 72 |
-
#
|
|
|
|
|
|
|
| 73 |
results_log = []
|
|
|
|
| 74 |
answers_payload = []
|
| 75 |
-
|
| 76 |
for item in questions_data:
|
|
|
|
| 77 |
task_id = item.get("task_id")
|
|
|
|
| 78 |
question_text = item.get("question")
|
|
|
|
| 79 |
if not task_id or question_text is None:
|
| 80 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
| 81 |
continue
|
|
|
|
| 82 |
try:
|
| 83 |
submitted_answer = agent(question_text)
|
| 84 |
-
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 85 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 86 |
-
except Exception as e:
|
| 87 |
-
print(f"Error running agent on task {task_id}: {e}")
|
| 88 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 89 |
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
-
# 5. Submit
|
| 100 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 101 |
try:
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
response.raise_for_status()
|
|
|
|
| 104 |
result_data = response.json()
|
|
|
|
| 105 |
final_status = (
|
| 106 |
-
f"Submission Successful!\n"
|
| 107 |
f"User: {result_data.get('username')}\n"
|
| 108 |
-
f"
|
| 109 |
-
f"
|
| 110 |
-
f"
|
|
|
|
| 111 |
)
|
| 112 |
-
|
| 113 |
results_df = pd.DataFrame(results_log)
|
|
|
|
| 114 |
return final_status, results_df
|
| 115 |
-
|
| 116 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
| 117 |
-
try:
|
| 118 |
-
error_json = e.response.json()
|
| 119 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 120 |
-
except requests.exceptions.JSONDecodeError:
|
| 121 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
| 122 |
-
status_message = f"Submission Failed: {error_detail}"
|
| 123 |
-
print(status_message)
|
| 124 |
-
results_df = pd.DataFrame(results_log)
|
| 125 |
-
return status_message, results_df
|
| 126 |
-
except requests.exceptions.Timeout:
|
| 127 |
-
status_message = "Submission Failed: The request timed out."
|
| 128 |
-
print(status_message)
|
| 129 |
-
results_df = pd.DataFrame(results_log)
|
| 130 |
-
return status_message, results_df
|
| 131 |
-
except requests.exceptions.RequestException as e:
|
| 132 |
-
status_message = f"Submission Failed: Network error - {e}"
|
| 133 |
-
print(status_message)
|
| 134 |
-
results_df = pd.DataFrame(results_log)
|
| 135 |
-
return status_message, results_df
|
| 136 |
except Exception as e:
|
| 137 |
-
|
| 138 |
-
print(status_message)
|
| 139 |
results_df = pd.DataFrame(results_log)
|
| 140 |
-
return status_message, results_df
|
| 141 |
|
|
|
|
| 142 |
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
| 144 |
with gr.Blocks() as demo:
|
| 145 |
-
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 146 |
-
gr.Markdown(
|
| 147 |
-
"""
|
| 148 |
-
**Instructions:**
|
| 149 |
|
| 150 |
-
|
| 151 |
-
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 152 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 153 |
|
| 154 |
-
|
| 155 |
-
**Disclaimers:**
|
| 156 |
-
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).
|
| 157 |
-
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.
|
| 158 |
"""
|
|
|
|
|
|
|
| 159 |
)
|
| 160 |
|
| 161 |
gr.LoginButton()
|
| 162 |
|
| 163 |
-
run_button = gr.Button(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
|
| 169 |
run_button.click(
|
| 170 |
fn=run_and_submit_all,
|
| 171 |
-
outputs=[
|
|
|
|
|
|
|
|
|
|
| 172 |
)
|
| 173 |
|
| 174 |
-
if __name__ == "__main__":
|
| 175 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 176 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 177 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
| 178 |
-
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 179 |
-
|
| 180 |
-
if space_host_startup:
|
| 181 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 182 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 183 |
-
else:
|
| 184 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 185 |
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
else:
|
| 191 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 192 |
|
| 193 |
-
print("
|
| 194 |
|
| 195 |
-
|
| 196 |
-
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
|
| 6 |
+
from smolagents import (
|
| 7 |
+
CodeAgent,
|
| 8 |
+
DuckDuckGoSearchTool,
|
| 9 |
+
InferenceClientModel
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
# -----------------------------
|
| 13 |
+
# Constants
|
| 14 |
+
# -----------------------------
|
| 15 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 16 |
|
| 17 |
+
|
| 18 |
+
# -----------------------------
|
| 19 |
+
# Smart Agent
|
| 20 |
+
# -----------------------------
|
| 21 |
class BasicAgent:
|
| 22 |
def __init__(self):
|
| 23 |
+
|
| 24 |
+
print("Initializing Smart Agent...")
|
| 25 |
+
|
| 26 |
+
# Web Search Tool
|
| 27 |
+
search_tool = DuckDuckGoSearchTool()
|
| 28 |
+
|
| 29 |
+
# Free Hugging Face Model
|
| 30 |
+
model = InferenceClientModel(
|
| 31 |
+
model_id="meta-llama/Llama-3.1-8B-Instruct"
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
# Main Agent
|
| 35 |
+
self.agent = CodeAgent(
|
| 36 |
+
tools=[search_tool],
|
| 37 |
+
model=model,
|
| 38 |
+
add_base_tools=True,
|
| 39 |
+
max_steps=5
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
def __call__(self, question: str) -> str:
|
| 43 |
+
|
| 44 |
+
print(f"Question: {question}")
|
| 45 |
+
|
| 46 |
+
prompt = f"""
|
| 47 |
+
You are a GAIA benchmark assistant.
|
| 48 |
+
|
| 49 |
+
IMPORTANT RULES:
|
| 50 |
+
- Return ONLY the final answer
|
| 51 |
+
- Do NOT explain your reasoning
|
| 52 |
+
- Do NOT write 'FINAL ANSWER'
|
| 53 |
+
- Keep answers short and exact
|
| 54 |
+
- If the answer is a number, return only the number
|
| 55 |
+
- If the answer is text, return only the text
|
| 56 |
+
|
| 57 |
+
Question:
|
| 58 |
+
{question}
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
try:
|
| 62 |
+
response = self.agent.run(prompt)
|
| 63 |
+
|
| 64 |
+
answer = str(response).strip()
|
| 65 |
+
|
| 66 |
+
print(f"Agent answer: {answer}")
|
| 67 |
+
|
| 68 |
+
return answer
|
| 69 |
+
|
| 70 |
+
except Exception as e:
|
| 71 |
+
print(f"Error while solving question: {e}")
|
| 72 |
+
|
| 73 |
+
return "Error"
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# -----------------------------
|
| 77 |
+
# Main Evaluation Function
|
| 78 |
+
# -----------------------------
|
| 79 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 80 |
+
|
| 81 |
+
space_id = os.getenv("SPACE_ID")
|
| 82 |
|
| 83 |
if profile:
|
| 84 |
+
username = f"{profile.username}"
|
| 85 |
print(f"User logged in: {username}")
|
| 86 |
else:
|
| 87 |
+
return "Please login with Hugging Face first.", None
|
|
|
|
| 88 |
|
| 89 |
api_url = DEFAULT_API_URL
|
| 90 |
+
|
| 91 |
questions_url = f"{api_url}/questions"
|
| 92 |
submit_url = f"{api_url}/submit"
|
| 93 |
|
| 94 |
+
# -----------------------------
|
| 95 |
+
# Create Agent
|
| 96 |
+
# -----------------------------
|
| 97 |
try:
|
| 98 |
agent = BasicAgent()
|
| 99 |
+
|
| 100 |
except Exception as e:
|
|
|
|
| 101 |
return f"Error initializing agent: {e}", None
|
| 102 |
+
|
| 103 |
+
# -----------------------------
|
| 104 |
+
# Space Code URL
|
| 105 |
+
# -----------------------------
|
| 106 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 107 |
+
|
| 108 |
print(agent_code)
|
| 109 |
|
| 110 |
+
# -----------------------------
|
| 111 |
+
# Fetch Questions
|
| 112 |
+
# -----------------------------
|
| 113 |
try:
|
| 114 |
+
response = requests.get(
|
| 115 |
+
questions_url,
|
| 116 |
+
timeout=30
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
response.raise_for_status()
|
| 120 |
+
|
| 121 |
questions_data = response.json()
|
| 122 |
+
|
| 123 |
+
print(f"Fetched {len(questions_data)} questions")
|
| 124 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
except Exception as e:
|
| 126 |
+
return f"Error fetching questions: {e}", None
|
|
|
|
| 127 |
|
| 128 |
+
# -----------------------------
|
| 129 |
+
# Run Agent
|
| 130 |
+
# -----------------------------
|
| 131 |
results_log = []
|
| 132 |
+
|
| 133 |
answers_payload = []
|
| 134 |
+
|
| 135 |
for item in questions_data:
|
| 136 |
+
|
| 137 |
task_id = item.get("task_id")
|
| 138 |
+
|
| 139 |
question_text = item.get("question")
|
| 140 |
+
|
| 141 |
if not task_id or question_text is None:
|
|
|
|
| 142 |
continue
|
| 143 |
+
|
| 144 |
try:
|
| 145 |
submitted_answer = agent(question_text)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
+
answers_payload.append({
|
| 148 |
+
"task_id": task_id,
|
| 149 |
+
"submitted_answer": submitted_answer
|
| 150 |
+
})
|
| 151 |
+
|
| 152 |
+
results_log.append({
|
| 153 |
+
"Task ID": task_id,
|
| 154 |
+
"Question": question_text,
|
| 155 |
+
"Submitted Answer": submitted_answer
|
| 156 |
+
})
|
| 157 |
+
|
| 158 |
+
except Exception as e:
|
| 159 |
|
| 160 |
+
results_log.append({
|
| 161 |
+
"Task ID": task_id,
|
| 162 |
+
"Question": question_text,
|
| 163 |
+
"Submitted Answer": f"ERROR: {e}"
|
| 164 |
+
})
|
| 165 |
+
|
| 166 |
+
# -----------------------------
|
| 167 |
+
# Submit Answers
|
| 168 |
+
# -----------------------------
|
| 169 |
+
submission_data = {
|
| 170 |
+
"username": username.strip(),
|
| 171 |
+
"agent_code": agent_code,
|
| 172 |
+
"answers": answers_payload
|
| 173 |
+
}
|
| 174 |
|
|
|
|
|
|
|
| 175 |
try:
|
| 176 |
+
|
| 177 |
+
response = requests.post(
|
| 178 |
+
submit_url,
|
| 179 |
+
json=submission_data,
|
| 180 |
+
timeout=120
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
response.raise_for_status()
|
| 184 |
+
|
| 185 |
result_data = response.json()
|
| 186 |
+
|
| 187 |
final_status = (
|
| 188 |
+
f"Submission Successful!\n\n"
|
| 189 |
f"User: {result_data.get('username')}\n"
|
| 190 |
+
f"Score: {result_data.get('score')}%\n"
|
| 191 |
+
f"Correct: {result_data.get('correct_count')}/"
|
| 192 |
+
f"{result_data.get('total_attempted')}\n\n"
|
| 193 |
+
f"Message: {result_data.get('message')}"
|
| 194 |
)
|
| 195 |
+
|
| 196 |
results_df = pd.DataFrame(results_log)
|
| 197 |
+
|
| 198 |
return final_status, results_df
|
| 199 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
except Exception as e:
|
| 201 |
+
|
|
|
|
| 202 |
results_df = pd.DataFrame(results_log)
|
|
|
|
| 203 |
|
| 204 |
+
return f"Submission Failed: {e}", results_df
|
| 205 |
|
| 206 |
+
|
| 207 |
+
# -----------------------------
|
| 208 |
+
# Gradio UI
|
| 209 |
+
# -----------------------------
|
| 210 |
with gr.Blocks() as demo:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
|
| 212 |
+
gr.Markdown("# GAIA Agent Evaluation")
|
|
|
|
|
|
|
| 213 |
|
| 214 |
+
gr.Markdown(
|
|
|
|
|
|
|
|
|
|
| 215 |
"""
|
| 216 |
+
Login with Hugging Face and run your AI agent on GAIA questions.
|
| 217 |
+
"""
|
| 218 |
)
|
| 219 |
|
| 220 |
gr.LoginButton()
|
| 221 |
|
| 222 |
+
run_button = gr.Button(
|
| 223 |
+
"Run Evaluation & Submit All Answers"
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
status_output = gr.Textbox(
|
| 227 |
+
label="Status",
|
| 228 |
+
lines=8
|
| 229 |
+
)
|
| 230 |
|
| 231 |
+
results_table = gr.DataFrame(
|
| 232 |
+
label="Agent Results"
|
| 233 |
+
)
|
| 234 |
|
| 235 |
run_button.click(
|
| 236 |
fn=run_and_submit_all,
|
| 237 |
+
outputs=[
|
| 238 |
+
status_output,
|
| 239 |
+
results_table
|
| 240 |
+
]
|
| 241 |
)
|
| 242 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 243 |
|
| 244 |
+
# -----------------------------
|
| 245 |
+
# Launch App
|
| 246 |
+
# -----------------------------
|
| 247 |
+
if __name__ == "__main__":
|
|
|
|
|
|
|
| 248 |
|
| 249 |
+
print("Starting GAIA Agent App...")
|
| 250 |
|
| 251 |
+
demo.launch(
|
| 252 |
+
debug=True,
|
| 253 |
+
share=False
|
| 254 |
+
)
|