New attempt.
Browse files
app.py
CHANGED
@@ -3,7 +3,9 @@ import gradio as gr
|
|
3 |
import requests
|
4 |
import inspect
|
5 |
import pandas as pd
|
6 |
-
from smolagents import
|
|
|
|
|
7 |
|
8 |
# (Keep Constants as is)
|
9 |
# --- Constants ---
|
@@ -11,42 +13,46 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
11 |
|
12 |
# --- Basic Agent Definition ---
|
13 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
14 |
-
|
15 |
-
|
16 |
class BasicAgent:
|
17 |
def __init__(self):
|
18 |
-
print("BasicAgent initialized
|
19 |
-
# Initialize
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
|
|
|
|
|
|
25 |
def __call__(self, question: str) -> str:
|
26 |
-
print(f"Agent received question: {question[:50]}...")
|
27 |
-
|
28 |
try:
|
29 |
-
#
|
30 |
-
prompt = f"
|
31 |
-
|
32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
except Exception as e:
|
34 |
-
|
35 |
-
|
36 |
-
print(f"Agent returning answer: {answer[:100]}...") # Print just a preview
|
37 |
-
return answer
|
38 |
-
|
39 |
|
40 |
-
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
41 |
"""
|
42 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
43 |
and displays the results.
|
44 |
"""
|
45 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
46 |
-
space_id = os.getenv("SPACE_ID")
|
47 |
|
48 |
if profile:
|
49 |
-
username
|
50 |
print(f"User logged in: {username}")
|
51 |
else:
|
52 |
print("User not logged in.")
|
@@ -73,16 +79,16 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
73 |
response.raise_for_status()
|
74 |
questions_data = response.json()
|
75 |
if not questions_data:
|
76 |
-
|
77 |
-
|
78 |
print(f"Fetched {len(questions_data)} questions.")
|
79 |
except requests.exceptions.RequestException as e:
|
80 |
print(f"Error fetching questions: {e}")
|
81 |
return f"Error fetching questions: {e}", None
|
82 |
except requests.exceptions.JSONDecodeError as e:
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
except Exception as e:
|
87 |
print(f"An unexpected error occurred fetching questions: {e}")
|
88 |
return f"An unexpected error occurred fetching questions: {e}", None
|
@@ -102,14 +108,14 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
102 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
103 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
104 |
except Exception as e:
|
105 |
-
|
106 |
-
|
107 |
|
108 |
if not answers_payload:
|
109 |
print("Agent did not produce any answers to submit.")
|
110 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
111 |
|
112 |
-
# 4. Prepare Submission
|
113 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
114 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
115 |
print(status_update)
|
@@ -160,7 +166,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
160 |
|
161 |
# --- Build Gradio Interface using Blocks ---
|
162 |
with gr.Blocks() as demo:
|
163 |
-
gr.Markdown("# Basic Agent Evaluation Runner (Test #
|
164 |
gr.Markdown(
|
165 |
"""
|
166 |
**Instructions:**
|
@@ -190,10 +196,10 @@ with gr.Blocks() as demo:
|
|
190 |
)
|
191 |
|
192 |
if __name__ == "__main__":
|
193 |
-
print("\n" + "-"
|
194 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
195 |
space_host_startup = os.getenv("SPACE_HOST")
|
196 |
-
space_id_startup = os.getenv("SPACE_ID")
|
197 |
|
198 |
if space_host_startup:
|
199 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
@@ -201,14 +207,14 @@ if __name__ == "__main__":
|
|
201 |
else:
|
202 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
203 |
|
204 |
-
if space_id_startup:
|
205 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
206 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
207 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
208 |
else:
|
209 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
210 |
|
211 |
-
print("-"
|
212 |
|
213 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
214 |
-
demo.launch(debug=True, share=False)
|
|
|
3 |
import requests
|
4 |
import inspect
|
5 |
import pandas as pd
|
6 |
+
from smolagents.agent import PythonInterpreterAgent
|
7 |
+
from smolagents.search import WebSummarySearch
|
8 |
+
from smolagents.task_manager import PythonInterpreterTaskManager
|
9 |
|
10 |
# (Keep Constants as is)
|
11 |
# --- Constants ---
|
|
|
13 |
|
14 |
# --- Basic Agent Definition ---
|
15 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
|
|
|
|
16 |
class BasicAgent:
|
17 |
def __init__(self):
|
18 |
+
print("BasicAgent initialized.")
|
19 |
+
# Initialize web search capability
|
20 |
+
self.search_tool = WebSummarySearch()
|
21 |
+
# Initialize Python interpreter agent with search tool
|
22 |
+
self.task_manager = PythonInterpreterTaskManager(
|
23 |
+
tools=[self.search_tool],
|
24 |
+
)
|
25 |
+
self.agent = PythonInterpreterAgent(self.task_manager)
|
26 |
+
print("Search capability initialized.")
|
27 |
+
|
28 |
def __call__(self, question: str) -> str:
|
29 |
+
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
|
|
30 |
try:
|
31 |
+
# Process the question with the agent
|
32 |
+
prompt = f"""
|
33 |
+
You are a helpful AI assistant. Please answer the following question:
|
34 |
+
{question}
|
35 |
+
|
36 |
+
If you need to search for information, use the search tool.
|
37 |
+
Provide a clear, concise, and accurate answer.
|
38 |
+
"""
|
39 |
+
response = self.agent.run(prompt)
|
40 |
+
print(f"Agent processed question and generated response.")
|
41 |
+
return response
|
42 |
except Exception as e:
|
43 |
+
print(f"Error in agent processing: {e}")
|
44 |
+
return f"I encountered an error while processing your question: {str(e)}"
|
|
|
|
|
|
|
45 |
|
46 |
+
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
47 |
"""
|
48 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
49 |
and displays the results.
|
50 |
"""
|
51 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
52 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
53 |
|
54 |
if profile:
|
55 |
+
username= f"{profile.username}"
|
56 |
print(f"User logged in: {username}")
|
57 |
else:
|
58 |
print("User not logged in.")
|
|
|
79 |
response.raise_for_status()
|
80 |
questions_data = response.json()
|
81 |
if not questions_data:
|
82 |
+
print("Fetched questions list is empty.")
|
83 |
+
return "Fetched questions list is empty or invalid format.", None
|
84 |
print(f"Fetched {len(questions_data)} questions.")
|
85 |
except requests.exceptions.RequestException as e:
|
86 |
print(f"Error fetching questions: {e}")
|
87 |
return f"Error fetching questions: {e}", None
|
88 |
except requests.exceptions.JSONDecodeError as e:
|
89 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
90 |
+
print(f"Response text: {response.text[:500]}")
|
91 |
+
return f"Error decoding server response for questions: {e}", None
|
92 |
except Exception as e:
|
93 |
print(f"An unexpected error occurred fetching questions: {e}")
|
94 |
return f"An unexpected error occurred fetching questions: {e}", None
|
|
|
108 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
109 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
110 |
except Exception as e:
|
111 |
+
print(f"Error running agent on task {task_id}: {e}")
|
112 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
113 |
|
114 |
if not answers_payload:
|
115 |
print("Agent did not produce any answers to submit.")
|
116 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
117 |
|
118 |
+
# 4. Prepare Submission
|
119 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
120 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
121 |
print(status_update)
|
|
|
166 |
|
167 |
# --- Build Gradio Interface using Blocks ---
|
168 |
with gr.Blocks() as demo:
|
169 |
+
gr.Markdown("# Basic Agent Evaluation Runner (Test #1)")
|
170 |
gr.Markdown(
|
171 |
"""
|
172 |
**Instructions:**
|
|
|
196 |
)
|
197 |
|
198 |
if __name__ == "__main__":
|
199 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
200 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
201 |
space_host_startup = os.getenv("SPACE_HOST")
|
202 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
203 |
|
204 |
if space_host_startup:
|
205 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
207 |
else:
|
208 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
209 |
|
210 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
211 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
212 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
213 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
214 |
else:
|
215 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
216 |
|
217 |
+
print("-"*(60 + len(" App Starting ")) + "\n")
|
218 |
|
219 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
220 |
+
demo.launch(debug=True, share=False)
|