Macmill commited on
Commit
1056032
·
verified ·
1 Parent(s): 72b18e0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -23
app.py CHANGED
@@ -4,7 +4,7 @@ import requests
4
  import pandas as pd
5
  from dotenv import load_dotenv
6
  import traceback
7
- from typing import Optional # <<< MAKE SURE THIS IMPORT IS PRESENT <<<
8
 
9
  # --- Constants ---
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
@@ -12,13 +12,15 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
  # --- Agent Integration ---
13
  AGENT_AVAILABLE = False
14
  AGENT_LOAD_ERROR = ""
 
 
15
  try:
16
- # Ensure this matches the filename and function name exactly
17
- from final_agent import answer_gaia_task
18
- print("Successfully imported answer_gaia_task from final_agent.py")
19
  AGENT_AVAILABLE = True
20
  except ImportError as e:
21
- error_msg = f"ERROR: Could not import answer_gaia_task from final_agent.py: {e}"
22
  print(error_msg)
23
  AGENT_LOAD_ERROR = error_msg
24
  except Exception as e:
@@ -28,11 +30,13 @@ except Exception as e:
28
  traceback.print_exc()
29
  AGENT_LOAD_ERROR = error_msg
30
 
31
- # Define a dummy function if import fails, so Gradio app can still load
32
  if not AGENT_AVAILABLE:
33
  # This dummy function will be used if the import fails
34
- def answer_gaia_task(question: str, file_path: Optional[str] = None) -> str:
35
- return f"ERROR: Agent function could not be loaded. Details: {AGENT_LOAD_ERROR}"
 
 
36
 
37
  # --- Agent Runner Class ---
38
  class AgentRunner:
@@ -49,20 +53,23 @@ class AgentRunner:
49
  print(f"\n--- AgentRunner received question: {question[:100]}... ---")
50
  # Always call the potentially dummy function; it returns error if needed
51
  try:
52
- # Call the imported (or dummy) function
53
- # Assuming file_path is handled by the agent based on question text for now
54
- final_answer = answer_gaia_task(question=question, file_path=None)
 
 
55
  # Ensure result is always a string for submission
56
  final_answer_str = str(final_answer)
57
  print(f"--- AgentRunner returning answer: {final_answer_str} ---")
58
  return final_answer_str
59
  except Exception as e:
60
  # Catch unexpected errors during the function call itself
61
- print(f"!!! ERROR calling answer_gaia_task function: {e} !!!")
62
  traceback.print_exc() # Log the full error to Space logs
63
- return f"ERROR: Agent function failed during execution - {e}"
 
64
 
65
- # --- Submission Logic ---
66
  def run_and_submit_all( profile: gr.OAuthProfile | None):
67
  """Fetches questions, runs agent, submits answers."""
68
  space_id = os.getenv("SPACE_ID")
@@ -77,7 +84,8 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
77
  agent = AgentRunner()
78
  # Check if agent loaded correctly before proceeding
79
  if not AGENT_AVAILABLE:
80
- return f"Agent failed to load. Check logs. Error: {AGENT_LOAD_ERROR}", None
 
81
  except Exception as e: print(f"Error instantiating AgentRunner: {e}"); return f"Init error: {e}", None
82
 
83
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Code URL N/A"
@@ -101,7 +109,8 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
101
  print(f"\n--- Processing Question {i+1}/{question_count} (ID: {task_id}) ---") # Add progress logging
102
  if not task_id or question_text is None: print(f"Skipping item: {item}"); continue
103
  try:
104
- submitted_answer = agent(question_text) # Calls AgentRunner.__call__
 
105
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
106
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
107
  except Exception as e:
@@ -136,28 +145,32 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
136
  print(status_message); results_df = pd.DataFrame(results_log); return status_message, results_df
137
 
138
 
139
- # --- Build Gradio Interface ---
140
  with gr.Blocks() as demo:
141
  gr.Markdown("# GAIA Agent Evaluation Runner")
142
  gr.Markdown(
143
  """
144
  **Instructions:**
145
- 1. Ensure your agent logic is in `final_agent.py` and dependencies in `requirements.txt`. Set secrets in Space settings.
146
  2. Log in to Hugging Face using the button below.
147
  3. Click 'Run Evaluation & Submit All Answers' to run your agent. Check Logs for detailed progress.
148
  ---
149
- **Disclaimers:** Execution can take significant time.
150
  """
151
  )
152
  gr.LoginButton()
153
  run_button = gr.Button("Run Evaluation & Submit All Answers")
154
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
155
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
156
- run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
157
 
158
- # --- Main execution block ---
159
  if __name__ == "__main__":
160
  print("\n" + "-"*30 + " App Starting " + "-"*30)
161
- # ... Keep startup checks ...
 
 
 
162
  print("Launching Gradio Interface...")
163
- demo.launch(debug=True, share=False) # debug=True helps during development
 
 
4
  import pandas as pd
5
  from dotenv import load_dotenv
6
  import traceback
7
+ from typing import Optional # Keep this import, good practice
8
 
9
  # --- Constants ---
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
12
  # --- Agent Integration ---
13
  AGENT_AVAILABLE = False
14
  AGENT_LOAD_ERROR = ""
15
+ AGENT_FUNCTION_NAME = "run_gaia_task" # Define the target function name
16
+
17
  try:
18
+ # --- MODIFIED: Import the correct function ---
19
+ from final_agent import run_gaia_task
20
+ print(f"Successfully imported {AGENT_FUNCTION_NAME} from final_agent.py")
21
  AGENT_AVAILABLE = True
22
  except ImportError as e:
23
+ error_msg = f"ERROR: Could not import {AGENT_FUNCTION_NAME} from final_agent.py: {e}"
24
  print(error_msg)
25
  AGENT_LOAD_ERROR = error_msg
26
  except Exception as e:
 
30
  traceback.print_exc()
31
  AGENT_LOAD_ERROR = error_msg
32
 
33
+ # --- MODIFIED: Define a dummy function matching the new signature ---
34
  if not AGENT_AVAILABLE:
35
  # This dummy function will be used if the import fails
36
+ def run_gaia_task(task_description: str) -> str:
37
+ """Dummy function used when the real agent fails to load."""
38
+ print(f"Executing dummy {AGENT_FUNCTION_NAME} because agent failed to load.")
39
+ return f"ERROR: Agent function '{AGENT_FUNCTION_NAME}' could not be loaded. Details: {AGENT_LOAD_ERROR}"
40
 
41
  # --- Agent Runner Class ---
42
  class AgentRunner:
 
53
  print(f"\n--- AgentRunner received question: {question[:100]}... ---")
54
  # Always call the potentially dummy function; it returns error if needed
55
  try:
56
+ # --- MODIFIED: Call the new agent function ---
57
+ # The 'question' variable holds the task description.
58
+ # The new agent handles file paths internally based on the description.
59
+ final_answer = run_gaia_task(task_description=question)
60
+
61
  # Ensure result is always a string for submission
62
  final_answer_str = str(final_answer)
63
  print(f"--- AgentRunner returning answer: {final_answer_str} ---")
64
  return final_answer_str
65
  except Exception as e:
66
  # Catch unexpected errors during the function call itself
67
+ print(f"!!! ERROR calling {AGENT_FUNCTION_NAME} function: {e} !!!")
68
  traceback.print_exc() # Log the full error to Space logs
69
+ # --- MODIFIED: Update error message ---
70
+ return f"ERROR: Agent function '{AGENT_FUNCTION_NAME}' failed during execution - {e}"
71
 
72
+ # --- Submission Logic (Largely Unchanged) ---
73
  def run_and_submit_all( profile: gr.OAuthProfile | None):
74
  """Fetches questions, runs agent, submits answers."""
75
  space_id = os.getenv("SPACE_ID")
 
84
  agent = AgentRunner()
85
  # Check if agent loaded correctly before proceeding
86
  if not AGENT_AVAILABLE:
87
+ # --- MODIFIED: Update error message ---
88
+ return f"Agent function '{AGENT_FUNCTION_NAME}' failed to load. Check logs. Error: {AGENT_LOAD_ERROR}", None
89
  except Exception as e: print(f"Error instantiating AgentRunner: {e}"); return f"Init error: {e}", None
90
 
91
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Code URL N/A"
 
109
  print(f"\n--- Processing Question {i+1}/{question_count} (ID: {task_id}) ---") # Add progress logging
110
  if not task_id or question_text is None: print(f"Skipping item: {item}"); continue
111
  try:
112
+ # Calls AgentRunner.__call__, which now calls run_gaia_task
113
+ submitted_answer = agent(question_text)
114
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
115
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
116
  except Exception as e:
 
145
  print(status_message); results_df = pd.DataFrame(results_log); return status_message, results_df
146
 
147
 
148
+ # --- Build Gradio Interface (Unchanged) ---
149
  with gr.Blocks() as demo:
150
  gr.Markdown("# GAIA Agent Evaluation Runner")
151
  gr.Markdown(
152
  """
153
  **Instructions:**
154
+ 1. Ensure your agent logic is in `final_agent.py` (exposing the `run_gaia_task` function) and dependencies in `requirements.txt`. Set secrets in Space settings (GROQ_API_KEY, TAVILY_API_KEY, OPENAI_API_KEY).
155
  2. Log in to Hugging Face using the button below.
156
  3. Click 'Run Evaluation & Submit All Answers' to run your agent. Check Logs for detailed progress.
157
  ---
158
+ **Disclaimers:** Execution can take significant time depending on the number of questions and agent complexity.
159
  """
160
  )
161
  gr.LoginButton()
162
  run_button = gr.Button("Run Evaluation & Submit All Answers")
163
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
164
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
165
+ run_button.click(fn=run_and_submit_all, inputs=gr.State(None), outputs=[status_output, results_table]) # Pass None for profile initially
166
 
167
+ # --- Main execution block (Unchanged) ---
168
  if __name__ == "__main__":
169
  print("\n" + "-"*30 + " App Starting " + "-"*30)
170
+ # Perform startup checks if needed (e.g., check essential env vars)
171
+ if not AGENT_AVAILABLE:
172
+ print(f"CRITICAL WARNING: Agent function '{AGENT_FUNCTION_NAME}' could not be loaded. The app will run but agent calls will fail.")
173
+ print(f"Load Error Details: {AGENT_LOAD_ERROR}")
174
  print("Launching Gradio Interface...")
175
+ # Consider removing debug=True for "production" submission space
176
+ demo.launch(debug=False, share=False)