jm-vis commited on
Commit
a3fb832
·
1 Parent(s): f00a3e7

Fix configuration error and runtime error

Browse files
Files changed (2) hide show
  1. agent.py +215 -1
  2. app.py +1 -1
agent.py CHANGED
@@ -696,4 +696,218 @@ def execute_tool(state: AgentState) -> AgentState:
696
  }],
697
  "current_step": current_step + 1,
698
  "error": f"Error during tool execution: {error_message}"
699
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
696
  }],
697
  "current_step": current_step + 1,
698
  "error": f"Error during tool execution: {error_message}"
699
+ }
700
+ """
701
+ GAIA (Grounded AI Assistant) agent with web search and content extraction capabilities.
702
+ This class provides a simplified interface for the app.py file to interact with.
703
+ """
704
+
705
+ def __init__(self):
706
+ """Initialize the GAIA agent with simplified configuration"""
707
+ self.memory = SimpleMemory()
708
+ logger.info("GAIA Agent initialized")
709
+
710
+ def __call__(self, question: str) -> str:
711
+ """
712
+ Process a question and generate an answer.
713
+ Compatible with the interface expected by app.py.
714
+
715
+ Args:
716
+ question (str): The question to process
717
+
718
+ Returns:
719
+ str: The answer to the question
720
+ """
721
+ return self.process_question(question)
722
+
723
+ def process_question(self, question: str) -> str:
724
+ """
725
+ Process a question and generate an answer.
726
+
727
+ Args:
728
+ question (str): The question to process
729
+
730
+ Returns:
731
+ str: The answer to the question
732
+ """
733
+ # Generate a cache key for this question
734
+ cache_key = f"question_{hashlib.md5(question.encode()).hexdigest()}"
735
+
736
+ # Check if we have a cached result
737
+ cached_answer = self.memory.get_cached_result(cache_key)
738
+ if cached_answer:
739
+ logger.info(f"Using cached answer for question: {question[:50]}...")
740
+ return cached_answer
741
+
742
+ try:
743
+ # Initialize LLM with error handling
744
+ if OPENAI_API_KEY:
745
+ llm = ChatOpenAI(
746
+ temperature=0,
747
+ model="gpt-3.5-turbo",
748
+ api_key=OPENAI_API_KEY
749
+ )
750
+
751
+ # Process with LangGraph
752
+ answer = self._process_with_langgraph(question, llm)
753
+ else:
754
+ # Fallback to simple pattern-matching responses when LLM is not available
755
+ logger.warning("Using fallback mode (no OpenAI API key provided)")
756
+ answer = self._fallback_processing(question)
757
+
758
+ # Cache the result
759
+ self.memory.cache_result(cache_key, answer)
760
+
761
+ return answer
762
+
763
+ except Exception as e:
764
+ logger.error(f"Error processing question: {str(e)}")
765
+ logger.error(traceback.format_exc())
766
+
767
+ return f"I apologize, but I encountered an error while processing your question: {str(e)}"
768
+
769
+ def _process_with_langgraph(self, question: str, llm) -> str:
770
+ """Process question using LangGraph workflow"""
771
+ try:
772
+ # Define state transitions
773
+ def should_continue(state: AgentState) -> Literal["continue", "complete"]:
774
+ """Determine if the agent should continue or is finished"""
775
+ current_step = state.get("current_step", 0)
776
+ plan = state.get("plan", [])
777
+
778
+ # Check if we still have steps to execute
779
+ if current_step is None or plan is None:
780
+ return "complete"
781
+
782
+ if current_step < len(plan):
783
+ return "continue"
784
+ else:
785
+ return "complete"
786
+
787
+ # Create the graph
788
+ workflow = StateGraph(AgentState)
789
+
790
+ # Add nodes
791
+ workflow.add_node("analyze", analyze_question)
792
+ workflow.add_node("create_plan", create_plan)
793
+ workflow.add_node("execute_tool", execute_tool)
794
+ workflow.add_node("formulate_answer", formulate_answer)
795
+
796
+ # Add edges
797
+ workflow.add_edge("analyze", "create_plan")
798
+ workflow.add_edge("create_plan", "execute_tool")
799
+ workflow.add_edge("execute_tool", should_continue)
800
+ workflow.add_conditional_edges(
801
+ "execute_tool",
802
+ should_continue,
803
+ {
804
+ "continue": "execute_tool",
805
+ "complete": "formulate_answer"
806
+ }
807
+ )
808
+ workflow.add_edge("formulate_answer", END)
809
+
810
+ # Set entry point
811
+ workflow.set_entry_point("analyze")
812
+
813
+ # Compile the graph
814
+ app = workflow.compile()
815
+
816
+ # Run the graph
817
+ state = {
818
+ "question": question,
819
+ "tool_results": []
820
+ }
821
+
822
+ result = app.invoke({
823
+ **state,
824
+ "llm": llm
825
+ })
826
+
827
+ # Return the answer or an error message
828
+ if "answer" in result and result["answer"]:
829
+ return result["answer"]
830
+ elif "error" in result and result["error"]:
831
+ return f"I encountered an error: {result['error']}"
832
+ else:
833
+ return "I was unable to generate an answer based on the available information."
834
+
835
+ except Exception as e:
836
+ logger.error(f"Error in LangGraph processing: {str(e)}")
837
+ logger.error(traceback.format_exc())
838
+ return f"I encountered an error while processing your question: {str(e)}"
839
+
840
+ def _fallback_processing(self, question: str) -> str:
841
+ """Simple fallback implementation when LLM is not available"""
842
+ try:
843
+ # Simple pattern matching for some question types
844
+ if "how" in question.lower():
845
+ 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."
846
+ elif "what" in question.lower():
847
+ 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."
848
+ elif "why" in question.lower():
849
+ 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."
850
+ else:
851
+ # Try a web search if available
852
+ try:
853
+ search_tool = WebSearchTool()
854
+ search_results = search_tool.search(question)
855
+
856
+ if search_results and search_results[0].get("snippet"):
857
+ snippet = search_results[0]["snippet"]
858
+ answer = f"Based on available information: {snippet}\n\nPlease note that without access to a language model, I can only provide this basic search result."
859
+ else:
860
+ answer = f"I'm sorry, but I cannot provide a comprehensive answer to '{question}' at this moment due to limited access to external knowledge and language model capabilities."
861
+ except Exception as search_err:
862
+ logger.error(f"Error in fallback search: {str(search_err)}")
863
+ answer = f"I'm sorry, but I cannot provide a comprehensive answer to '{question}' at this moment due to limited access to external knowledge and language model capabilities."
864
+
865
+ return answer
866
+ except Exception as e:
867
+ logger.error(f"Error in fallback processing: {str(e)}")
868
+ return f"I apologize, but I'm currently unable to process your question due to system limitations."
869
+
870
+ def query(self, question: str) -> Dict[str, Any]:
871
+ """
872
+ Query the agent with a question to get an answer with metadata.
873
+
874
+ Args:
875
+ question (str): The question to answer
876
+
877
+ Returns:
878
+ Dict[str, Any]: Dictionary containing the answer and metadata
879
+ """
880
+ try:
881
+ # Track timing
882
+ start_time = time.time()
883
+
884
+ # Process the question
885
+ answer = self.process_question(question)
886
+
887
+ # Calculate processing time
888
+ processing_time = time.time() - start_time
889
+
890
+ # Return result with metadata
891
+ return {
892
+ "question": question,
893
+ "answer": answer,
894
+ "processing_time": processing_time,
895
+ "timestamp": time.time(),
896
+ "status": "success"
897
+ }
898
+ except Exception as e:
899
+ logger.error(f"Error in query: {str(e)}")
900
+
901
+ return {
902
+ "question": question,
903
+ "answer": f"Error processing query: {str(e)}",
904
+ "processing_time": time.time() - start_time,
905
+ "timestamp": time.time(),
906
+ "status": "error",
907
+ "error": str(e)
908
+ }
909
+
910
+ def clear_memory(self):
911
+ """Clear the agent's memory"""
912
+ self.memory.clear()
913
+ logger.info("Agent memory cleared")
app.py CHANGED
@@ -20,7 +20,7 @@ import traceback
20
  from typing import Dict, Any, Optional
21
 
22
  # Import our GAIA Agent
23
- from agent import GAIAAgent
24
 
25
  # Configure logging
26
  logging.basicConfig(
 
20
  from typing import Dict, Any, Optional
21
 
22
  # Import our GAIA Agent
23
+ from gaia_agent import GAIAAgent
24
 
25
  # Configure logging
26
  logging.basicConfig(