Files changed (3) hide show
  1. app.py +380 -188
  2. prompts.yaml +312 -0
  3. requirements.txt +13 -0
app.py CHANGED
@@ -1,210 +1,402 @@
 
 
 
1
  import gradio as gr
2
- from datasets import load_dataset, Dataset
3
- from datetime import datetime
4
- from datetime import date
5
  import requests
6
- import tempfile
7
- import asyncio
8
- from huggingface_hub import upload_file
9
- from functools import partial
10
- import io
11
- import os
12
- from PIL import Image, ImageDraw, ImageFont
13
- from huggingface_hub import login
14
-
15
- login(token=os.environ["HUGGINGFACE_TOKEN"])
16
-
17
- # Constants
18
- SCORES_DATASET = "agents-course/unit4-students-scores"
19
- CERTIFICATES_DATASET = "agents-course/course-certificates-of-excellence"
20
- THRESHOLD_SCORE = 30
21
- CERTIFYING_ORG_LINKEDIN_ID = os.getenv("CERTIFYING_ORG_LINKEDIN_ID", "000000")
22
- COURSE_TITLE = os.getenv("COURSE_TITLE", "Hugging Face Agents Course")
23
-
24
- # Function to check user score
25
- def check_user_score(username):
26
- score_data = load_dataset(SCORES_DATASET, split="train", download_mode="force_redownload")
27
- matches = [row for row in score_data if row["username"] == username]
28
- return matches[0] if matches else None
29
-
30
- # Function to check if certificate entry exists
31
- def has_certificate_entry(username):
32
- cert_data = load_dataset(CERTIFICATES_DATASET, split="train", download_mode="force_redownload")
33
- print(username)
34
- return any(row["username"] == username for row in cert_data)
35
-
36
- # Function to add certificate entry
37
- def add_certificate_entry(username, name, score):
38
- # Load current dataset
39
- ds = load_dataset(CERTIFICATES_DATASET, split="train", download_mode="force_redownload")
40
-
41
- # Remove any existing entry with the same username
42
- filtered_rows = [row for row in ds if row["username"] != username]
43
-
44
- # Append the updated/new entry
45
- new_entry = {
46
- "username": username,
47
- "score": score,
48
- "timestamp": datetime.now().isoformat()
49
  }
50
- filtered_rows.append(new_entry)
51
-
52
- # Rebuild dataset and push
53
- updated_ds = Dataset.from_list(filtered_rows)
54
- updated_ds.push_to_hub(CERTIFICATES_DATASET)
55
-
56
- # Function to generate certificate PDF
57
- def generate_certificate(name, score):
58
- """Generate certificate image and PDF."""
59
- certificate_path = os.path.join(
60
- os.path.dirname(__file__), "templates", "certificate.png"
61
- )
62
- im = Image.open(certificate_path)
63
- d = ImageDraw.Draw(im)
64
-
65
- name_font = ImageFont.truetype("Quattrocento-Regular.ttf", 100)
66
- date_font = ImageFont.truetype("Quattrocento-Regular.ttf", 48)
67
-
68
- name = name.title()
69
- d.text((1000, 740), name, fill="black", anchor="mm", font=name_font)
70
-
71
- d.text((1480, 1170), str(date.today()), fill="black", anchor="mm", font=date_font)
72
-
73
- pdf = im.convert("RGB")
74
- pdf.save("certificate.pdf")
75
-
76
- return im, "certificate.pdf"
77
-
78
- async def upload_certificate_to_hub(username: str, certificate_img) -> str:
79
- """Upload certificate to the dataset hub and return the URL asynchronously."""
80
- # Save image to temporary file
81
- with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
82
- certificate_img.save(tmp.name)
83
-
84
- try:
85
- # Run upload in a thread pool since upload_file is blocking
86
- loop = asyncio.get_event_loop()
87
- upload_func = partial(
88
- upload_file,
89
- path_or_fileobj=tmp.name,
90
- path_in_repo=f"certificates/{username}/{date.today()}.png",
91
- repo_id="agents-course/final-certificates",
92
- repo_type="dataset",
93
- token=os.getenv("HF_TOKEN"),
94
- )
95
- await loop.run_in_executor(None, upload_func)
96
-
97
- # Construct the URL to the image
98
- cert_url = (
99
- f"https://huggingface.co/datasets/agents-course/final-certificates/"
100
- f"resolve/main/certificates/{username}/{date.today()}.png"
101
- )
102
-
103
- # Clean up temp file
104
- os.unlink(tmp.name)
105
- return cert_url
106
-
107
- except Exception as e:
108
- print(f"Error uploading certificate: {e}")
109
- os.unlink(tmp.name)
110
- return None
111
-
112
- def create_linkedin_button(username: str, cert_url: str | None) -> str:
113
- """Create LinkedIn 'Add to Profile' button HTML."""
114
- current_year = date.today().year
115
- current_month = date.today().month
116
-
117
- # Use the dataset certificate URL if available, otherwise fallback to default
118
- certificate_url = cert_url or "https://huggingface.co/agents-course-finishers"
119
-
120
- linkedin_params = {
121
- "startTask": "CERTIFICATION_NAME",
122
- "name": COURSE_TITLE,
123
- "organizationName": "Hugging Face",
124
- "organizationId": CERTIFYING_ORG_LINKEDIN_ID,
125
- "issueYear": str(current_year),
126
- "issueMonth": str(current_month),
127
- "certUrl": certificate_url,
128
- "certId": username, # Using username as cert ID
129
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
 
131
- # Build the LinkedIn button URL
132
- base_url = "https://www.linkedin.com/profile/add?"
133
- params = "&".join(
134
- f"{k}={requests.utils.quote(v)}" for k, v in linkedin_params.items()
135
- )
136
- button_url = base_url + params
137
-
138
- message = f"""
139
- <a href="{button_url}" target="_blank" style="display: block; margin: 0 auto; width: fit-content;">
140
- <img src="https://download.linkedin.com/desktop/add2profile/buttons/en_US.png"
141
- alt="LinkedIn Add to Profile button"
142
- style="height: 40px; width: auto; display: block;" />
143
- </a>
144
  """
145
- return message
146
 
147
- # Main function to handle certificate generation
148
- async def handle_certificate(name, profile: gr.OAuthProfile):
149
- if profile is None:
150
- return "You must be logged in with your Hugging Face account.", None
 
 
 
 
 
 
 
151
 
152
- username = profile.username
153
- user_score = check_user_score(username)
 
 
 
 
 
 
 
 
 
 
 
154
 
155
- if not user_score:
156
- return "You need to complete Unit 4 first.", None, None, None
 
 
 
 
 
 
 
 
 
157
 
158
- score = user_score["score"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
 
160
- if score < THRESHOLD_SCORE:
161
- return f"Your score is {score}. You need at least {THRESHOLD_SCORE} to pass.", None, None
162
 
163
- certificate_image, certificate_pdf = generate_certificate(name, score)
164
- add_certificate_entry(username, name, score)
 
 
 
 
 
 
 
 
 
 
 
 
165
 
166
- # Start certificate upload asynchronously
167
- gr.Info("Uploading your certificate...")
168
- cert_url = await upload_certificate_to_hub(username, certificate_image)
 
169
 
170
- if cert_url is None:
171
- gr.Warning("Certificate upload failed, but you still passed!")
172
- cert_url = "https://huggingface.co/agents-course"
173
 
174
- linkedin_button = create_linkedin_button(username, cert_url)
175
- return "Congratulations! Here's your certificate:", certificate_image, gr.update(value=linkedin_button, visible=True), certificate_pdf
 
 
 
 
 
 
 
 
 
 
 
 
 
176
 
177
 
178
- # Gradio interface
179
- with gr.Blocks() as demo:
180
- gr.Markdown("# 🎓 Agents Course - Get Your Final Certificate")
181
- gr.Markdown("Welcome! Follow the steps below to receive your official certificate:")
182
- gr.Markdown("⚠️ **Note**: Due to high demand, you might experience occasional bugs. If something doesn't work, please try again after a moment!")
183
 
184
- with gr.Group():
185
- gr.Markdown("## ✅ How it works")
186
- gr.Markdown("""
187
- 1. **Sign in** with your Hugging Face account using the button below.
188
- 2. **Enter your full name** (this will appear on the certificate).
189
- 3. Click **'Get My Certificate'** to check your score and download your certificate.
190
- """)
191
- gr.Markdown("---")
192
- gr.Markdown("📝 **Note**: You must have completed [Unit 4](https://huggingface.co/learn/agents-course/unit4/introduction) and your Agent must have scored **above 30** to get your certificate.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
 
194
  gr.LoginButton()
195
- with gr.Row():
196
- name_input = gr.Text(label="Enter your name (this will appear on the certificate)")
197
- generate_btn = gr.Button("Get my certificate")
198
- output_text = gr.Textbox(label="Result")
199
- linkedin_btn = gr.HTML(visible=False)
200
-
201
- cert_image = gr.Image(label="Your Certificate")
202
- cert_file = gr.File(label="Download Certificate (PDF)", file_types=[".pdf"])
203
-
204
- generate_btn.click(
205
- fn=handle_certificate,
206
- inputs=[name_input],
207
- outputs=[output_text, cert_image, linkedin_btn, cert_file]
208
  )
209
 
210
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ load_dotenv()
4
  import gradio as gr
 
 
 
5
  import requests
6
+ import inspect
7
+ import pandas as pd
8
+ #model requirement
9
+ from smolagents import DuckDuckGoSearchTool, load_tool, tool, CodeAgent,InferenceClientModel
10
+ from typing import TypedDict, List, Dict, Any, Optional,Callable
11
+ from langgraph.graph import StateGraph, END
12
+ from langchain_openai import ChatOpenAI
13
+ from langchain_core.messages import HumanMessage
14
+ from langchain_community.tools.tavily_search import TavilySearchResults
15
+ from langchain_community.document_loaders import WikipediaLoader
16
+ from langchain_community.document_loaders import ArxivLoader
17
+ from youtube_transcript_api import YouTubeTranscriptApi
18
+
19
+ # (Keep Constants as is)
20
+ # --- Constants ---
21
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
22
+
23
+ def openrouter_inference(prompt, model="deepseek/deepseek-r1:free"):
24
+ api_key = os.environ["OPENROUTER_API_KEY"]
25
+ url = "https://openrouter.ai/api/v1/chat/completions"
26
+ headers = {
27
+ "Authorization": f"Bearer {api_key}",
28
+ "Content-Type": "application/json"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  }
30
+ payload = {
31
+ "model": model,
32
+ "messages": [
33
+ {"role": "user", "content": prompt}
34
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  }
36
+ response = requests.post(url, headers=headers, json=payload)
37
+ response.raise_for_status()
38
+ data = response.json()
39
+ # Extract the answer from the response
40
+ return data["choices"][0]["message"]["content"]
41
+
42
+ @tool
43
+ def add(a:int,b:int)->int:
44
+ """
45
+ Adds two integers.
46
+ Args:
47
+ a (int): The first integer.
48
+ b (int): The second integer.
49
+ Returns:
50
+ int: The sum of the two integers.
51
+ """
52
+ return a + b
53
 
54
+ @tool
55
+ def subtract(a:int,b:int)->int:
56
+ """
57
+ Subtracts two integers.
58
+ Args:
59
+ a (int): The first integer.
60
+ b (int): The second integer.
61
+ Returns:
62
+ int: The difference of the two integers.
 
 
 
 
63
  """
64
+ return a - b
65
 
66
+ @tool
67
+ def multiply(a:int,b:int)->int:
68
+ """
69
+ Multiplies two integers.
70
+ Args:
71
+ a (int): The first integer.
72
+ b (int): The second integer.
73
+ Returns:
74
+ int: The product of the two integers.
75
+ """
76
+ return a * b
77
 
78
+ @tool
79
+ def divide(a:int,b:int)->float:
80
+ """
81
+ Divides two integers.
82
+ Args:
83
+ a (int): The numerator.
84
+ b (int): The denominator.
85
+ Returns:
86
+ float: The quotient of the two integers.
87
+ """
88
+ if b == 0:
89
+ raise ValueError("Division by zero is not allowed.")
90
+ return a / b
91
 
92
+ @tool
93
+ def modulus(a: int, b: int) -> int:
94
+ """Get the modulus of two numbers.
95
+
96
+ Args:
97
+ a: first int
98
+ b: second int
99
+ """
100
+ return a % b
101
+
102
+ search_tool = DuckDuckGoSearchTool()
103
 
104
+ @tool
105
+ def web_search(query: str) -> str:
106
+ """Search Tavily for a query and return maximum 3 results.
107
+
108
+ Args:
109
+ query: The search query."""
110
+ search_docs = TavilySearchResults(max_results=3).invoke(query=query)
111
+ formatted_search_docs = "\n\n---\n\n".join(
112
+ [
113
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
114
+ for doc in search_docs
115
+ ])
116
+ return {"web_results": formatted_search_docs}
117
+
118
+ @tool
119
+ def arvix_search(query: str) -> str:
120
+ """Search Arxiv for a query and return maximum 3 result.
121
+
122
+ Args:
123
+ query: The search query."""
124
+ search_docs = ArxivLoader(query=query, load_max_docs=3).load()
125
+ formatted_search_docs = "\n\n---\n\n".join(
126
+ [
127
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
128
+ for doc in search_docs
129
+ ])
130
+ return {"arvix_results": formatted_search_docs}
131
+
132
+ @tool
133
+ def wikipedia_tool(query: str) -> str:
134
+ """
135
+ Searches Wikipedia for the given query and returns a summary.
136
 
137
+ Args:
138
+ query (str): The search term or question to look up on Wikipedia.
139
 
140
+ Returns:
141
+ str: A summary or error message.
142
+ """
143
+ try:
144
+ search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
145
+ formatted_search_docs = "\n\n---\n\n".join(
146
+ [
147
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
148
+ for doc in search_docs
149
+ ]
150
+ )
151
+ return formatted_search_docs
152
+ except Exception as e:
153
+ return f"Wikipedia search error: {e}"
154
 
155
+ @tool
156
+ def youtube_transcript_tool(video_id: str,query:str) -> str:
157
+ """
158
+ Fetches the transcript of a YouTube video.
159
 
160
+ Args:
161
+ video_id (str): The YouTube video ID.
162
+ query (str): The question to be answered based on the transcript.
163
 
164
+ Returns:
165
+ str: The transcript text or an error message.
166
+ """
167
+ try:
168
+ transcript = YouTubeTranscriptApi.get_transcript(video_id)
169
+ question = f"Answer the question based on the transcript: {query}"
170
+ prompt = (
171
+ f"Given the following YouTube transcript, answer the question as directly as possible:\n"
172
+ f"Question: {question}\n"
173
+ f"Transcript: {transcript}\n"
174
+ f"Answer:"
175
+ )
176
+ answer = openrouter_inference(prompt)
177
+ except Exception as e:
178
+ return f"Transcript error: {e}"
179
 
180
 
 
 
 
 
 
181
 
182
+
183
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
184
+
185
+
186
+ # --- Basic Agent Definition ---
187
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
188
+ class BasicAgent:
189
+ def __init__(self):
190
+ print("BasicAgent initialized.")
191
+ token=os.environ["OPENROUTER_API_KEY"]
192
+ self.system_prompt = """
193
+ You are a helpful assistant. Answer each question as directly and briefly as possible.
194
+ Return only the answer, with no extra text, no punctuation, and no justification.
195
+ If the answer is a list, return it as a comma-separated list with no brackets or bullets.
196
+ If the answer is a number, write it in digits with no units.
197
+ If the answer is a string, use lowercase and no articles or abbreviations.
198
+ """
199
+
200
+ model = InferenceClientModel(
201
+ model_id="deepseek/deepseek-r1:free", # Correct OpenRouter model ID
202
+ token=os.environ["OPENROUTER_API_KEY"], # Your OpenRouter API key
203
+ provider="openrouter" # Explicitly set to openrouter
204
+ )
205
+ self.agent= CodeAgent(
206
+ tools = [add, subtract, multiply, divide,modulus,arvix_search, web_search, image_generation_tool,youtube_transcript_tool, wikipedia_tool],
207
+ model=model,
208
+ )
209
+ def __call__(self, question: str, context: str = "") -> str:
210
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
211
+ # Inject system prompt + question
212
+ question_with_prompt = f"{self.system_prompt}\n\nContext: {context}\n\nQuestion: {question.strip()}"
213
+ try:
214
+ answer = openrouter_inference(question_with_prompt)
215
+ except Exception as e:
216
+ print(f"Error calling OpenRouter: {e}")
217
+ answer = f"Sorry, I couldn't get an answer from the model {e}."
218
+ print(f"Agent returning answer: {answer.strip()}")
219
+ return answer.strip()
220
+ # # Fix: handle dict or string
221
+ # if isinstance(answer, dict) and "content" in answer:
222
+ # result = answer["content"]
223
+ # else:
224
+ # result = str(answer)
225
+ # print(f"Agent returning answer: {result.strip()}")
226
+ # return result.strip()
227
+
228
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
229
+ """
230
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
231
+ and displays the results.
232
+ """
233
+ # --- Determine HF Space Runtime URL and Repo URL ---
234
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
235
+
236
+ if profile:
237
+ username= f"{profile.username}"
238
+ print(f"User logged in: {username}")
239
+ else:
240
+ print("User not logged in.")
241
+ return "Please Login to Hugging Face with the button.", None
242
+
243
+ api_url = DEFAULT_API_URL
244
+ questions_url = f"{api_url}/questions"
245
+ submit_url = f"{api_url}/submit"
246
+
247
+ # 1. Instantiate Agent ( modify this part to create your agent)
248
+ try:
249
+ agent = BasicAgent()
250
+ except Exception as e:
251
+ print(f"Error instantiating agent: {e}")
252
+ return f"Error initializing agent: {e}", None
253
+ # 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)
254
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
255
+ print(agent_code)
256
+
257
+ # 2. Fetch Questions
258
+ print(f"Fetching questions from: {questions_url}")
259
+ try:
260
+ response = requests.get(questions_url, timeout=15)
261
+ response.raise_for_status()
262
+ questions_data = response.json()
263
+ if not questions_data:
264
+ print("Fetched questions list is empty.")
265
+ return "Fetched questions list is empty or invalid format.", None
266
+ print(f"Fetched {len(questions_data)} questions.")
267
+ except requests.exceptions.RequestException as e:
268
+ print(f"Error fetching questions: {e}")
269
+ return f"Error fetching questions: {e}", None
270
+ except requests.exceptions.JSONDecodeError as e:
271
+ print(f"Error decoding JSON response from questions endpoint: {e}")
272
+ print(f"Response text: {response.text[:500]}")
273
+ return f"Error decoding server response for questions: {e}", None
274
+ except Exception as e:
275
+ print(f"An unexpected error occurred fetching questions: {e}")
276
+ return f"An unexpected error occurred fetching questions: {e}", None
277
+
278
+ # 3. Run your Agent
279
+ results_log = []
280
+ answers_payload = []
281
+ print(f"Running agent on {len(questions_data)} questions...")
282
+ for item in questions_data:
283
+ task_id = item.get("task_id")
284
+ question_text = item.get("question")
285
+ if not task_id or question_text is None:
286
+ print(f"Skipping item with missing task_id or question: {item}")
287
+ continue
288
+ try:
289
+ submitted_answer = agent(question_text)
290
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
291
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
292
+ except Exception as e:
293
+ print(f"Error running agent on task {task_id}: {e}")
294
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
295
+
296
+ if not answers_payload:
297
+ print("Agent did not produce any answers to submit.")
298
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
299
+
300
+ # 4. Prepare Submission
301
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
302
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
303
+ print(status_update)
304
+
305
+ # 5. Submit
306
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
307
+ try:
308
+ response = requests.post(submit_url, json=submission_data, timeout=60)
309
+ response.raise_for_status()
310
+ result_data = response.json()
311
+ final_status = (
312
+ f"Submission Successful!\n"
313
+ f"User: {result_data.get('username')}\n"
314
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
315
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
316
+ f"Message: {result_data.get('message', 'No message received.')}"
317
+ )
318
+ print("Submission successful.")
319
+ results_df = pd.DataFrame(results_log)
320
+ return final_status, results_df
321
+ except requests.exceptions.HTTPError as e:
322
+ error_detail = f"Server responded with status {e.response.status_code}."
323
+ try:
324
+ error_json = e.response.json()
325
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
326
+ except requests.exceptions.JSONDecodeError:
327
+ error_detail += f" Response: {e.response.text[:500]}"
328
+ status_message = f"Submission Failed: {error_detail}"
329
+ print(status_message)
330
+ results_df = pd.DataFrame(results_log)
331
+ return status_message, results_df
332
+ except requests.exceptions.Timeout:
333
+ status_message = "Submission Failed: The request timed out."
334
+ print(status_message)
335
+ results_df = pd.DataFrame(results_log)
336
+ return status_message, results_df
337
+ except requests.exceptions.RequestException as e:
338
+ status_message = f"Submission Failed: Network error - {e}"
339
+ print(status_message)
340
+ results_df = pd.DataFrame(results_log)
341
+ return status_message, results_df
342
+ except Exception as e:
343
+ status_message = f"An unexpected error occurred during submission: {e}"
344
+ print(status_message)
345
+ results_df = pd.DataFrame(results_log)
346
+ return status_message, results_df
347
+
348
+
349
+ # --- Build Gradio Interface using Blocks ---
350
+ with gr.Blocks() as demo:
351
+ gr.Markdown("# Basic Agent Evaluation Runner")
352
+ gr.Markdown(
353
+ """
354
+ **Instructions:**
355
+
356
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
357
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
358
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
359
+
360
+ ---
361
+ **Disclaimers:**
362
+ 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).
363
+ 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.
364
+ """
365
+ )
366
 
367
  gr.LoginButton()
368
+
369
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
370
+
371
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
372
+ # Removed max_rows=10 from DataFrame constructor
373
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
374
+
375
+ run_button.click(
376
+ fn=run_and_submit_all,
377
+ outputs=[status_output, results_table]
 
 
 
378
  )
379
 
380
+ if __name__ == "__main__":
381
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
382
+ # Check for SPACE_HOST and SPACE_ID at startup for information
383
+ space_host_startup = os.getenv("SPACE_HOST")
384
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
385
+
386
+ if space_host_startup:
387
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
388
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
389
+ else:
390
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
391
+
392
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
393
+ print(f"✅ SPACE_ID found: {space_id_startup}")
394
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
395
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
396
+ else:
397
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
398
+
399
+ print("-"*(60 + len(" App Starting ")) + "\n")
400
+
401
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
402
+ demo.launch(debug=True, share=False)
prompts.yaml ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "system_prompt": |-
2
+ You are an expert assistant who can solve any task using code blobs. You will be given a task to solve as best you can.
3
+ To do so, you have been given access to a list of tools: these tools are basically Python functions which you can call with code.
4
+ To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.
5
+ At each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task and the tools that you want to use.
6
+ Then in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '<end_code>' sequence.
7
+ During each intermediate step, you can use 'print()' to save whatever important information you will then need.
8
+ These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
9
+ In the end you have to return a final answer using the `final_answer` tool.
10
+
11
+ Here are a few examples using notional tools:
12
+ ---
13
+ Task: "Generate an image of the oldest person in this document."
14
+
15
+ Thought: I will proceed step by step and use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.
16
+ Code:
17
+ ```py
18
+ answer = document_qa(document=document, question="Who is the oldest person mentioned?")
19
+ print(answer)
20
+ ```<end_code>
21
+ Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland."
22
+
23
+ Thought: I will now generate an image showcasing the oldest person.
24
+ Code:
25
+ ```py
26
+ image = image_generator("A portrait of John Doe, a 55-year-old man living in Canada.")
27
+ final_answer(image)
28
+ ```<end_code>
29
+
30
+ ---
31
+ Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
32
+
33
+ Thought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool
34
+ Code:
35
+ ```py
36
+ result = 5 + 3 + 1294.678
37
+ final_answer(result)
38
+ ```<end_code>
39
+
40
+ ---
41
+ Task:
42
+ "Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.
43
+ You have been provided with these additional arguments, that you can access using the keys as variables in your python code:
44
+ {'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}"
45
+
46
+ Thought: I will use the following tools: `translator` to translate the question into English and then `image_qa` to answer the question on the input image.
47
+ Code:
48
+ ```py
49
+ translated_question = translator(question=question, src_lang="French", tgt_lang="English")
50
+ print(f"The translated question is {translated_question}.")
51
+ answer = image_qa(image=image, question=translated_question)
52
+ final_answer(f"The answer is {answer}")
53
+ ```<end_code>
54
+ ---
55
+ Task:
56
+ In a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.
57
+ What does he say was the consequence of Einstein learning too much math on his creativity, in one word?
58
+ Thought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.
59
+ Code:
60
+ ```py
61
+ pages = search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein")
62
+ print(pages)
63
+ ```<end_code>
64
+ Observation:
65
+ No result found for query "1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein".
66
+
67
+ Thought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.
68
+ Code:
69
+ ```py
70
+ pages = search(query="1979 interview Stanislaus Ulam")
71
+ print(pages)
72
+ ```<end_code>
73
+ Observation:
74
+ Found 6 pages:
75
+ [Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)
76
+
77
+ [Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)
78
+
79
+ (truncated)
80
+
81
+ Thought: I will read the first 2 pages to know more.
82
+ Code:
83
+ ```py
84
+ for url in ["https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/", "https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/"]:
85
+ whole_page = visit_webpage(url)
86
+ print(whole_page)
87
+ print("\n" + "="*80 + "\n") # Print separator between pages
88
+ ```<end_code>
89
+ Observation:
90
+ Manhattan Project Locations:
91
+ Los Alamos, NM
92
+ Stanislaus Ulam was a Polish-American mathematician. He worked on the Manhattan Project at Los Alamos and later helped design the hydrogen bomb. In this interview, he discusses his work at
93
+ (truncated)
94
+
95
+ Thought: I now have the final answer: from the webpages visited, Stanislaus Ulam says of Einstein: "He learned too much mathematics and sort of diminished, it seems to me personally, it seems to me his purely physics creativity." Let's answer in one word.
96
+ Code:
97
+ ```py
98
+ final_answer("diminished")
99
+ ```<end_code>
100
+
101
+ ---
102
+ Task: "Which city has the highest population: Guangzhou or Shanghai?"
103
+
104
+ Thought: I need to get the populations for both cities and compare them: I will use the tool `search` to get the population of both cities.
105
+ Code:
106
+ ```py
107
+ for city in ["Guangzhou", "Shanghai"]:
108
+ print(f"Population {city}:", search(f"{city} population")
109
+ ```<end_code>
110
+ Observation:
111
+ Population Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
112
+ Population Shanghai: '26 million (2019)'
113
+
114
+ Thought: Now I know that Shanghai has the highest population.
115
+ Code:
116
+ ```py
117
+ final_answer("Shanghai")
118
+ ```<end_code>
119
+
120
+ ---
121
+ Task: "What is the current age of the pope, raised to the power 0.36?"
122
+
123
+ Thought: I will use the tool `wiki` to get the age of the pope, and confirm that with a web search.
124
+ Code:
125
+ ```py
126
+ pope_age_wiki = wiki(query="current pope age")
127
+ print("Pope age as per wikipedia:", pope_age_wiki)
128
+ pope_age_search = web_search(query="current pope age")
129
+ print("Pope age as per google search:", pope_age_search)
130
+ ```<end_code>
131
+ Observation:
132
+ Pope age: "The pope Francis is currently 88 years old."
133
+
134
+ Thought: I know that the pope is 88 years old. Let's compute the result using python code.
135
+ Code:
136
+ ```py
137
+ pope_current_age = 88 ** 0.36
138
+ final_answer(pope_current_age)
139
+ ```<end_code>
140
+
141
+ Above example were using notional tools that might not exist for you. On top of performing computations in the Python code snippets that you create, you only have access to these tools:
142
+ {%- for tool in tools.values() %}
143
+ - {{ tool.name }}: {{ tool.description }}
144
+ Takes inputs: {{tool.inputs}}
145
+ Returns an output of type: {{tool.output_type}}
146
+ {%- endfor %}
147
+
148
+ {%- if managed_agents and managed_agents.values() | list %}
149
+ You can also give tasks to team members.
150
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task', a long string explaining your task.
151
+ Given that this team member is a real human, you should be very verbose in your task.
152
+ Here is a list of the team members that you can call:
153
+ {%- for agent in managed_agents.values() %}
154
+ - {{ agent.name }}: {{ agent.description }}
155
+ {%- endfor %}
156
+ {%- else %}
157
+ {%- endif %}
158
+
159
+ Here are the rules you should always follow to solve your task:
160
+ 1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_code>' sequence, else you will fail.
161
+ 2. Use only variables that you have defined!
162
+ 3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = wiki({'query': "What is the place where James Bond lives?"})', but use the arguments directly as in 'answer = wiki(query="What is the place where James Bond lives?")'.
163
+ 4. Take care to not chain too many sequential tool calls in the same code block, especially when the output format is unpredictable. For instance, a call to search has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block.
164
+ 5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
165
+ 6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
166
+ 7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
167
+ 8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
168
+ 9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
169
+ 10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
170
+
171
+ Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
172
+ "planning":
173
+ "initial_facts": |-
174
+ Below I will present you a task.
175
+ You will now build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.
176
+ To do so, you will have to read the task and identify things that must be discovered in order to successfully complete it.
177
+ Don't make any assumptions. For each item, provide a thorough reasoning. Here is how you will structure this survey:
178
+
179
+ ---
180
+ ### 1. Facts given in the task
181
+ List here the specific facts given in the task that could help you (there might be nothing here).
182
+
183
+ ### 2. Facts to look up
184
+ List here any facts that we may need to look up.
185
+ Also list where to find each of these, for instance a website, a file... - maybe the task contains some sources that you should re-use here.
186
+
187
+ ### 3. Facts to derive
188
+ List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.
189
+
190
+ Keep in mind that "facts" will typically be specific names, dates, values, etc. Your answer should use the below headings:
191
+ ### 1. Facts given in the task
192
+ ### 2. Facts to look up
193
+ ### 3. Facts to derive
194
+ Do not add anything else.
195
+ "initial_plan": |-
196
+ You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
197
+ Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
198
+ This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
199
+ Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
200
+ After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
201
+
202
+ Here is your task:
203
+
204
+ Task:
205
+ ```
206
+ {{task}}
207
+ ```
208
+ You can leverage these tools:
209
+ {%- for tool in tools.values() %}
210
+ - {{ tool.name }}: {{ tool.description }}
211
+ Takes inputs: {{tool.inputs}}
212
+ Returns an output of type: {{tool.output_type}}
213
+ {%- endfor %}
214
+
215
+ {%- if managed_agents and managed_agents.values() | list %}
216
+ You can also give tasks to team members.
217
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'request', a long string explaining your request.
218
+ Given that this team member is a real human, you should be very verbose in your request.
219
+ Here is a list of the team members that you can call:
220
+ {%- for agent in managed_agents.values() %}
221
+ - {{ agent.name }}: {{ agent.description }}
222
+ {%- endfor %}
223
+ {%- else %}
224
+ {%- endif %}
225
+
226
+ List of facts that you know:
227
+ ```
228
+ {{answer_facts}}
229
+ ```
230
+
231
+ Now begin! Write your plan below.
232
+ "update_facts_pre_messages": |-
233
+ You are a world expert at gathering known and unknown facts based on a conversation.
234
+ Below you will find a task, and a history of attempts made to solve the task. You will have to produce a list of these:
235
+ ### 1. Facts given in the task
236
+ ### 2. Facts that we have learned
237
+ ### 3. Facts still to look up
238
+ ### 4. Facts still to derive
239
+ Find the task and history below:
240
+ "update_facts_post_messages": |-
241
+ Earlier we've built a list of facts.
242
+ But since in your previous steps you may have learned useful new facts or invalidated some false ones.
243
+ Please update your list of facts based on the previous history, and provide these headings:
244
+ ### 1. Facts given in the task
245
+ ### 2. Facts that we have learned
246
+ ### 3. Facts still to look up
247
+ ### 4. Facts still to derive
248
+ Now write your new list of facts below.
249
+ "update_plan_pre_messages": |-
250
+ You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
251
+ You have been given a task:
252
+ ```
253
+ {{task}}
254
+ ```
255
+
256
+ Find below the record of what has been tried so far to solve it. Then you will be asked to make an updated plan to solve the task.
257
+ If the previous tries so far have met some success, you can make an updated plan based on these actions.
258
+ If you are stalled, you can make a completely new plan starting from scratch.
259
+ "update_plan_post_messages": |-
260
+ You're still working towards solving this task:
261
+ ```
262
+ {{task}}
263
+ ```
264
+ You can leverage these tools:
265
+ {%- for tool in tools.values() %}
266
+ - {{ tool.name }}: {{ tool.description }}
267
+ Takes inputs: {{tool.inputs}}
268
+ Returns an output of type: {{tool.output_type}}
269
+ {%- endfor %}
270
+
271
+ {%- if managed_agents and managed_agents.values() | list %}
272
+ You can also give tasks to team members.
273
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
274
+ Given that this team member is a real human, you should be very verbose in your task, it should be a long string providing informations as detailed as necessary.
275
+ Here is a list of the team members that you can call:
276
+ {%- for agent in managed_agents.values() %}
277
+ - {{ agent.name }}: {{ agent.description }}
278
+ {%- endfor %}
279
+ {%- else %}
280
+ {%- endif %}
281
+
282
+ Here is the up to date list of facts that you know:
283
+ ```
284
+ {{facts_update}}
285
+ ```
286
+
287
+ Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
288
+ This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
289
+ Beware that you have {remaining_steps} steps remaining.
290
+ Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
291
+ After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
292
+
293
+ Now write your new plan below.
294
+ "managed_agent":
295
+ "task": |-
296
+ You're a helpful agent named '{{name}}'.
297
+ You have been submitted this task by your manager.
298
+ ---
299
+ Task:
300
+ {{task}}
301
+ ---
302
+ You're helping your manager solve a wider task: so make sure to not provide a one-line answer, but give as much information as possible to give them a clear understanding of the answer.
303
+ Your final_answer WILL HAVE to contain these parts:
304
+ ### 1. Task outcome (short version):
305
+ ### 2. Task outcome (extremely detailed version):
306
+ ### 3. Additional context (if relevant):
307
+
308
+ Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
309
+ And even if your task resolution is not successful, please return as much context as possible, so that your manager can act upon this feedback.
310
+ "report": |-
311
+ Here is the final answer from your managed agent '{{name}}':
312
+ {{final_answer}}
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ requests
3
+ pandas
4
+ langchain
5
+ langchain-openai
6
+ langchain-core
7
+ smolagents
8
+ duckduckgo_search
9
+ langgraph
10
+ langchain_community
11
+ dotenv
12
+ wikipedia
13
+ youtube-transcript-api