Spaces:
Runtime error
Runtime error
Commit
·
96b071f
1
Parent(s):
81917a3
added agent
Browse files
app.py
CHANGED
@@ -1,38 +1,50 @@
|
|
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 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
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(
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
|
|
|
|
|
|
36 |
|
37 |
api_url = DEFAULT_API_URL
|
38 |
questions_url = f"{api_url}/questions"
|
@@ -40,7 +52,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
40 |
|
41 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
42 |
try:
|
43 |
-
agent =
|
44 |
except Exception as e:
|
45 |
print(f"Error instantiating agent: {e}")
|
46 |
return f"Error initializing agent: {e}", None
|
@@ -55,16 +67,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
|
@@ -80,19 +92,37 @@ def run_and_submit_all( profile: gr.OAuthProfile | 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(
|
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 +192,26 @@ 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(
|
178 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
179 |
|
180 |
if space_host_startup:
|
181 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
@@ -183,14 +219,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)
|
|
|
1 |
import os
|
2 |
+
|
3 |
import gradio as gr
|
|
|
|
|
4 |
import pandas as pd
|
5 |
+
import requests
|
6 |
+
from dotenv import load_dotenv
|
7 |
+
from smolagents import (
|
8 |
+
CodeAgent,
|
9 |
+
OpenAIServerModel,
|
10 |
+
WebSearchTool,
|
11 |
+
WikipediaSearchTool,
|
12 |
+
)
|
13 |
|
14 |
# (Keep Constants as is)
|
15 |
# --- Constants ---
|
16 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
17 |
+
load_dotenv()
|
18 |
|
19 |
# --- Basic Agent Definition ---
|
20 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
21 |
+
code_agent = CodeAgent(
|
22 |
+
model=OpenAIServerModel(model_id="gpt-4o"),
|
23 |
+
tools=[WebSearchTool(), WikipediaSearchTool()],
|
24 |
+
name="Intelligent_Agent",
|
25 |
+
description="An intelligent agent that can search the web and Wikipedia. Intelligently answers all questions.",
|
26 |
+
)
|
27 |
+
|
28 |
+
code_agent.run("who are you")
|
29 |
+
|
30 |
+
|
31 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
32 |
"""
|
33 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
34 |
and displays the results.
|
35 |
"""
|
36 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
37 |
+
space_id = os.getenv(
|
38 |
+
"SPACE_ID", "darylfunggg/Final_Assignment_Template"
|
39 |
+
) # Get the SPACE_ID for sending link to the code
|
40 |
+
|
41 |
+
# if profile:
|
42 |
+
# username = f"{profile.username}"
|
43 |
+
# print(f"User logged in: {username}")
|
44 |
+
# else:
|
45 |
+
# print("User not logged in.")
|
46 |
+
# return "Please Login to Hugging Face with the button.", None
|
47 |
+
username = "darylfunggg"
|
48 |
|
49 |
api_url = DEFAULT_API_URL
|
50 |
questions_url = f"{api_url}/questions"
|
|
|
52 |
|
53 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
54 |
try:
|
55 |
+
agent = code_agent
|
56 |
except Exception as e:
|
57 |
print(f"Error instantiating agent: {e}")
|
58 |
return f"Error initializing agent: {e}", None
|
|
|
67 |
response.raise_for_status()
|
68 |
questions_data = response.json()
|
69 |
if not questions_data:
|
70 |
+
print("Fetched questions list is empty.")
|
71 |
+
return "Fetched questions list is empty or invalid format.", None
|
72 |
print(f"Fetched {len(questions_data)} questions.")
|
73 |
except requests.exceptions.RequestException as e:
|
74 |
print(f"Error fetching questions: {e}")
|
75 |
return f"Error fetching questions: {e}", None
|
76 |
except requests.exceptions.JSONDecodeError as e:
|
77 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
78 |
+
print(f"Response text: {response.text[:500]}")
|
79 |
+
return f"Error decoding server response for questions: {e}", None
|
80 |
except Exception as e:
|
81 |
print(f"An unexpected error occurred fetching questions: {e}")
|
82 |
return f"An unexpected error occurred fetching questions: {e}", None
|
|
|
92 |
print(f"Skipping item with missing task_id or question: {item}")
|
93 |
continue
|
94 |
try:
|
95 |
+
submitted_answer = agent.run(question_text)
|
96 |
+
answers_payload.append(
|
97 |
+
{"task_id": task_id, "submitted_answer": submitted_answer}
|
98 |
+
)
|
99 |
+
results_log.append(
|
100 |
+
{
|
101 |
+
"Task ID": task_id,
|
102 |
+
"Question": question_text,
|
103 |
+
"Submitted Answer": submitted_answer,
|
104 |
+
}
|
105 |
+
)
|
106 |
except Exception as e:
|
107 |
+
print(f"Error running agent on task {task_id}: {e}")
|
108 |
+
results_log.append(
|
109 |
+
{
|
110 |
+
"Task ID": task_id,
|
111 |
+
"Question": question_text,
|
112 |
+
"Submitted Answer": f"AGENT ERROR: {e}",
|
113 |
+
}
|
114 |
+
)
|
115 |
|
116 |
if not answers_payload:
|
117 |
print("Agent did not produce any answers to submit.")
|
118 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
119 |
|
120 |
+
# 4. Prepare Submission
|
121 |
+
submission_data = {
|
122 |
+
"username": username.strip(),
|
123 |
+
"agent_code": agent_code,
|
124 |
+
"answers": answers_payload,
|
125 |
+
}
|
126 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
127 |
print(status_update)
|
128 |
|
|
|
192 |
|
193 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
194 |
|
195 |
+
status_output = gr.Textbox(
|
196 |
+
label="Run Status / Submission Result", lines=5, interactive=False
|
197 |
+
)
|
198 |
# Removed max_rows=10 from DataFrame constructor
|
199 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
200 |
|
201 |
+
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
|
|
|
|
|
|
202 |
|
203 |
if __name__ == "__main__":
|
204 |
+
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
205 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
206 |
+
space_host_startup = os.getenv(
|
207 |
+
"SPACE_HOST", "darylfunggg-final-assignment-template"
|
208 |
+
)
|
209 |
+
space_id_startup = os.getenv(
|
210 |
+
"SPACE_ID", "darylfunggg/Final_Assignment_Template"
|
211 |
+
) # Get SPACE_ID at startup
|
212 |
+
|
213 |
+
os.environ["SPACE_HOST"] = "darylfunggg-final-assignment-template"
|
214 |
+
os.environ["SPACE_ID"] = "darylfunggg/Final_Assignment_Template"
|
215 |
|
216 |
if space_host_startup:
|
217 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
219 |
else:
|
220 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
221 |
|
222 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
223 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
224 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
225 |
+
print(
|
226 |
+
f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main"
|
227 |
+
)
|
228 |
else:
|
229 |
+
print(
|
230 |
+
"ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined."
|
231 |
+
)
|
232 |
|
233 |
+
print("-" * (60 + len(" App Starting ")) + "\n")
|
234 |
|
235 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
236 |
+
demo.launch(debug=True, share=False)
|