GoodLuckChuck commited on
Commit
44cc71d
·
verified ·
1 Parent(s): 0406043

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -1
app.py CHANGED
@@ -5,6 +5,10 @@ from typing import List, Dict, Any, Optional
5
  from pydantic import BaseModel, Field
6
  from openai import OpenAI
7
  from dotenv import load_dotenv # Keep for potential local testing, but HF uses secrets
 
 
 
 
8
 
9
  # --- API Configuration (from your course) ---
10
  API_BASE_URL = "https://agents-course-unit4-scoring.hf.space"
@@ -327,17 +331,106 @@ class AIAgent:
327
  "reasoning_trace": self.reasoning_trace
328
  }
329
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330
  # --- Main Execution Example ---
331
  # ... (all your previous code: GAIA_FINAL_ANSWER_SYSTEM_PROMPT, Pydantic models, Tool functions, AIAgent class,
332
  # and the API interaction functions: api_get_questions, api_download_file, api_submit_answers
333
  # should be defined above this block) ...
334
 
335
  # --- Main Execution Block (Using API for Questions) ---
 
 
336
  if __name__ == "__main__":
337
  print("===== Application Startup =====")
338
 
339
  # !!! ACTION REQUIRED: Set your username and agent_code identifier here !!!
340
- YOUR_USERNAME = "nik" # Replace with your actual username for the course platform
341
  YOUR_AGENT_CODE_IDENTIFIER = "NikAgent_HF_App_v1" # A name for your agent submission
342
 
343
  if not OPENAI_API_KEY_VALUE:
 
5
  from pydantic import BaseModel, Field
6
  from openai import OpenAI
7
  from dotenv import load_dotenv # Keep for potential local testing, but HF uses secrets
8
+ from fastapi import FastAPI, HTTPException
9
+ from fastapi.middleware.cors import CORSMiddleware
10
+ import uvicorn
11
+ from datetime import datetime
12
 
13
  # --- API Configuration (from your course) ---
14
  API_BASE_URL = "https://agents-course-unit4-scoring.hf.space"
 
331
  "reasoning_trace": self.reasoning_trace
332
  }
333
 
334
+
335
+ # Initialize FastAPI app
336
+ app = FastAPI(title="AI Agent API")
337
+
338
+ # Add CORS middleware
339
+ app.add_middleware(
340
+ CORSMiddleware,
341
+ allow_origins=["*"],
342
+ allow_credentials=True,
343
+ allow_methods=["*"],
344
+ allow_headers=["*"],
345
+ )
346
+
347
+ # Initialize the AI Agent globally
348
+ if OPENAI_API_KEY_VALUE and client:
349
+ global_agent = AIAgent(openai_client=client)
350
+ else:
351
+ global_agent = None
352
+
353
+ @app.get("/")
354
+ async def root():
355
+ """Root endpoint to verify the API is running."""
356
+ return {
357
+ "status": "online",
358
+ "timestamp": datetime.now().isoformat(),
359
+ "agent_status": "initialized" if global_agent else "not initialized"
360
+ }
361
+
362
+ @app.post("/process")
363
+ async def process_questions():
364
+ """Endpoint to process questions and submit answers."""
365
+ if not global_agent:
366
+ raise HTTPException(status_code=500, detail="AI Agent not initialized")
367
+
368
+ try:
369
+ # Fetch questions
370
+ api_questions = api_get_questions()
371
+ if not api_questions:
372
+ return {"status": "error", "message": "No questions retrieved from API"}
373
+
374
+ all_submission_answers = []
375
+
376
+ # Process each question
377
+ for question_data in api_questions:
378
+ task_id = question_data.get("task_id")
379
+ question_text = question_data.get("question")
380
+ original_file_name = question_data.get("file_name")
381
+
382
+ if not task_id or not question_text:
383
+ continue
384
+
385
+ local_file_path = None
386
+ if original_file_name:
387
+ local_file_path = api_download_file(task_id, original_file_name)
388
+
389
+ # Process question
390
+ agent_result = global_agent.process_question(
391
+ task_id=task_id,
392
+ question_text=question_text,
393
+ file_name=local_file_path
394
+ )
395
+
396
+ clean_answer = agent_result.get("model_answer", "ERROR: No answer from agent")
397
+ all_submission_answers.append({
398
+ "task_id": task_id,
399
+ "answer": clean_answer
400
+ })
401
+
402
+ # Submit answers
403
+ if all_submission_answers:
404
+ submission_result = api_submit_answers(
405
+ username=GoodLuckChuck,
406
+ agent_code_identifier=GoodLuckChuck_Agent_v1,
407
+ processed_answers=all_submission_answers
408
+ )
409
+ return {
410
+ "status": "success",
411
+ "processed_questions": len(all_submission_answers),
412
+ "submission_result": submission_result
413
+ }
414
+ else:
415
+ return {"status": "error", "message": "No answers were generated"}
416
+
417
+ except Exception as e:
418
+ raise HTTPException(status_code=500, detail=str(e))
419
+
420
+
421
  # --- Main Execution Example ---
422
  # ... (all your previous code: GAIA_FINAL_ANSWER_SYSTEM_PROMPT, Pydantic models, Tool functions, AIAgent class,
423
  # and the API interaction functions: api_get_questions, api_download_file, api_submit_answers
424
  # should be defined above this block) ...
425
 
426
  # --- Main Execution Block (Using API for Questions) ---
427
+
428
+
429
  if __name__ == "__main__":
430
  print("===== Application Startup =====")
431
 
432
  # !!! ACTION REQUIRED: Set your username and agent_code identifier here !!!
433
+ YOUR_USERNAME = GoodLuckChuck # Replace with your actual username for the course platform
434
  YOUR_AGENT_CODE_IDENTIFIER = "NikAgent_HF_App_v1" # A name for your agent submission
435
 
436
  if not OPENAI_API_KEY_VALUE: