Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,103 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
|
|
2 |
import gradio as gr
|
3 |
import requests
|
4 |
-
import inspect
|
5 |
import pandas as pd
|
6 |
|
7 |
-
#
|
|
|
|
|
8 |
# --- Constants ---
|
9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
10 |
|
11 |
-
# ---
|
12 |
-
|
13 |
-
#
|
14 |
-
|
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 |
-
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
23 |
"""
|
24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
and displays the results.
|
26 |
"""
|
27 |
-
|
28 |
-
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
29 |
-
|
30 |
-
if profile:
|
31 |
-
username= f"{profile.username}"
|
32 |
-
print(f"User logged in: {username}")
|
33 |
-
else:
|
34 |
print("User not logged in.")
|
35 |
-
return "Please
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
|
|
|
|
|
|
|
|
40 |
|
41 |
-
#
|
|
|
|
|
|
|
42 |
try:
|
43 |
agent_executor = create_agent_executor(provider="google") # or "groq"
|
44 |
except Exception as e:
|
45 |
print(f"Error instantiating agent: {e}")
|
46 |
-
return f"Error
|
47 |
-
# In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
|
48 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
49 |
-
print(agent_code)
|
50 |
|
51 |
-
# 2. Fetch Questions
|
52 |
print(f"Fetching questions from: {questions_url}")
|
53 |
try:
|
54 |
-
response = requests.get(questions_url, timeout=
|
55 |
response.raise_for_status()
|
56 |
questions_data = response.json()
|
57 |
-
if not questions_data:
|
58 |
-
print("Fetched questions list is empty.")
|
59 |
-
return "Fetched questions list is empty or invalid format.", None
|
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 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
66 |
-
print(f"Response text: {response.text[:500]}")
|
67 |
-
return f"Error decoding server response for questions: {e}", None
|
68 |
except Exception as e:
|
69 |
-
|
70 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
71 |
|
72 |
-
# 3. Run your Agent
|
73 |
results_log = []
|
74 |
answers_payload = []
|
75 |
print(f"Running agent on {len(questions_data)} questions...")
|
76 |
-
for item in questions_data:
|
77 |
task_id = item.get("task_id")
|
78 |
question_text = item.get("question")
|
|
|
79 |
if not task_id or question_text is None:
|
80 |
-
print(f"Skipping item with missing
|
81 |
continue
|
|
|
|
|
|
|
|
|
82 |
try:
|
83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
print(f"
|
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
|
95 |
-
submission_data = {"username": username
|
96 |
-
|
97 |
-
print(status_update)
|
98 |
-
|
99 |
-
# 5. Submit
|
100 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
101 |
try:
|
102 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
103 |
response.raise_for_status()
|
@@ -106,91 +129,35 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
106 |
f"Submission Successful!\n"
|
107 |
f"User: {result_data.get('username')}\n"
|
108 |
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
109 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)
|
110 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
111 |
)
|
112 |
print("Submission successful.")
|
113 |
-
|
114 |
-
return final_status, results_df
|
115 |
-
except requests.exceptions.HTTPError as e:
|
116 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
117 |
-
try:
|
118 |
-
error_json = e.response.json()
|
119 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
120 |
-
except requests.exceptions.JSONDecodeError:
|
121 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
122 |
-
status_message = f"Submission Failed: {error_detail}"
|
123 |
-
print(status_message)
|
124 |
-
results_df = pd.DataFrame(results_log)
|
125 |
-
return status_message, results_df
|
126 |
-
except requests.exceptions.Timeout:
|
127 |
-
status_message = "Submission Failed: The request timed out."
|
128 |
-
print(status_message)
|
129 |
-
results_df = pd.DataFrame(results_log)
|
130 |
-
return status_message, results_df
|
131 |
-
except requests.exceptions.RequestException as e:
|
132 |
-
status_message = f"Submission Failed: Network error - {e}"
|
133 |
-
print(status_message)
|
134 |
-
results_df = pd.DataFrame(results_log)
|
135 |
-
return status_message, results_df
|
136 |
except Exception as e:
|
137 |
-
status_message = f"
|
138 |
print(status_message)
|
139 |
-
|
140 |
-
return status_message, results_df
|
141 |
|
142 |
|
143 |
-
# --- Build Gradio Interface using Blocks ---
|
144 |
with gr.Blocks() as demo:
|
145 |
-
gr.Markdown("#
|
146 |
-
gr.Markdown(
|
147 |
-
"""
|
148 |
-
**Instructions:**
|
149 |
-
|
150 |
-
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
151 |
-
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
152 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
153 |
-
|
154 |
-
---
|
155 |
-
**Disclaimers:**
|
156 |
-
Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
|
157 |
-
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
|
158 |
-
"""
|
159 |
-
)
|
160 |
-
|
161 |
gr.LoginButton()
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
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 |
-
#
|
177 |
-
|
178 |
-
space_id_startup
|
179 |
-
|
180 |
-
if space_host_startup:
|
181 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
182 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
183 |
-
else:
|
184 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
185 |
-
|
186 |
-
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
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
|
192 |
-
|
193 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
194 |
-
|
195 |
-
|
196 |
-
demo.launch(debug=True, share=False)
|
|
|
1 |
+
"""
|
2 |
+
app.py
|
3 |
+
|
4 |
+
This script provides the Gradio web interface to run the evaluation for the
|
5 |
+
Hugging Face Agents course. It fetches questions from a server, runs the
|
6 |
+
agent defined in agent.py on them, and submits the answers for scoring.
|
7 |
+
"""
|
8 |
+
|
9 |
import os
|
10 |
+
import re # <-- 1. ADDED IMPORT for Regular Expressions
|
11 |
import gradio as gr
|
12 |
import requests
|
|
|
13 |
import pandas as pd
|
14 |
|
15 |
+
# --- Import your agent's factory function ---
|
16 |
+
from agent import create_agent_executor # <-- 2. ADDED IMPORT for your agent
|
17 |
+
|
18 |
# --- Constants ---
|
19 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
20 |
|
21 |
+
# --- DELETED BasicAgent class as it's no longer needed ---
|
22 |
+
|
23 |
+
# --- 3. ADDED HELPER FUNCTION TO PARSE THE AGENT'S OUTPUT ---
|
24 |
+
def parse_final_answer(agent_response: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
"""
|
26 |
+
Extracts the final answer from the agent's full response string.
|
27 |
+
The agent is prompted to return 'FINAL ANSWER: [answer]'.
|
28 |
+
This function isolates and returns '[answer]'.
|
29 |
+
"""
|
30 |
+
# Use a regular expression to find the text after "FINAL ANSWER:"
|
31 |
+
match = re.search(r"FINAL ANSWER:\s*(.*)", agent_response, re.IGNORECASE | re.DOTALL)
|
32 |
+
if match:
|
33 |
+
# If a match is found, return the captured group, stripped of whitespace
|
34 |
+
return match.group(1).strip()
|
35 |
+
|
36 |
+
# As a fallback, if the specific format is not found, return the last non-empty line
|
37 |
+
lines = [line for line in agent_response.split('\n') if line.strip()]
|
38 |
+
if lines:
|
39 |
+
return lines[-1].strip()
|
40 |
+
|
41 |
+
# If all else fails, return a default message
|
42 |
+
return "Could not parse a final answer."
|
43 |
+
|
44 |
+
|
45 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
46 |
+
"""
|
47 |
+
Fetches all questions, runs the agent on them, submits all answers,
|
48 |
and displays the results.
|
49 |
"""
|
50 |
+
if not profile:
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
print("User not logged in.")
|
52 |
+
return "Please log in to Hugging Face with the button above to submit.", None
|
53 |
+
|
54 |
+
username = profile.username
|
55 |
+
print(f"User logged in: {username}")
|
56 |
+
|
57 |
+
space_id = os.getenv("SPACE_ID")
|
58 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
59 |
+
questions_url = f"{DEFAULT_API_URL}/questions"
|
60 |
+
submit_url = f"{DEFAULT_API_URL}/submit"
|
61 |
|
62 |
+
# --- 4. MODIFIED AGENT INSTANTIATION AND EXECUTION ---
|
63 |
+
|
64 |
+
# 1. Instantiate Agent (using your factory function from agent.py)
|
65 |
+
print("Initializing your custom agent...")
|
66 |
try:
|
67 |
agent_executor = create_agent_executor(provider="google") # or "groq"
|
68 |
except Exception as e:
|
69 |
print(f"Error instantiating agent: {e}")
|
70 |
+
return f"Fatal Error: Could not initialize agent. Check logs. Details: {e}", None
|
|
|
|
|
|
|
71 |
|
72 |
+
# 2. Fetch Questions (this part is correct)
|
73 |
print(f"Fetching questions from: {questions_url}")
|
74 |
try:
|
75 |
+
response = requests.get(questions_url, timeout=20)
|
76 |
response.raise_for_status()
|
77 |
questions_data = response.json()
|
|
|
|
|
|
|
78 |
print(f"Fetched {len(questions_data)} questions.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
79 |
except Exception as e:
|
80 |
+
return f"Error fetching questions: {e}", None
|
|
|
81 |
|
82 |
+
# 3. Run your Agent (THIS IS THE MOST IMPORTANTLY CORRECTED SECTION)
|
83 |
results_log = []
|
84 |
answers_payload = []
|
85 |
print(f"Running agent on {len(questions_data)} questions...")
|
86 |
+
for i, item in enumerate(questions_data):
|
87 |
task_id = item.get("task_id")
|
88 |
question_text = item.get("question")
|
89 |
+
|
90 |
if not task_id or question_text is None:
|
91 |
+
print(f"Skipping item with missing data: {item}")
|
92 |
continue
|
93 |
+
|
94 |
+
print(f"\n--- Running Task {i+1}/{len(questions_data)} (ID: {task_id}) ---")
|
95 |
+
print(f"Question: {question_text}")
|
96 |
+
|
97 |
try:
|
98 |
+
# CORRECT INVOCATION: Use the agent_executor with the .invoke() method
|
99 |
+
# The input must be a dictionary with a "messages" key
|
100 |
+
result = agent_executor.invoke({"messages": [("user", question_text)]})
|
101 |
+
|
102 |
+
# The agent's final response is in the 'messages' list of the output
|
103 |
+
raw_answer = result['messages'][-1].content
|
104 |
+
|
105 |
+
# Use our helper function to extract the clean answer
|
106 |
+
submitted_answer = parse_final_answer(raw_answer)
|
107 |
+
|
108 |
+
print(f"Raw LLM Response: '{raw_answer}'")
|
109 |
+
print(f"PARSED FINAL ANSWER: '{submitted_answer}'")
|
110 |
+
|
111 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
112 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
113 |
except Exception as e:
|
114 |
+
print(f"!! AGENT ERROR on task {task_id}: {e}")
|
115 |
+
# It's important to log errors so you can see them in the UI
|
116 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT RUNTIME ERROR: {e}"})
|
117 |
|
118 |
if not answers_payload:
|
|
|
119 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
120 |
|
121 |
+
# 4. Prepare and 5. Submit (these parts are correct)
|
122 |
+
submission_data = {"username": username, "agent_code": agent_code, "answers": answers_payload}
|
123 |
+
print(f"\nSubmitting {len(answers_payload)} answers for user '{username}'...")
|
|
|
|
|
|
|
|
|
124 |
try:
|
125 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
126 |
response.raise_for_status()
|
|
|
129 |
f"Submission Successful!\n"
|
130 |
f"User: {result_data.get('username')}\n"
|
131 |
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
132 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)"
|
|
|
133 |
)
|
134 |
print("Submission successful.")
|
135 |
+
return final_status, pd.DataFrame(results_log)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
136 |
except Exception as e:
|
137 |
+
status_message = f"Submission Failed: {e}"
|
138 |
print(status_message)
|
139 |
+
return status_message, pd.DataFrame(results_log)
|
|
|
140 |
|
141 |
|
142 |
+
# --- Build Gradio Interface using Blocks (This part is correct) ---
|
143 |
with gr.Blocks() as demo:
|
144 |
+
gr.Markdown("# Agent Evaluation Runner")
|
145 |
+
gr.Markdown("Run your custom agent against the evaluation questions and submit for a score.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
146 |
gr.LoginButton()
|
147 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
|
148 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=4, interactive=False)
|
149 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True, max_rows=10)
|
150 |
+
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
151 |
|
152 |
if __name__ == "__main__":
|
153 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
154 |
+
# The startup info logs are helpful, so we keep them.
|
155 |
+
space_id_startup = os.getenv("SPACE_ID")
|
156 |
+
if space_id_startup:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
157 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
158 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
|
|
159 |
else:
|
160 |
+
print("ℹ️ SPACE_ID environment variable not found (likely running locally).")
|
|
|
161 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
162 |
+
print("Launching Gradio Interface...")
|
163 |
+
demo.launch()
|
|