GoodLuckChuck commited on
Commit
10df2f5
·
verified ·
1 Parent(s): 58bfba1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +294 -26
app.py CHANGED
@@ -812,6 +812,294 @@ def create_agent(openai_module, knowledge_base_path: Path) -> ImprovedAgent:
812
  ]
813
  return ImprovedAgent(openai_module, tools)
814
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
815
  # Create Gradio interface
816
  with gr.Blocks() as demo:
817
  gr.Markdown("# Improved GAIA Agent")
@@ -830,33 +1118,13 @@ with gr.Blocks() as demo:
830
  outputs=[status_output, results_table]
831
  )
832
 
833
- # Create FastAPI app with startup event
834
- app = FastAPI(title="Improved GAIA Agent API")
835
-
836
- @app.on_event("startup")
837
- async def startup_event():
838
- logger.info("Starting up the application...")
839
- # Any initialization code can go here
840
- pass
841
-
842
- app.add_middleware(
843
- CORSMiddleware,
844
- allow_origins=["*"],
845
- allow_credentials=True,
846
- allow_methods=["*"],
847
- allow_headers=["*"],
848
- )
849
-
850
  # Mount Gradio app to FastAPI
851
  app = gr.mount_gradio_app(app, demo, path="/")
852
 
853
- # Create a proper ASGI app
 
854
  if __name__ == "__main__":
855
- import uvicorn
856
- uvicorn.run(
857
- "app:app",
858
- host="0.0.0.0",
859
- port=7860,
860
- reload=False,
861
- workers=1
862
- )
 
812
  ]
813
  return ImprovedAgent(openai_module, tools)
814
 
815
+ # Add after the create_agent function
816
+ app = FastAPI(title="Improved GAIA Agent API")
817
+
818
+ app.add_middleware(
819
+ CORSMiddleware,
820
+ allow_origins=["*"],
821
+ allow_credentials=True,
822
+ allow_methods=["*"],
823
+ allow_headers=["*"],
824
+ )
825
+
826
+ # Initialize OpenAI client with HF secret
827
+ try:
828
+ # Get API key from HF secrets
829
+ hf_token = os.environ.get("HF_TOKEN", "").strip()
830
+ if hf_token:
831
+ api = HfApi(token=hf_token)
832
+ try:
833
+ openai_api_key = os.environ.get("OPENAI_API_KEY", "").strip()
834
+ if not openai_api_key:
835
+ logger.error("OPENAI_API_KEY not found in environment variables")
836
+ raise ValueError("OPENAI_API_KEY not found")
837
+
838
+ # Configure OpenAI with cleaned API key
839
+ client = OpenAI(api_key=openai_api_key.strip())
840
+
841
+ # Test the API key
842
+ test_response = client.chat.completions.create(
843
+ model="gpt-4",
844
+ messages=[{"role": "user", "content": "test"}],
845
+ max_tokens=5
846
+ )
847
+ logger.info("OpenAI initialized successfully with GPT-4")
848
+ except Exception as e:
849
+ logger.error(f"Error accessing OpenAI API key from secrets: {str(e)}")
850
+ raise
851
+ else:
852
+ logger.error("HF_TOKEN not found in environment variables")
853
+ raise ValueError("HF_TOKEN not found")
854
+ except Exception as e:
855
+ logger.error(f"Error initializing OpenAI: {str(e)}")
856
+ raise
857
+
858
+ # Create necessary directories
859
+ try:
860
+ base_dir = Path("downloaded_gaia_files")
861
+ for subdir in ['text', 'data', 'media', 'other']:
862
+ (base_dir / subdir).mkdir(parents=True, exist_ok=True)
863
+ logger.info("Created knowledge base directories successfully")
864
+ except Exception as e:
865
+ logger.error(f"Error creating directories: {str(e)}")
866
+ raise
867
+
868
+ # Initialize OpenAI client and agent globally
869
+ agent = None
870
+ try:
871
+ # Get API key from environment (HF Secrets)
872
+ api_key = os.environ.get("OPENAI_API_KEY", "").strip()
873
+ if not api_key:
874
+ raise ValueError("OPENAI_API_KEY not found in environment variables")
875
+
876
+ # Configure OpenAI with cleaned API key
877
+ client = OpenAI(api_key=api_key.strip())
878
+
879
+ # Test the API key
880
+ test_response = client.chat.completions.create(
881
+ model="gpt-4",
882
+ messages=[{"role": "user", "content": "test"}],
883
+ max_tokens=5
884
+ )
885
+ print("OpenAI initialized successfully with GPT-4")
886
+
887
+ # Create agent
888
+ knowledge_base_path = Path(__file__).parent / "knowledge_base"
889
+ agent = create_agent(client, knowledge_base_path)
890
+ except Exception as e:
891
+ print(f"Error initializing OpenAI or agent: {e}")
892
+
893
+ # Add API interaction functions
894
+ @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
895
+ async def api_get_questions() -> List[Dict[str, Any]]:
896
+ """Fetch questions from the course API with retry logic."""
897
+ try:
898
+ logger.info(f"Fetching questions from: {config.api_base_url}/questions")
899
+ async with aiohttp.ClientSession() as session:
900
+ async with session.get(
901
+ f"{config.api_base_url}/questions",
902
+ headers=config.headers,
903
+ timeout=config.timeout
904
+ ) as response:
905
+ if response.status != 200:
906
+ error_text = await response.text()
907
+ logger.error(f"API error (status {response.status}): {error_text}")
908
+ raise HTTPException(
909
+ status_code=response.status,
910
+ detail=f"API error: {error_text}"
911
+ )
912
+
913
+ questions = await response.json()
914
+ logger.info(f"Successfully fetched {len(questions)} questions")
915
+ return questions
916
+
917
+ except asyncio.TimeoutError:
918
+ logger.error("Timeout while fetching questions")
919
+ raise HTTPException(
920
+ status_code=504,
921
+ detail="Timeout while fetching questions"
922
+ )
923
+ except Exception as e:
924
+ logger.error(f"Error fetching questions: {str(e)}")
925
+ raise HTTPException(
926
+ status_code=500,
927
+ detail=f"Error fetching questions: {str(e)}"
928
+ )
929
+
930
+ @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
931
+ async def api_submit_answers(
932
+ processed_answers: List[Dict[str, Any]],
933
+ username: str = config.username
934
+ ) -> Dict[str, Any]:
935
+ """Submit answers to the course API with retry logic."""
936
+ try:
937
+ # Validate answers format
938
+ for answer in processed_answers:
939
+ if 'task_id' not in answer or 'submitted_answer' not in answer:
940
+ raise ValueError(
941
+ "Invalid answer format. Each answer must contain 'task_id' and 'submitted_answer'"
942
+ )
943
+
944
+ submission_data = {
945
+ "username": username,
946
+ "agent_code": config.agent_code_identifier,
947
+ "answers": processed_answers
948
+ }
949
+
950
+ logger.info("=== Submission Details ===")
951
+ logger.info(f"Username: {username}")
952
+ logger.info(f"Agent Code: {config.agent_code_identifier}")
953
+ logger.info(f"Number of Answers: {len(processed_answers)}")
954
+ logger.debug(f"Sample answer format: {json.dumps(processed_answers[0], indent=2) if processed_answers else 'No answers'}")
955
+ logger.debug(f"Full submission data: {json.dumps(submission_data, indent=2)}")
956
+
957
+ async with aiohttp.ClientSession() as session:
958
+ async with session.post(
959
+ f"{config.api_base_url}/submit",
960
+ headers=config.headers,
961
+ json=submission_data,
962
+ timeout=config.timeout
963
+ ) as response:
964
+ if response.status != 200:
965
+ error_text = await response.text()
966
+ logger.error(f"Submission error (status {response.status}): {error_text}")
967
+ raise HTTPException(
968
+ status_code=response.status,
969
+ detail=f"Submission error: {error_text}"
970
+ )
971
+
972
+ result = await response.json()
973
+ logger.info("Submission successful")
974
+ logger.debug(f"Submission response: {json.dumps(result, indent=2)}")
975
+ return result
976
+
977
+ except asyncio.TimeoutError:
978
+ logger.error("Timeout while submitting answers")
979
+ raise HTTPException(
980
+ status_code=504,
981
+ detail="Timeout while submitting answers"
982
+ )
983
+ except ValueError as e:
984
+ logger.error(f"Validation error: {str(e)}")
985
+ raise HTTPException(
986
+ status_code=400,
987
+ detail=str(e)
988
+ )
989
+ except Exception as e:
990
+ logger.error(f"Error submitting answers: {str(e)}")
991
+ raise HTTPException(
992
+ status_code=500,
993
+ detail=f"Error submitting answers: {str(e)}"
994
+ )
995
+
996
+ # Define the function before using it in the Gradio interface
997
+ async def run_and_submit_all(profile: gr.OAuthProfile | None):
998
+ """Process and submit all questions with enhanced error handling."""
999
+ if not profile:
1000
+ return "Authentication required", None
1001
+
1002
+ try:
1003
+ # Get questions
1004
+ questions = await api_get_questions()
1005
+ if not questions:
1006
+ logger.warning("No questions received from API")
1007
+ return "No questions available", None
1008
+
1009
+ # Create agent
1010
+ agent = create_agent(OpenAI(api_key=os.environ.get("OPENAI_API_KEY", "")), Path("knowledge_base"))
1011
+
1012
+ # Process questions
1013
+ processed_answers = []
1014
+ results_log = [] # Track detailed results for display
1015
+
1016
+ for question in questions:
1017
+ try:
1018
+ # Log the raw question for debugging
1019
+ logger.debug(f"Raw question data: {json.dumps(question, indent=2)}")
1020
+
1021
+ # Extract question text safely
1022
+ question_text = question.get('question', question.get('text', ''))
1023
+ if not question_text:
1024
+ logger.error(f"Question text not found in: {question}")
1025
+ continue
1026
+
1027
+ # Create Question object with proper validation
1028
+ agent_question = Question(
1029
+ text=question_text,
1030
+ context=question.get('context', ''),
1031
+ attachments=question.get('attachments', []),
1032
+ metadata={
1033
+ 'task_id': question.get('task_id', ''),
1034
+ 'original_data': question
1035
+ }
1036
+ )
1037
+
1038
+ answer = await agent.process_question(agent_question)
1039
+
1040
+ if not answer or not answer.text:
1041
+ logger.error(f"No valid answer produced for question {question.get('task_id', 'unknown')}")
1042
+ continue
1043
+
1044
+ processed_answers.append({
1045
+ 'task_id': question.get('task_id', ''),
1046
+ 'submitted_answer': answer.text
1047
+ })
1048
+
1049
+ # Add to results log for display
1050
+ results_log.append({
1051
+ 'Task ID': question.get('task_id', ''),
1052
+ 'Question': question_text[:200] + ('...' if len(question_text) > 200 else ''), # Truncate long questions
1053
+ 'Answer': answer.text[:200] + ('...' if len(answer.text) > 200 else ''), # Truncate long answers
1054
+ 'Confidence': f"{answer.confidence:.2f}",
1055
+ 'Processing Time': f"{answer.processing_time:.2f}s"
1056
+ })
1057
+
1058
+ logger.info(f"Processed question {question.get('task_id', '')} with confidence {answer.confidence}")
1059
+ except Exception as e:
1060
+ logger.error(f"Error processing question: {str(e)}")
1061
+ logger.error(f"Question data: {json.dumps(question, indent=2)}")
1062
+ results_log.append({
1063
+ 'Task ID': question.get('task_id', 'unknown'),
1064
+ 'Question': question.get('question', question.get('text', 'unknown')),
1065
+ 'Answer': f"Error: {str(e)}",
1066
+ 'Confidence': '0.00',
1067
+ 'Processing Time': '0.00s'
1068
+ })
1069
+ continue
1070
+
1071
+ if not processed_answers:
1072
+ logger.error("No answers were successfully processed")
1073
+ if results_log:
1074
+ return "No answers were successfully processed - check results table for errors", pd.DataFrame(results_log)
1075
+ return "No answers were successfully processed - no questions were valid", None
1076
+
1077
+ # Submit answers
1078
+ submission_result = await api_submit_answers(processed_answers, profile.username)
1079
+
1080
+ status_message = (
1081
+ f"Successfully processed {len(processed_answers)} questions\n"
1082
+ f"Username: {profile.username}\n"
1083
+ f"Submission Result: {submission_result.get('message', 'No message')}\n"
1084
+ f"Total Questions: {len(questions)}, Successfully Processed: {len(processed_answers)}"
1085
+ )
1086
+
1087
+ return status_message, pd.DataFrame(results_log)
1088
+
1089
+ except Exception as e:
1090
+ error_msg = f"Error in processing: {str(e)}"
1091
+ logger.error(error_msg)
1092
+ # Log the full traceback for debugging
1093
+ import traceback
1094
+ logger.error(f"Full traceback: {traceback.format_exc()}")
1095
+ return error_msg, pd.DataFrame([{
1096
+ 'Task ID': 'Error',
1097
+ 'Question': 'Error occurred during processing',
1098
+ 'Answer': str(e),
1099
+ 'Confidence': '0.00',
1100
+ 'Processing Time': '0.00s'
1101
+ }])
1102
+
1103
  # Create Gradio interface
1104
  with gr.Blocks() as demo:
1105
  gr.Markdown("# Improved GAIA Agent")
 
1118
  outputs=[status_output, results_table]
1119
  )
1120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1121
  # Mount Gradio app to FastAPI
1122
  app = gr.mount_gradio_app(app, demo, path="/")
1123
 
1124
+ # For Hugging Face Spaces, we don't need to run the server manually
1125
+ # The platform will handle it for us
1126
  if __name__ == "__main__":
1127
+ # Only run the server directly when not in a Hugging Face Space
1128
+ if not os.environ.get("SPACE_ID"):
1129
+ import uvicorn
1130
+ uvicorn.run(app, host="0.0.0.0", port=7860)