jwgcurrie commited on
Commit
f3c3f5b
·
1 Parent(s): 81917a3

First attempt

Browse files
Files changed (2) hide show
  1. app.py +115 -123
  2. requirements.txt +90 -2
app.py CHANGED
@@ -4,28 +4,72 @@ 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 ---
28
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
29
 
30
  if profile:
31
  username= f"{profile.username}"
@@ -38,132 +82,85 @@ 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}")
53
  try:
54
- response = requests.get(questions_url, timeout=15)
55
  response.raise_for_status()
56
  questions_data = response.json()
57
- if not questions_data:
58
- print("Fetched questions list is empty.")
59
- return "Fetched questions list is empty or invalid format.", None
60
- print(f"Fetched {len(questions_data)} questions.")
61
  except requests.exceptions.RequestException as e:
62
- print(f"Error fetching questions: {e}")
63
- return f"Error fetching questions: {e}", None
64
- except requests.exceptions.JSONDecodeError as e:
65
- print(f"Error decoding JSON response from questions endpoint: {e}")
66
- print(f"Response text: {response.text[:500]}")
67
- return f"Error decoding server response for questions: {e}", None
68
- except Exception as e:
69
- print(f"An unexpected error occurred fetching questions: {e}")
70
- return f"An unexpected error occurred fetching questions: {e}", None
71
-
72
- # 3. Run your Agent
73
- results_log = []
74
- answers_payload = []
75
- print(f"Running agent on {len(questions_data)} questions...")
76
- for item in questions_data:
77
- task_id = item.get("task_id")
78
- question_text = item.get("question")
79
- if not task_id or question_text is None:
80
- print(f"Skipping item with missing task_id or question: {item}")
81
  continue
82
- try:
83
- submitted_answer = agent(question_text)
84
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
86
- except Exception as e:
87
- print(f"Error running agent on task {task_id}: {e}")
88
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
89
 
90
- if not answers_payload:
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)
 
 
98
 
99
- # 5. Submit
100
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
101
  try:
102
- response = requests.post(submit_url, json=submission_data, timeout=60)
103
- response.raise_for_status()
104
- result_data = response.json()
105
- final_status = (
106
- f"Submission Successful!\n"
107
- f"User: {result_data.get('username')}\n"
108
- f"Overall Score: {result_data.get('score', 'N/A')}% "
109
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
110
- f"Message: {result_data.get('message', 'No message received.')}"
111
- )
112
- print("Submission successful.")
113
- results_df = pd.DataFrame(results_log)
114
- return final_status, results_df
115
- except requests.exceptions.HTTPError as e:
116
- error_detail = f"Server responded with status {e.response.status_code}."
117
- try:
118
- error_json = e.response.json()
119
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
120
- except requests.exceptions.JSONDecodeError:
121
- error_detail += f" Response: {e.response.text[:500]}"
122
- status_message = f"Submission Failed: {error_detail}"
123
- print(status_message)
124
- results_df = pd.DataFrame(results_log)
125
- return status_message, results_df
126
- except requests.exceptions.Timeout:
127
- status_message = "Submission Failed: The request timed out."
128
- print(status_message)
129
- results_df = pd.DataFrame(results_log)
130
- return status_message, results_df
131
- except requests.exceptions.RequestException as e:
132
- status_message = f"Submission Failed: Network error - {e}"
133
- print(status_message)
134
- results_df = pd.DataFrame(results_log)
135
- return status_message, results_df
136
- except Exception as e:
137
- status_message = f"An unexpected error occurred during submission: {e}"
138
- print(status_message)
139
- results_df = pd.DataFrame(results_log)
140
  return status_message, results_df
141
 
 
 
 
 
 
 
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(
@@ -173,9 +170,8 @@ with gr.Blocks() as demo:
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}")
@@ -183,14 +179,10 @@ if __name__ == "__main__":
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)
 
4
  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"
16
 
17
+ # --- LangChain Agent Definition ---
18
+ class GAIAAgent:
 
19
  def __init__(self):
20
+ print("GAIAAgent initialized using LangChain.")
21
+
22
+ repo_id = "mistralai/Mistral-7B-Instruct-v0.3"
23
+
24
+ self.llm = HuggingFaceEndpoint(
25
+ endpoint_url=f"https://api-inference.huggingface.co/models/{repo_id}", # Explicitly set endpoint URL
26
+ temperature=0.1, # Directly pass model parameters
27
+ max_new_tokens=512, # Directly pass model parameters (common for generation)
28
+ huggingfacehub_api_token=os.getenv("HUGGINGFACEHUB_API_TOKEN") # Env var name is correct
29
+ )
30
+
31
+ # Define tools for the agent
32
+ self.tools = []
33
+
34
+ # Initialize SerpAPIWrapper tool
35
+ # It will automatically pick up SERPAPI_API_KEY from environment variables
36
+ self.serpapi_tool = SerpAPIWrapper()
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.",
44
+ func=self.serpapi_tool.run,
45
+ )
46
+ self.tools.append(web_search_tool)
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:
56
  print(f"Agent received question (first 50 chars): {question[:50]}...")
57
+ try:
58
+ response = self.agent_executor.invoke({"input": question})
59
+ agent_answer = response["output"]
60
+ print(f"Agent returning answer: {agent_answer}")
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.
70
  """
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}"
 
82
  questions_url = f"{api_url}/questions"
83
  submit_url = f"{api_url}/submit"
84
 
 
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)
92
  response.raise_for_status()
93
  questions_data = response.json()
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 = []
101
+
102
+ for q_data in questions:
103
+ q_id = q_data.get("task_id") # Use 'task_id' as per the data
104
+ q_text = q_data.get("question")
105
+ if not q_id or not q_text:
106
+ print(f"Skipping malformed question data: {q_data}")
 
 
 
 
 
 
 
 
 
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
+
115
+ results_df = pd.DataFrame(results_for_display)
116
 
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
 
 
 
124
  try:
125
+ print(f"\nSubmitting {len(all_answers)} answers to {submit_url}...")
126
+ submit_response = requests.post(submit_url, json=submission_data)
127
+ submit_response.raise_for_status()
128
+ submission_result = submit_response.json()
129
+ print("Submission successful!")
130
+ print(f"Submission Result: {submission_result}")
131
+
132
+ score = submission_result.get("score", "N/A")
133
+ leaderboard_link = submission_result.get("leaderboard_link", "")
134
+ status_message = f"Evaluation complete! Your score: {score:.2f}%\n"
135
+ if leaderboard_link:
136
+ status_message += f"Check the leaderboard: {leaderboard_link}\n"
137
+ else:
138
+ status_message += "No leaderboard link provided."
139
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  return status_message, results_df
141
 
142
+ except requests.exceptions.RequestException as e:
143
+ error_message = f"Failed to submit answers: {e}"
144
+ if hasattr(e, 'response') and e.response is not None:
145
+ error_message += f"\nResponse: {e.response.text}"
146
+ print(error_message)
147
+ return error_message, results_df
148
 
149
+ # (Keep Gradio UI setup as is)
150
  with gr.Blocks() as demo:
 
151
  gr.Markdown(
152
+ """
153
+ # Unit 4: Agentic AI for GAIA Benchmark
 
 
 
 
 
 
 
 
 
 
 
154
 
155
+ This Gradio app allows you to run your agent against the GAIA benchmark questions and submit your answers.
156
+ Your goal is to modify the `GAIAAgent` class in `app.py` to achieve a score above 30%.
157
+ """
158
+ )
159
  gr.LoginButton()
160
 
161
  run_button = gr.Button("Run Evaluation & Submit All Answers")
162
 
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
 
166
  run_button.click(
 
170
 
171
  if __name__ == "__main__":
172
  print("\n" + "-"*30 + " App Starting " + "-"*30)
 
173
  space_host_startup = os.getenv("SPACE_HOST")
174
+ space_id_startup = os.getenv("SPACE_ID")
175
 
176
  if space_host_startup:
177
  print(f"✅ SPACE_HOST found: {space_host_startup}")
 
179
  else:
180
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
181
 
182
+ if space_id_startup:
183
  print(f"✅ SPACE_ID found: {space_id_startup}")
184
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
185
  print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
186
  else:
187
+ print("ℹ️ SPACE_ID environment variable not found...")
188
+ demo.launch()
 
 
 
 
requirements.txt CHANGED
@@ -1,2 +1,90 @@
1
- gradio
2
- requests
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiofiles==24.1.0
2
+ aiohappyeyeballs==2.6.1
3
+ aiohttp==3.12.13
4
+ aiosignal==1.3.2
5
+ annotated-types==0.7.0
6
+ anyio==4.9.0
7
+ attrs==25.3.0
8
+ Authlib==1.6.0
9
+ certifi==2025.6.15
10
+ cffi==1.17.1
11
+ charset-normalizer==3.4.2
12
+ click==8.2.1
13
+ cryptography==45.0.4
14
+ dataclasses-json==0.6.7
15
+ fastapi==0.115.13
16
+ ffmpy==0.6.0
17
+ filelock==3.18.0
18
+ frozenlist==1.7.0
19
+ fsspec==2025.5.1
20
+ google_search_results==2.4.2
21
+ gradio==5.34.2
22
+ gradio_client==1.10.3
23
+ greenlet==3.2.3
24
+ groovy==0.1.2
25
+ h11==0.16.0
26
+ hf-xet==1.1.5
27
+ httpcore==1.0.9
28
+ httpx==0.28.1
29
+ httpx-sse==0.4.0
30
+ huggingface-hub==0.33.0
31
+ idna==3.10
32
+ itsdangerous==2.2.0
33
+ Jinja2==3.1.6
34
+ jsonpatch==1.33
35
+ jsonpointer==3.0.0
36
+ langchain==0.3.26
37
+ langchain-community==0.3.26
38
+ langchain-core==0.3.66
39
+ langchain-huggingface==0.3.0
40
+ langchain-text-splitters==0.3.8
41
+ langsmith==0.4.1
42
+ markdown-it-py==3.0.0
43
+ MarkupSafe==3.0.2
44
+ marshmallow==3.26.1
45
+ mdurl==0.1.2
46
+ multidict==6.5.0
47
+ mypy_extensions==1.1.0
48
+ numpy==2.3.1
49
+ orjson==3.10.18
50
+ packaging==24.2
51
+ pandas==2.3.0
52
+ pillow==11.2.1
53
+ propcache==0.3.2
54
+ pycparser==2.22
55
+ pydantic==2.11.7
56
+ pydantic-settings==2.10.0
57
+ pydantic_core==2.33.2
58
+ pydub==0.25.1
59
+ Pygments==2.19.2
60
+ python-dateutil==2.9.0.post0
61
+ python-dotenv==1.1.0
62
+ python-multipart==0.0.20
63
+ pytz==2025.2
64
+ PyYAML==6.0.2
65
+ requests==2.32.4
66
+ requests-toolbelt==1.0.0
67
+ rich==14.0.0
68
+ ruff==0.12.0
69
+ safehttpx==0.1.6
70
+ semantic-version==2.10.0
71
+ serpapi==0.1.5
72
+ shellingham==1.5.4
73
+ six==1.17.0
74
+ sniffio==1.3.1
75
+ SQLAlchemy==2.0.41
76
+ starlette==0.46.2
77
+ tenacity==9.1.2
78
+ tokenizers==0.21.1
79
+ tomlkit==0.13.3
80
+ tqdm==4.67.1
81
+ typer==0.16.0
82
+ typing-inspect==0.9.0
83
+ typing-inspection==0.4.1
84
+ typing_extensions==4.14.0
85
+ tzdata==2025.2
86
+ urllib3==2.5.0
87
+ uvicorn==0.34.3
88
+ websockets==15.0.1
89
+ yarl==1.20.1
90
+ zstandard==0.23.0