dalybuilds commited on
Commit
2a43fe1
·
verified ·
1 Parent(s): 96867be

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -42
app.py CHANGED
@@ -3,25 +3,64 @@ 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
- def run_and_submit_all( profile: gr.OAuthProfile | None):
 
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 ---
@@ -38,15 +77,20 @@ 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 Agent ( modify this part to create your agent)
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
- # 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}")
@@ -91,7 +135,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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)
@@ -142,55 +186,50 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
142
 
143
  # --- Build Gradio Interface using Blocks ---
144
  with gr.Blocks() as demo:
145
- gr.Markdown("# Basic Agent Evaluation Runner")
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
  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") # Get SPACE_ID at 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?). 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)
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ from groq import Groq
7
 
 
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
+ # --- Groq Powered Agent Definition ---
12
+ # This new agent uses the Groq API to generate answers.
13
+ class GroqAgent:
14
+ def __init__(self, api_key):
15
+ """
16
+ Initializes the GroqAgent with the Groq API client.
17
+ """
18
+ print("Initializing GroqAgent...")
19
+ self.client = Groq(api_key=api_key)
20
+ print("GroqAgent initialized successfully.")
21
+
22
  def __call__(self, question: str) -> str:
23
+ """
24
+ This method is called to answer a question using the Groq API.
25
+ """
26
+ print(f"GroqAgent received question (first 50 chars): {question[:50]}...")
27
+
28
+ # A system prompt is used to guide the model to provide concise, direct answers,
29
+ # which is ideal for the GAIA benchmark's exact-match scoring.
30
+ system_prompt = (
31
+ "You are an expert AI agent. Your goal is to answer the following question as accurately "
32
+ "and concisely as possible. Provide only the final answer, without any introductory text, "
33
+ "explanations, or additional formatting."
34
+ )
35
+
36
+ try:
37
+ chat_completion = self.client.chat.completions.create(
38
+ messages=[
39
+ {
40
+ "role": "system",
41
+ "content": system_prompt,
42
+ },
43
+ {
44
+ "role": "user",
45
+ "content": question,
46
+ }
47
+ ],
48
+ model="llama3-70b-8192", # A powerful model available via Groq
49
+ temperature=0.0, # Set to 0 for deterministic, factual answers
50
+ )
51
+
52
+ answer = chat_completion.choices[0].message.content.strip()
53
+ print(f"GroqAgent generated answer: {answer}")
54
+ return answer
55
+
56
+ except Exception as e:
57
+ print(f"An error occurred while calling Groq API: {e}")
58
+ return f"Error generating answer: {e}"
59
 
60
+
61
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
62
  """
63
+ Fetches all questions, runs the GroqAgent on them, submits all answers,
64
  and displays the results.
65
  """
66
  # --- Determine HF Space Runtime URL and Repo URL ---
 
77
  questions_url = f"{api_url}/questions"
78
  submit_url = f"{api_url}/submit"
79
 
80
+ # 1. Instantiate Agent (Now using GroqAgent)
81
  try:
82
+ # Securely get the API key from Hugging Face Space secrets
83
+ groq_api_key = os.getenv("GROQ_API_KEY")
84
+ if not groq_api_key:
85
+ raise ValueError("GROQ_API_KEY secret not found! Please set it in your Space's settings.")
86
+ agent = GroqAgent(api_key=groq_api_key)
87
  except Exception as e:
88
  print(f"Error instantiating agent: {e}")
89
  return f"Error initializing agent: {e}", None
90
+
91
+ # The link to your codebase (useful for verification, so please keep your space public)
92
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
93
+ print(f"Agent code link: {agent_code}")
94
 
95
  # 2. Fetch Questions
96
  print(f"Fetching questions from: {questions_url}")
 
135
  print("Agent did not produce any answers to submit.")
136
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
137
 
138
+ # 4. Prepare Submission
139
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
140
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
141
  print(status_update)
 
186
 
187
  # --- Build Gradio Interface using Blocks ---
188
  with gr.Blocks() as demo:
189
+ gr.Markdown("# Groq-Powered Agent Evaluation Runner")
190
  gr.Markdown(
191
  """
192
  **Instructions:**
193
+ 1. Make sure you have set your `GROQ_API_KEY` in the 'Secrets' section of your Space settings.
194
+ 2. Log in to your Hugging Face account using the button below. This is required for submission.
195
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see your score.
 
 
196
  ---
197
  **Disclaimers:**
198
+ Once you click the "submit" button, the process can take some time as the agent answers all the questions.
199
+ This space provides a basic setup. You are encouraged to modify the `GroqAgent` class to experiment with different models, prompts, or even add tools to improve your score!
200
  """
201
  )
202
 
203
+ # We need to get the user's profile information for the submission
204
+ auth_button = gr.LoginButton()
205
 
206
  run_button = gr.Button("Run Evaluation & Submit All Answers")
207
 
208
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
209
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
210
 
211
+ # The `auth_button` provides the profile info to the click function
212
  run_button.click(
213
  fn=run_and_submit_all,
214
+ inputs=[auth_button],
215
  outputs=[status_output, results_table]
216
  )
217
 
218
  if __name__ == "__main__":
219
  print("\n" + "-"*30 + " App Starting " + "-"*30)
220
+ space_id_startup = os.getenv("SPACE_ID")
221
+ if space_id_startup:
 
 
 
 
 
 
 
 
 
222
  print(f"✅ SPACE_ID found: {space_id_startup}")
223
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
 
224
  else:
225
+ print("ℹ️ SPACE_ID environment variable not found (running locally?).")
226
+
227
+ if not os.getenv("GROQ_API_KEY"):
228
+ print("⚠️ WARNING: GROQ_API_KEY secret is not set. The app will fail if run.")
229
+ else:
230
+ print("✅ GROQ_API_KEY secret is set.")
231
 
 
232
 
233
+ print("-"*(60 + len(" App Starting ")) + "\n")
234
+ print("Launching Gradio Interface for Groq Agent Evaluation...")
235
  demo.launch(debug=True, share=False)