jm-vis commited on
Commit
528d2e7
·
1 Parent(s): 479e45b

Fix runtime error and enhance GAIA Agent implementation

Browse files
Files changed (3) hide show
  1. README.md +0 -13
  2. agent.py +216 -407
  3. app.py +307 -53
README.md CHANGED
@@ -1,16 +1,3 @@
1
- ---
2
- title: GAIA Agent
3
- emoji: 🤖
4
- colorFrom: blue
5
- colorTo: green
6
- sdk: gradio
7
- sdk_version: 3.44.4
8
- app_file: app.py
9
- pinned: false
10
- hf_oauth: true
11
- hf_oauth_expiration_minutes: 480
12
- ---
13
-
14
  # GAIA Agent - Grounded AI Assistant
15
 
16
  ![GAIA Agent Logo](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter9/gaia-agent.png)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # GAIA Agent - Grounded AI Assistant
2
 
3
  ![GAIA Agent Logo](https://huggingface.co/datasets/huggingface-course/documentation-images/resolve/main/en/chapter9/gaia-agent.png)
agent.py CHANGED
@@ -36,14 +36,27 @@ logging.basicConfig(
36
  )
37
  logger = logging.getLogger("gaia_agent")
38
 
39
- # Environment variables and configuration
40
- OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
41
- SERPER_API_KEY = os.getenv("SERPER_API_KEY")
 
42
  SERPER_API_URL = os.getenv("SERPER_API_URL", "https://google.serper.dev/search")
43
- SUPABASE_URL = os.getenv("SUPABASE_URL")
44
- SUPABASE_KEY = os.getenv("SUPABASE_KEY")
45
  USER_AGENT = os.getenv("USER_AGENT", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36")
46
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  # Try to import web search libraries but handle ImportError gracefully
48
  try:
49
  from duckduckgo_search import DDGS
@@ -139,10 +152,27 @@ class WebSearchTool:
139
 
140
  def search(self, query: str) -> List[Dict[str, Any]]:
141
  """Search using the best available search method"""
 
142
  if DDGS_AVAILABLE:
143
- return self._search_duckduckgo(query)
144
- else:
145
- return self._search_serper(query)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
 
147
  def _search_duckduckgo(self, query: str) -> List[Dict[str, Any]]:
148
  """Search using DuckDuckGo"""
@@ -173,8 +203,12 @@ class WebSearchTool:
173
 
174
  def _search_serper(self, query: str) -> List[Dict[str, Any]]:
175
  """Search using Serper API if available"""
176
- if not SERPER_API_KEY or not WEB_TOOLS_AVAILABLE:
177
- logger.warning("Serper API key not set or web tools not available")
 
 
 
 
178
  return []
179
 
180
  try:
@@ -223,7 +257,13 @@ class ContentExtractor:
223
  """Extract content from a web page"""
224
  if not WEB_TOOLS_AVAILABLE:
225
  logger.warning("Web tools not available for content extraction")
226
- return {"error": "Web content extraction not available"}
 
 
 
 
 
 
227
 
228
  try:
229
  headers = {"User-Agent": USER_AGENT}
@@ -430,81 +470,180 @@ def create_fallback_plan(state: AgentState) -> List[Dict[str, Any]]:
430
 
431
  def execute_tool(state: AgentState) -> AgentState:
432
  """Execute the current tool in the plan"""
 
 
 
 
 
 
433
  try:
434
- # Get current step
435
- current_step = state.get("current_step", 0)
436
- plan = state.get("plan", [])
437
 
438
  # Check if we've reached the end of the plan
439
  if current_step >= len(plan):
 
440
  return {
441
  **state,
442
  "current_step": current_step + 1
443
  }
444
 
445
- # Get step details
446
  step = plan[current_step]
 
 
 
 
447
  tool_name = step.get("tool")
448
  tool_input = step.get("tool_input", {})
449
 
450
  # Skip if no tool is specified
451
  if not tool_name:
 
452
  return {
453
  **state,
454
  "current_step": current_step + 1
455
  }
456
 
457
- # Execute the appropriate tool
 
 
458
  result = {"tool_name": tool_name, "success": False, "error": None}
459
 
460
  if tool_name == "web_search":
461
- # Execute web search
462
- query = tool_input.get("query", state["question"])
463
- search_tool = WebSearchTool()
464
- search_results = search_tool.search(query)
465
-
466
- result = {
467
- "tool_name": tool_name,
468
- "success": True,
469
- "query": query,
470
- "results": search_results,
471
- "error": None
472
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
473
 
474
  elif tool_name == "content_extraction":
475
- # Extract content from URL
476
- url = tool_input.get("url")
477
-
478
- # If URL is not directly specified, get it from search results
479
- if not url and tool_input.get("url_from_search_results", False):
480
- # Find the most recent web_search results
481
- for past_result in reversed(state.get("tool_results", [])):
482
- if past_result.get("tool_name") == "web_search" and past_result.get("success"):
483
- search_results = past_result.get("results", [])
484
- if search_results:
485
- url = search_results[0].get("link")
486
- break
487
-
488
- if url:
489
- extractor = ContentExtractor()
490
- content = extractor.extract_content(url)
491
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
492
  result = {
493
  "tool_name": tool_name,
494
- "success": content.get("success", False),
495
- "url": url,
496
- "content": content,
497
- "error": content.get("error")
498
  }
499
- else:
 
 
 
 
 
 
 
 
 
500
  result = {
501
  "tool_name": tool_name,
502
  "success": False,
503
- "error": "No URL provided or found in search results"
 
504
  }
505
 
506
  else:
507
  # Unknown tool
 
508
  result = {
509
  "tool_name": tool_name,
510
  "success": False,
@@ -514,6 +653,12 @@ def execute_tool(state: AgentState) -> AgentState:
514
  # Update state with tool results
515
  tool_results = state.get("tool_results", []) or []
516
 
 
 
 
 
 
 
517
  return {
518
  **state,
519
  "tool_results": tool_results + [result],
@@ -521,370 +666,34 @@ def execute_tool(state: AgentState) -> AgentState:
521
  }
522
 
523
  except Exception as e:
524
- logger.error(f"Error executing tool: {str(e)}")
525
- traceback.print_exc()
 
526
 
527
  # Update state with error
528
  tool_results = state.get("tool_results", []) or []
529
 
 
 
 
 
 
 
 
 
 
 
 
 
 
530
  return {
531
  **state,
532
  "tool_results": tool_results + [{
533
- "tool_name": plan[current_step].get("tool", "unknown"),
534
  "success": False,
535
- "error": str(e)
 
536
  }],
537
  "current_step": current_step + 1,
538
- "error": f"Error during tool execution: {str(e)}"
539
- }
540
-
541
- def formulate_answer(state: AgentState, llm) -> AgentState:
542
- """Formulate an answer based on tool results and reasoning"""
543
- try:
544
- template = """
545
- You are an expert assistant answering questions based on the information gathered using various tools.
546
-
547
- Question: {question}
548
-
549
- Tool Results:
550
- {tool_results}
551
-
552
- Based on these tool results, provide:
553
- 1. A detailed, comprehensive answer to the question
554
- 2. Your reasoning process that led to this answer
555
-
556
- If the tools didn't provide enough information, explain what additional information would be needed and provide the best answer possible with the available information.
557
-
558
- Answer the question directly and comprehensively.
559
- """
560
-
561
- # Format tool results for the prompt
562
- tool_results_formatted = json.dumps(state.get("tool_results", []), indent=2)
563
-
564
- prompt = ChatPromptTemplate.from_messages([
565
- ("system", template),
566
- ("human", "Please formulate an answer to the question.")
567
- ])
568
-
569
- chain = prompt | llm | StrOutputParser()
570
-
571
- response = chain.invoke({
572
- "question": state["question"],
573
- "tool_results": tool_results_formatted
574
- })
575
-
576
- # Extract reasoning and answer
577
- # Typically LLMs format with "Reasoning:" and "Answer:" sections
578
- reasoning = ""
579
- answer = response
580
-
581
- reasoning_match = re.search(r'(?:Reasoning:|My reasoning:|Reasoning process:)(.*?)(?:Answer:|My answer:|Comprehensive answer:)', response, re.DOTALL | re.IGNORECASE)
582
- answer_match = re.search(r'(?:Answer:|My answer:|Comprehensive answer:)(.*)', response, re.DOTALL | re.IGNORECASE)
583
-
584
- if reasoning_match:
585
- reasoning = reasoning_match.group(1).strip()
586
-
587
- if answer_match:
588
- answer = answer_match.group(1).strip()
589
- # If no structured format found, keep the whole response as the answer
590
-
591
- return {
592
- **state,
593
- "reasoning": reasoning,
594
- "answer": answer
595
- }
596
- except Exception as e:
597
- logger.error(f"Error formulating answer: {str(e)}")
598
-
599
- # Create a fallback answer
600
- return {
601
- **state,
602
- "reasoning": f"Error occurred: {str(e)}",
603
- "answer": "I apologize, but I encountered an error while formulating my answer. The available information wasn't sufficient to provide a comprehensive response. Please try asking your question again, perhaps with more details or in a different way.",
604
- "error": f"Error during answer formulation: {str(e)}"
605
- }
606
-
607
- def should_continue(state: AgentState) -> Literal["continue", "complete"]:
608
- """Determine if the agent should continue or is finished"""
609
- current_step = state.get("current_step", 0)
610
- plan = state.get("plan", [])
611
-
612
- # Check if we still have steps to execute
613
- if current_step is None or plan is None:
614
- return "complete"
615
-
616
- if current_step < len(plan):
617
- return "continue"
618
-
619
- return "complete"
620
-
621
- def run_agent_graph(question: str) -> Dict[str, Any]:
622
- """Run the agent graph workflow with the given question"""
623
- try:
624
- # Initialize LLM with error handling
625
- if OPENAI_API_KEY:
626
- llm = ChatOpenAI(
627
- temperature=0,
628
- model="gpt-3.5-turbo",
629
- api_key=OPENAI_API_KEY
630
- )
631
- else:
632
- logger.warning("OPENAI_API_KEY not set, using Hugging Face fallback")
633
- # Fallback implementation will use a simpler approach
634
- return run_fallback_agent(question)
635
-
636
- # Create initial state
637
- state: AgentState = {
638
- "question": question,
639
- "analysis": None,
640
- "plan": None,
641
- "current_step": None,
642
- "tool_results": [],
643
- "reasoning": None,
644
- "answer": None,
645
- "error": None
646
- }
647
-
648
- # Create workflow as sequential function calls
649
- # This is a simplified version of a LangGraph workflow
650
- state = analyze_question(state, llm)
651
- state = create_plan(state, llm)
652
-
653
- # Execute tools until complete
654
- while should_continue(state) == "continue":
655
- state = execute_tool(state)
656
-
657
- state = formulate_answer(state, llm)
658
-
659
- # Cache results for future use if the same question comes up
660
- memory = SimpleMemory()
661
- cache_key = f"answer:{hashlib.md5(question.encode()).hexdigest()}"
662
- memory.cache_result(cache_key, state["answer"])
663
-
664
- logger.info(f"Agent workflow completed for question: {question[:50]}...")
665
-
666
- # Return final state with answer and reasoning
667
- return {
668
- "answer": state["answer"],
669
- "reasoning": state["reasoning"],
670
- "error": state["error"]
671
- }
672
-
673
- except Exception as e:
674
- logger.error(f"Error running agent graph: {str(e)}")
675
- traceback.print_exc()
676
-
677
- # Return error information
678
- return {
679
- "answer": f"I encountered an error while processing your question: {str(e)}",
680
- "reasoning": f"An error occurred: {str(e)}",
681
- "error": str(e)
682
- }
683
-
684
- def run_fallback_agent(question: str) -> Dict[str, Any]:
685
- """Simple fallback implementation when LLM is not available"""
686
- try:
687
- # Simple pattern matching for some question types
688
- if "how" in question.lower():
689
- answer = f"To address '{question.strip('?')}', I would recommend following these steps: 1) Understand the core concepts, 2) Apply a structured approach, 3) Evaluate results, and 4) Refine as needed. Without being able to access external knowledge at the moment, this is a general framework for addressing how-to questions."
690
- elif "what" in question.lower():
691
- answer = f"Regarding '{question.strip('?')}', this typically involves understanding several key factors. While I don't have access to external knowledge at the moment, this type of question usually requires defining terms, establishing context, and examining relevant concepts."
692
- elif "why" in question.lower():
693
- answer = f"The question '{question.strip('?')}' relates to causality and explanation. Such questions typically involve understanding underlying mechanisms, historical context, and logical relationships between factors."
694
- else:
695
- answer = f"I've considered your question: '{question.strip('?')}'. To provide a comprehensive answer, I would normally research this topic and analyze relevant information from reliable sources. However, I'm currently operating in a fallback mode without access to external knowledge or advanced language models."
696
-
697
- return {
698
- "answer": answer,
699
- "reasoning": "Using fallback pattern matching due to unavailable language model",
700
- "error": None
701
- }
702
- except Exception as e:
703
- logger.error(f"Error in fallback agent: {str(e)}")
704
-
705
- return {
706
- "answer": f"I apologize, but I encountered an error while processing your question. Please try asking in a different way.",
707
- "reasoning": f"Error in fallback processing: {str(e)}",
708
- "error": str(e)
709
- }
710
-
711
- class GAIAAgent:
712
- """
713
- Simplified GAIA Agent that uses LangGraph workflow for processing questions
714
-
715
- This implementation provides direct tool integration, simplified prompt construction,
716
- clear execution flow, and robust error handling.
717
- """
718
-
719
- def __init__(self):
720
- """Initialize the GAIA agent with simplified configuration"""
721
- self.memory = SimpleMemory()
722
- logger.info("GAIA Agent initialized")
723
-
724
- def __call__(self, question: str) -> str:
725
- """
726
- Process a question and generate an answer.
727
- Compatible with the interface expected by app.py.
728
-
729
- Args:
730
- question (str): The question to process
731
-
732
- Returns:
733
- str: The answer to the question
734
- """
735
- return self.process_question(question)
736
-
737
- def process_question(self, question: str) -> str:
738
- """
739
- Process a question and generate an answer.
740
-
741
- Args:
742
- question (str): The question to process
743
-
744
- Returns:
745
- str: The answer to the question
746
- """
747
- start_time = time.time()
748
-
749
- try:
750
- logger.info(f"Processing question: {question[:100]}...")
751
-
752
- # Check cache first
753
- cache_key = f"answer:{hashlib.md5(question.encode()).hexdigest()}"
754
- cached_answer = self.memory.get_cached_result(cache_key)
755
-
756
- if cached_answer:
757
- logger.info(f"Using cached answer for question: {question[:50]}...")
758
- return cached_answer
759
-
760
- # Special case handling for reversed text questions
761
- # First, try directly checking for the reversed pattern
762
- reversed_question = question[::-1]
763
-
764
- # Check if the reversed question makes sense
765
- if "Write the opposite of" in reversed_question:
766
- logger.info(f"Detected reversed question. Reversed text: {reversed_question}")
767
-
768
- # Check for specific words in the reversed question
769
- if "'up'" in reversed_question or '"up"' in reversed_question or "up." in reversed_question:
770
- return "down"
771
- elif "'down'" in reversed_question or '"down"' in reversed_question or "down." in reversed_question:
772
- return "up"
773
- elif "'left'" in reversed_question or '"left"' in reversed_question or "left." in reversed_question:
774
- return "right"
775
- elif "'right'" in reversed_question or '"right"' in reversed_question or "right." in reversed_question:
776
- return "left"
777
-
778
- # Alternative patterns detection
779
- if ".rewsna eht sa" in question or ".etirW" in question:
780
- logger.info(f"Detected possible reversed question via patterns. Reversed: {reversed_question}")
781
-
782
- # Handle specific reversed text cases
783
- if "left" in reversed_question and "opposite" in reversed_question:
784
- return "right"
785
- elif "right" in reversed_question and "opposite" in reversed_question:
786
- return "left"
787
- elif "up" in reversed_question and "opposite" in reversed_question:
788
- return "down"
789
- elif "down" in reversed_question and "opposite" in reversed_question:
790
- return "up"
791
-
792
- # Check for the word pattern without quotes
793
- if "word up" in reversed_question:
794
- return "down"
795
- elif "word down" in reversed_question:
796
- return "up"
797
- elif "word left" in reversed_question:
798
- return "right"
799
- elif "word right" in reversed_question:
800
- return "left"
801
-
802
- # Handle direct text manipulation questions
803
- if question.lower() == "write the opposite of the word 'up'.":
804
- return "down"
805
- elif question.lower() == "write the opposite of the word 'down'.":
806
- return "up"
807
- elif question.lower() == "write the opposite of the word 'left'.":
808
- return "right"
809
- elif question.lower() == "write the opposite of the word 'right'.":
810
- return "left"
811
-
812
- # Process the question using the agent graph
813
- result = run_agent_graph(question)
814
- answer = result["answer"]
815
-
816
- # Cache the result
817
- self.memory.cache_result(cache_key, answer)
818
-
819
- end_time = time.time()
820
- processing_time = end_time - start_time
821
-
822
- logger.info(f"Question processed in {processing_time:.2f} seconds")
823
-
824
- return answer
825
-
826
- except Exception as e:
827
- end_time = time.time()
828
- processing_time = end_time - start_time
829
-
830
- logger.error(f"Error processing question: {str(e)}")
831
- logger.error(traceback.format_exc())
832
-
833
- logger.info(f"Question processing failed in {processing_time:.2f} seconds")
834
-
835
- return f"I apologize, but I encountered an error while processing your question: {str(e)}. Please try asking in a different way."
836
-
837
- def query(self, question: str) -> Dict[str, Any]:
838
- """
839
- Query the agent with a question to get an answer with metadata.
840
-
841
- Args:
842
- question (str): The question to answer
843
-
844
- Returns:
845
- Dict[str, Any]: Dictionary containing the answer and metadata
846
- """
847
- try:
848
- start_time = time.time()
849
-
850
- # Process the question
851
- result = run_agent_graph(question)
852
- answer = result["answer"]
853
- reasoning = result.get("reasoning", "")
854
- error = result.get("error")
855
-
856
- end_time = time.time()
857
- processing_time = end_time - start_time
858
-
859
- # Determine tools used based on the workflow
860
- tools_used = []
861
- if "web search" in reasoning.lower() or "search results" in reasoning.lower():
862
- tools_used.append("web_search")
863
- if "extract" in reasoning.lower() and "content" in reasoning.lower():
864
- tools_used.append("content_extraction")
865
-
866
- return {
867
- "answer": answer,
868
- "reasoning": reasoning,
869
- "time_taken": processing_time,
870
- "tools_used": tools_used,
871
- "success": error is None,
872
- "error": error
873
- }
874
-
875
- except Exception as e:
876
- logger.error(f"Error in query: {str(e)}")
877
-
878
- return {
879
- "answer": f"Error: {str(e)}",
880
- "reasoning": f"An error occurred: {str(e)}",
881
- "time_taken": 0,
882
- "tools_used": [],
883
- "success": False,
884
- "error": str(e)
885
- }
886
-
887
- def clear_memory(self):
888
- """Clear the agent's memory"""
889
- self.memory.clear()
890
- logger.info("Agent memory cleared")
 
36
  )
37
  logger = logging.getLogger("gaia_agent")
38
 
39
+ # Environment variables and configuration with default values
40
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
41
+ SERPER_API_KEY = os.getenv("SERPER_API_KEY", "")
42
+ PERPLEXITY_API_KEY = os.getenv("PERPLEXITY_API_KEY", "")
43
  SERPER_API_URL = os.getenv("SERPER_API_URL", "https://google.serper.dev/search")
44
+ SUPABASE_URL = os.getenv("SUPABASE_URL", "")
45
+ SUPABASE_KEY = os.getenv("SUPABASE_KEY", "")
46
  USER_AGENT = os.getenv("USER_AGENT", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36")
47
 
48
+ # Log warnings for critical missing environment variables
49
+ if not OPENAI_API_KEY:
50
+ logger.warning("OPENAI_API_KEY is not set. Agent will use fallback mode with limited capabilities.")
51
+ if not SERPER_API_KEY and not PERPLEXITY_API_KEY:
52
+ logger.warning("Neither SERPER_API_KEY nor PERPLEXITY_API_KEY is set. Web search capabilities will be limited.")
53
+ elif not SERPER_API_KEY:
54
+ logger.warning("SERPER_API_KEY is not set. Will attempt to use Perplexity for search if available.")
55
+ elif not PERPLEXITY_API_KEY:
56
+ logger.warning("PERPLEXITY_API_KEY is not set. Will use Serper for search capabilities.")
57
+ if not SUPABASE_URL or not SUPABASE_KEY:
58
+ logger.warning("SUPABASE_URL or SUPABASE_KEY is not set. Memory persistence will be limited to in-memory storage.")
59
+
60
  # Try to import web search libraries but handle ImportError gracefully
61
  try:
62
  from duckduckgo_search import DDGS
 
152
 
153
  def search(self, query: str) -> List[Dict[str, Any]]:
154
  """Search using the best available search method"""
155
+ # Prioritize DuckDuckGo as it doesn't require an API key
156
  if DDGS_AVAILABLE:
157
+ results = self._search_duckduckgo(query)
158
+ if results: # If DuckDuckGo returns results, use them
159
+ return results
160
+
161
+ # Fall back to Serper if DuckDuckGo fails or is unavailable
162
+ if SERPER_API_KEY and WEB_TOOLS_AVAILABLE:
163
+ results = self._search_serper(query)
164
+ if results:
165
+ return results
166
+
167
+ # If all search methods fail, return a message in search result format
168
+ logger.warning("All search methods failed or unavailable")
169
+ return [
170
+ {
171
+ "title": "Search Unavailable",
172
+ "link": "",
173
+ "snippet": "Search functionality is currently unavailable. Please ensure that either DuckDuckGo package is installed or SERPER_API_KEY is set."
174
+ }
175
+ ]
176
 
177
  def _search_duckduckgo(self, query: str) -> List[Dict[str, Any]]:
178
  """Search using DuckDuckGo"""
 
203
 
204
  def _search_serper(self, query: str) -> List[Dict[str, Any]]:
205
  """Search using Serper API if available"""
206
+ if not SERPER_API_KEY:
207
+ logger.warning("Serper API key not set")
208
+ return []
209
+
210
+ if not WEB_TOOLS_AVAILABLE:
211
+ logger.warning("Web tools not available")
212
  return []
213
 
214
  try:
 
257
  """Extract content from a web page"""
258
  if not WEB_TOOLS_AVAILABLE:
259
  logger.warning("Web tools not available for content extraction")
260
+ return {
261
+ "url": url,
262
+ "title": "Content Extraction Unavailable",
263
+ "content": "Web content extraction is currently unavailable. Please ensure that requests and BeautifulSoup packages are installed.",
264
+ "success": False,
265
+ "error": "Web tools dependencies not available"
266
+ }
267
 
268
  try:
269
  headers = {"User-Agent": USER_AGENT}
 
470
 
471
  def execute_tool(state: AgentState) -> AgentState:
472
  """Execute the current tool in the plan"""
473
+ # Initialize variables at the top for use in except blocks
474
+ current_step = state.get("current_step", 0)
475
+ plan = state.get("plan", [])
476
+ tool_name = "unknown"
477
+ tool_input = {}
478
+
479
  try:
480
+ # Validate state
481
+ if not isinstance(state, dict):
482
+ raise ValueError(f"Invalid state type: {type(state)}. Expected dict.")
483
 
484
  # Check if we've reached the end of the plan
485
  if current_step >= len(plan):
486
+ logger.info("Execute tool: reached end of plan")
487
  return {
488
  **state,
489
  "current_step": current_step + 1
490
  }
491
 
492
+ # Get step details with validation
493
  step = plan[current_step]
494
+ if not isinstance(step, dict):
495
+ logger.error(f"Invalid step format at position {current_step}: {type(step)}")
496
+ raise ValueError(f"Invalid step format at position {current_step}")
497
+
498
  tool_name = step.get("tool")
499
  tool_input = step.get("tool_input", {})
500
 
501
  # Skip if no tool is specified
502
  if not tool_name:
503
+ logger.info(f"No tool specified for step {current_step}, skipping")
504
  return {
505
  **state,
506
  "current_step": current_step + 1
507
  }
508
 
509
+ logger.info(f"Executing tool '{tool_name}' for step {current_step}")
510
+
511
+ # Execute the appropriate tool with specific error handling for each tool type
512
  result = {"tool_name": tool_name, "success": False, "error": None}
513
 
514
  if tool_name == "web_search":
515
+ try:
516
+ # Execute web search with input validation
517
+ query = tool_input.get("query", state["question"])
518
+ if not query or not isinstance(query, str):
519
+ raise ValueError("Invalid search query: must be a non-empty string")
520
+
521
+ # Truncate overly long queries
522
+ if len(query) > 500:
523
+ logger.warning(f"Search query too long ({len(query)} chars), truncating to 500 chars")
524
+ query = query[:497] + "..."
525
+
526
+ search_tool = WebSearchTool()
527
+ search_results = search_tool.search(query)
528
+
529
+ # Validate search results
530
+ if not isinstance(search_results, list):
531
+ logger.warning(f"Invalid search results type: {type(search_results)}")
532
+ search_results = []
533
+
534
+ result = {
535
+ "tool_name": tool_name,
536
+ "success": len(search_results) > 0,
537
+ "query": query,
538
+ "results": search_results,
539
+ "error": None if search_results else "No search results found"
540
+ }
541
+
542
+ # Check if search results indicate an API error
543
+ if any("API key" in result.get("title", "") or "API key" in result.get("snippet", "")
544
+ for result in search_results):
545
+ logger.error("Search results indicate API key issue")
546
+ result["error"] = "Search API key error detected in results"
547
+ result["success"] = False
548
+
549
+ except ConnectionError as conn_err:
550
+ logger.error(f"Connection error in web search: {str(conn_err)}")
551
+ result = {
552
+ "tool_name": tool_name,
553
+ "success": False,
554
+ "query": tool_input.get("query", state["question"]),
555
+ "results": [],
556
+ "error": f"Connection error: {str(conn_err)}"
557
+ }
558
+ except TimeoutError as timeout_err:
559
+ logger.error(f"Timeout error in web search: {str(timeout_err)}")
560
+ result = {
561
+ "tool_name": tool_name,
562
+ "success": False,
563
+ "query": tool_input.get("query", state["question"]),
564
+ "results": [],
565
+ "error": f"Search timed out: {str(timeout_err)}"
566
+ }
567
+ except Exception as search_err:
568
+ logger.error(f"Error in web search: {str(search_err)}")
569
+ result = {
570
+ "tool_name": tool_name,
571
+ "success": False,
572
+ "query": tool_input.get("query", state["question"]),
573
+ "results": [],
574
+ "error": f"Search error: {str(search_err)}"
575
+ }
576
 
577
  elif tool_name == "content_extraction":
578
+ try:
579
+ # Extract content from URL with validation
580
+ url = tool_input.get("url")
 
 
 
 
 
 
 
 
 
 
 
 
 
581
 
582
+ # If URL is not directly specified, get it from search results
583
+ if not url and tool_input.get("url_from_search_results", False):
584
+ # Find the most recent web_search results
585
+ for past_result in reversed(state.get("tool_results", [])):
586
+ if past_result.get("tool_name") == "web_search" and past_result.get("success"):
587
+ search_results = past_result.get("results", [])
588
+ if search_results:
589
+ url = search_results[0].get("link")
590
+ break
591
+
592
+ # Validate URL
593
+ if not url or not isinstance(url, str):
594
+ logger.warning("No valid URL found for content extraction")
595
+ result = {
596
+ "tool_name": tool_name,
597
+ "success": False,
598
+ "error": "No valid URL provided or found in search results"
599
+ }
600
+ elif not url.startswith(("http://", "https://")):
601
+ logger.warning(f"Invalid URL format: {url}")
602
+ result = {
603
+ "tool_name": tool_name,
604
+ "success": False,
605
+ "url": url,
606
+ "error": "Invalid URL format: URL must start with http:// or https://"
607
+ }
608
+ else:
609
+ extractor = ContentExtractor()
610
+ content = extractor.extract_content(url)
611
+
612
+ result = {
613
+ "tool_name": tool_name,
614
+ "success": content.get("success", False),
615
+ "url": url,
616
+ "content": content,
617
+ "error": content.get("error")
618
+ }
619
+ except ConnectionError as conn_err:
620
+ logger.error(f"Connection error in content extraction: {str(conn_err)}")
621
  result = {
622
  "tool_name": tool_name,
623
+ "success": False,
624
+ "url": tool_input.get("url", "unknown"),
625
+ "error": f"Connection error during content extraction: {str(conn_err)}"
 
626
  }
627
+ except TimeoutError as timeout_err:
628
+ logger.error(f"Timeout error in content extraction: {str(timeout_err)}")
629
+ result = {
630
+ "tool_name": tool_name,
631
+ "success": False,
632
+ "url": tool_input.get("url", "unknown"),
633
+ "error": f"Content extraction timed out: {str(timeout_err)}"
634
+ }
635
+ except Exception as extract_err:
636
+ logger.error(f"Error in content extraction: {str(extract_err)}")
637
  result = {
638
  "tool_name": tool_name,
639
  "success": False,
640
+ "url": tool_input.get("url", "unknown"),
641
+ "error": f"Content extraction error: {str(extract_err)}"
642
  }
643
 
644
  else:
645
  # Unknown tool
646
+ logger.warning(f"Unknown tool requested: {tool_name}")
647
  result = {
648
  "tool_name": tool_name,
649
  "success": False,
 
653
  # Update state with tool results
654
  tool_results = state.get("tool_results", []) or []
655
 
656
+ # Log tool execution result
657
+ if result.get("success"):
658
+ logger.info(f"Tool '{tool_name}' executed successfully")
659
+ else:
660
+ logger.warning(f"Tool '{tool_name}' execution failed: {result.get('error')}")
661
+
662
  return {
663
  **state,
664
  "tool_results": tool_results + [result],
 
666
  }
667
 
668
  except Exception as e:
669
+ error_type = type(e).__name__
670
+ logger.error(f"Error executing tool '{tool_name}': {error_type}: {str(e)}")
671
+ logger.error(traceback.format_exc())
672
 
673
  # Update state with error
674
  tool_results = state.get("tool_results", []) or []
675
 
676
+ # Provide specific error message based on error type
677
+ error_message = str(e)
678
+ if "ConnectionError" in error_type or "requests.exceptions" in error_type:
679
+ error_message = f"Connection error during tool execution: {str(e)}. This might be due to network issues or the service being unavailable."
680
+ elif "TimeoutError" in error_type:
681
+ error_message = f"Tool execution timed out: {str(e)}. The operation took too long to complete."
682
+ elif "JSONDecodeError" in error_type:
683
+ error_message = f"Error parsing response data: {str(e)}. The service returned an unexpected format."
684
+ elif "KeyError" in error_type or "AttributeError" in error_type:
685
+ error_message = f"Missing or invalid data during tool execution: {str(e)}. This might be due to incomplete or malformed data."
686
+ elif "AuthenticationError" in error_type or "api key" in str(e).lower():
687
+ error_message = f"Authentication error during tool execution: {str(e)}. This might be due to invalid API credentials."
688
+
689
  return {
690
  **state,
691
  "tool_results": tool_results + [{
692
+ "tool_name": tool_name,
693
  "success": False,
694
+ "error": error_message,
695
+ "error_type": error_type
696
  }],
697
  "current_step": current_step + 1,
698
+ "error": f"Error during tool execution: {error_message}"
699
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -29,11 +29,62 @@ logging.basicConfig(
29
  )
30
  logger = logging.getLogger("gaia_app")
31
 
32
- # Check for required environment variables
33
- OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
34
- SERPER_API_KEY = os.getenv("SERPER_API_KEY")
35
- SUPABASE_URL = os.getenv("SUPABASE_URL")
36
- SUPABASE_KEY = os.getenv("SUPABASE_KEY")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  # Custom CSS for improved appearance
39
  custom_css = """
@@ -88,13 +139,14 @@ def check_environment() -> Dict[str, bool]:
88
  return {
89
  "OPENAI_API_KEY": bool(OPENAI_API_KEY),
90
  "SERPER_API_KEY": bool(SERPER_API_KEY),
 
91
  "SUPABASE_URL": bool(SUPABASE_URL),
92
  "SUPABASE_KEY": bool(SUPABASE_KEY),
93
  }
94
 
95
  def process_question(
96
- message: str,
97
- history: list,
98
  agent_instance: Optional[GAIAAgent] = None,
99
  progress=gr.Progress()
100
  ) -> tuple:
@@ -110,34 +162,115 @@ def process_question(
110
  Returns:
111
  Tuple of (history, error_message)
112
  """
113
- if not message.strip():
 
 
 
 
114
  return history, "Please enter a question."
 
 
 
 
 
 
 
 
 
 
 
 
 
115
 
116
- # Check if agent is available
117
  if agent_instance is None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  return (
119
- history + [(message, "Error: GAIA Agent is not initialized. Please check logs for details.")],
120
- "GAIA Agent initialization failed. Please check that all required environment variables are set."
121
  )
122
 
123
- progress(0.1, desc="Processing question...")
 
 
 
 
 
 
124
  error_message = ""
125
 
126
  try:
127
- # Process the question
128
- progress(0.4, desc="Thinking...")
 
 
 
 
 
 
 
129
  response = agent_instance.process_question(message)
130
- progress(1.0, desc="Done!")
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
  # Return the updated history and empty error message
133
  return history + [(message, response)], ""
 
134
  except Exception as e:
135
  error_details = traceback.format_exc()
136
- logger.error(f"Error processing question: {e}")
 
137
  logger.error(error_details)
138
 
139
- error_message = f"Error processing your question: {str(e)}"
140
- return history + [(message, f"I encountered an error while processing your question. Please try again or rephrase your question.")], error_message
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
 
142
  def clear_conversation(agent_instance: Optional[GAIAAgent] = None) -> tuple:
143
  """
@@ -149,14 +282,47 @@ def clear_conversation(agent_instance: Optional[GAIAAgent] = None) -> tuple:
149
  Returns:
150
  Empty history and status message
151
  """
 
 
 
 
 
152
  if agent_instance:
153
  try:
 
 
 
 
 
 
 
154
  agent_instance.clear_memory()
155
- logger.info("Conversation and agent memory cleared")
 
 
 
 
156
  except Exception as e:
157
- logger.error(f"Error clearing agent memory: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
158
 
159
- return [], "Conversation cleared."
 
 
 
 
160
 
161
  def create_interface():
162
  """
@@ -246,40 +412,128 @@ def create_interface():
246
  """
247
  )
248
 
249
- # Set up event handlers
250
- submit_btn.click(
251
- fn=process_question,
252
- inputs=[msg, chatbot, agent_instance],
253
- outputs=[chatbot, error_box],
254
- api_name="submit"
255
- )
256
-
257
- msg.submit(
258
- fn=process_question,
259
- inputs=[msg, chatbot, agent_instance],
260
- outputs=[chatbot, error_box],
261
- api_name="ask"
262
- )
 
 
 
 
 
 
 
 
 
 
263
 
264
- clear_btn.click(
265
- fn=clear_conversation,
266
- inputs=[agent_instance],
267
- outputs=[chatbot, error_box],
268
- api_name="clear"
269
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
 
271
  return demo
272
 
273
  if __name__ == "__main__":
274
- # Check if running in a Hugging Face Space
275
- space_host = os.getenv("SPACE_HOST")
276
- space_id = os.getenv("SPACE_ID")
277
-
278
- if space_host:
279
- logger.info(f"Running on Hugging Face Space: {space_host}")
280
- if space_id:
281
- logger.info(f"Space ID: {space_id}")
282
-
283
- # Create and launch the interface
284
- demo = create_interface()
285
- demo.launch(debug=True, share=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  )
30
  logger = logging.getLogger("gaia_app")
31
 
32
+ # Load environment variables with error handling
33
+ def get_env_var(name, default="", required=False):
34
+ """Helper function to get environment variables with logging"""
35
+ value = os.getenv(name, default)
36
+ if not value and required:
37
+ logger.error(f"Required environment variable {name} is not set")
38
+ elif not value:
39
+ logger.warning(f"Optional environment variable {name} is not set")
40
+ return value
41
+
42
+ # Check for required environment variables with default values
43
+ OPENAI_API_KEY = get_env_var("OPENAI_API_KEY", "", True) # Critical for agent operation
44
+ SERPER_API_KEY = get_env_var("SERPER_API_KEY", "") # Optional but recommended
45
+ PERPLEXITY_API_KEY = get_env_var("PERPLEXITY_API_KEY", "") # Optional alternative to SERPER
46
+ SUPABASE_URL = get_env_var("SUPABASE_URL", "") # Optional for memory persistence
47
+ SUPABASE_KEY = get_env_var("SUPABASE_KEY", "") # Optional for memory persistence
48
+ SPACE_HOST = get_env_var("SPACE_HOST", "") # For Hugging Face Space detection
49
+ SPACE_ID = get_env_var("SPACE_ID", "") # For Hugging Face Space identification
50
+
51
+ # Validate critical dependencies
52
+ try:
53
+ import gradio as gr
54
+ except ImportError as e:
55
+ logger.critical(f"Critical dependency 'gradio' not found: {e}")
56
+ raise ImportError("Gradio is required for the app interface. Please install it with 'pip install gradio'.")
57
+
58
+ # Log warnings and detailed diagnostics for missing environment variables
59
+ if not OPENAI_API_KEY:
60
+ logger.warning("OPENAI_API_KEY is not set. Agent will use fallback mode with limited capabilities.")
61
+ logger.info("To get an OpenAI API key, visit: https://platform.openai.com/api-keys")
62
+
63
+ # Check search capabilities
64
+ search_capability = "full"
65
+ if not SERPER_API_KEY and not PERPLEXITY_API_KEY:
66
+ search_capability = "limited"
67
+ logger.warning("Neither SERPER_API_KEY nor PERPLEXITY_API_KEY is set. Web search capabilities will be limited to DuckDuckGo.")
68
+ logger.info("To get a Serper API key, visit: https://serper.dev/")
69
+ elif not SERPER_API_KEY:
70
+ search_capability = "partial"
71
+ logger.warning("SERPER_API_KEY is not set. Will attempt to use Perplexity for search if available.")
72
+ elif not PERPLEXITY_API_KEY:
73
+ search_capability = "partial"
74
+ logger.warning("PERPLEXITY_API_KEY is not set. Will use Serper for search capabilities.")
75
+
76
+ # Check memory persistence
77
+ if not SUPABASE_URL or not SUPABASE_KEY:
78
+ logger.warning("SUPABASE_URL or SUPABASE_KEY is not set. Memory persistence will be limited to in-memory storage.")
79
+ if SUPABASE_URL and not SUPABASE_KEY:
80
+ logger.error("SUPABASE_URL is set but SUPABASE_KEY is missing. Memory persistence will not work correctly.")
81
+ elif SUPABASE_KEY and not SUPABASE_URL:
82
+ logger.error("SUPABASE_KEY is set but SUPABASE_URL is missing. Memory persistence will not work correctly.")
83
+
84
+ # Log overall capability assessment
85
+ logger.info(f"GAIA Agent capabilities: LLM: {'available' if OPENAI_API_KEY else 'unavailable'}, "
86
+ f"Search: {search_capability}, "
87
+ f"Memory: {'persistent' if (SUPABASE_URL and SUPABASE_KEY) else 'in-memory only'}")
88
 
89
  # Custom CSS for improved appearance
90
  custom_css = """
 
139
  return {
140
  "OPENAI_API_KEY": bool(OPENAI_API_KEY),
141
  "SERPER_API_KEY": bool(SERPER_API_KEY),
142
+ "PERPLEXITY_API_KEY": bool(PERPLEXITY_API_KEY),
143
  "SUPABASE_URL": bool(SUPABASE_URL),
144
  "SUPABASE_KEY": bool(SUPABASE_KEY),
145
  }
146
 
147
  def process_question(
148
+ message: str,
149
+ history: list,
150
  agent_instance: Optional[GAIAAgent] = None,
151
  progress=gr.Progress()
152
  ) -> tuple:
 
162
  Returns:
163
  Tuple of (history, error_message)
164
  """
165
+ logger.info(f"Processing question request with message length: {len(message) if message else 0}")
166
+
167
+ # Input validation with detailed error messages
168
+ if not message:
169
+ logger.warning("Empty question received")
170
  return history, "Please enter a question."
171
+
172
+ if not isinstance(message, str):
173
+ logger.error(f"Invalid message type: {type(message)}. Expected string.")
174
+ return history, "Invalid input type. Please enter a text question."
175
+
176
+ if not message.strip():
177
+ logger.warning("Blank question (only whitespace) received")
178
+ return history, "Please enter a non-empty question."
179
+
180
+ # Validate history parameter
181
+ if not isinstance(history, list):
182
+ logger.error(f"Invalid history type: {type(history)}. Expected list.")
183
+ history = [] # Reset to empty list for recovery
184
 
185
+ # Check if agent is available with enhanced diagnostics
186
  if agent_instance is None:
187
+ logger.error("Agent instance is None when processing question")
188
+ # Generate a more specific error message based on environment variables
189
+ env_status = check_environment()
190
+ missing_vars = [key for key, value in env_status.items() if not value]
191
+
192
+ # Check if OPENAI_API_KEY is missing, as it's critical
193
+ critical_vars_missing = "OPENAI_API_KEY" in missing_vars
194
+
195
+ if missing_vars:
196
+ if critical_vars_missing:
197
+ error_detail = f"Critical environment variables missing: {', '.join(missing_vars)}"
198
+ logger.error(error_detail)
199
+ else:
200
+ error_detail = f"Some environment variables are missing: {', '.join(missing_vars)}"
201
+ logger.warning(error_detail)
202
+ else:
203
+ error_detail = "Unknown initialization error. Please check the application logs."
204
+ logger.error("Agent is None but no environment variables are missing")
205
+
206
+ user_message = "I'm unable to process your question because the AI agent isn't properly initialized."
207
+ if critical_vars_missing:
208
+ user_message += " This is likely due to missing API keys required for my operation."
209
+
210
  return (
211
+ history + [(message, user_message)],
212
+ f"GAIA Agent initialization failed. {error_detail}"
213
  )
214
 
215
+ # Initialize progress indicator with better error handling
216
+ try:
217
+ progress(0.1, desc="Processing question...")
218
+ except Exception as progress_err:
219
+ logger.warning(f"Non-critical error with progress indicator: {progress_err}")
220
+ # Continue execution - progress indicator issues shouldn't block processing
221
+
222
  error_message = ""
223
 
224
  try:
225
+ # Process the question with timing
226
+ start_time = time.time()
227
+ logger.info(f"Sending question to agent: '{message[:50]}{'...' if len(message) > 50 else ''}'")
228
+
229
+ try:
230
+ progress(0.4, desc="Thinking...")
231
+ except:
232
+ pass # Non-critical, continue even if progress update fails
233
+
234
  response = agent_instance.process_question(message)
235
+
236
+ try:
237
+ progress(1.0, desc="Done!")
238
+ except:
239
+ pass # Non-critical
240
+
241
+ processing_time = time.time() - start_time
242
+ logger.info(f"Question processed successfully in {processing_time:.2f} seconds")
243
+
244
+ # Validate response
245
+ if not response or not isinstance(response, str):
246
+ logger.warning(f"Agent returned invalid response type: {type(response)}")
247
+ response = "I generated a response but it was in an invalid format. Please try asking again."
248
 
249
  # Return the updated history and empty error message
250
  return history + [(message, response)], ""
251
+
252
  except Exception as e:
253
  error_details = traceback.format_exc()
254
+ error_type = type(e).__name__
255
+ logger.error(f"Error processing question: {error_type}: {e}")
256
  logger.error(error_details)
257
 
258
+ # Create user-friendly error message based on exception type
259
+ user_message = "I encountered an error while processing your question."
260
+
261
+ if "ConnectionError" in error_type or "Timeout" in error_type:
262
+ user_message += " It seems I'm having trouble connecting to my knowledge services. This might be a temporary network issue."
263
+ elif "JSONDecodeError" in error_type:
264
+ user_message += " I had trouble processing some data. This might be due to an unexpected format."
265
+ elif "AuthenticationError" in error_type or "api key" in str(e).lower():
266
+ user_message += " There seems to be an issue with my authentication to external services."
267
+ elif "MemoryError" in error_type or "OutOfMemoryError" in error_type:
268
+ user_message += " The question might be too complex for me to process with current resources."
269
+ else:
270
+ user_message += " Please try again or rephrase your question."
271
+
272
+ error_message = f"Error processing question: {error_type}: {str(e)}"
273
+ return history + [(message, user_message)], error_message
274
 
275
  def clear_conversation(agent_instance: Optional[GAIAAgent] = None) -> tuple:
276
  """
 
282
  Returns:
283
  Empty history and status message
284
  """
285
+ logger.info("Clear conversation request received")
286
+
287
+ # Track completion status to provide feedback
288
+ agent_memory_cleared = False
289
+
290
  if agent_instance:
291
  try:
292
+ # Validate agent instance has clear_memory method
293
+ if not hasattr(agent_instance, 'clear_memory') or not callable(getattr(agent_instance, 'clear_memory')):
294
+ logger.error("Agent instance does not have clear_memory method or it's not callable")
295
+ return [], "Failed to clear conversation: Invalid agent configuration."
296
+
297
+ # Clear the agent memory with detailed logging
298
+ start_time = time.time()
299
  agent_instance.clear_memory()
300
+ clear_time = time.time() - start_time
301
+
302
+ logger.info(f"Agent memory cleared successfully in {clear_time:.2f} seconds")
303
+ agent_memory_cleared = True
304
+
305
  except Exception as e:
306
+ error_type = type(e).__name__
307
+ error_details = traceback.format_exc()
308
+ logger.error(f"Error clearing agent memory: {error_type}: {e}")
309
+ logger.error(error_details)
310
+
311
+ # Return more specific error message based on exception type
312
+ if "AttributeError" in error_type:
313
+ return [], "Failed to clear conversation: Agent memory interface error."
314
+ elif "ConnectionError" in error_type:
315
+ return [], "Failed to clear persistent memory: Connection issue."
316
+ else:
317
+ return [], f"Partially cleared conversation: {error_type}."
318
+ else:
319
+ logger.warning("Clear conversation called with None agent instance")
320
 
321
+ # Provide different message based on what was cleared
322
+ if agent_memory_cleared:
323
+ return [], "Conversation and agent memory cleared successfully."
324
+ else:
325
+ return [], "Conversation history cleared. Note: Agent memory may not have been cleared."
326
 
327
  def create_interface():
328
  """
 
412
  """
413
  )
414
 
415
+ # Set up event handlers with error handling wrapper
416
+ def safe_handler(fn):
417
+ """Wrapper to provide additional error handling for event handlers"""
418
+ def wrapped_fn(*args, **kwargs):
419
+ try:
420
+ return fn(*args, **kwargs)
421
+ except Exception as e:
422
+ error_type = type(e).__name__
423
+ logger.error(f"Unhandled error in UI event handler: {error_type}: {str(e)}")
424
+ logger.error(traceback.format_exc())
425
+
426
+ # Determine what function was called for better error messages
427
+ if fn.__name__ == "process_question":
428
+ # For process_question failures, return original history + error message
429
+ history = args[1] if len(args) > 1 and isinstance(args[1], list) else []
430
+ user_msg = args[0] if args and isinstance(args[0], str) else "Unknown question"
431
+ return history + [(user_msg, f"The system encountered an unexpected error. Please try again later.")], f"UI handler error: {error_type}"
432
+ else:
433
+ # For other function failures (e.g., clear_conversation)
434
+ return [], f"Operation failed due to a system error: {error_type}"
435
+ # Preserve original function metadata
436
+ wrapped_fn.__name__ = fn.__name__
437
+ wrapped_fn.__doc__ = fn.__doc__
438
+ return wrapped_fn
439
 
440
+ # Use the safe handler wrapper for all event handlers
441
+ try:
442
+ # Set up submit button handler
443
+ submit_btn.click(
444
+ fn=safe_handler(process_question),
445
+ inputs=[msg, chatbot, agent_instance],
446
+ outputs=[chatbot, error_box],
447
+ api_name="submit"
448
+ )
449
+ logger.info("Submit button handler registered successfully")
450
+
451
+ # Set up message input submission handler
452
+ msg.submit(
453
+ fn=safe_handler(process_question),
454
+ inputs=[msg, chatbot, agent_instance],
455
+ outputs=[chatbot, error_box],
456
+ api_name="ask"
457
+ )
458
+ logger.info("Message submission handler registered successfully")
459
+
460
+ # Set up clear button handler
461
+ clear_btn.click(
462
+ fn=safe_handler(clear_conversation),
463
+ inputs=[agent_instance],
464
+ outputs=[chatbot, error_box],
465
+ api_name="clear"
466
+ )
467
+ logger.info("Clear button handler registered successfully")
468
+ except Exception as handler_err:
469
+ logger.error(f"Failed to register event handlers: {str(handler_err)}")
470
+ logger.error(traceback.format_exc())
471
+ # Add error message to the interface
472
+ error_box.value = "Warning: Some interface features may not be working correctly due to initialization errors."
473
 
474
  return demo
475
 
476
  if __name__ == "__main__":
477
+ try:
478
+ # Check if running in a Hugging Face Space
479
+ space_host = os.getenv("SPACE_HOST", "")
480
+ space_id = os.getenv("SPACE_ID", "")
481
+ running_in_space = bool(space_host and space_id)
482
+
483
+ if running_in_space:
484
+ logger.info(f"Running on Hugging Face Space: {space_host}")
485
+ logger.info(f"Space ID: {space_id}")
486
+ logger.info("Debug mode disabled for production environment")
487
+ debug_mode = False
488
+ else:
489
+ logger.info("Running in local development environment")
490
+ debug_mode = True
491
+
492
+ # Create and launch the interface
493
+ start_time = time.time()
494
+ demo = create_interface()
495
+ launch_time = time.time() - start_time
496
+ logger.info(f"Interface created in {launch_time:.2f} seconds")
497
+
498
+ # Configure launch parameters based on environment
499
+ if running_in_space:
500
+ # Production settings for Hugging Face Space
501
+ demo.launch(
502
+ debug=False,
503
+ share=False,
504
+ show_error=True,
505
+ server_name="0.0.0.0"
506
+ )
507
+ else:
508
+ # Development settings for local testing
509
+ demo.launch(
510
+ debug=True,
511
+ share=False,
512
+ show_error=True
513
+ )
514
+
515
+ except Exception as e:
516
+ error_type = type(e).__name__
517
+ logger.critical(f"Fatal error launching application: {error_type}: {str(e)}")
518
+ logger.critical(traceback.format_exc())
519
+
520
+ # Create a minimal emergency interface to show the error
521
+ try:
522
+ with gr.Blocks(title="GAIA Agent - Error") as emergency_ui:
523
+ gr.Markdown("# ❌ GAIA Agent - Critical Error")
524
+ gr.Markdown(f"**Error Type**: {error_type}")
525
+ gr.Markdown(f"**Error Message**: {str(e)}")
526
+ gr.Markdown("Please check the application logs for details.")
527
+ gr.Markdown("### Common Solutions:")
528
+ gr.Markdown("- Check that required environment variables are set")
529
+ gr.Markdown("- Verify network connectivity for API access")
530
+ gr.Markdown("- Ensure all dependencies are correctly installed")
531
+
532
+ emergency_ui.launch(debug=True, share=False)
533
+ except:
534
+ # If even the emergency UI fails, print to console as last resort
535
+ print("=" * 80)
536
+ print("CRITICAL ERROR: Could not launch GAIA Agent application")
537
+ print(f"Error: {error_type}: {str(e)}")
538
+ print("Check log files for details.")
539
+ print("=" * 80)