Update app.py
Browse files
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 |
-
# ---
|
12 |
-
#
|
13 |
-
class
|
14 |
-
def __init__(self):
|
15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
def __call__(self, question: str) -> str:
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
-
|
|
|
23 |
"""
|
24 |
-
Fetches all questions, runs the
|
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 (
|
42 |
try:
|
43 |
-
|
|
|
|
|
|
|
|
|
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 |
|
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("#
|
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
|
158 |
"""
|
159 |
)
|
160 |
|
161 |
-
|
|
|
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 |
-
|
177 |
-
|
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?).
|
|
|
|
|
|
|
|
|
|
|
192 |
|
193 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
194 |
|
195 |
-
print("
|
|
|
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)
|