Integrate Azrock agent
Browse files
app.py
CHANGED
@@ -1,34 +1,37 @@
|
|
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 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 |
fixed_answer = "This is a default answer."
|
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.")
|
@@ -40,7 +43,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 +58,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
|
@@ -73,26 +76,44 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
73 |
results_log = []
|
74 |
answers_payload = []
|
75 |
print(f"Running agent on {len(questions_data)} questions...")
|
76 |
-
for
|
77 |
-
task_id =
|
78 |
-
question_text =
|
79 |
if not task_id or question_text is None:
|
80 |
-
print(f"Skipping item with missing task_id or question: {
|
81 |
continue
|
82 |
try:
|
83 |
-
submitted_answer = agent(
|
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 +183,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 +203,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 |
import gradio as gr
|
3 |
import requests
|
|
|
4 |
import pandas as pd
|
5 |
+
from azrock.agent import create_agent
|
6 |
|
7 |
# (Keep Constants as is)
|
8 |
# --- Constants ---
|
9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
10 |
|
11 |
+
|
12 |
# --- Basic Agent Definition ---
|
13 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
14 |
class BasicAgent:
|
15 |
def __init__(self):
|
16 |
print("BasicAgent initialized.")
|
17 |
+
|
18 |
def __call__(self, question: str) -> str:
|
19 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
20 |
fixed_answer = "This is a default answer."
|
21 |
print(f"Agent returning fixed answer: {fixed_answer}")
|
22 |
return fixed_answer
|
23 |
|
24 |
+
|
25 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
26 |
"""
|
27 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
28 |
and displays the results.
|
29 |
"""
|
30 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
31 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
32 |
|
33 |
if profile:
|
34 |
+
username = f"{profile.username}"
|
35 |
print(f"User logged in: {username}")
|
36 |
else:
|
37 |
print("User not logged in.")
|
|
|
43 |
|
44 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
45 |
try:
|
46 |
+
agent = create_agent()
|
47 |
except Exception as e:
|
48 |
print(f"Error instantiating agent: {e}")
|
49 |
return f"Error initializing agent: {e}", None
|
|
|
58 |
response.raise_for_status()
|
59 |
questions_data = response.json()
|
60 |
if not questions_data:
|
61 |
+
print("Fetched questions list is empty.")
|
62 |
+
return "Fetched questions list is empty or invalid format.", None
|
63 |
print(f"Fetched {len(questions_data)} questions.")
|
64 |
except requests.exceptions.RequestException as e:
|
65 |
print(f"Error fetching questions: {e}")
|
66 |
return f"Error fetching questions: {e}", None
|
67 |
except requests.exceptions.JSONDecodeError as e:
|
68 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
69 |
+
print(f"Response text: {response.text[:500]}")
|
70 |
+
return f"Error decoding server response for questions: {e}", None
|
71 |
except Exception as e:
|
72 |
print(f"An unexpected error occurred fetching questions: {e}")
|
73 |
return f"An unexpected error occurred fetching questions: {e}", None
|
|
|
76 |
results_log = []
|
77 |
answers_payload = []
|
78 |
print(f"Running agent on {len(questions_data)} questions...")
|
79 |
+
for question in questions_data:
|
80 |
+
task_id = question.get("task_id")
|
81 |
+
question_text = question.get("question")
|
82 |
if not task_id or question_text is None:
|
83 |
+
print(f"Skipping item with missing task_id or question: {question}")
|
84 |
continue
|
85 |
try:
|
86 |
+
submitted_answer = agent.run(str(question))
|
87 |
+
answers_payload.append(
|
88 |
+
{"task_id": task_id, "submitted_answer": submitted_answer}
|
89 |
+
)
|
90 |
+
results_log.append(
|
91 |
+
{
|
92 |
+
"Task ID": task_id,
|
93 |
+
"Question": question_text,
|
94 |
+
"Submitted Answer": submitted_answer,
|
95 |
+
}
|
96 |
+
)
|
97 |
except Exception as e:
|
98 |
+
print(f"Error running agent on task {task_id}: {e}")
|
99 |
+
results_log.append(
|
100 |
+
{
|
101 |
+
"Task ID": task_id,
|
102 |
+
"Question": question_text,
|
103 |
+
"Submitted Answer": f"AGENT ERROR: {e}",
|
104 |
+
}
|
105 |
+
)
|
106 |
|
107 |
if not answers_payload:
|
108 |
print("Agent did not produce any answers to submit.")
|
109 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
110 |
|
111 |
+
# 4. Prepare Submission
|
112 |
+
submission_data = {
|
113 |
+
"username": username.strip(),
|
114 |
+
"agent_code": agent_code,
|
115 |
+
"answers": answers_payload,
|
116 |
+
}
|
117 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
118 |
print(status_update)
|
119 |
|
|
|
183 |
|
184 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
185 |
|
186 |
+
status_output = gr.Textbox(
|
187 |
+
label="Run Status / Submission Result", lines=5, interactive=False
|
188 |
+
)
|
189 |
# Removed max_rows=10 from DataFrame constructor
|
190 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
191 |
|
192 |
+
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
|
|
|
|
|
|
193 |
|
194 |
if __name__ == "__main__":
|
195 |
+
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
196 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
197 |
space_host_startup = os.getenv("SPACE_HOST")
|
198 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
199 |
|
200 |
if space_host_startup:
|
201 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
203 |
else:
|
204 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
205 |
|
206 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
207 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
208 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
209 |
+
print(
|
210 |
+
f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main"
|
211 |
+
)
|
212 |
else:
|
213 |
+
print(
|
214 |
+
"ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined."
|
215 |
+
)
|
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)
|