GoodLuckChuck commited on
Commit
e34a52e
·
verified ·
1 Parent(s): 81917a3

Update app.py

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