shsad commited on
Commit
5464362
·
verified ·
1 Parent(s): b3ad4af

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +178 -150
app.py CHANGED
@@ -1,195 +1,223 @@
1
  import os
2
  import gradio as gr
3
  import requests
4
- import inspect
5
  import pandas as pd
 
6
 
7
 
 
 
8
  # (Keep Constants as is)
9
  # --- Constants ---
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
 
 
 
12
  class BasicAgent:
13
  def __init__(self):
14
- print("BasicAgent initialized.")
15
- def __call__(self, question: str) -> str:
16
- print(f"Agent received question (first 50 chars): {question[:50]}...")
17
- fixed_answer = "This is a default answer."
18
- print(f"Agent returning fixed answer: {fixed_answer}")
19
- return fixed_answer
20
-
21
- def run_and_submit_all( profile: gr.OAuthProfile | None):
22
- """
23
- Fetches all questions, runs the BasicAgent on them, submits all answers,
24
- and displays the results.
25
- """
26
- # --- Determine HF Space Runtime URL and Repo URL ---
27
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
- if profile:
30
- username= f"{profile.username}"
31
- print(f"User logged in: {username}")
32
- else:
33
- print("User not logged in.")
34
- return "Please Login to Hugging Face with the button.", None
 
 
 
 
 
 
 
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  api_url = DEFAULT_API_URL
37
  questions_url = f"{api_url}/questions"
38
  submit_url = f"{api_url}/submit"
39
 
40
- # 1. Instantiate Agent ( modify this part to create your agent)
41
  try:
42
  agent = BasicAgent()
43
  except Exception as e:
44
- print(f"Error instantiating agent: {e}")
45
- return f"Error initializing agent: {e}", None
46
- # 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)
47
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
48
- print(agent_code)
49
-
50
- # 2. Fetch Questions
51
- print(f"Fetching questions from: {questions_url}")
52
  try:
53
- response = requests.get(questions_url, timeout=15)
54
- response.raise_for_status()
55
- questions_data = response.json()
56
- if not questions_data:
57
- print("Fetched questions list is empty.")
58
- return "Fetched questions list is empty or invalid format.", None
59
- print(f"Fetched {len(questions_data)} questions.")
60
- except requests.exceptions.RequestException as e:
61
- print(f"Error fetching questions: {e}")
62
- return f"Error fetching questions: {e}", None
63
- except requests.exceptions.JSONDecodeError as e:
64
- print(f"Error decoding JSON response from questions endpoint: {e}")
65
- print(f"Response text: {response.text[:500]}")
66
- return f"Error decoding server response for questions: {e}", None
67
  except Exception as e:
68
- print(f"An unexpected error occurred fetching questions: {e}")
69
- return f"An unexpected error occurred fetching questions: {e}", None
70
 
71
- # 3. Run your Agent
72
  results_log = []
73
  answers_payload = []
74
- print(f"Running agent on {len(questions_data)} questions...")
 
 
 
75
  for item in questions_data:
76
- task_id = item.get("task_id")
77
- question_text = item.get("question")
78
- if not task_id or question_text is None:
79
- print(f"Skipping item with missing task_id or question: {item}")
80
- continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  try:
82
- submitted_answer = agent(question_text)
 
 
 
 
83
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
84
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
 
 
85
  except Exception as e:
86
- print(f"Error running agent on task {task_id}: {e}")
87
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
88
 
89
- if not answers_payload:
90
- print("Agent did not produce any answers to submit.")
91
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
92
 
93
- # 4. Prepare Submission
94
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
95
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
96
- print(status_update)
97
-
 
 
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
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
150
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
151
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
152
- ---
153
- **Disclaimers:**
154
- 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).
155
- 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.
156
- """
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
- # Removed max_rows=10 from DataFrame constructor
165
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
166
-
167
- run_button.click(
168
  fn=run_and_submit_all,
169
- outputs=[status_output, results_table]
170
  )
171
 
172
-
173
  if __name__ == "__main__":
174
- print("\n" + "-"*30 + " App Starting " + "-"*30)
175
- # Check for SPACE_HOST and SPACE_ID at startup for information
176
- space_host_startup = os.getenv("SPACE_HOST")
177
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
178
-
179
- if space_host_startup:
180
- print(f"✅ SPACE_HOST found: {space_host_startup}")
181
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
182
- else:
183
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
184
-
185
- if space_id_startup: # Print repo URLs if SPACE_ID is found
186
- print(f"✅ SPACE_ID found: {space_id_startup}")
187
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
188
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
189
- else:
190
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
191
-
192
- print("-"*(60 + len(" App Starting ")) + "\n")
193
-
194
- print("Launching Gradio Interface for Basic Agent Evaluation...")
195
- demo.launch(debug=True, share=False)
 
1
  import os
2
  import gradio as gr
3
  import requests
4
+ # import inspect
5
  import pandas as pd
6
+ from typing import Optional
7
 
8
 
9
+ from smolagents import CodeAgent, LiteLLMModel, VisitWebpageTool, DuckDuckGoSearchTool
10
+
11
  # (Keep Constants as is)
12
  # --- Constants ---
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
 
15
+
16
+ # Define the Agent Class
17
  class BasicAgent:
18
  def __init__(self):
19
+ print("Initializing Mistral-Powered Agent...")
20
+
21
+ # --- 1. API KEY CHECK ---
22
+ mistral_key = os.getenv("MISTRAL_API_KEY")
23
+ if not mistral_key:
24
+ # Agar Mistral nahi hai to error mat do, Qwen try karo (Fallback)
25
+ print("Mistral Key not found. Please set MISTRAL_API_KEY for best results.")
26
+ # Fallback logic if needed, but for now we raise error to alert user
27
+ raise ValueError("MISTRAL_API_KEY missing!")
28
+
29
+ # --- 2. MODEL SETUP ---
30
+ model = LiteLLMModel(
31
+ model_id="mistral/mistral-large-latest",
32
+ api_key=mistral_key
33
+ )
34
+
35
+ # --- 3. TOOLS ---
36
+ search_tool = DuckDuckGoSearchTool()
37
+ visit_tool = VisitWebpageTool()
38
+
39
+ # --- 4. CREATE AGENT ---
40
+ self.agent = CodeAgent(
41
+ tools=[search_tool, visit_tool],
42
+ model=model,
43
+ additional_authorized_imports=[
44
+ "numpy", "pandas", "math", "datetime", "re", "csv", "json", "random", "itertools"
45
+ ],
46
+ max_steps=25,
47
+ verbosity_level=2,
48
+ name="Mistral_Gaia_Solver"
49
+ )
50
 
51
+ def __call__(self, question: str, file_path: str = None) -> str:
52
+ # Prompt Logic
53
+ prompt = f"""
54
+ Task: {question}
55
+
56
+ INSTRUCTIONS:
57
+ 1. Use Python code to solve this step-by-step.
58
+ 2. If a file is attached, YOU MUST READ IT using Python immediately.
59
+ 3. Output ONLY the final answer value.
60
+ """
61
+
62
+ if file_path:
63
+ prompt += f"\n\n ATTACHED FILE: '{file_path}'"
64
 
65
+ try:
66
+ print(f" Agent working on: {question[:30]}...")
67
+ response = self.agent.run(prompt)
68
+
69
+ # Output Cleaning
70
+ final_answer = str(response).replace("Final Answer:", "").strip()
71
+
72
+ if final_answer.endswith(".") and len(final_answer) < 20:
73
+ final_answer = final_answer[:-1]
74
+
75
+ return final_answer
76
+
77
+ except Exception as e:
78
+ print(f" Error in Agent: {e}")
79
+ return f"Error: {e}"
80
+
81
+ # Evaluation
82
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
83
+ """
84
+ 1. Fetch questions.
85
+ 2. Download the file (previously missing).
86
+ 3. Run the agent.
87
+ 4. Submit the results.
88
+ """
89
+
90
+ # --- A. LOGIN CHECK ---
91
+ if profile is None:
92
+ return " Please Login to Hugging Face with the button above.", None
93
+
94
+ username = profile.username
95
+ space_id = os.getenv("SPACE_ID")
96
+
97
+ # URLs
98
  api_url = DEFAULT_API_URL
99
  questions_url = f"{api_url}/questions"
100
  submit_url = f"{api_url}/submit"
101
 
102
+ # --- B. INIT AGENT ---
103
  try:
104
  agent = BasicAgent()
105
  except Exception as e:
106
+ return f" Agent Init Error: {e}", None
107
+
108
+ agent_code_link = f"https://huggingface.co/spaces/{space_id}/tree/main"
109
+ print(f"🔗 Code Link: {agent_code_link}")
110
+
111
+ # --- C. FETCH QUESTIONS ---
 
 
112
  try:
113
+ print(" Fetching questions...")
114
+ questions_data = requests.get(questions_url).json()
 
 
 
 
 
 
 
 
 
 
 
 
115
  except Exception as e:
116
+ return f"Error fetching questions: {e}", None
 
117
 
 
118
  results_log = []
119
  answers_payload = []
120
+
121
+ print(f" Starting processing of {len(questions_data)} questions...")
122
+
123
+ # --- D. PROCESSING LOOP ---
124
  for item in questions_data:
125
+ task_id = item["task_id"]
126
+ question_text = item["question"]
127
+ file_name = item.get("file_name") # GAIA tasks often have files
128
+
129
+ print(f"\n--- Processing Task {task_id} ---")
130
+
131
+ local_file_path = None
132
+
133
+ # 1. DOWNLOAD FILE (CRITICAL STEP)
134
+ if file_name:
135
+ print(f" Downloading file: {file_name}")
136
+ try:
137
+ file_url = f"{api_url}/files/{task_id}"
138
+ file_resp = requests.get(file_url, timeout=10)
139
+
140
+ if file_resp.status_code == 200:
141
+ with open(file_name, "wb") as f:
142
+ f.write(file_resp.content)
143
+ local_file_path = file_name
144
+ print(" File downloaded successfully.")
145
+ else:
146
+ print(f" File download failed (Status {file_resp.status_code})")
147
+ except Exception as e:
148
+ print(f" File download error: {e}")
149
+
150
+ # 2. RUN AGENT
151
  try:
152
+ # The agent receives the file path as input.
153
+ submitted_answer = agent(question_text, file_path=local_file_path)
154
+
155
+ print(f" Final Answer: {submitted_answer}")
156
+
157
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
158
+ results_log.append({
159
+ "Task ID": task_id,
160
+ "Question": question_text,
161
+ "File": file_name if file_name else "None",
162
+ "Answer": submitted_answer
163
+ })
164
+
165
  except Exception as e:
166
+ results_log.append({"Task ID": task_id, "Error": str(e)})
 
167
 
168
+ # 3. CLEANUP (File delete karo)
169
+ if local_file_path and os.path.exists(local_file_path):
170
+ os.remove(local_file_path)
171
 
172
+ # --- E. SUBMIT ---
173
+ print("Submitting answers to leaderboard...")
174
+ submission_data = {
175
+ "username": username,
176
+ "agent_code": agent_code_link,
177
+ "answers": answers_payload
178
+ }
179
 
 
 
180
  try:
181
  response = requests.post(submit_url, json=submission_data, timeout=60)
182
+ res_json = response.json()
183
+
184
+ score = res_json.get('score', 0)
185
+ correct = res_json.get('correct_count', 0)
186
+
187
+ status_msg = (
188
+ f"Submission Done!\n"
189
+ f"User: {username}\n"
190
+ f"Score: {score}%\n"
191
+ f"Correct: {correct}"
192
  )
193
+ return status_msg, pd.DataFrame(results_log)
194
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  except Exception as e:
196
+ return f"Submission Failed: {e}", pd.DataFrame(results_log)
 
 
 
197
 
198
 
199
+ # --- GRADIO UI ---
200
  with gr.Blocks() as demo:
201
+ gr.Markdown("# 🤖 GAIA Agent Solver (Mistral + Files Fix)")
202
+ gr.Markdown("""
203
+ **Instruction:**
204
+ 1. Login via Hugging Face button.
205
+ 2. Click 'Run Evaluation'.
206
+ 3. Wait (it takes time to process all questions).
207
+ """)
208
+
 
 
 
 
 
 
209
  gr.LoginButton()
210
+
211
+ run_btn = gr.Button("Run Evaluation & Submit", variant="primary")
212
+
213
+ status_out = gr.Textbox(label="Status")
214
+ results_df = gr.DataFrame(label="Detailed Logs")
215
+
216
+ run_btn.click(
 
217
  fn=run_and_submit_all,
218
+ outputs=[status_out, results_df]
219
  )
220
 
 
221
  if __name__ == "__main__":
222
+ # Enabling the queue eliminates timeout issues.
223
+ demo.queue(default_concurrency_limit=1).launch()