GoodLuckChuck commited on
Commit
cfcd7e8
·
verified ·
1 Parent(s): 6fbab6e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -74
app.py CHANGED
@@ -272,83 +272,105 @@ class AIAgent:
272
  }
273
 
274
  # --- Main Execution Example ---
 
 
 
 
 
275
  if __name__ == "__main__":
276
- if not client:
277
- print("OpenAI client is not initialized. Please set your OPENAI_API_KEY. Exiting.")
 
 
 
 
 
 
 
 
278
  else:
279
  agent = AIAgent(openai_client=client)
280
-
281
- input_gaia_file = "/home/nik/hf-agent-class/final test/metadata.jsonl"
282
- output_results_file = "/home/nik/hf-agent-class/final test/gaia_agent_processed_answers.jsonl"
283
-
284
- processed_results = []
285
-
286
- try:
287
- with open(input_gaia_file, 'r', encoding='utf-8') as f_in:
288
- for line_number, line in enumerate(f_in, 1):
289
- try:
290
- gaia_question_data = json.loads(line.strip())
291
- task_id = gaia_question_data.get("task_id")
292
- question = gaia_question_data.get("Question") # Note the capital Q
293
- file_name = gaia_question_data.get("file_name")
294
-
295
- print(f"\nProcessing question {line_number}:")
296
- print(f"Task ID: {task_id}")
297
- print(f"Question: {question}")
298
-
299
- # Process the question with the agent
300
- result = agent.process_question(
301
- task_id=task_id,
302
- question_text=question,
303
- file_name=file_name
304
- )
305
-
306
- # Format the result according to GAIA requirements
307
- formatted_result = {
308
- "task_id": task_id,
309
- "model_answer": result["model_answer"].strip(),
310
- "reasoning_trace": result["reasoning_trace"]
311
- }
312
-
313
- processed_results.append(formatted_result)
314
-
315
- # Print progress
316
- print(f"Answer: {formatted_result['model_answer']}")
317
- print("-" * 80)
318
-
319
- except json.JSONDecodeError as e:
320
- print(f"Skipping line {line_number} due to JSON decode error: {e}")
321
- processed_results.append({
322
- "task_id": f"error_line_{line_number}",
323
- "model_answer": "Error: Could not parse JSON",
324
- "reasoning_trace": f"JSON decode error: {str(e)}"
325
- })
326
- except Exception as e:
327
- print(f"Error processing line {line_number}: {e}")
328
- processed_results.append({
329
- "task_id": f"error_line_{line_number}",
330
- "model_answer": "Error: Processing failed",
331
- "reasoning_trace": f"Processing error: {str(e)}"
332
- })
333
-
334
- # Save results locally
335
- with open(output_results_file, 'w', encoding='utf-8') as f_out:
336
- for result in processed_results:
337
- f_out.write(json.dumps(result) + '\n')
 
 
 
 
 
338
 
339
- print(f"\nProcessing complete. Results saved to {output_results_file}")
340
- print(f"Processed {len(processed_results)} questions")
341
-
342
- # Submit results to API
343
- print("\nSubmitting results to API...")
344
- api_response = api_submit_answers(processed_results)
345
- if "error" not in api_response:
346
- print("Results submitted successfully!")
347
- print(f"API Response: {json.dumps(api_response, indent=2)}")
 
 
 
 
348
  else:
349
- print(f"Error submitting results: {api_response['error']}")
 
 
 
350
 
351
- except FileNotFoundError:
352
- print(f"Error: Input file '{input_gaia_file}' not found.")
353
- except Exception as e:
354
- print(f"An unexpected error occurred: {e}")
 
272
  }
273
 
274
  # --- Main Execution Example ---
275
+ # ... (all your previous code: GAIA_FINAL_ANSWER_SYSTEM_PROMPT, Pydantic models, Tool functions, AIAgent class,
276
+ # and the API interaction functions: api_get_questions, api_download_file, api_submit_answers
277
+ # should be defined above this block) ...
278
+
279
+ # --- Main Execution Block (Using API for Questions) ---
280
  if __name__ == "__main__":
281
+ print("===== Application Startup =====")
282
+
283
+ # !!! ACTION REQUIRED: Set your username and agent_code identifier here !!!
284
+ YOUR_USERNAME = "nik" # Replace with your actual username for the course platform
285
+ YOUR_AGENT_CODE_IDENTIFIER = "NikAgent_HF_App_v1" # A name for your agent submission
286
+
287
+ if not OPENAI_API_KEY_VALUE:
288
+ print("CRITICAL: OpenAI API Key is not available. Main execution cannot proceed.")
289
+ elif not client:
290
+ print("CRITICAL: OpenAI client failed to initialize. Main execution cannot proceed.")
291
  else:
292
  agent = AIAgent(openai_client=client)
293
+ all_submission_answers = [] # To collect {"task_id": ..., "answer": ...} dicts
294
+
295
+ # 1. Fetch questions from the API
296
+ print("\nSTEP 1: Fetching questions from API...")
297
+ api_questions = api_get_questions() # This function calls the course API
298
+
299
+ if api_questions:
300
+ print(f"Fetched {len(api_questions)} questions from the API.")
301
+ # You might want to process a subset for testing during development:
302
+ # questions_to_process = api_questions[:1] # Example: process only the first question
303
+ questions_to_process = api_questions
304
+
305
+
306
+ for question_data_from_api in questions_to_process:
307
+ task_id = question_data_from_api.get("task_id")
308
+ # Ensure you are using the correct key for question text from the API response.
309
+ # Common keys: "question", "text", "query". Check API docs or a sample response.
310
+ question_text = question_data_from_api.get("question")
311
+
312
+ # Check the structure of question_data_from_api to see how file info is provided.
313
+ # It might be 'file_name', 'filename', 'associated_file', 'has_file', etc.
314
+ original_file_name_from_api = question_data_from_api.get("file_name") # Assuming 'file_name'
315
+ local_downloaded_file_path = None
316
+
317
+ if not task_id or not question_text:
318
+ print(f"Skipping question due to missing task_id or question text in API response: {question_data_from_api}")
319
+ continue
320
+
321
+ print(f"\n-----------------------------------\nProcessing Task ID: {task_id}")
322
+
323
+ # 2. Download file if it's indicated by the API response for the current question
324
+ if original_file_name_from_api:
325
+ print(f"STEP 2: File indicated by API ({original_file_name_from_api}). Attempting download...")
326
+ # Files will be downloaded into 'downloaded_gaia_files' relative to where app.py runs in the Space
327
+ local_downloaded_file_path = api_download_file(
328
+ task_id,
329
+ original_file_name_from_api,
330
+ download_dir="downloaded_gaia_files" # This will be created inside your HF Space app directory
331
+ )
332
+ else:
333
+ print(f"STEP 2: No file indicated by API for task {task_id}.")
334
+
335
+ # 3. Process the question with your AI Agent
336
+ print(f"\nSTEP 3: Processing task {task_id} with AI Agent...")
337
+ agent_result = agent.process_question(
338
+ task_id=task_id,
339
+ question_text=question_text,
340
+ file_path_for_agent=local_downloaded_file_path # Pass the path of the downloaded file
341
+ )
342
+
343
+ # agent_result["model_answer"] should be the clean answer, stripped of "FINAL ANSWER:"
344
+ clean_answer = agent_result.get("model_answer", "ERROR: No answer from agent")
345
+
346
+ print(f"Agent's Clean Answer for {task_id}: {clean_answer}")
347
+
348
+ all_submission_answers.append({
349
+ "task_id": task_id,
350
+ "answer": clean_answer
351
+ })
352
+
353
+ # Optional: Add a small delay if processing many questions to be kind to APIs
354
+ # import time
355
+ # time.sleep(0.5)
356
 
357
+ # 4. Submit all collected answers
358
+ if all_submission_answers:
359
+ print("\nSTEP 4: Submitting all processed answers...")
360
+ submission_result = api_submit_answers(
361
+ username=YOUR_USERNAME,
362
+ agent_code_identifier=YOUR_AGENT_CODE_IDENTIFIER,
363
+ processed_answers=all_submission_answers
364
+ )
365
+ if submission_result:
366
+ print("\n--- Submission Summary Received from API ---")
367
+ # Process/display submission_result as needed (e.g., score)
368
+ else:
369
+ print("Submission attempt failed or no result returned from submission API.")
370
  else:
371
+ print("No answers were generated to submit.")
372
+
373
+ else:
374
+ print("Could not fetch questions from API. Exiting.")
375
 
376
+ print("\n===== Application Finished =====")