GoodLuckChuck commited on
Commit
2c947c8
·
verified ·
1 Parent(s): de5fd62

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +330 -178
app.py CHANGED
@@ -1,194 +1,346 @@
1
  import os
2
- import gradio as gr
3
  import requests
4
- import inspect
5
- import pandas as pd
6
-
7
- # (Keep Constants as is)
8
- # --- Constants ---
9
- 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
- """
24
- Fetches all questions, runs the BasicAgent on them, submits all answers,
25
- and displays the results.
26
- """
27
- # --- Determine HF Space Runtime URL and Repo URL ---
28
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
29
-
30
- if profile:
31
- username= f"{profile.username}"
32
- print(f"User logged in: {username}")
33
- else:
34
- print("User not logged in.")
35
- return "Please Login to Hugging Face with the button.", None
36
 
37
- api_url = DEFAULT_API_URL
38
- questions_url = f"{api_url}/questions"
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}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  try:
54
- response = requests.get(questions_url, timeout=15)
55
- response.raise_for_status()
56
- questions_data = response.json()
57
- if not questions_data:
58
- print("Fetched questions list is empty.")
59
- return "Fetched questions list is empty or invalid format.", None
60
- print(f"Fetched {len(questions_data)} questions.")
61
- except requests.exceptions.RequestException as e:
62
- print(f"Error fetching questions: {e}")
63
- return f"Error fetching questions: {e}", None
64
- except requests.exceptions.JSONDecodeError as e:
65
- print(f"Error decoding JSON response from questions endpoint: {e}")
66
- print(f"Response text: {response.text[:500]}")
67
- return f"Error decoding server response for questions: {e}", None
68
  except Exception as e:
69
- print(f"An unexpected error occurred fetching questions: {e}")
70
- return f"An unexpected error occurred fetching questions: {e}", None
71
-
72
- # 3. Run your Agent
73
- results_log = []
74
- answers_payload = []
75
- print(f"Running agent on {len(questions_data)} questions...")
76
- for item in questions_data:
77
- task_id = item.get("task_id")
78
- question_text = item.get("question")
79
- if not task_id or question_text is None:
80
- print(f"Skipping item with missing task_id or question: {item}")
81
- continue
82
- try:
83
- submitted_answer = agent(question_text)
84
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
86
- except Exception as e:
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}'..."
97
- print(status_update)
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
  if __name__ == "__main__":
173
- print("\n" + "-"*30 + " App Starting " + "-"*30)
174
- # Check for SPACE_HOST and SPACE_ID at startup for information
175
- space_host_startup = os.getenv("SPACE_HOST")
176
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
177
-
178
- if space_host_startup:
179
- print(f"✅ SPACE_HOST found: {space_host_startup}")
180
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
181
  else:
182
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
 
 
 
 
 
183
 
184
- if space_id_startup: # Print repo URLs if SPACE_ID is found
185
- print(f"✅ SPACE_ID found: {space_id_startup}")
186
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
187
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
188
- else:
189
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
 
191
- print("-"*(60 + len(" App Starting ")) + "\n")
 
 
 
 
 
 
192
 
193
- print("Launching Gradio Interface for Basic Agent Evaluation...")
194
- demo.launch(debug=True, share=False)
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import json
3
  import requests
4
+ from typing import List, Dict, Any, Optional, Type
5
+ from pydantic import BaseModel, Field
6
+ from openai import OpenAI
7
+ from dotenv import load_dotenv
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
+ # Load environment variables from .env file
10
+ env_path = '/home/nik/hf-agent-class/final test/.env'
11
+ if not os.path.exists(env_path):
12
+ print(f"Warning: .env file not found at {env_path}")
13
+ load_dotenv(env_path)
14
 
15
+ if not os.environ.get("OPENAI_API_KEY"):
16
+ raise ValueError("OPENAI_API_KEY not found in environment variables")
17
+
18
+ # --- Configuration ---
19
+ # Ensure your OPENAI_API_KEY is set as an environment variable
20
+ # client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
21
+ # For this example, let's ensure the script can run even if the key isn't immediately set
22
+ # by initializing client later or handling the potential error.
23
+ try:
24
+ client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
25
+ if not os.environ.get("OPENAI_API_KEY"):
26
+ print("Warning: OPENAI_API_KEY environment variable not set. API calls will fail.")
27
+ except Exception as e:
28
+ print(f"Error initializing OpenAI client: {e}. Ensure API key is set.")
29
+ client = None # API calls will fail
30
+
31
+ # Update model to use ChatGPT
32
+ LLM_MODEL = "gpt-3.5-turbo" # Using ChatGPT model
33
+
34
+ # --- Step 4: GAIA System Prompt for Final Answer Formatting ---
35
+ GAIA_FINAL_ANSWER_SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string."""
36
+
37
+ # --- Step 3: Pydantic Models for Tool Inputs ---
38
+ class WebSearchInput(BaseModel):
39
+ query: str = Field(..., description="The search query to find information on the web.")
40
+
41
+ class CalculatorInput(BaseModel):
42
+ expression: str = Field(..., description="The mathematical expression to evaluate (e.g., '2+2', '100 * 3.14').")
43
+
44
+ class ImageAnalysisInput(BaseModel):
45
+ image_url: Optional[str] = Field(None, description="The URL of the image to analyze.")
46
+ file_name: Optional[str] = Field(None, description="The file name of the image if provided in the question.")
47
+ prompt: str = Field(..., description="Specific question or instruction for analyzing the image.")
48
+
49
+ # --- Step 3: Mock Tool Functions ---
50
+ # In a real scenario, these would interact with actual services or models.
51
+
52
+ def execute_web_search(query: str) -> Dict[str, Any]:
53
+ """Mock web search tool."""
54
+ print(f" 🔎 [Tool Called] WebSearch with query: '{query}'")
55
+ # Simulate finding information
56
+ if "capital of france" in query.lower():
57
+ return {"result": "Paris is the capital of France.", "source": "mock_wikipedia.org"}
58
+ elif "tallest building" in query.lower():
59
+ return {"result": "The Burj Khalifa is currently the tallest building in the world.", "source": "mock_guinnessworldrecords.com"}
60
+ return {"result": f"No specific information found for '{query}'.", "source": "mock_search_engine.com"}
61
+
62
+ def execute_calculator(expression: str) -> Dict[str, Any]:
63
+ """Mock calculator tool."""
64
+ print(f" 🧮 [Tool Called] Calculator with expression: '{expression}'")
65
  try:
66
+ # IMPORTANT: eval() is unsafe with arbitrary user input.
67
+ # A production system would use a dedicated math parsing library.
68
+ result = eval(expression, {"__builtins__": {}}, {})
69
+ return {"result": str(result)}
 
 
 
 
 
 
 
 
 
 
70
  except Exception as e:
71
+ return {"error": f"Invalid expression or calculation error: {str(e)}"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
+ def execute_image_analysis(image_url: Optional[str], file_name: Optional[str], prompt: str) -> Dict[str, Any]:
74
+ """Mock image analysis tool."""
75
+ identifier = image_url or file_name
76
+ print(f" 🖼️ [Tool Called] ImageAnalysis for '{identifier}' with prompt: '{prompt}'")
77
+ if identifier and "cat" in prompt.lower():
78
+ return {"description": "The image appears to show a cat sitting on a mat.", "objects_detected": ["cat", "mat"]}
79
+ elif identifier and "fruit" in prompt.lower():
80
+ return {"description": "The image contains various fruits, possibly apples and bananas.", "objects_detected": ["apple", "banana"]}
81
+ return {"description": f"Could not analyze image '{identifier}' for prompt '{prompt}'. Details unavailable.", "objects_detected": []}
82
 
83
+ # --- Step 3: AI Agent Definition ---
 
 
 
84
 
85
+ class AIAgent:
86
+ def __init__(self, openai_client):
87
+ self.client = openai_client
88
+ self.reasoning_trace = []
89
+
90
+ # Update image analysis parameters in tools
91
+ self.tools_available = [
92
+ {
93
+ "type": "function",
94
+ "function": {
95
+ "name": "web_search",
96
+ "description": "Searches the web for information based on a query.",
97
+ "parameters": WebSearchInput.model_json_schema()
98
+ }
99
+ },
100
+ {
101
+ "type": "function",
102
+ "function": {
103
+ "name": "calculator",
104
+ "description": "Evaluates mathematical expressions.",
105
+ "parameters": CalculatorInput.model_json_schema()
106
+ }
107
+ },
108
+ {
109
+ "type": "function",
110
+ "function": {
111
+ "name": "image_analysis",
112
+ "description": "Analyzes an image given its file path.",
113
+ "parameters": {
114
+ "type": "object",
115
+ "properties": {
116
+ "image_identifier": {
117
+ "type": "string",
118
+ "description": "The file path of the image to analyze"
119
+ },
120
+ "prompt": {
121
+ "type": "string",
122
+ "description": "Specific question or instruction for analyzing the image"
123
+ }
124
+ },
125
+ "required": ["prompt"]
126
+ }
127
+ }
128
+ }
129
+ ]
130
+ self.tool_executors = {
131
+ "web_search": lambda params: execute_web_search(**params),
132
+ "calculator": lambda params: execute_calculator(**params),
133
+ "image_analysis": lambda params: execute_image_analysis(**params)
134
+ }
135
+
136
+ def _log_step(self, message: str, data: Optional[Dict] = None):
137
+ print(message)
138
+ entry = {"message": message}
139
+ if data:
140
+ entry.update(data)
141
+ self.reasoning_trace.append(entry)
142
+
143
+ def process_question(self, task_id: str, question_text: str, file_name: Optional[str] = None, max_iterations: int = 5) -> Dict[str, Any]:
144
+ self.reasoning_trace = []
145
+
146
+ # Handle file path for the agent
147
+ file_path_for_agent = None
148
+ if file_name:
149
+ file_path_for_agent = os.path.join('/home/nik/hf-agent-class/final test', file_name)
150
+ if not os.path.exists(file_path_for_agent):
151
+ self._log_step(f"Warning: File not found at {file_path_for_agent}")
152
+ file_path_for_agent = None
153
+
154
+ # Update user message to include file information
155
+ user_message_content = question_text
156
+ if file_path_for_agent:
157
+ user_message_content += f" (Note: The file is located at '{file_path_for_agent}')"
158
+
159
+ if not self.client:
160
+ self._log_step("ERROR: OpenAI client not initialized. Cannot process question.")
161
+ return {
162
+ "task_id": task_id,
163
+ "model_answer": "ERROR: Agent configuration issue.",
164
+ "reasoning_trace": self.reasoning_trace
165
+ }
166
+
167
+ self._log_step(f"Processing Task ID: {task_id}")
168
+ self._log_step(f"Original Question: {question_text}")
169
+ if file_path_for_agent:
170
+ self._log_step(f"Associated File: {file_path_for_agent}")
171
+
172
+ # Initial system prompt for the agent's overall behavior,
173
+ # including the GAIA final answer format from the start.
174
+ # This encourages the LLM to structure its thoughts and final output correctly.
175
+ # (This is Option A from the thought process - integrating GAIA format early)
176
+ agent_system_prompt = (
177
+ "You are a helpful AI assistant. Your goal is to answer the user's question accurately. "
178
+ "Think step-by-step. If you need to use a tool to find information or perform a calculation, "
179
+ "you will be given the option to call available functions. "
180
+ "After any tool use, review the information and continue. "
181
+ "When you have enough information to answer the question, provide your comprehensive thought process. "
182
+ f"{GAIA_FINAL_ANSWER_SYSTEM_PROMPT}" # Embedding the GAIA formatting rules
183
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
 
185
+ messages = [{"role": "system", "content": agent_system_prompt}]
186
+ messages.append({"role": "user", "content": user_message_content})
187
+
188
+ for iteration in range(max_iterations):
189
+ self._log_step(f"\nIteration {iteration + 1}")
190
+ try:
191
+ self._log_step("🤖 Assistant thinking...", {"current_messages_for_llm_count": len(messages)})
192
+ response = self.client.chat.completions.create(
193
+ model=LLM_MODEL,
194
+ messages=messages,
195
+ tools=self.tools_available,
196
+ tool_choice="auto" # Let the model decide if it needs a tool
197
+ )
198
+ response_message = response.choices[0].message
199
+ messages.append(response_message) # Add assistant's response to history
200
+
201
+ if response_message.tool_calls:
202
+ self._log_step("🛠️ Assistant decided to use tools:")
203
+ for tool_call in response_message.tool_calls:
204
+ function_name = tool_call.function.name
205
+ function_args = json.loads(tool_call.function.arguments) # Arguments are a JSON string
206
+ self._log_step(f" - Tool: {function_name}, Args: {function_args}")
207
+
208
+ if function_name in self.tool_executors:
209
+ # Automatically pass file_name to image_analysis if it's not in args but available
210
+ if function_name == "image_analysis" and 'file_name' not in function_args and file_path_for_agent:
211
+ function_args['image_identifier'] = file_path_for_agent
212
+
213
+ tool_output = self.tool_executors[function_name](function_args)
214
+ self._log_step(f" ✔️ Tool Output ({function_name}): {tool_output}")
215
+ messages.append({
216
+ "tool_call_id": tool_call.id,
217
+ "role": "tool",
218
+ "name": function_name,
219
+ "content": json.dumps(tool_output) # Tool output must be a string
220
+ })
221
+ else:
222
+ self._log_step(f" ⚠️ Error: Unknown tool '{function_name}'.")
223
+ messages.append({
224
+ "tool_call_id": tool_call.id,
225
+ "role": "tool",
226
+ "name": function_name,
227
+ "content": json.dumps({"error": f"Tool {function_name} not found."})
228
+ })
229
+ else: # No tool calls, LLM should be providing the final answer
230
+ self._log_step("✅ Assistant providing final answer (or thought process leading to it).")
231
+ llm_final_content = response_message.content
232
+ self._log_step("Raw LLM Final Content:\n" + "="*20 + f"\n{llm_final_content}\n" + "="*20)
233
+
234
+ # Extract the answer part after "FINAL ANSWER:"
235
+ # The GAIA_FINAL_ANSWER_SYSTEM_PROMPT should guide the LLM to produce this.
236
+ if "FINAL ANSWER:" in llm_final_content:
237
+ final_answer_text = llm_final_content.split("FINAL ANSWER:", 1)[1].strip()
238
+ else:
239
+ # If the LLM didn't use the template, we might take the whole content
240
+ # or try a final re-prompting (Option B - more complex, not implemented here for simplicity)
241
+ self._log_step("Warning: 'FINAL ANSWER:' template not found in LLM response. Using entire content with a note.")
242
+ final_answer_text = llm_final_content + " (Warning: FINAL ANSWER template not strictly followed by LLM)"
243
+
244
+ return {
245
+ "task_id": task_id,
246
+ "model_answer": final_answer_text,
247
+ "reasoning_trace": self.reasoning_trace,
248
+ "full_llm_output": llm_final_content
249
+ }
250
+
251
+ except Exception as e:
252
+ self._log_step(f"🚨 An error occurred during LLM call or tool execution: {str(e)}")
253
+ return {
254
+ "task_id": task_id,
255
+ "model_answer": f"ERROR: An exception occurred - {str(e)}",
256
+ "reasoning_trace": self.reasoning_trace
257
+ }
258
+
259
+ self._log_step("⚠️ Agent reached maximum iterations without a conclusive answer.")
260
+ return {
261
+ "task_id": task_id,
262
+ "model_answer": "ERROR: Agent reached maximum iterations.",
263
+ "reasoning_trace": self.reasoning_trace
264
+ }
265
+
266
+ # --- Main Execution Example ---
267
  if __name__ == "__main__":
268
+ if not client:
269
+ print("OpenAI client is not initialized. Please set your OPENAI_API_KEY. Exiting.")
 
 
 
 
 
 
270
  else:
271
+ agent = AIAgent(openai_client=client)
272
+
273
+ input_gaia_file = "/home/nik/hf-agent-class/final test/metadata.jsonl"
274
+ output_results_file = "/home/nik/hf-agent-class/final test/gaia_agent_processed_answers.jsonl"
275
+
276
+ processed_results = []
277
 
278
+ try:
279
+ with open(input_gaia_file, 'r', encoding='utf-8') as f_in:
280
+ for line_number, line in enumerate(f_in, 1):
281
+ try:
282
+ gaia_question_data = json.loads(line.strip())
283
+ task_id = gaia_question_data.get("task_id")
284
+ question = gaia_question_data.get("Question") # Note the capital Q
285
+ file_name = gaia_question_data.get("file_name")
286
+
287
+ print(f"\nProcessing question {line_number}:")
288
+ print(f"Task ID: {task_id}")
289
+ print(f"Question: {question}")
290
+
291
+ # Process the question with the agent
292
+ result = agent.process_question(
293
+ task_id=task_id,
294
+ question_text=question,
295
+ file_name=file_name
296
+ )
297
+
298
+ # Format the result according to GAIA requirements
299
+ formatted_result = {
300
+ "task_id": task_id,
301
+ "model_answer": result["model_answer"].strip(),
302
+ "reasoning_trace": result["reasoning_trace"]
303
+ }
304
+
305
+ processed_results.append(formatted_result)
306
+
307
+ # Print progress
308
+ print(f"Answer: {formatted_result['model_answer']}")
309
+ print("-" * 80)
310
+
311
+ except json.JSONDecodeError as e:
312
+ print(f"Skipping line {line_number} due to JSON decode error: {e}")
313
+ processed_results.append({
314
+ "task_id": f"error_line_{line_number}",
315
+ "model_answer": "Error: Could not parse JSON",
316
+ "reasoning_trace": f"JSON decode error: {str(e)}"
317
+ })
318
+ except Exception as e:
319
+ print(f"Error processing line {line_number}: {e}")
320
+ processed_results.append({
321
+ "task_id": f"error_line_{line_number}",
322
+ "model_answer": "Error: Processing failed",
323
+ "reasoning_trace": f"Processing error: {str(e)}"
324
+ })
325
 
326
+ # Save results locally
327
+ with open(output_results_file, 'w', encoding='utf-8') as f_out:
328
+ for result in processed_results:
329
+ f_out.write(json.dumps(result) + '\n')
330
+
331
+ print(f"\nProcessing complete. Results saved to {output_results_file}")
332
+ print(f"Processed {len(processed_results)} questions")
333
 
334
+ # Submit results to API
335
+ print("\nSubmitting results to API...")
336
+ api_response = api_submit_answers(processed_results)
337
+ if "error" not in api_response:
338
+ print("Results submitted successfully!")
339
+ print(f"API Response: {json.dumps(api_response, indent=2)}")
340
+ else:
341
+ print(f"Error submitting results: {api_response['error']}")
342
+
343
+ except FileNotFoundError:
344
+ print(f"Error: Input file '{input_gaia_file}' not found.")
345
+ except Exception as e:
346
+ print(f"An unexpected error occurred: {e}")