Ankit Anand commited on
Commit
e8d474f
·
1 Parent(s): c89ff86

Final Agent Code

Browse files
Files changed (1) hide show
  1. app.py +100 -148
app.py CHANGED
@@ -1,31 +1,83 @@
1
  import os
2
-
3
- import gradio as gr
4
- import pandas as pd
5
  import requests
 
 
6
 
7
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
8
 
9
- class BasicAgent:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  def __init__(self):
11
- print("BasicAgent initialized.")
12
- print("BasicAgent setup complete.")
13
-
14
- def __call__(self, question: str) -> str:
15
- print(f"Agent received question (first 50 chars): {question[:50]}...")
16
- fixed_answer = "This is a default answer."
17
- print(f"Agent returning fixed answer: {fixed_answer}")
18
- return fixed_answer
19
-
20
- class GeneralAIAssistant(BasicAgent):
21
- def __call__(self, question: str) -> str:
22
- thoughts = f"Thinking about the question: {question}"
23
- answer = self.answer_question(question)
24
- response = f"{thoughts}\nFINAL ANSWER: {answer}"
25
- return response
26
-
27
- def answer_question(self, question: str) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  q = question.lower()
 
29
  if "capital of france" in q:
30
  return "Paris"
31
  if "12 * 8" in q or "12 times 8" in q:
@@ -36,158 +88,58 @@ class GeneralAIAssistant(BasicAgent):
36
  return "100"
37
  return "unknown"
38
 
39
- def run_and_submit_all(username):
40
- space_id = os.getenv("SPACE_ID")
41
  if not username or not username.strip():
42
  return "Please enter your username.", None
43
-
44
- api_url = DEFAULT_API_URL
45
- questions_url = f"{api_url}/questions"
46
- submit_url = f"{api_url}/submit"
47
-
48
  try:
49
- agent = GeneralAIAssistant()
50
  except Exception as e:
51
- print(f"Error instantiating agent: {e}")
52
- return f"Error initializing agent: {e}", None
53
-
54
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "N/A"
55
- print(agent_code)
56
-
57
- print(f"Fetching questions from: {questions_url}")
58
- try:
59
- response = requests.get(questions_url, timeout=15)
60
- response.raise_for_status()
61
- questions_data = response.json()
62
- if not questions_data:
63
- print("Fetched questions list is empty.")
64
- return "Fetched questions list is empty or invalid format.", None
65
- print(f"Fetched {len(questions_data)} questions.")
66
- except requests.exceptions.RequestException as e:
67
- print(f"Error fetching questions: {e}")
68
- return f"Error fetching questions: {e}", None
69
- except requests.exceptions.JSONDecodeError as e:
70
- print(f"Error decoding JSON response from questions endpoint: {e}")
71
- print(f"Response text: {response.text[:500]}")
72
- return f"Error decoding server response for questions: {e}", None
73
- except Exception as e:
74
- print(f"An unexpected error occurred fetching questions: {e}")
75
- return f"An unexpected error occurred fetching questions: {e}", None
76
 
 
77
  results_log = []
78
- answers_payload = []
79
- print(f"Running agent on {len(questions_data)} questions...")
80
- for item in questions_data:
81
- task_id = item.get("task_id")
82
- question_text = item.get("question")
83
- if not task_id or question_text is None:
84
- print(f"Skipping item with missing task_id or question: {item}")
85
- continue
86
- try:
87
- submitted_answer = agent(question_text)
88
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
89
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
90
- except Exception as e:
91
- print(f"Error running agent on task {task_id}: {e}")
92
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
93
-
94
- if not answers_payload:
95
- print("Agent did not produce any answers to submit.")
96
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
97
-
98
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
99
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
100
- print(status_update)
101
-
102
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
103
- try:
104
- response = requests.post(submit_url, json=submission_data, timeout=60)
105
- response.raise_for_status()
106
- result_data = response.json()
107
- final_status = (
108
- f"Submission Successful!\n"
109
- f"User: {result_data.get('username')}\n"
110
- f"Overall Score: {result_data.get('score', 'N/A')}% "
111
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
112
- f"Message: {result_data.get('message', 'No message received.')}"
113
- )
114
- print("Submission successful.")
115
- results_df = pd.DataFrame(results_log)
116
- return final_status, results_df
117
- except requests.exceptions.HTTPError as e:
118
- error_detail = f"Server responded with status {e.response.status_code}."
119
- try:
120
- error_json = e.response.json()
121
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
122
- except requests.exceptions.JSONDecodeError:
123
- error_detail += f" Response: {e.response.text[:500]}"
124
- status_message = f"Submission Failed: {error_detail}"
125
- print(status_message)
126
- results_df = pd.DataFrame(results_log)
127
- return status_message, results_df
128
- except requests.exceptions.Timeout:
129
- status_message = "Submission Failed: The request timed out."
130
- print(status_message)
131
- results_df = pd.DataFrame(results_log)
132
- return status_message, results_df
133
- except requests.exceptions.RequestException as e:
134
- status_message = f"Submission Failed: Network error - {e}"
135
- print(status_message)
136
- results_df = pd.DataFrame(results_log)
137
- return status_message, results_df
138
- except Exception as e:
139
- status_message = f"An unexpected error occurred during submission: {e}"
140
- print(status_message)
141
- results_df = pd.DataFrame(results_log)
142
- return status_message, results_df
143
 
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. Enter your username below.
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
  username_input = gr.Textbox(label="Username", placeholder="Enter your username here")
 
 
162
  run_button = gr.Button("Run Evaluation & Submit All Answers")
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(
167
  fn=run_and_submit_all,
168
- inputs=[username_input],
169
  outputs=[status_output, results_table]
170
  )
171
 
172
  if __name__ == "__main__":
173
  print("\n" + "-" * 30 + " App Starting " + "-" * 30)
174
- space_host_startup = os.getenv("SPACE_HOST")
175
- space_id_startup = os.getenv("SPACE_ID")
176
-
177
- if space_host_startup:
178
- print(f"✅ SPACE_HOST found: {space_host_startup}")
179
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
180
- else:
181
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
182
-
183
- if space_id_startup:
184
- print(f"✅ SPACE_ID found: {space_id_startup}")
185
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
186
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
187
- else:
188
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
189
-
190
- print("-" * (60 + len(" App Starting ")) + "\n")
191
-
192
- print("Launching Gradio Interface for Basic Agent Evaluation...")
193
  demo.launch(debug=True, share=False)
 
1
  import os
2
+ import json
 
 
3
  import requests
4
+ import pandas as pd
5
+ from typing import Optional, List, Dict
6
 
7
+ import gradio as gr
8
 
9
+ GAIA_BASE_URL = "https://huggingface.co/datasets/gaia-benchmark/GAIA/resolve/main"
10
+ GAIA_LEVELS = ["level1", "level2", "level3"]
11
+ GAIA_SPLITS = ["dev", "test"]
12
+
13
+ # Optional: Use transformers/torchvision for image analysis if available
14
+ try:
15
+ from PIL import Image
16
+ from io import BytesIO
17
+ import torch
18
+ from transformers import BlipProcessor, BlipForConditionalGeneration
19
+ HAS_VISION = True
20
+ except ImportError:
21
+ HAS_VISION = False
22
+
23
+ def download_gaia_metadata(level: str, split: str) -> List[Dict]:
24
+ url = f"{GAIA_BASE_URL}/{level}/{split}/metadata.jsonl"
25
+ response = requests.get(url)
26
+ response.raise_for_status()
27
+ return [json.loads(line) for line in response.text.strip().splitlines()]
28
+
29
+ class GeneralAIAssistant:
30
  def __init__(self):
31
+ if HAS_VISION:
32
+ self.vision_processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
33
+ self.vision_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
34
+ else:
35
+ self.vision_processor = None
36
+ self.vision_model = None
37
+
38
+ def __call__(self, question: str, file_url: Optional[str] = None) -> str:
39
+ steps = self.plan_steps(question, file_url)
40
+ results = []
41
+ for step in steps:
42
+ results.append(self.execute_step(step))
43
+ structured_response = {
44
+ "question": question,
45
+ "steps": steps,
46
+ "results": results,
47
+ "final_answer": results[-1] if results else "unknown"
48
+ }
49
+ return json.dumps(structured_response, indent=2)
50
+
51
+ def plan_steps(self, question, file_url):
52
+ steps = []
53
+ if file_url:
54
+ steps.append({"action": "analyze_file", "file_url": file_url})
55
+ steps.append({"action": "answer_question", "question": question})
56
+ return steps
57
+
58
+ def execute_step(self, step):
59
+ if step["action"] == "analyze_file":
60
+ return self.analyze_file(step["file_url"])
61
+ elif step["action"] == "answer_question":
62
+ return self.answer_question(step["question"])
63
+ return "unknown"
64
+
65
+ def analyze_file(self, file_url):
66
+ if not HAS_VISION:
67
+ return "Image analysis unavailable (missing dependencies)."
68
+ try:
69
+ response = requests.get(file_url)
70
+ img = Image.open(BytesIO(response.content)).convert("RGB")
71
+ inputs = self.vision_processor(images=img, return_tensors="pt")
72
+ out = self.vision_model.generate(**inputs)
73
+ caption = self.vision_processor.decode(out[0], skip_special_tokens=True)
74
+ return f"Image caption: {caption}"
75
+ except Exception as e:
76
+ return f"File analysis failed: {e}"
77
+
78
+ def answer_question(self, question):
79
  q = question.lower()
80
+ # Example: simple logic for some questions
81
  if "capital of france" in q:
82
  return "Paris"
83
  if "12 * 8" in q or "12 times 8" in q:
 
88
  return "100"
89
  return "unknown"
90
 
91
+ def run_and_submit_all(username, level, split):
 
92
  if not username or not username.strip():
93
  return "Please enter your username.", None
 
 
 
 
 
94
  try:
95
+ questions = download_gaia_metadata(level, split)
96
  except Exception as e:
97
+ return f"Failed to download GAIA metadata: {e}", None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
+ agent = GeneralAIAssistant()
100
  results_log = []
101
+ for item in questions:
102
+ q = item.get("question")
103
+ file_url = None
104
+ if "file_name" in item and item["file_name"]:
105
+ file_url = f"{GAIA_BASE_URL}/{level}/{split}/{item['file_name']}"
106
+ answer = agent(q, file_url)
107
+ results_log.append({
108
+ "Task ID": item.get("task_id"),
109
+ "Question": q,
110
+ "Submitted Answer": answer
111
+ })
112
+ results_df = pd.DataFrame(results_log)
113
+ return f"Processed {len(results_log)} questions for {username}.", results_df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
  with gr.Blocks() as demo:
116
+ gr.Markdown("# GAIA Multimodal Agent Evaluation Runner")
117
  gr.Markdown(
118
  """
119
  **Instructions:**
120
+ 1. Select GAIA level and split.
121
+ 2. Enter your username.
122
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, and see the results.
 
123
 
124
  ---
125
+ This agent is a template. Expand the agent logic for better performance and multimodal reasoning.
 
 
126
  """
127
  )
128
 
129
  username_input = gr.Textbox(label="Username", placeholder="Enter your username here")
130
+ level_dropdown = gr.Dropdown(choices=GAIA_LEVELS, label="GAIA Level", value="level1")
131
+ split_dropdown = gr.Dropdown(choices=GAIA_SPLITS, label="GAIA Split", value="dev")
132
  run_button = gr.Button("Run Evaluation & Submit All Answers")
133
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
134
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
135
 
136
  run_button.click(
137
  fn=run_and_submit_all,
138
+ inputs=[username_input, level_dropdown, split_dropdown],
139
  outputs=[status_output, results_table]
140
  )
141
 
142
  if __name__ == "__main__":
143
  print("\n" + "-" * 30 + " App Starting " + "-" * 30)
144
+ print("Launching Gradio Interface for GAIA Agent Evaluation...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  demo.launch(debug=True, share=False)