GoodLuckChuck commited on
Commit
a4a90e4
·
verified ·
1 Parent(s): 612f99b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -23
app.py CHANGED
@@ -15,6 +15,7 @@ from fastapi.middleware.cors import CORSMiddleware
15
  import os
16
  import pandas as pd
17
  import openai
 
18
 
19
  # Configure logging
20
  logging.basicConfig(
@@ -23,6 +24,12 @@ logging.basicConfig(
23
  )
24
  logger = logging.getLogger("gaia_agent")
25
 
 
 
 
 
 
 
26
  # Add after imports, before ToolType class
27
  async def load_test_questions(file_path: str) -> List[Dict[str, Any]]:
28
  """Load test questions from a JSONL file"""
@@ -389,6 +396,59 @@ try:
389
  except Exception as e:
390
  print(f"Error initializing OpenAI or agent: {e}")
391
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
392
  def run_and_submit_all(profile: gr.OAuthProfile | None):
393
  """Process questions and submit answers"""
394
  if not profile:
@@ -398,16 +458,12 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
398
  return "Agent not properly initialized. Check configuration.", None
399
 
400
  try:
401
- # Get Space information
402
- space_id = os.getenv("SPACE_ID")
403
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
404
-
405
- # Load and process questions
406
- test_questions_path = Path(__file__).parent / "metadata.jsonl"
407
- questions = asyncio.run(load_test_questions(str(test_questions_path)))
408
-
409
  if not questions:
410
- return "No questions loaded.", None
 
 
411
 
412
  # Process questions
413
  results_log = []
@@ -415,35 +471,57 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
415
 
416
  for q in questions:
417
  try:
418
- answer = asyncio.run(agent.process_question(q['Question']))
 
 
 
 
 
419
  answers_payload.append({
420
- "task_id": q['task_id'],
421
  "submitted_answer": answer.text,
422
  "reasoning_trace": answer.reasoning_trace
423
  })
 
424
  results_log.append({
425
- "Question": q['Question'],
 
426
  "Answer": answer.text,
427
  "Confidence": answer.confidence,
428
  "Processing Time": f"{answer.processing_time:.2f}s"
429
  })
 
 
 
 
430
  except Exception as e:
431
  print(f"Error processing question: {e}")
432
  continue
433
 
434
- # Submit results
435
- submission_data = {
436
- "username": profile.username,
437
- "agent_code": agent_code,
438
- "answers": answers_payload
439
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
440
 
441
- # Here you would submit to the actual API
442
- # For now, return results
443
- return f"Processed {len(answers_payload)} questions successfully.", pd.DataFrame(results_log)
444
-
445
  except Exception as e:
446
- return f"Error: {str(e)}", None
 
 
447
 
448
  # Create Gradio interface
449
  with gr.Blocks() as demo:
 
15
  import os
16
  import pandas as pd
17
  import openai
18
+ import requests
19
 
20
  # Configure logging
21
  logging.basicConfig(
 
24
  )
25
  logger = logging.getLogger("gaia_agent")
26
 
27
+ # Add API configuration constants at the top after imports
28
+ API_BASE_URL = "https://agents-course-unit4-scoring.hf.space"
29
+ HEADERS = {"Content-Type": "application/json", "accept": "application/json"}
30
+ USERNAME = "GoodLuckChuck" # Update this with your username
31
+ AGENT_CODE_IDENTIFIER = "GoodLuckChuck_Agent_v1" # Update this with your identifier
32
+
33
  # Add after imports, before ToolType class
34
  async def load_test_questions(file_path: str) -> List[Dict[str, Any]]:
35
  """Load test questions from a JSONL file"""
 
396
  except Exception as e:
397
  print(f"Error initializing OpenAI or agent: {e}")
398
 
399
+ # Add API interaction functions
400
+ def api_get_questions() -> List[Dict[str, Any]]:
401
+ """Fetch questions from the course API."""
402
+ try:
403
+ print(f"Attempting to fetch questions from: {API_BASE_URL}/questions")
404
+ response = requests.get(f"{API_BASE_URL}/questions", headers=HEADERS)
405
+ print(f"API Response Status Code: {response.status_code}")
406
+
407
+ response.raise_for_status()
408
+ questions = response.json()
409
+ if not questions:
410
+ print("Warning: API returned empty questions list")
411
+ return questions
412
+ except requests.exceptions.RequestException as e:
413
+ print(f"Error fetching questions from API: {e}")
414
+ return []
415
+ except json.JSONDecodeError as e:
416
+ print(f"Error decoding API response: {e}")
417
+ print(f"Response content: {response.text[:500]}...")
418
+ return []
419
+
420
+ def api_submit_answers(processed_answers: List[Dict[str, Any]], username: str) -> Dict[str, Any]:
421
+ """Submit processed answers to the course API."""
422
+ try:
423
+ # Format answers for submission
424
+ submission_data = {
425
+ "username": username,
426
+ "agent_code": AGENT_CODE_IDENTIFIER,
427
+ "answers": processed_answers
428
+ }
429
+
430
+ print("\n=== Submission Details ===")
431
+ print(f"Username: {username}")
432
+ print(f"Agent Code: {AGENT_CODE_IDENTIFIER}")
433
+ print(f"Number of Answers: {len(processed_answers)}")
434
+
435
+ response = requests.post(
436
+ f"{API_BASE_URL}/submit",
437
+ headers=HEADERS,
438
+ json=submission_data
439
+ )
440
+ response.raise_for_status()
441
+
442
+ result = response.json()
443
+ print(f"\nSubmission Response:\n{json.dumps(result, indent=2)}")
444
+ return result
445
+
446
+ except requests.exceptions.RequestException as e:
447
+ print(f"\nError submitting answers to API: {str(e)}")
448
+ if hasattr(e.response, 'text'):
449
+ print(f"API Error Response: {e.response.text}")
450
+ return {}
451
+
452
  def run_and_submit_all(profile: gr.OAuthProfile | None):
453
  """Process questions and submit answers"""
454
  if not profile:
 
458
  return "Agent not properly initialized. Check configuration.", None
459
 
460
  try:
461
+ # Get questions from API
462
+ questions = api_get_questions()
 
 
 
 
 
 
463
  if not questions:
464
+ return "No questions loaded from API.", None
465
+
466
+ print(f"Fetched {len(questions)} questions from API")
467
 
468
  # Process questions
469
  results_log = []
 
471
 
472
  for q in questions:
473
  try:
474
+ task_id = q['task_id']
475
+ question_text = q['question']
476
+
477
+ print(f"\nProcessing question: {question_text}")
478
+ answer = asyncio.run(agent.process_question(question_text))
479
+
480
  answers_payload.append({
481
+ "task_id": task_id,
482
  "submitted_answer": answer.text,
483
  "reasoning_trace": answer.reasoning_trace
484
  })
485
+
486
  results_log.append({
487
+ "Task ID": task_id,
488
+ "Question": question_text,
489
  "Answer": answer.text,
490
  "Confidence": answer.confidence,
491
  "Processing Time": f"{answer.processing_time:.2f}s"
492
  })
493
+
494
+ print(f"Answer: {answer.text}")
495
+ print(f"Confidence: {answer.confidence}")
496
+
497
  except Exception as e:
498
  print(f"Error processing question: {e}")
499
  continue
500
 
501
+ if not answers_payload:
502
+ return "No answers were generated.", None
503
+
504
+ # Submit answers
505
+ print("\nSubmitting answers to API...")
506
+ submission_result = api_submit_answers(answers_payload, profile.username)
507
+
508
+ if submission_result:
509
+ status = (
510
+ f"Submission Successful!\n"
511
+ f"User: {submission_result.get('username')}\n"
512
+ f"Score: {submission_result.get('score', 'N/A')}% "
513
+ f"({submission_result.get('correct_count', '?')}/{submission_result.get('total_attempted', '?')} correct)\n"
514
+ f"Message: {submission_result.get('message', 'No message received.')}"
515
+ )
516
+ else:
517
+ status = "Submission failed. Check logs for details."
518
+
519
+ return status, pd.DataFrame(results_log)
520
 
 
 
 
 
521
  except Exception as e:
522
+ error_msg = f"Error in processing: {str(e)}"
523
+ print(error_msg)
524
+ return error_msg, None
525
 
526
  # Create Gradio interface
527
  with gr.Blocks() as demo: