Update app.py
Browse files
app.py
CHANGED
@@ -4,31 +4,87 @@ 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 |
-
# ----- 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 |
-
|
20 |
-
|
|
|
|
|
|
|
|
|
21 |
|
22 |
-
|
|
|
23 |
"""
|
24 |
-
Fetches all questions, runs the BasicAgent on them,
|
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.")
|
@@ -38,13 +94,14 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
38 |
questions_url = f"{api_url}/questions"
|
39 |
submit_url = f"{api_url}/submit"
|
40 |
|
41 |
-
# 1. Instantiate
|
42 |
try:
|
43 |
agent = BasicAgent()
|
44 |
except Exception as e:
|
45 |
print(f"Error instantiating agent: {e}")
|
46 |
return f"Error initializing agent: {e}", None
|
47 |
-
|
|
|
48 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
49 |
print(agent_code)
|
50 |
|
@@ -55,21 +112,21 @@ 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
|
71 |
|
72 |
-
# 3. Run your Agent
|
73 |
results_log = []
|
74 |
answers_payload = []
|
75 |
print(f"Running agent on {len(questions_data)} questions...")
|
@@ -84,19 +141,19 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
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 |
-
|
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 = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
96 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
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)
|
@@ -146,51 +203,40 @@ with gr.Blocks() as demo:
|
|
146 |
gr.Markdown(
|
147 |
"""
|
148 |
**Instructions:**
|
149 |
-
|
150 |
-
|
151 |
-
|
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
|
157 |
-
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own
|
|
|
158 |
"""
|
159 |
)
|
160 |
-
|
161 |
gr.LoginButton()
|
162 |
-
|
163 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
164 |
-
|
165 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
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}")
|
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?). Repo URL cannot be determined.")
|
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)
|
|
|
4 |
import inspect
|
5 |
import pandas as pd
|
6 |
|
7 |
+
# Import the Google Gen AI modules
|
8 |
+
from google import genai
|
9 |
+
from google.genai import types
|
10 |
+
|
11 |
# --- Constants ---
|
12 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
13 |
|
14 |
+
# --- Updated Agent Definition using Google Gen AI API ---
|
|
|
15 |
class BasicAgent:
|
16 |
def __init__(self):
|
17 |
+
print("BasicAgent (Google Gen AI) initialized.")
|
18 |
+
|
19 |
+
def generate_answer(self, question: str) -> str:
|
20 |
+
"""
|
21 |
+
Generates a precise answer using the Google Gen AI API.
|
22 |
+
The system instruction mandates that the output contain only the final answer.
|
23 |
+
"""
|
24 |
+
api_key = os.environ.get("GEMINI_API_KEY")
|
25 |
+
if not api_key:
|
26 |
+
raise ValueError("GEMINI_API_KEY environment variable not set. Please set it before running.")
|
27 |
+
client = genai.Client(api_key=api_key)
|
28 |
+
model = "gemini-2.0-flash"
|
29 |
+
|
30 |
+
# Define a strict system instruction. Ensure that the output is minimal:
|
31 |
+
system_instruction_text = (
|
32 |
+
"You are a general AI assistant. Answer the question with a precise, final answer only. "
|
33 |
+
"If asked for a number, reply with only that number (without commas or units unless explicitly required). "
|
34 |
+
"If asked for a string, reply with minimal text (do not include articles or abbreviations). "
|
35 |
+
"If the answer is a comma separated list, format accordingly with minimal punctuation. "
|
36 |
+
"Output the answer only, with no extra commentary or explanation."
|
37 |
+
)
|
38 |
+
|
39 |
+
# Build the conversation contents with the user query.
|
40 |
+
contents = [
|
41 |
+
types.Content(
|
42 |
+
role="user",
|
43 |
+
parts=[types.Part.from_text(text=question)]
|
44 |
+
)
|
45 |
+
]
|
46 |
+
|
47 |
+
# Include the built-in Google Search tool so the model can fetch live data if needed.
|
48 |
+
tools = [types.Tool(google_search=types.GoogleSearch())]
|
49 |
+
|
50 |
+
# Prepare the configuration with the system instruction.
|
51 |
+
generate_config = types.GenerateContentConfig(
|
52 |
+
tools=tools,
|
53 |
+
response_mime_type="text/plain",
|
54 |
+
system_instruction=[types.Part.from_text(text=system_instruction_text)]
|
55 |
+
)
|
56 |
+
|
57 |
+
answer = ""
|
58 |
+
# Stream the response in chunks and aggregate the final answer.
|
59 |
+
for chunk in client.models.generate_content_stream(
|
60 |
+
model=model,
|
61 |
+
contents=contents,
|
62 |
+
config=generate_config
|
63 |
+
):
|
64 |
+
answer += chunk.text
|
65 |
+
|
66 |
+
return answer.strip()
|
67 |
+
|
68 |
def __call__(self, question: str) -> str:
|
69 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
70 |
+
try:
|
71 |
+
answer = self.generate_answer(question)
|
72 |
+
print(f"Agent returning answer: {answer}")
|
73 |
+
except Exception as e:
|
74 |
+
print(f"Error generating answer: {e}")
|
75 |
+
answer = f"AGENT ERROR: {e}"
|
76 |
+
return answer
|
77 |
|
78 |
+
|
79 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
80 |
"""
|
81 |
+
Fetches all evaluation questions, runs the BasicAgent on them,
|
82 |
+
submits all answers to the scoring API, and displays the results.
|
83 |
"""
|
84 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
85 |
+
space_id = os.getenv("SPACE_ID") # Used to send a link to your code repository
|
|
|
86 |
if profile:
|
87 |
+
username = f"{profile.username}"
|
88 |
print(f"User logged in: {username}")
|
89 |
else:
|
90 |
print("User not logged in.")
|
|
|
94 |
questions_url = f"{api_url}/questions"
|
95 |
submit_url = f"{api_url}/submit"
|
96 |
|
97 |
+
# 1. Instantiate your agent
|
98 |
try:
|
99 |
agent = BasicAgent()
|
100 |
except Exception as e:
|
101 |
print(f"Error instantiating agent: {e}")
|
102 |
return f"Error initializing agent: {e}", None
|
103 |
+
|
104 |
+
# Link to your public code (your Hugging Face Space breadboard)
|
105 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
106 |
print(agent_code)
|
107 |
|
|
|
112 |
response.raise_for_status()
|
113 |
questions_data = response.json()
|
114 |
if not questions_data:
|
115 |
+
print("Fetched questions list is empty.")
|
116 |
+
return "Fetched questions list is empty or invalid format.", None
|
117 |
print(f"Fetched {len(questions_data)} questions.")
|
118 |
except requests.exceptions.RequestException as e:
|
119 |
print(f"Error fetching questions: {e}")
|
120 |
return f"Error fetching questions: {e}", None
|
121 |
except requests.exceptions.JSONDecodeError as e:
|
122 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
123 |
+
print(f"Response text: {response.text[:500]}")
|
124 |
+
return f"Error decoding server response for questions: {e}", None
|
125 |
except Exception as e:
|
126 |
print(f"An unexpected error occurred fetching questions: {e}")
|
127 |
return f"An unexpected error occurred fetching questions: {e}", None
|
128 |
|
129 |
+
# 3. Run your Agent on each question
|
130 |
results_log = []
|
131 |
answers_payload = []
|
132 |
print(f"Running agent on {len(questions_data)} questions...")
|
|
|
141 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
142 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
143 |
except Exception as e:
|
144 |
+
print(f"Error running agent on task {task_id}: {e}")
|
145 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
146 |
|
147 |
if not answers_payload:
|
148 |
print("Agent did not produce any answers to submit.")
|
149 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
150 |
|
151 |
+
# 4. Prepare Submission data
|
152 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
153 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
154 |
print(status_update)
|
155 |
|
156 |
+
# 5. Submit the answers for scoring
|
157 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
158 |
try:
|
159 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
|
|
203 |
gr.Markdown(
|
204 |
"""
|
205 |
**Instructions:**
|
206 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, and necessary packages.
|
207 |
+
2. Log in to your Hugging Face account using the button below. Your HF username is used for submission.
|
208 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see your score.
|
|
|
|
|
209 |
---
|
210 |
**Disclaimers:**
|
211 |
+
Once you click the submit button it may take some time as the agent processes all the questions.
|
212 |
+
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own robust solution.
|
213 |
+
For instance, you might cache the answers and submit in a separate action or process them asynchronously.
|
214 |
"""
|
215 |
)
|
|
|
216 |
gr.LoginButton()
|
|
|
217 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
|
|
218 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
|
|
219 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
|
|
220 |
run_button.click(
|
221 |
fn=run_and_submit_all,
|
222 |
outputs=[status_output, results_table]
|
223 |
)
|
224 |
|
225 |
if __name__ == "__main__":
|
226 |
+
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
|
|
227 |
space_host_startup = os.getenv("SPACE_HOST")
|
228 |
+
space_id_startup = os.getenv("SPACE_ID")
|
|
|
229 |
if space_host_startup:
|
230 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
231 |
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
232 |
else:
|
233 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
234 |
+
if space_id_startup:
|
|
|
235 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
236 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
237 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
238 |
else:
|
239 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
240 |
+
print("-" * (60 + len(" App Starting ")) + "\n")
|
|
|
|
|
241 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
242 |
demo.launch(debug=True, share=False)
|