MohamedAliAmiraa commited on
Commit
d0a07b2
·
verified ·
1 Parent(s): 67f5c64

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -24
app.py CHANGED
@@ -29,9 +29,8 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
29
  # --- Basic Agent Definition ---
30
  class BasicAgent:
31
  def __init__(self):
32
- print("Initializing Advanced Agent logic within BasicAgent class...")
33
  try:
34
- # Using hardcoded values for easier debugging, only API Key is from secrets
35
  self.llm = AzureChatOpenAI(
36
  azure_endpoint="https://dsap.openai.azure.com/",
37
  api_key=os.environ["AZURE_API_KEY"],
@@ -41,12 +40,11 @@ class BasicAgent:
41
  max_retries=3,
42
  )
43
  print("AzureChatOpenAI client initialized successfully.")
44
- except KeyError as e:
45
- raise KeyError(f"CRITICAL: Missing environment variable 'AZURE_API_KEY'. Please add it to your Hugging Face Space secrets.")
46
  except Exception as e:
47
  print(f"FAILED to initialize Azure client. Error: {e}")
48
  raise
49
-
50
  self.tools = {
51
  "search": self.search, "browse": self.browse,
52
  "python": self.python_interpreter, "get_youtube_transcript": self.get_youtube_transcript,
@@ -148,18 +146,15 @@ Thought:
148
  return "Agent failed to find an answer within the loop limit."
149
 
150
 
151
- # *** THE FIX IS HERE ***
152
- def run_and_submit_all(request: gr.Request):
153
- """
154
- This function now accepts a gr.Request object to safely get user profile info.
155
- """
156
  space_id = os.getenv("SPACE_ID")
157
 
158
- # Get username from the request object
159
- if request and request.username:
160
- username = request.username
161
  print(f"User logged in: {username}")
162
  else:
 
163
  return "Could not get user profile. Please log in using the button above.", None
164
 
165
  api_url, submit_url = DEFAULT_API_URL, f"{DEFAULT_API_URL}/submit"
@@ -169,7 +164,6 @@ def run_and_submit_all(request: gr.Request):
169
  except Exception as e: return f"Error initializing agent: {e}", None
170
 
171
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "https://github.com/huggingface/agents-course"
172
- print(f"Agent code URL: {agent_code}")
173
 
174
  try:
175
  response = requests.get(questions_url, timeout=20)
@@ -204,24 +198,35 @@ def run_and_submit_all(request: gr.Request):
204
  f"Overall Score: {result_data.get('score', 'N/A')}% "
205
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)")
206
  return final_status, pd.DataFrame(results_log)
207
- except requests.exceptions.HTTPError as e:
208
- error_detail = f"Server responded with {e.response.status_code}. Detail: {e.response.text[:500]}"
209
- return f"Submission Failed: {error_detail}", pd.DataFrame(results_log)
210
  except Exception as e: return f"Submission Failed: {e}", pd.DataFrame(results_log)
211
 
212
 
213
  # --- Build Gradio Interface ---
214
- with gr.Blocks() as demo:
215
  gr.Markdown("# Agent Evaluation Runner")
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
 
221
- # *** AND THE FIX IS HERE ***
222
- # The click event now passes the request object implicitly to the function.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  run_button.click(
224
  fn=run_and_submit_all,
 
225
  outputs=[status_output, results_table]
226
  )
227
 
 
29
  # --- Basic Agent Definition ---
30
  class BasicAgent:
31
  def __init__(self):
32
+ print("Initializing Advanced Agent logic...")
33
  try:
 
34
  self.llm = AzureChatOpenAI(
35
  azure_endpoint="https://dsap.openai.azure.com/",
36
  api_key=os.environ["AZURE_API_KEY"],
 
40
  max_retries=3,
41
  )
42
  print("AzureChatOpenAI client initialized successfully.")
43
+ except KeyError:
44
+ raise KeyError("CRITICAL: Missing 'AZURE_API_KEY'. Please add it to your Space secrets.")
45
  except Exception as e:
46
  print(f"FAILED to initialize Azure client. Error: {e}")
47
  raise
 
48
  self.tools = {
49
  "search": self.search, "browse": self.browse,
50
  "python": self.python_interpreter, "get_youtube_transcript": self.get_youtube_transcript,
 
146
  return "Agent failed to find an answer within the loop limit."
147
 
148
 
149
+ # The function signature is changed to accept the profile object directly
150
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
 
 
 
151
  space_id = os.getenv("SPACE_ID")
152
 
153
+ if profile and profile.username:
154
+ username = profile.username
 
155
  print(f"User logged in: {username}")
156
  else:
157
+ # This is the message you were seeing.
158
  return "Could not get user profile. Please log in using the button above.", None
159
 
160
  api_url, submit_url = DEFAULT_API_URL, f"{DEFAULT_API_URL}/submit"
 
164
  except Exception as e: return f"Error initializing agent: {e}", None
165
 
166
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "https://github.com/huggingface/agents-course"
 
167
 
168
  try:
169
  response = requests.get(questions_url, timeout=20)
 
198
  f"Overall Score: {result_data.get('score', 'N/A')}% "
199
  f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)")
200
  return final_status, pd.DataFrame(results_log)
 
 
 
201
  except Exception as e: return f"Submission Failed: {e}", pd.DataFrame(results_log)
202
 
203
 
204
  # --- Build Gradio Interface ---
205
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
206
  gr.Markdown("# Agent Evaluation Runner")
 
 
 
 
207
 
208
+ # This state object will hold the user profile. It's invisible.
209
+ profile_state = gr.State(value=None)
210
+
211
+ with gr.Row():
212
+ # The login button is now just for show and triggering the login flow.
213
+ gr.LoginButton()
214
+
215
+ with gr.Row():
216
+ run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
217
+
218
+ with gr.Column():
219
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
220
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
221
+
222
+ # *** THE NEW, ROBUST FIX IS HERE ***
223
+ # 1. When the page loads, get the user's auth info and store it in our invisible state object.
224
+ demo.load(lambda request: request.auth, inputs=[], outputs=[profile_state])
225
+
226
+ # 2. When the run button is clicked, take the stored profile from the state object as input.
227
  run_button.click(
228
  fn=run_and_submit_all,
229
+ inputs=[profile_state],
230
  outputs=[status_output, results_table]
231
  )
232