Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,25 +10,51 @@ 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 BasicAgent:
|
| 14 |
def __init__(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
print("BasicAgent initialized.")
|
|
|
|
| 16 |
def __call__(self, question: str) -> str:
|
| 17 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 18 |
-
|
| 19 |
-
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 20 |
-
return fixed_answer
|
| 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.")
|
|
@@ -55,16 +81,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
|
|
@@ -81,18 +107,36 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 81 |
continue
|
| 82 |
try:
|
| 83 |
submitted_answer = agent(question_text)
|
| 84 |
-
answers_payload.append(
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 = {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 97 |
print(status_update)
|
| 98 |
|
|
@@ -162,20 +206,19 @@ with gr.Blocks() as demo:
|
|
| 162 |
|
| 163 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 164 |
|
| 165 |
-
status_output = gr.Textbox(
|
|
|
|
|
|
|
| 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 +226,18 @@ 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(
|
|
|
|
|
|
|
| 190 |
else:
|
| 191 |
-
print(
|
|
|
|
|
|
|
| 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)
|
|
|
|
| 10 |
|
| 11 |
# --- Basic Agent Definition ---
|
| 12 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 13 |
+
from smolagents import (
|
| 14 |
+
CodeAgent,
|
| 15 |
+
ToolCallingAgent,
|
| 16 |
+
HfApiModel,
|
| 17 |
+
DuckDuckGoSearchTool,
|
| 18 |
+
VisitWebpageTool,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
class BasicAgent:
|
| 23 |
def __init__(self):
|
| 24 |
+
model = HfApiModel("Qwen/Qwen2.5-Coder-32B-Instruct")
|
| 25 |
+
|
| 26 |
+
web_agent = ToolCallingAgent(
|
| 27 |
+
tools=[DuckDuckGoSearchTool(), VisitWebpageTool()],
|
| 28 |
+
model=model,
|
| 29 |
+
max_steps=10,
|
| 30 |
+
name="search",
|
| 31 |
+
description="Runs web searches for you. Give it your query as an argument.",
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
manager_agent = CodeAgent(
|
| 35 |
+
tools=[],
|
| 36 |
+
model=model,
|
| 37 |
+
managed_agents=[web_agent],
|
| 38 |
+
additional_authorized_imports=["time", "numpy", "pandas"],
|
| 39 |
+
)
|
| 40 |
+
self.agent = manager_agent
|
| 41 |
print("BasicAgent initialized.")
|
| 42 |
+
|
| 43 |
def __call__(self, question: str) -> str:
|
| 44 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 45 |
+
return self.agent.run(question)
|
|
|
|
|
|
|
| 46 |
|
| 47 |
+
|
| 48 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 49 |
"""
|
| 50 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 51 |
and displays the results.
|
| 52 |
"""
|
| 53 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 54 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 55 |
|
| 56 |
if profile:
|
| 57 |
+
username = f"{profile.username}"
|
| 58 |
print(f"User logged in: {username}")
|
| 59 |
else:
|
| 60 |
print("User not logged in.")
|
|
|
|
| 81 |
response.raise_for_status()
|
| 82 |
questions_data = response.json()
|
| 83 |
if not questions_data:
|
| 84 |
+
print("Fetched questions list is empty.")
|
| 85 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 86 |
print(f"Fetched {len(questions_data)} questions.")
|
| 87 |
except requests.exceptions.RequestException as e:
|
| 88 |
print(f"Error fetching questions: {e}")
|
| 89 |
return f"Error fetching questions: {e}", None
|
| 90 |
except requests.exceptions.JSONDecodeError as e:
|
| 91 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 92 |
+
print(f"Response text: {response.text[:500]}")
|
| 93 |
+
return f"Error decoding server response for questions: {e}", None
|
| 94 |
except Exception as e:
|
| 95 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 96 |
return f"An unexpected error occurred fetching questions: {e}", None
|
|
|
|
| 107 |
continue
|
| 108 |
try:
|
| 109 |
submitted_answer = agent(question_text)
|
| 110 |
+
answers_payload.append(
|
| 111 |
+
{"task_id": task_id, "submitted_answer": submitted_answer}
|
| 112 |
+
)
|
| 113 |
+
results_log.append(
|
| 114 |
+
{
|
| 115 |
+
"Task ID": task_id,
|
| 116 |
+
"Question": question_text,
|
| 117 |
+
"Submitted Answer": submitted_answer,
|
| 118 |
+
}
|
| 119 |
+
)
|
| 120 |
except Exception as e:
|
| 121 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 122 |
+
results_log.append(
|
| 123 |
+
{
|
| 124 |
+
"Task ID": task_id,
|
| 125 |
+
"Question": question_text,
|
| 126 |
+
"Submitted Answer": f"AGENT ERROR: {e}",
|
| 127 |
+
}
|
| 128 |
+
)
|
| 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 = {
|
| 136 |
+
"username": username.strip(),
|
| 137 |
+
"agent_code": agent_code,
|
| 138 |
+
"answers": answers_payload,
|
| 139 |
+
}
|
| 140 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 141 |
print(status_update)
|
| 142 |
|
|
|
|
| 206 |
|
| 207 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 208 |
|
| 209 |
+
status_output = gr.Textbox(
|
| 210 |
+
label="Run Status / Submission Result", lines=5, interactive=False
|
| 211 |
+
)
|
| 212 |
# Removed max_rows=10 from DataFrame constructor
|
| 213 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 214 |
|
| 215 |
+
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
|
|
|
|
|
|
|
|
|
| 216 |
|
| 217 |
if __name__ == "__main__":
|
| 218 |
+
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
| 219 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 220 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 221 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 222 |
|
| 223 |
if space_host_startup:
|
| 224 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
|
| 226 |
else:
|
| 227 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 228 |
|
| 229 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 230 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 231 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 232 |
+
print(
|
| 233 |
+
f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main"
|
| 234 |
+
)
|
| 235 |
else:
|
| 236 |
+
print(
|
| 237 |
+
"ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined."
|
| 238 |
+
)
|
| 239 |
|
| 240 |
+
print("-" * (60 + len(" App Starting ")) + "\n")
|
| 241 |
|
| 242 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 243 |
demo.launch(debug=True, share=False)
|