ramanand-r commited on
Commit
35af4bb
Β·
verified Β·
1 Parent(s): 14ba390

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +136 -75
app.py CHANGED
@@ -1,109 +1,170 @@
1
  import os
2
  import requests
3
  import json
4
- from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiClient
 
5
 
6
- # --- CONFIGURATION ---
7
  API_BASE_URL = "https://agents-course-unit4-scoring.hf.space"
8
- # Ensure your space code link looks exactly like this (.../tree/main)
9
- HF_USERNAME = "your_hf_username"
10
- CODE_LINK = f"https://huggingface.co/spaces/{HF_USERNAME}/Final_Assignment_Template/tree/main"
11
 
12
- # --- ENGINE SETUP ---
13
  search_tool = DuckDuckGoSearchTool()
14
  agent = CodeAgent(
15
- model=HfApiClient(),
16
  tools=[search_tool],
17
- additional_authorized_imports=["pandas", "numpy", "requests", "bs4", "openpyxl", "pypdf"]
18
  )
19
 
20
- def fetch_questions():
21
- """Retrieve the 20 filtered evaluation questions."""
22
- response = requests.get(f"{API_BASE_URL}/questions")
 
23
  response.raise_for_status()
24
- return response.json() # Returns a list of dicts with task_id, question, etc.
25
 
26
- def download_file_if_needed(task_id: str, file_name: str):
27
- """Downloads an evaluation attachment if present and returns the local path."""
28
  if not file_name:
29
  return None
30
 
31
- local_path = f"./downloads/{task_id}_{file_name}"
32
- os.makedirs("./downloads", exist_ok=True)
 
33
 
 
 
 
 
34
  url = f"{API_BASE_URL}/files/{task_id}"
35
  response = requests.get(url, stream=True)
36
 
37
  if response.status_code == 200:
38
- with open(local_path, 'wb') as f:
39
  for chunk in response.iter_content(chunk_size=8192):
40
- f.write(chunk)
41
- print(f"πŸ“₯ Downloaded asset for Task {task_id}: {local_path}")
42
- return local_path
43
  else:
44
- print(f"⚠️ No downloadable file asset found for Task {task_id} (Status {response.status_code})")
45
  return None
46
 
47
- def run_evaluation_pipeline():
48
- questions = fetch_questions()
49
- submitted_answers = []
50
-
51
- # Strictly instruct the agent to avoid conversational text
52
- formatting_instructions = (
53
- "\n\nCRITICAL OUTCOME INSTRUCTION: Output ONLY the literal final string answer. "
54
- "Do NOT prefix with 'FINAL ANSWER:', do NOT use markdown code blocks for text, "
55
- "and do NOT include conversational explanations. Your complete response must contain "
56
- "only the raw value matching the requested format."
57
- )
58
-
59
- for item in questions:
60
- task_id = item['task_id']
61
- raw_question = item['question']
62
- # Level 1 items occasionally reference attached data sheets
63
- file_name = item.get('file_name', None)
64
-
65
- print(f"\nπŸš€ Processing Task ID: {task_id}")
66
 
67
- # Pull any related assets down locally before execution
68
- local_file_path = download_file_if_needed(task_id, file_name)
 
 
 
 
 
69
 
70
- full_prompt = raw_question
71
- if local_file_path:
72
- full_prompt += f"\nNote: The file provided for this task has been downloaded locally to: {local_file_path}"
 
 
73
 
74
- full_prompt += formatting_instructions
75
-
76
- try:
77
- # Execute agent reasoning loop
78
- raw_output = agent.run(full_prompt)
79
- final_answer = str(raw_output).strip()
80
 
81
- # Safe fallbacks if formatting leaks through
82
- if "the answer is" in final_answer.lower():
83
- final_answer = final_answer.lower().split("the answer is")[-1].strip(" :.`\"")
84
-
85
- print(f"🎯 Cleaned Agent Result: '{final_answer}'")
86
 
87
- submitted_answers.append({
88
- "task_id": task_id,
89
- "submitted_answer": final_answer
90
- })
 
91
 
92
- except Exception as e:
93
- print(f"❌ Error processing task {task_id}: {e}")
94
- submitted_answers.append({
95
- "task_id": task_id,
96
- "submitted_answer": "ERROR_FALLBACK"
97
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
- # --- PAYLOAD GENERATION FOR POST /SUBMIT ---
100
- payload = {
101
- "username": HF_USERNAME,
102
- "agent_code": CODE_LINK,
103
- "answers": submitted_answers
104
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
- print("\nπŸ“¦ Built Submission Payload successfully.")
107
- return payload
 
 
 
 
 
108
 
109
- # execution_payload = run_evaluation_pipeline()
 
 
1
  import os
2
  import requests
3
  import json
4
+ import gradio as ui
5
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
6
 
7
+ # --- SCORING CONFIGURATION ---
8
  API_BASE_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
 
9
 
10
+ # Initialize core agent dependencies
11
  search_tool = DuckDuckGoSearchTool()
12
  agent = CodeAgent(
13
+ model=HfApiModel(), # Serverless inference engine
14
  tools=[search_tool],
15
+ additional_authorized_imports=["pandas", "numpy", "requests", "bs4", "openpyxl", "pypdf", "PIL"]
16
  )
17
 
18
+ def fetch_evaluation_questions():
19
+ """Fetches the 20 level 1 filtered validation questions from the course API."""
20
+ url = f"{API_BASE_URL}/questions"
21
+ response = requests.get(url)
22
  response.raise_for_status()
23
+ return response.json()
24
 
25
+ def download_task_file(task_id: str, file_name: str):
26
+ """Downloads an evaluation asset if present and maps it to a local workspace path."""
27
  if not file_name:
28
  return None
29
 
30
+ local_directory = "./downloads"
31
+ os.makedirs(local_directory, exist_ok=True)
32
+ local_file_path = os.path.join(local_directory, f"{task_id}_{file_name}")
33
 
34
+ # Don't re-download if file already exists locally
35
+ if os.path.exists(local_file_path):
36
+ return local_file_path
37
+
38
  url = f"{API_BASE_URL}/files/{task_id}"
39
  response = requests.get(url, stream=True)
40
 
41
  if response.status_code == 200:
42
+ with open(local_file_path, 'wb') as file:
43
  for chunk in response.iter_content(chunk_size=8192):
44
+ file.write(chunk)
45
+ print(f"πŸ“₯ Asset downloaded successfully for Task {task_id} -> {local_file_path}")
46
+ return local_file_path
47
  else:
48
+ print(f"ℹ️ No download asset found or status code error for Task {task_id}: {response.status_code}")
49
  return None
50
 
51
+ def process_agent_evaluation(hf_username: str, profile_code_url: str, progress=ui.Progress()):
52
+ """Iterates through all evaluation steps, manages files, runs agent queries, and returns results."""
53
+ if not hf_username.strip() or not profile_code_url.strip():
54
+ return "❌ Error: Please fill in both your Hugging Face Username and your Public Space Code Link before submitting."
55
+
56
+ try:
57
+ progress(0, desc="Fetching GAIA evaluation questions...")
58
+ questions = fetch_evaluation_questions()
59
+ submitted_answers = []
 
 
 
 
 
 
 
 
 
 
60
 
61
+ # Strict context formatting boundary to prevent verbose conversational leaks
62
+ formatting_instructions = (
63
+ "\n\nCRITICAL OUTCOME INSTRUCTION: Output ONLY the literal final string answer. "
64
+ "Do NOT prefix with 'FINAL ANSWER:', do NOT use markdown code blocks for text, "
65
+ "and do NOT include conversational explanations. Your complete response must contain "
66
+ "only the raw value matching the requested format."
67
+ )
68
 
69
+ total_questions = len(questions)
70
+ for index, item in enumerate(questions):
71
+ task_id = item['task_id']
72
+ raw_question = item['question']
73
+ file_name = item.get('file_name', None)
74
 
75
+ progress((index / total_questions), desc=f"Evaluating Task {index + 1}/{total_questions} (ID: {task_id})...")
 
 
 
 
 
76
 
77
+ # Look up and handle data attachments
78
+ local_file_path = download_task_file(task_id, file_name)
 
 
 
79
 
80
+ full_prompt = raw_question
81
+ if local_file_path:
82
+ full_prompt += f"\nNote: The file provided for this task has been downloaded locally to: {local_file_path}"
83
+
84
+ full_prompt += formatting_instructions
85
 
86
+ try:
87
+ # Fire up the agent loop
88
+ raw_output = agent.run(full_prompt)
89
+ final_answer = str(raw_output).strip()
90
+
91
+ # Cleanup parser fallback if agent leaked phrases
92
+ if "the answer is" in final_answer.lower():
93
+ final_answer = final_answer.lower().split("the answer is")[-1].strip(" :.`\"*")
94
+
95
+ submitted_answers.append({
96
+ "task_id": task_id,
97
+ "submitted_answer": final_answer
98
+ })
99
+ print(f"βœ… Clean Answer Logged [{task_id}]: {final_answer}")
100
+
101
+ except Exception as e:
102
+ print(f"❌ Execution crash on task {task_id}: {e}")
103
+ submitted_answers.append({
104
+ "task_id": task_id,
105
+ "submitted_answer": "ERROR_FALLBACK"
106
+ })
107
+
108
+ # --- POST SUBMISSION PAYLOAD ---
109
+ progress(0.95, desc="Transmitting data package to student leaderboard...")
110
+ payload = {
111
+ "username": hf_username.strip(),
112
+ "agent_code": profile_code_url.strip(),
113
+ "answers": submitted_answers
114
+ }
115
+
116
+ headers = {"Content-Type": "application/json"}
117
+ submit_url = f"{API_BASE_URL}/submit"
118
+
119
+ response = requests.post(submit_url, json=payload, headers=headers)
120
+
121
+ if response.status_code == 200:
122
+ result_data = response.json()
123
+ score = result_data.get("score", 0)
124
+ percentage = score * 100
125
 
126
+ status_summary = (
127
+ f"### πŸŽ‰ Evaluation Complete!\n\n"
128
+ f"**πŸ“Š Final Score:** {percentage:.1f}% ({int(score * total_questions)} / {total_questions} Correct)\n\n"
129
+ f"**πŸ’¬ API Server Response:** {result_data.get('message', 'Submission saved successfully!')}\n\n"
130
+ f"Check your standing on the leaderboard right now!"
131
+ )
132
+ return status_summary
133
+ else:
134
+ return f"❌ Submission Error (HTTP {response.status_code}): {response.text}"
135
+
136
+ except Exception as general_error:
137
+ return f"❌ A structural runtime execution crash occurred: {str(general_error)}"
138
+
139
+ # --- GRADIO WEB USER INTERFACE ---
140
+ with ui.Blocks(theme=ui.themes.Soft()) as interface:
141
+ ui.Markdown("# πŸ† Unit 4: GAIA Benchmark Agent Certification Engine")
142
+ ui.Markdown(
143
+ "Welcome! This portal coordinates your custom `smolagents` architecture against the "
144
+ "20 curated Level-1 GAIA tasks. Fill in your identification markers below to run evaluation and sync metrics."
145
+ )
146
+
147
+ with ui.Row():
148
+ input_username = ui.Textbox(
149
+ label="Hugging Face Username",
150
+ placeholder="e.g., dev_pioneer",
151
+ lines=1
152
+ )
153
+ input_code_link = ui.Textbox(
154
+ label="Public Space Repository Link (agent_code URL)",
155
+ placeholder="https://huggingface.co/spaces/your_username/your_space/tree/main",
156
+ lines=1
157
+ )
158
+
159
+ evaluate_button = ui.Button("πŸš€ Start Evaluation & Submit Answers", variant="primary")
160
 
161
+ output_display = ui.Markdown(value="πŸ’‘ Provide your workspace metrics above and click run to engage the loop.")
162
+
163
+ evaluate_button.click(
164
+ fn=process_agent_evaluation,
165
+ inputs=[input_username, input_code_link],
166
+ outputs=output_display
167
+ )
168
 
169
+ if __name__ == "__main__":
170
+ interface.launch()