Omachoko commited on
Commit
c7fc100
·
1 Parent(s): 997480e

Conform app.py to required evaluation runner design

Browse files
Files changed (1) hide show
  1. app.py +163 -11
app.py CHANGED
@@ -9,20 +9,151 @@ import gradio as gr
9
  import json
10
  from datetime import datetime
11
  from gaia_agent import ModularGAIAAgent
 
 
 
12
 
13
  agent = ModularGAIAAgent()
14
 
15
- def run_api_questions():
16
- results = agent.run(from_api=True)
17
- answers = ""
18
- for r in results:
19
- answers += f"Task ID: {r['task_id']}\nAnswer: {r['answer']}\nReasoning Trace: {' | '.join(r['reasoning_trace'])}\n\n"
20
- return answers
21
 
22
- def run_manual_question(question):
23
- qobj = {"task_id": "manual", "question": question, "file_name": ""}
24
- answer, trace = agent.answer_question(qobj)
25
- return answer, "\n".join(trace)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  def show_help():
28
  return (
@@ -74,4 +205,25 @@ with demo:
74
  help_md = gr.Markdown(show_help())
75
 
76
  if __name__ == "__main__":
77
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  import json
10
  from datetime import datetime
11
  from gaia_agent import ModularGAIAAgent
12
+ import requests
13
+ import inspect
14
+ import pandas as pd
15
 
16
  agent = ModularGAIAAgent()
17
 
18
+ # (Keep Constants as is)
19
+ # --- Constants ---
20
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
 
21
 
22
+ # --- Basic Agent Definition ---
23
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
24
+ class BasicAgent:
25
+ def __init__(self):
26
+ print("BasicAgent (GAIA Modular Agent) initialized.")
27
+ self.agent = ModularGAIAAgent()
28
+ def __call__(self, question: str) -> str:
29
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
30
+ try:
31
+ answer, trace = self.agent.answer_question({"task_id": "manual", "question": question, "file_name": ""})
32
+ print(f"Agent returning answer: {answer}")
33
+ return answer
34
+ except Exception as e:
35
+ print(f"Agent error: {e}")
36
+ return f"AGENT ERROR: {e}"
37
+
38
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
39
+ """
40
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
41
+ and displays the results.
42
+ """
43
+ # --- Determine HF Space Runtime URL and Repo URL ---
44
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
45
+
46
+ if profile:
47
+ username= f"{profile.username}"
48
+ print(f"User logged in: {username}")
49
+ else:
50
+ print("User not logged in.")
51
+ return "Please Login to Hugging Face with the button.", None
52
+
53
+ api_url = DEFAULT_API_URL
54
+ questions_url = f"{api_url}/questions"
55
+ submit_url = f"{api_url}/submit"
56
+
57
+ # 1. Instantiate Agent ( modify this part to create your agent)
58
+ try:
59
+ agent = BasicAgent()
60
+ except Exception as e:
61
+ print(f"Error instantiating agent: {e}")
62
+ return f"Error initializing agent: {e}", None
63
+ # 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)
64
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
65
+ print(agent_code)
66
+
67
+ # 2. Fetch Questions
68
+ print(f"Fetching questions from: {questions_url}")
69
+ try:
70
+ response = requests.get(questions_url, timeout=15)
71
+ response.raise_for_status()
72
+ questions_data = response.json()
73
+ if not questions_data:
74
+ print("Fetched questions list is empty.")
75
+ return "Fetched questions list is empty or invalid format.", None
76
+ print(f"Fetched {len(questions_data)} questions.")
77
+ except requests.exceptions.RequestException as e:
78
+ print(f"Error fetching questions: {e}")
79
+ return f"Error fetching questions: {e}", None
80
+ except requests.exceptions.JSONDecodeError as e:
81
+ print(f"Error decoding JSON response from questions endpoint: {e}")
82
+ print(f"Response text: {response.text[:500]}")
83
+ return f"Error decoding server response for questions: {e}", None
84
+ except Exception as e:
85
+ print(f"An unexpected error occurred fetching questions: {e}")
86
+ return f"An unexpected error occurred fetching questions: {e}", None
87
+
88
+ # 3. Run your Agent
89
+ results_log = []
90
+ answers_payload = []
91
+ print(f"Running agent on {len(questions_data)} questions...")
92
+ for item in questions_data:
93
+ task_id = item.get("task_id")
94
+ question_text = item.get("question")
95
+ if not task_id or question_text is None:
96
+ print(f"Skipping item with missing task_id or question: {item}")
97
+ continue
98
+ try:
99
+ submitted_answer = agent(question_text)
100
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
101
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
102
+ except Exception as e:
103
+ print(f"Error running agent on task {task_id}: {e}")
104
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
105
+
106
+ if not answers_payload:
107
+ print("Agent did not produce any answers to submit.")
108
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
109
+
110
+ # 4. Prepare Submission
111
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
112
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
113
+ print(status_update)
114
+
115
+ # 5. Submit
116
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
117
+ try:
118
+ response = requests.post(submit_url, json=submission_data, timeout=60)
119
+ response.raise_for_status()
120
+ result_data = response.json()
121
+ final_status = (
122
+ f"Submission Successful!\n"
123
+ f"User: {result_data.get('username')}\n"
124
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
125
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
126
+ f"Message: {result_data.get('message', 'No message received.')}"
127
+ )
128
+ print("Submission successful.")
129
+ results_df = pd.DataFrame(results_log)
130
+ return final_status, results_df
131
+ except requests.exceptions.HTTPError as e:
132
+ error_detail = f"Server responded with status {e.response.status_code}."
133
+ try:
134
+ error_json = e.response.json()
135
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
136
+ except requests.exceptions.JSONDecodeError:
137
+ error_detail += f" Response: {e.response.text[:500]}"
138
+ status_message = f"Submission Failed: {error_detail}"
139
+ print(status_message)
140
+ results_df = pd.DataFrame(results_log)
141
+ return status_message, results_df
142
+ except requests.exceptions.Timeout:
143
+ status_message = "Submission Failed: The request timed out."
144
+ print(status_message)
145
+ results_df = pd.DataFrame(results_log)
146
+ return status_message, results_df
147
+ except requests.exceptions.RequestException as e:
148
+ status_message = f"Submission Failed: Network error - {e}"
149
+ print(status_message)
150
+ results_df = pd.DataFrame(results_log)
151
+ return status_message, results_df
152
+ except Exception as e:
153
+ status_message = f"An unexpected error occurred during submission: {e}"
154
+ print(status_message)
155
+ results_df = pd.DataFrame(results_log)
156
+ return status_message, results_df
157
 
158
  def show_help():
159
  return (
 
205
  help_md = gr.Markdown(show_help())
206
 
207
  if __name__ == "__main__":
208
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
209
+ # Check for SPACE_HOST and SPACE_ID at startup for information
210
+ space_host_startup = os.getenv("SPACE_HOST")
211
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
212
+
213
+ if space_host_startup:
214
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
215
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
216
+ else:
217
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
218
+
219
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
220
+ print(f"✅ SPACE_ID found: {space_id_startup}")
221
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
222
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
223
+ else:
224
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
225
+
226
+ print("-"*(60 + len(" App Starting ")) + "\n")
227
+
228
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
229
+ demo.launch(debug=True, share=False)