a-ge commited on
Commit
b18a31b
·
verified ·
1 Parent(s): 1de4b32

Create new_agent.py

Browse files
Files changed (1) hide show
  1. new_agent.py +342 -0
new_agent.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import os
3
+ import gradio as gr
4
+ import requests
5
+ import pandas as pd
6
+ from dotenv import load_dotenv
7
+ from smolagents import (
8
+ InferenceClientModel,
9
+ CodeAgent,
10
+ VisitWebpageTool,
11
+ WebSearchTool,
12
+ WikipediaSearchTool,
13
+ tool,
14
+ )
15
+ from langchain_community.document_loaders import ArxivLoader
16
+
17
+ load_dotenv()
18
+
19
+ token = os.environ["HF_KEY"]
20
+ model_id = "deepseek-ai/DeepSeek-R1-0528"
21
+ # model_id = "meta-llama/Llama-3.3-70B-Instruct"
22
+
23
+
24
+ @tool
25
+ def arxiv_search(query: str) -> str:
26
+ """Search Arxiv for a query and return maximum 3 result.
27
+
28
+ Args:
29
+ query: The search query."""
30
+ search_docs = ArxivLoader(query=query, load_max_docs=3).load()
31
+ formatted_search_docs = "\n\n---\n\n".join(
32
+ [
33
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
34
+ for doc in search_docs
35
+ ]
36
+ )
37
+ return {"arxiv_results": formatted_search_docs}
38
+
39
+
40
+ # (Keep Constants as is)
41
+ # --- Constants ---
42
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
43
+
44
+
45
+ # --- Basic Agent Definition ---
46
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
47
+ class BasicAgent:
48
+ def __init__(self):
49
+ model = InferenceClientModel(model_id=model_id, provider="nebius", token=token)
50
+ self.agent = CodeAgent(
51
+ tools=[
52
+ VisitWebpageTool(),
53
+ WebSearchTool(),
54
+ WikipediaSearchTool(),
55
+ arxiv_search,
56
+ ],
57
+ model=model,
58
+ additional_authorized_imports=[
59
+ "pandas",
60
+ "numpy",
61
+ "requests",
62
+ "os",
63
+ "math",
64
+ "sympy",
65
+ "scipy",
66
+ "markdownify",
67
+ "unicodedata",
68
+ "stat",
69
+ "datetime",
70
+ "random",
71
+ "itertools",
72
+ "statistics",
73
+ "queue",
74
+ "time",
75
+ "collections",
76
+ "re",
77
+ ],
78
+ add_base_tools=True,
79
+ max_steps=10,
80
+ )
81
+ print("Agent initialized.")
82
+
83
+ def __call__(self, question: str, file_path: str = None) -> str:
84
+ print(f"Agent received question: {question}...")
85
+ file_info = ""
86
+ if file_path:
87
+ print(f"Agent received file: {file_path}")
88
+ try:
89
+ if file_path.endswith(".xlsx"):
90
+ df = pd.read_excel(file_path)
91
+ file_info = f"\n[Attached Excel file preview (first 10 rows)]:\n{df.head(10).to_string(index=False)}\n"
92
+ elif file_path.endswith(".py"):
93
+ with open(file_path, "r", encoding="utf-8") as f:
94
+ code = "".join([line for _, line in zip(range(400), f)])
95
+ file_info = f"\n[Attached Python file]:\n{code}\n"
96
+ elif file_path.endswith(".png"):
97
+ with open(file_path, "rb") as img_file:
98
+ b64_string = base64.b64encode(img_file.read()).decode("utf-8")
99
+ file_info = f"\n[Attached PNG image as base64]:\n{b64_string}\n"
100
+ else:
101
+ with open(file_path, "r", encoding="utf-8") as f:
102
+ content = f.read(2000)
103
+ file_info = (
104
+ f"\n[Attached file content (first 2000 chars)]:\n{content}\n"
105
+ )
106
+ except Exception as e:
107
+ file_info = f"\n[Could not read attached file: {e}]\n"
108
+ answer = self.agent.run(
109
+ f"""You are a general AI assistant. You can use the provided tools and websearch for finding answers. Some questions may include attached files like excel, python code, or images. Include them while evaluating for answer. I will ask you a question. Report your thoughts, and finish your answer. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
110
+ {question}
111
+ {file_info}
112
+ """,
113
+ )
114
+ print(f"Agent returning answer: {answer}")
115
+ return answer
116
+
117
+
118
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
119
+ """
120
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
121
+ and displays the results.
122
+ """
123
+ # --- Determine HF Space Runtime URL and Repo URL ---
124
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
125
+
126
+ if profile:
127
+ username = f"{profile.username}"
128
+ print(f"User logged in: {username}")
129
+ else:
130
+ print("User not logged in.")
131
+ return "Please Login to Hugging Face with the button.", None
132
+
133
+ api_url = DEFAULT_API_URL
134
+ questions_url = f"{api_url}/questions"
135
+ submit_url = f"{api_url}/submit"
136
+
137
+ # 1. Instantiate Agent ( modify this part to create your agent)
138
+ try:
139
+ agent = BasicAgent()
140
+ except Exception as e:
141
+ print(f"Error instantiating agent: {e}")
142
+ return f"Error initializing agent: {e}", None
143
+ # 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)
144
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
145
+ print(agent_code)
146
+
147
+ # 2. Fetch Questions
148
+ print(f"Fetching questions from: {questions_url}")
149
+ try:
150
+ response = requests.get(questions_url, timeout=15)
151
+ response.raise_for_status()
152
+ questions_data = response.json()
153
+ if not questions_data:
154
+ print("Fetched questions list is empty.")
155
+ return "Fetched questions list is empty or invalid format.", None
156
+ print(f"Fetched {len(questions_data)} questions.")
157
+ except requests.exceptions.RequestException as e:
158
+ print(f"Error fetching questions: {e}")
159
+ return f"Error fetching questions: {e}", None
160
+ except requests.exceptions.JSONDecodeError as e:
161
+ print(f"Error decoding JSON response from questions endpoint: {e}")
162
+ print(f"Response text: {response.text[:500]}")
163
+ return f"Error decoding server response for questions: {e}", None
164
+ except Exception as e:
165
+ print(f"An unexpected error occurred fetching questions: {e}")
166
+ return f"An unexpected error occurred fetching questions: {e}", None
167
+
168
+ # 3. Run your Agent
169
+ results_log = []
170
+ answers_payload = []
171
+ print(f"Running agent on {len(questions_data)} questions...")
172
+ for item in questions_data:
173
+ task_id = item.get("task_id")
174
+ question_text = item.get("question")
175
+ file_name = item.get("file") # Check for file key
176
+ file_path = None
177
+
178
+ if not task_id or question_text is None:
179
+ print(f"Skipping item with missing task_id or question: {item}")
180
+ continue
181
+
182
+ # Download file if present
183
+ if file_name:
184
+ files_url = f"{api_url}/files/{task_id}"
185
+ print(f"Downloading file for task {task_id} from {files_url}")
186
+ try:
187
+ file_response = requests.get(files_url, timeout=30)
188
+ file_response.raise_for_status()
189
+ # Save file to a temp location
190
+ temp_dir = "downloaded_files"
191
+ os.makedirs(temp_dir, exist_ok=True)
192
+ file_path = os.path.join(temp_dir, file_name)
193
+ with open(file_path, "wb") as f:
194
+ f.write(file_response.content)
195
+ print(f"File saved to {file_path}")
196
+ except Exception as e:
197
+ print(f"Error downloading file for task {task_id}: {e}")
198
+ results_log.append(
199
+ {
200
+ "Task ID": task_id,
201
+ "Question": question_text,
202
+ "Submitted Answer": f"FILE DOWNLOAD ERROR: {e}",
203
+ }
204
+ )
205
+ continue
206
+
207
+ try:
208
+ submitted_answer = agent(question_text, file_path=file_path)
209
+ answers_payload.append(
210
+ {"task_id": task_id, "submitted_answer": submitted_answer}
211
+ )
212
+ results_log.append(
213
+ {
214
+ "Task ID": task_id,
215
+ "Question": question_text,
216
+ "Submitted Answer": submitted_answer,
217
+ }
218
+ )
219
+ except Exception as e:
220
+ print(f"Error running agent on task {task_id}: {e}")
221
+ results_log.append(
222
+ {
223
+ "Task ID": task_id,
224
+ "Question": question_text,
225
+ "Submitted Answer": f"AGENT ERROR: {e}",
226
+ }
227
+ )
228
+
229
+ if not answers_payload:
230
+ print("Agent did not produce any answers to submit.")
231
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
232
+
233
+ # 4. Prepare Submission
234
+ submission_data = {
235
+ "username": username.strip(),
236
+ "agent_code": agent_code,
237
+ "answers": answers_payload,
238
+ }
239
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
240
+ print(status_update)
241
+
242
+ # 5. Submit
243
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
244
+ try:
245
+ response = requests.post(submit_url, json=submission_data, timeout=60)
246
+ response.raise_for_status()
247
+ result_data = response.json()
248
+ final_status = (
249
+ f"Submission Successful!\n"
250
+ f"User: {result_data.get('username')}\n"
251
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
252
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
253
+ f"Message: {result_data.get('message', 'No message received.')}"
254
+ )
255
+ print("Submission successful.")
256
+ results_df = pd.DataFrame(results_log)
257
+ return final_status, results_df
258
+ except requests.exceptions.HTTPError as e:
259
+ error_detail = f"Server responded with status {e.response.status_code}."
260
+ try:
261
+ error_json = e.response.json()
262
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
263
+ except requests.exceptions.JSONDecodeError:
264
+ error_detail += f" Response: {e.response.text[:500]}"
265
+ status_message = f"Submission Failed: {error_detail}"
266
+ print(status_message)
267
+ results_df = pd.DataFrame(results_log)
268
+ return status_message, results_df
269
+ except requests.exceptions.Timeout:
270
+ status_message = "Submission Failed: The request timed out."
271
+ print(status_message)
272
+ results_df = pd.DataFrame(results_log)
273
+ return status_message, results_df
274
+ except requests.exceptions.RequestException as e:
275
+ status_message = f"Submission Failed: Network error - {e}"
276
+ print(status_message)
277
+ results_df = pd.DataFrame(results_log)
278
+ return status_message, results_df
279
+ except Exception as e:
280
+ status_message = f"An unexpected error occurred during submission: {e}"
281
+ print(status_message)
282
+ results_df = pd.DataFrame(results_log)
283
+ return status_message, results_df
284
+
285
+
286
+ # --- Build Gradio Interface using Blocks ---
287
+ with gr.Blocks() as demo:
288
+ gr.Markdown("# Basic Agent Evaluation Runner")
289
+ gr.Markdown(
290
+ """
291
+ **Instructions:**
292
+
293
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
294
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
295
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
296
+
297
+ ---
298
+ **Disclaimers:**
299
+ 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).
300
+ 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.
301
+ """
302
+ )
303
+
304
+ gr.LoginButton()
305
+
306
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
307
+
308
+ status_output = gr.Textbox(
309
+ label="Run Status / Submission Result", lines=5, interactive=False
310
+ )
311
+ # Removed max_rows=10 from DataFrame constructor
312
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
313
+
314
+ run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
315
+
316
+ if __name__ == "__main__":
317
+ print("\n" + "-" * 30 + " App Starting " + "-" * 30)
318
+ # Check for SPACE_HOST and SPACE_ID at startup for information
319
+ space_host_startup = os.getenv("SPACE_HOST")
320
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
321
+
322
+ if space_host_startup:
323
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
324
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
325
+ else:
326
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
327
+
328
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
329
+ print(f"✅ SPACE_ID found: {space_id_startup}")
330
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
331
+ print(
332
+ f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main"
333
+ )
334
+ else:
335
+ print(
336
+ "ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined."
337
+ )
338
+
339
+ print("-" * (60 + len(" App Starting ")) + "\n")
340
+
341
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
342
+ demo.launch(debug=True, share=False)