anssio commited on
Commit
d1a9284
·
verified ·
1 Parent(s): 241d57a

Delete agent.py

Browse files
Files changed (1) hide show
  1. agent.py +0 -206
agent.py DELETED
@@ -1,206 +0,0 @@
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)