jwgcurrie commited on
Commit
cfde807
·
1 Parent(s): cb15ce5

hopefully app.py fixed

Browse files
Files changed (1) hide show
  1. app.py +30 -16
app.py CHANGED
@@ -5,11 +5,11 @@ import inspect
5
  import pandas as pd
6
 
7
  # Import necessary libraries for LangChain Agent
8
- from langchain_huggingface import HuggingFaceEndpoint # NEW IMPORT!
9
  from langchain.agents import AgentExecutor, create_react_agent
10
  from langchain import hub
11
- # Removed from langchain.tools import tool, as SerpAPIWrapper is a direct tool
12
  from langchain_community.utilities import SerpAPIWrapper
 
13
 
14
  # --- Constants ---
15
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
@@ -37,7 +37,6 @@ class GAIAAgent:
37
 
38
  # Define a LangChain tool function that uses the SerpAPIWrapper
39
  # The description is crucial for the LLM to know when to use this tool
40
- from langchain.tools import Tool # Re-import Tool if needed for explicit wrapping
41
  web_search_tool = Tool(
42
  name="Serpapi Search",
43
  description="useful for when you need to answer questions about current events or facts. Input should be a search query.",
@@ -47,9 +46,16 @@ class GAIAAgent:
47
 
48
  self.prompt = hub.pull("hwchase17/react")
49
 
 
50
  self.agent = create_react_agent(self.llm, self.tools, self.prompt)
51
-
52
- self.agent_executor = AgentExecutor(agent=self.agent, tools=self.tools, verbose=True, handle_parsing_errors=True)
 
 
 
 
 
 
53
 
54
 
55
  def __call__(self, question: str) -> str:
@@ -61,9 +67,10 @@ class GAIAAgent:
61
  return agent_answer
62
  except Exception as e:
63
  print(f"Error during agent execution: {e}")
64
- return f"An error occurred while processing your request: {e}. Please ensure API keys are set correctly."
 
65
 
66
- def run_and_submit_all( profile: gr.OAuthProfile | None):
67
  """
68
  Fetches all questions, runs the GAIAAgent on them, submits all answers,
69
  and displays the results.
@@ -71,12 +78,14 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
71
  # --- Determine HF Space Runtime URL and Repo URL ---
72
  space_id = os.getenv("SPACE_ID")
73
 
74
- if profile:
75
- username= f"{profile.username}"
76
- print(f"User logged in: {username}")
 
 
77
  else:
78
- print("User not logged in.")
79
- return "Please Login to Hugging Face with the button.", None
80
 
81
  api_url = DEFAULT_API_URL
82
  questions_url = f"{api_url}/questions"
@@ -85,7 +94,11 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
85
  try:
86
  agent = GAIAAgent()
87
  except Exception as e:
88
- return f"Failed to initialize agent: {e}", None
 
 
 
 
89
 
90
  try:
91
  response = requests.get(questions_url)
@@ -94,7 +107,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
94
  questions = questions_data # Assume questions_data is directly the list of questions
95
  print(f"Fetched {len(questions)} questions.")
96
  except requests.exceptions.RequestException as e:
97
- return f"Failed to fetch questions: {e}", None
98
 
99
  all_answers = []
100
  results_for_display = []
@@ -107,8 +120,9 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
107
  continue
108
 
109
  print(f"\n--- Processing Question ID: {q_id} ---")
110
- agent_answer = agent(q_text)
111
 
 
112
  all_answers.append({"task_id": q_id, "submitted_answer": agent_answer})
113
  results_for_display.append({"Question ID": q_id, "Question": q_text, "Agent Answer": agent_answer})
114
 
@@ -117,7 +131,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
117
  submission_data = {
118
  "answers": all_answers,
119
  "space_id": space_id, # Include SPACE_ID for the leaderboard link
120
- "username": username, # Add the username here
121
  "agent_code": inspect.getsource(GAIAAgent), # Add agent code (for debugging on leaderboard)
122
  }
123
 
 
5
  import pandas as pd
6
 
7
  # Import necessary libraries for LangChain Agent
8
+ from langchain_huggingface import HuggingFaceEndpoint
9
  from langchain.agents import AgentExecutor, create_react_agent
10
  from langchain import hub
 
11
  from langchain_community.utilities import SerpAPIWrapper
12
+ from langchain.tools import Tool # Moved to top-level import for clarity and consistent access
13
 
14
  # --- Constants ---
15
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
37
 
38
  # Define a LangChain tool function that uses the SerpAPIWrapper
39
  # The description is crucial for the LLM to know when to use this tool
 
40
  web_search_tool = Tool(
41
  name="Serpapi Search",
42
  description="useful for when you need to answer questions about current events or facts. Input should be a search query.",
 
46
 
47
  self.prompt = hub.pull("hwchase17/react")
48
 
49
+ # Increased max_iterations and max_execution_time for better performance on complex GAIA questions
50
  self.agent = create_react_agent(self.llm, self.tools, self.prompt)
51
+ self.agent_executor = AgentExecutor(
52
+ agent=self.agent,
53
+ tools=self.tools,
54
+ verbose=True,
55
+ handle_parsing_errors=True,
56
+ max_iterations=25, # Increased from default, allow more thinking steps
57
+ max_execution_time=180.0 # Increased from default, allow more time per question (3 minutes)
58
+ )
59
 
60
 
61
  def __call__(self, question: str) -> str:
 
67
  return agent_answer
68
  except Exception as e:
69
  print(f"Error during agent execution: {e}")
70
+ # Ensure a clean error message is returned when agent execution fails
71
+ return f"Agent execution failed: {e}. Check tool outputs and LLM reasoning."
72
 
73
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
74
  """
75
  Fetches all questions, runs the GAIAAgent on them, submits all answers,
76
  and displays the results.
 
78
  # --- Determine HF Space Runtime URL and Repo URL ---
79
  space_id = os.getenv("SPACE_ID")
80
 
81
+ # Robust username handling
82
+ current_username = "anonymous_user" # Default for local testing or if not logged in
83
+ if profile and profile.username:
84
+ current_username = profile.username
85
+ print(f"User logged in: {current_username}")
86
  else:
87
+ print("User not logged in through Gradio OAuth, using default username for submission.")
88
+ # Do NOT return here, allow the app to run locally without HF login
89
 
90
  api_url = DEFAULT_API_URL
91
  questions_url = f"{api_url}/questions"
 
94
  try:
95
  agent = GAIAAgent()
96
  except Exception as e:
97
+ # Improved error handling for agent initialization
98
+ error_message = f"Failed to initialize agent: {e}. Please ensure all required API keys (HUGGINGFACEHUB_API_TOKEN, SERPAPI_API_KEY, GOOGLE_API_KEY) are set in Hugging Face Space secrets, and model terms accepted."
99
+ print(error_message)
100
+ # Return empty DataFrame with the error message to display in Gradio UI
101
+ return error_message, pd.DataFrame([{"Question ID": "N/A", "Question": "Agent Initialization Failed", "Agent Answer": str(e)}])
102
 
103
  try:
104
  response = requests.get(questions_url)
 
107
  questions = questions_data # Assume questions_data is directly the list of questions
108
  print(f"Fetched {len(questions)} questions.")
109
  except requests.exceptions.RequestException as e:
110
+ return f"Failed to fetch questions: {e}", pd.DataFrame() # Return empty DataFrame on fetch error
111
 
112
  all_answers = []
113
  results_for_display = []
 
120
  continue
121
 
122
  print(f"\n--- Processing Question ID: {q_id} ---")
123
+ agent_answer = agent(q_text) # This calls the GAIAAgent.__call__ method
124
 
125
+ # Ensured submission keys are correct as per GAIA benchmark expectations
126
  all_answers.append({"task_id": q_id, "submitted_answer": agent_answer})
127
  results_for_display.append({"Question ID": q_id, "Question": q_text, "Agent Answer": agent_answer})
128
 
 
131
  submission_data = {
132
  "answers": all_answers,
133
  "space_id": space_id, # Include SPACE_ID for the leaderboard link
134
+ "username": current_username, # Use the robustly determined username
135
  "agent_code": inspect.getsource(GAIAAgent), # Add agent code (for debugging on leaderboard)
136
  }
137