Update app.py
Browse files
app.py
CHANGED
|
@@ -1,34 +1,68 @@
|
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
-
import requests
|
| 4 |
-
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
# (Keep Constants as is)
|
| 8 |
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
|
|
|
| 11 |
# --- Basic Agent Definition ---
|
| 12 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 13 |
-
class
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def __call__(self, question: str) -> str:
|
| 17 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 18 |
-
|
| 19 |
-
print(f"Agent returning
|
| 20 |
-
return
|
| 21 |
|
| 22 |
-
|
|
|
|
| 23 |
"""
|
| 24 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 25 |
and displays the results.
|
| 26 |
"""
|
| 27 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 28 |
-
space_id = os.getenv("SPACE_ID")
|
| 29 |
|
| 30 |
if profile:
|
| 31 |
-
username= f"{profile.username}"
|
| 32 |
print(f"User logged in: {username}")
|
| 33 |
else:
|
| 34 |
print("User not logged in.")
|
|
@@ -40,7 +74,13 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 40 |
|
| 41 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 42 |
try:
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
except Exception as e:
|
| 45 |
print(f"Error instantiating agent: {e}")
|
| 46 |
return f"Error initializing agent: {e}", None
|
|
@@ -55,16 +95,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 55 |
response.raise_for_status()
|
| 56 |
questions_data = response.json()
|
| 57 |
if not questions_data:
|
| 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 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
except Exception as e:
|
| 69 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 70 |
return f"An unexpected error occurred fetching questions: {e}", None
|
|
@@ -84,14 +124,14 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 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 |
-
|
| 88 |
-
|
| 89 |
|
| 90 |
if not answers_payload:
|
| 91 |
print("Agent did not produce any answers to submit.")
|
| 92 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 93 |
|
| 94 |
-
# 4. Prepare Submission
|
| 95 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 96 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 97 |
print(status_update)
|
|
@@ -166,16 +206,13 @@ with gr.Blocks() as demo:
|
|
| 166 |
# Removed max_rows=10 from DataFrame constructor
|
| 167 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 168 |
|
| 169 |
-
run_button.click(
|
| 170 |
-
fn=run_and_submit_all,
|
| 171 |
-
outputs=[status_output, results_table]
|
| 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")
|
| 179 |
|
| 180 |
if space_host_startup:
|
| 181 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
@@ -183,14 +220,14 @@ if __name__ == "__main__":
|
|
| 183 |
else:
|
| 184 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 185 |
|
| 186 |
-
if space_id_startup:
|
| 187 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 188 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 189 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 190 |
else:
|
| 191 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 192 |
|
| 193 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 194 |
|
| 195 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 196 |
-
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
import os
|
| 3 |
+
|
| 4 |
import gradio as gr
|
|
|
|
|
|
|
| 5 |
import pandas as pd
|
| 6 |
+
import requests
|
| 7 |
+
from smolagents import (
|
| 8 |
+
AmazonBedrockServerModel,
|
| 9 |
+
DuckDuckGoSearchTool,
|
| 10 |
+
FinalAnswerPromptTemplate,
|
| 11 |
+
ManagedAgentPromptTemplate,
|
| 12 |
+
Model,
|
| 13 |
+
PlanningPromptTemplate,
|
| 14 |
+
PromptTemplates,
|
| 15 |
+
ToolCallingAgent,
|
| 16 |
+
VisitWebpageTool,
|
| 17 |
+
)
|
| 18 |
|
| 19 |
# (Keep Constants as is)
|
| 20 |
# --- Constants ---
|
| 21 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 22 |
|
| 23 |
+
|
| 24 |
# --- Basic Agent Definition ---
|
| 25 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 26 |
+
class GAIAgent:
|
| 27 |
+
SYSTEM_PROMPT = """You are a helpful assistant with web browsing capabilities.
|
| 28 |
+
You can search the web and visit webpages to find relevant information.
|
| 29 |
+
You should answer user questions based on the information you find."""
|
| 30 |
+
|
| 31 |
+
def __init__(self, model: Model):
|
| 32 |
+
prompt_templates = PromptTemplates(
|
| 33 |
+
system_prompt=self.SYSTEM_PROMPT,
|
| 34 |
+
planning=PlanningPromptTemplate(
|
| 35 |
+
initial_plan="",
|
| 36 |
+
update_plan_pre_messages="",
|
| 37 |
+
update_plan_post_messages="",
|
| 38 |
+
),
|
| 39 |
+
managed_agent=ManagedAgentPromptTemplate(task="", report=""),
|
| 40 |
+
final_answer=FinalAnswerPromptTemplate(pre_messages="", post_messages=""),
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
self.agent = ToolCallingAgent(
|
| 44 |
+
tools=[DuckDuckGoSearchTool(), VisitWebpageTool()],
|
| 45 |
+
model=model,
|
| 46 |
+
prompt_templates=prompt_templates,
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
def __call__(self, question: str) -> str:
|
| 50 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 51 |
+
answer = self.agent.run(question)
|
| 52 |
+
print(f"Agent returning answer: {answer}")
|
| 53 |
+
return answer
|
| 54 |
|
| 55 |
+
|
| 56 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 57 |
"""
|
| 58 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 59 |
and displays the results.
|
| 60 |
"""
|
| 61 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 62 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 63 |
|
| 64 |
if profile:
|
| 65 |
+
username = f"{profile.username}"
|
| 66 |
print(f"User logged in: {username}")
|
| 67 |
else:
|
| 68 |
print("User not logged in.")
|
|
|
|
| 74 |
|
| 75 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 76 |
try:
|
| 77 |
+
model = AmazonBedrockServerModel(
|
| 78 |
+
model_id="eu.anthropic.claude-3-7-sonnet-20250219-v1:0",
|
| 79 |
+
client_kwargs={
|
| 80 |
+
"region_name": "eu-west-1",
|
| 81 |
+
},
|
| 82 |
+
)
|
| 83 |
+
agent = GAIAgent(model=model)
|
| 84 |
except Exception as e:
|
| 85 |
print(f"Error instantiating agent: {e}")
|
| 86 |
return f"Error initializing agent: {e}", None
|
|
|
|
| 95 |
response.raise_for_status()
|
| 96 |
questions_data = response.json()
|
| 97 |
if not questions_data:
|
| 98 |
+
print("Fetched questions list is empty.")
|
| 99 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 100 |
print(f"Fetched {len(questions_data)} questions.")
|
| 101 |
except requests.exceptions.RequestException as e:
|
| 102 |
print(f"Error fetching questions: {e}")
|
| 103 |
return f"Error fetching questions: {e}", None
|
| 104 |
except requests.exceptions.JSONDecodeError as e:
|
| 105 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 106 |
+
print(f"Response text: {response.text[:500]}")
|
| 107 |
+
return f"Error decoding server response for questions: {e}", None
|
| 108 |
except Exception as e:
|
| 109 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 110 |
return f"An unexpected error occurred fetching questions: {e}", None
|
|
|
|
| 124 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 125 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 126 |
except Exception as e:
|
| 127 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 128 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 129 |
|
| 130 |
if not answers_payload:
|
| 131 |
print("Agent did not produce any answers to submit.")
|
| 132 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 133 |
|
| 134 |
+
# 4. Prepare Submission
|
| 135 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 136 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 137 |
print(status_update)
|
|
|
|
| 206 |
# Removed max_rows=10 from DataFrame constructor
|
| 207 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 208 |
|
| 209 |
+
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
|
|
|
|
|
|
|
|
|
| 210 |
|
| 211 |
if __name__ == "__main__":
|
| 212 |
+
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
| 213 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 214 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 215 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 216 |
|
| 217 |
if space_host_startup:
|
| 218 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
|
| 220 |
else:
|
| 221 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 222 |
|
| 223 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 224 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 225 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 226 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 227 |
else:
|
| 228 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 229 |
|
| 230 |
+
print("-" * (60 + len(" App Starting ")) + "\n")
|
| 231 |
|
| 232 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 233 |
+
demo.launch(debug=True, share=False)
|