Freddolin commited on
Commit
7b248e2
·
verified ·
1 Parent(s): 81917a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -11
app.py CHANGED
@@ -10,14 +10,39 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
  # --- Basic Agent Definition ---
12
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
- class BasicAgent:
 
 
14
  def __init__(self):
15
- print("BasicAgent initialized.")
 
 
16
  def __call__(self, question: str) -> str:
17
- print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  def run_and_submit_all( profile: gr.OAuthProfile | None):
23
  """
@@ -39,14 +64,22 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
39
  submit_url = f"{api_url}/submit"
40
 
41
  # 1. Instantiate Agent ( modify this part to create your agent)
42
- try:
43
- agent = BasicAgent()
44
  except Exception as e:
45
- print(f"Error instantiating agent: {e}")
46
  return f"Error initializing agent: {e}", None
47
- # 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)
48
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
49
- print(agent_code)
 
 
 
 
 
 
 
 
 
50
 
51
  # 2. Fetch Questions
52
  print(f"Fetching questions from: {questions_url}")
@@ -87,10 +120,15 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
87
  print(f"Error running agent on task {task_id}: {e}")
88
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
89
 
 
 
 
90
  if not answers_payload:
91
  print("Agent did not produce any answers to submit.")
92
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
 
 
 
94
  # 4. Prepare Submission
95
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
@@ -139,6 +177,21 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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:
 
10
 
11
  # --- Basic Agent Definition ---
12
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
+
14
+ # --- GAIA Agent Definition ---
15
+ class GAIAAgent:
16
  def __init__(self):
17
+ print("Initializing GAIAAgent using build_graph()...")
18
+ self.graph = build_graph()
19
+
20
  def __call__(self, question: str) -> str:
21
+ print(f"Received question: {question[:60]}...")
22
+ try:
23
+ messages = [HumanMessage(content=question)]
24
+ result = self.graph.invoke({"messages": messages})
25
+ raw_output = result["messages"][-1].content
26
+ print(f"Raw output: {raw_output}")
27
+
28
+ # Extract FINAL ANSWER
29
+ if "FINAL ANSWER:" in raw_output:
30
+ return raw_output.split("FINAL ANSWER:")[-1].strip()
31
+ else:
32
+ print("⚠️ 'FINAL ANSWER:' not found — returning full output")
33
+ return raw_output.strip()
34
+ except Exception as e:
35
+ print(f"Agent error: {e}")
36
+ return f"AGENT ERROR: {e}"
37
+
38
+ # class BasicAgent:
39
+ # def __init__(self):
40
+ # print("BasicAgent initialized.")
41
+ # def __call__(self, question: str) -> str:
42
+ # print(f"Agent received question (first 50 chars): {question[:50]}...")
43
+ # fixed_answer = "This is a default answer."
44
+ # print(f"Agent returning fixed answer: {fixed_answer}")
45
+ # return fixed_answer
46
 
47
  def run_and_submit_all( profile: gr.OAuthProfile | None):
48
  """
 
64
  submit_url = f"{api_url}/submit"
65
 
66
  # 1. Instantiate Agent ( modify this part to create your agent)
67
+ try:
68
+ agent = GAIAAgent()
69
  except Exception as e:
 
70
  return f"Error initializing agent: {e}", None
71
+
72
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
73
+ print(f"Agent code URL: {agent_code}")
74
+
75
+ # try:
76
+ # agent = BasicAgent()
77
+ # except Exception as e:
78
+ # print(f"Error instantiating agent: {e}")
79
+ # return f"Error initializing agent: {e}", None
80
+ # 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)
81
+ # agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
82
+ # print(agent_code)
83
 
84
  # 2. Fetch Questions
85
  print(f"Fetching questions from: {questions_url}")
 
120
  print(f"Error running agent on task {task_id}: {e}")
121
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
122
 
123
+ # Save answers to file
124
+ save_answers_to_jsonl(answers_payload, filename="gaia_submission.jsonl")
125
+
126
  if not answers_payload:
127
  print("Agent did not produce any answers to submit.")
128
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
129
 
130
+
131
+
132
  # 4. Prepare Submission
133
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
134
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
 
177
  results_df = pd.DataFrame(results_log)
178
  return status_message, results_df
179
 
180
+ def save_answers_to_jsonl(answers_payload, filename="gaia_submission.jsonl"):
181
+ """
182
+ Save the agent's answers to a .jsonl file for manual submission.
183
+ """
184
+ try:
185
+ with open(filename, "w", encoding="utf-8") as f:
186
+ for answer in answers_payload:
187
+ f.write(json.dumps({
188
+ "task_id": answer["task_id"],
189
+ "model_answer": answer["submitted_answer"]
190
+ }) + "\n")
191
+ print(f" Saved {len(answers_payload)} answers to {filename}")
192
+ except Exception as e:
193
+ print(f" Error saving answers to file: {e}")
194
+
195
 
196
  # --- Build Gradio Interface using Blocks ---
197
  with gr.Blocks() as demo: