anssio commited on
Commit
4aecd9b
·
verified ·
1 Parent(s): 4eec6e9

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +197 -62
agent.py CHANGED
@@ -1,71 +1,206 @@
1
  # 17/08/2025 -AO
2
- import math
3
- import re
4
  import requests
5
- from typing import Optional
 
 
6
 
 
7
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
8
 
9
- class BasicAgent:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  """
11
- Very simple baseline agent.
12
- - Tries to solve basic arithmetic expressions found in the question.
13
- - If it cannot, returns a default safe string.
14
- Keep responses concise because the grader does exact-match comparison.
15
  """
 
16
 
17
- def __init__(self, api_url: str = DEFAULT_API_URL):
18
- self.api_url = api_url
19
- # Precompile a simple arithmetic pattern like "12 + 3 * 4" or "(5+2)/7"
20
- self.expr_pattern = re.compile(r"^[\s\d\+\-\*/\(\)\.]+$")
21
-
22
- def try_eval_math(self, text: str) -> Optional[str]:
23
- # Extract a math-like snippet if the whole string looks like math.
24
- s = text.strip()
25
- if not s:
26
- return None
27
- if self.expr_pattern.match(s):
28
- try:
29
- # Safe eval using eval on limited globals/locals.
30
- val = eval(s, {"__builtins": {}}, {"math": math})
31
- # Format as plain value string.
32
- return str(val)
33
- except Exception:
34
- return None
35
- return None
36
 
37
- def __call__(self, question: str) -> str:
38
- # Try direct arithmetic
39
- ans = self.try_eval_math(question)
40
- if ans is not None:
41
- return ans
42
-
43
- # Extremely small heuristics: look for numbers and operations within the sentence.
44
- digits = re.findall(r"[\d\.]+", question)
45
- if len(digits) >= 2:
46
- try:
47
- # If words like 'sum' or 'add' appear, add the numbers.
48
- ql = question.lower()
49
- nums = list(map(float, digits))
50
- if any(k in ql for k in ["sum", "add", "+"]):
51
- return str(sum(nums))
52
- if any(k in ql for k in ["difference", "subtract", "-"]):
53
- return str(nums[0] - sum(nums[1:]))
54
- if any(k in ql for k in ["product", "multiply", "*"]):
55
- p = 1.0
56
- for n in nums:
57
- p *= n
58
- return str(p)
59
- if any(k in ql for k in ["divide", "ratio", "/"]):
60
- try:
61
- res = nums[0]
62
- for n in nums[1:]:
63
- res /= n
64
- return str(res)
65
- except ZeroDivisionError:
66
- return "undefined"
67
- except Exception:
68
- pass
69
-
70
- # Fallback default answer; keep minimal for exact-match grading.
71
- return "unknown"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # 17/08/2025 -AO
2
+ import os
3
+ import gradio as gr
4
  import requests
5
+ import pandas as pd
6
+ from transformers import HfAgent
7
+ from transformers.tools import DuckDuckGoSearchTool
8
 
9
+ # --- Constants ---
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
 
12
+ # --- Advanced Agent Definition ---
13
+ class MyAgent:
14
+ def __init__(self):
15
+ # Define the LLM for the agent. Use a supported model from the Hugging Face Hub.
16
+ # Ensure you have the necessary environment variables (e.g., HF_TOKEN).
17
+ # You'll likely need a powerful model to get a high score.
18
+ # Example: Using a powerful hosted model
19
+ self.agent = HfAgent("HuggingFaceH4/zephyr-7b-beta",
20
+ additional_tools=[DuckDuckGoSearchTool()])
21
+
22
+ def __call__(self, question: str) -> str:
23
+ print(f"Agent received question: {question[:50]}...")
24
+ # Use a try-except block to handle potential errors during execution.
25
+ try:
26
+ # Let the agent reason and find the answer.
27
+ # Use verbose=True to see the agent's thought process for debugging.
28
+ result = self.agent.run(question)
29
+ # The GAIA scoring is an "EXACT MATCH".
30
+ # The prompt asks the agent to just return the answer, not a verbose explanation.
31
+ # You might need to add a post-processing step to extract the final answer.
32
+ # For example, by telling the model in the prompt to only output the answer.
33
+ final_answer = str(result)
34
+ print(f"Agent returning answer: {final_answer}")
35
+ return final_answer
36
+ except Exception as e:
37
+ print(f"An error occurred during agent execution: {e}")
38
+ return f"Error: {e}"
39
+
40
+ # The rest of the `run_and_submit_all` and Gradio code remains the same as in the template.
41
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
42
  """
43
+ Fetches all questions, runs the agent on them, submits all answers,
44
+ and displays the results.
 
 
45
  """
46
+ space_id = os.getenv("SPACE_ID")
47
 
48
+ if profile:
49
+ username = f"{profile.username}"
50
+ print(f"User logged in: {username}")
51
+ else:
52
+ print("User not logged in.")
53
+ return "Please Login to Hugging Face with the button.", None
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
+ api_url = DEFAULT_API_URL
56
+ questions_url = f"{api_url}/questions"
57
+ submit_url = f"{api_url}/submit"
58
+
59
+ # 1. Instantiate Agent
60
+ try:
61
+ agent = MyAgent() # Instantiate your new agent class
62
+ except Exception as e:
63
+ print(f"Error instantiating agent: {e}")
64
+ return f"Error initializing agent: {e}", None
65
+
66
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
67
+ print(agent_code)
68
+
69
+ # 2. Fetch Questions
70
+ print(f"Fetching questions from: {questions_url}")
71
+ try:
72
+ response = requests.get(questions_url, timeout=15)
73
+ response.raise_for_status()
74
+ questions_data = response.json()
75
+ if not questions_data:
76
+ print("Fetched questions list is empty.")
77
+ return "Fetched questions list is empty or invalid format.", None
78
+ print(f"Fetched {len(questions_data)} questions.")
79
+ except requests.exceptions.RequestException as e:
80
+ print(f"Error fetching questions: {e}")
81
+ return f"Error fetching questions: {e}", None
82
+ except requests.exceptions.JSONDecodeError as e:
83
+ print(f"Error decoding JSON response from questions endpoint: {e}")
84
+ print(f"Response text: {response.text[:500]}")
85
+ return f"Error decoding server response for questions: {e}", None
86
+ except Exception as e:
87
+ print(f"An unexpected error occurred fetching questions: {e}")
88
+ return f"An unexpected error occurred fetching questions: {e}", None
89
+
90
+ # 3. Run your Agent
91
+ results_log = []
92
+ answers_payload = []
93
+ print(f"Running agent on {len(questions_data)} questions...")
94
+ for item in questions_data:
95
+ task_id = item.get("task_id")
96
+ question_text = item.get("question")
97
+ if not task_id or question_text is None:
98
+ print(f"Skipping item with missing task_id or question: {item}")
99
+ continue
100
+ try:
101
+ submitted_answer = agent(question_text)
102
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
103
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
104
+ except Exception as e:
105
+ print(f"Error running agent on task {task_id}: {e}")
106
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
107
+
108
+ if not answers_payload:
109
+ print("Agent did not produce any answers to submit.")
110
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
111
+
112
+ # 4. Prepare Submission
113
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
114
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
115
+ print(status_update)
116
+
117
+ # 5. Submit
118
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
119
+ try:
120
+ response = requests.post(submit_url, json=submission_data, timeout=60)
121
+ response.raise_for_status()
122
+ result_data = response.json()
123
+ final_status = (
124
+ f"Submission Successful!\n"
125
+ f"User: {result_data.get('username')}\n"
126
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
127
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
128
+ f"Message: {result_data.get('message', 'No message received.')}"
129
+ )
130
+ print("Submission successful.")
131
+ results_df = pd.DataFrame(results_log)
132
+ return final_status, results_df
133
+ except requests.exceptions.HTTPError as e:
134
+ error_detail = f"Server responded with status {e.response.status_code}."
135
+ try:
136
+ error_json = e.response.json()
137
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
138
+ except requests.exceptions.JSONDecodeError:
139
+ error_detail += f" Response: {e.response.text[:500]}"
140
+ status_message = f"Submission Failed: {error_detail}"
141
+ print(status_message)
142
+ results_df = pd.DataFrame(results_log)
143
+ return status_message, results_df
144
+ except requests.exceptions.Timeout:
145
+ status_message = "Submission Failed: The request timed out."
146
+ print(status_message)
147
+ results_df = pd.DataFrame(results_log)
148
+ return status_message, results_df
149
+ except requests.exceptions.RequestException as e:
150
+ status_message = f"Submission Failed: Network error - {e}"
151
+ print(status_message)
152
+ results_df = pd.DataFrame(results_log)
153
+ return status_message, results_df
154
+ except Exception as e:
155
+ status_message = f"An unexpected error occurred during submission: {e}"
156
+ print(status_message)
157
+ results_df = pd.DataFrame(results_log)
158
+ return status_message, results_df
159
+
160
+
161
+ # --- Build Gradio Interface using Blocks ---
162
+ with gr.Blocks() as demo:
163
+ gr.Markdown("# Advanced Agent Evaluation Runner")
164
+ gr.Markdown(
165
+ """
166
+ **Instructions:**
167
+
168
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
169
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
170
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
171
+ """
172
+ )
173
+ gr.LoginButton()
174
+
175
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
176
+
177
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
178
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
179
+
180
+ run_button.click(
181
+ fn=run_and_submit_all,
182
+ outputs=[status_output, results_table]
183
+ )
184
+
185
+ if __name__ == "__main__":
186
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
187
+ space_host_startup = os.getenv("SPACE_HOST")
188
+ space_id_startup = os.getenv("SPACE_ID")
189
+
190
+ if space_host_startup:
191
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
192
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
193
+ else:
194
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
195
+
196
+ if space_id_startup:
197
+ print(f"✅ SPACE_ID found: {space_id_startup}")
198
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
199
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
200
+ else:
201
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
202
+
203
+ print("-"*(60 + len(" App Starting ")) + "\n")
204
+
205
+ print("Launching Gradio Interface for Advanced Agent Evaluation...")
206
+ demo.launch(debug=True, share=False)