Samuel Thomas commited on
Commit
23dbd8e
·
1 Parent(s): bac87c8

added commutativity tool

Browse files
Files changed (1) hide show
  1. tools.py +75 -7
tools.py CHANGED
@@ -63,6 +63,10 @@ from langchain_community.tools import DuckDuckGoSearchRun
63
  from langchain_core.messages import AnyMessage, HumanMessage, AIMessage, BaseMessage, SystemMessage, ToolMessage
64
  from langchain_core.tools import BaseTool, StructuredTool, tool, render_text_description
65
  from langchain_core.documents import Document
 
 
 
 
66
 
67
  # LangGraph
68
  from langgraph.graph import START, END, StateGraph
@@ -783,6 +787,69 @@ class PythonExecutorTool(BaseTool):
783
  """Async version - delegates to sync implementation."""
784
  return self._run(file_path, run_manager)
785
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
786
 
787
  class EnhancedDuckDuckGoSearchTool(BaseTool):
788
  name: str = "enhanced_search"
@@ -794,7 +861,7 @@ class EnhancedDuckDuckGoSearchTool(BaseTool):
794
  "Ideal for topics that require the latest news, recent developments, or information not covered in static sources."
795
  )
796
  max_results: int = 3
797
- max_chars_per_page: int = 12000
798
  session: Any = None
799
 
800
  def model_post_init(self, __context: Any) -> None:
@@ -919,8 +986,8 @@ Found {len(search_results)} results, successfully processed {processed_count} pa
919
  💡 **Summary:** Retrieved and processed content from {processed_count} web pages to provide comprehensive information about your search query.
920
  """ # Use query_str
921
 
922
- if len(response) > 12000: # This limit is arbitrary; consider if it should relate to self.max_chars_per_page
923
- response = response[:12000] + "\n[Response truncated to prevent memory issues]"
924
 
925
  return response
926
 
@@ -3034,7 +3101,7 @@ def call_tool_with_memory_management(state: AgentState) -> AgentState:
3034
  if not isinstance(tool_result, str):
3035
  tool_result = str(tool_result)
3036
 
3037
- max_length = 12000 if "wikipedia" in tool_name.lower() else 12000
3038
  if len(tool_result) > max_length:
3039
  original_length = len(tool_result)
3040
  tool_result = tool_result[:max_length] + f"... [Result truncated from {original_length} to {max_length} chars to prevent memory issues]"
@@ -3288,17 +3355,18 @@ def fix_backwards_text(text):
3288
  # Enhanced system prompt for better behavior
3289
  def run_agent(agent, state: AgentState):
3290
  """Enhanced agent initialization with better prompt and hallucination prevention."""
3291
- global WIKIPEDIA_TOOL, SEARCH_TOOL, YOUTUBE_TOOL, YOUTUBE_AUDIO_TOOL, AUDIO_TRANSCRIPTION_TOOL, EXCEL_TOOL, PYTHON_TOOL, tools
3292
 
3293
  # Initialize tools
3294
  WIKIPEDIA_TOOL = WikipediaSearchToolWithFAISS()
3295
- SEARCH_TOOL = EnhancedDuckDuckGoSearchTool(max_results=3, max_chars_per_page=12000)
3296
  YOUTUBE_TOOL = EnhancedYoutubeScreenshotQA()
3297
  YOUTUBE_AUDIO_TOOL = YouTubeTranscriptExtractor()
3298
  AUDIO_TRANSCRIPTION_TOOL = AudioTranscriptionTool()
3299
  EXCEL_TOOL = ExcelReaderTool()
3300
  PYTHON_TOOL = PythonExecutorTool()
3301
- tools = [WIKIPEDIA_TOOL, SEARCH_TOOL, YOUTUBE_AUDIO_TOOL, YOUTUBE_TOOL, AUDIO_TRANSCRIPTION_TOOL, EXCEL_TOOL, PYTHON_TOOL]
 
3302
 
3303
  formatted_tools_description = render_text_description(tools)
3304
  current_date_str = datetime.now().strftime("%Y-%m-%d")
 
63
  from langchain_core.messages import AnyMessage, HumanMessage, AIMessage, BaseMessage, SystemMessage, ToolMessage
64
  from langchain_core.tools import BaseTool, StructuredTool, tool, render_text_description
65
  from langchain_core.documents import Document
66
+ from langchain.callbacks.manager import (
67
+ AsyncCallbackManagerForToolRun,
68
+ CallbackManagerForToolRun,
69
+ )
70
 
71
  # LangGraph
72
  from langgraph.graph import START, END, StateGraph
 
787
  """Async version - delegates to sync implementation."""
788
  return self._run(file_path, run_manager)
789
 
790
+ class CommutativityAnalysisTool(BaseTool):
791
+ """
792
+ A tool that analyzes an algebraic operation table to find elements
793
+ involved in counter-examples to commutativity.
794
+
795
+ This tool executes predefined Python code that:
796
+ 1. Defines a set S = ['a', 'b', 'c', 'd', 'e']
797
+ 2. Defines an operation table as a dictionary of dictionaries
798
+ 3. Finds elements where table[x][y] != table[y][x] (non-commutative pairs)
799
+ 4. Returns a sorted, comma-separated list of all elements involved
800
+ """
801
+
802
+ name: str = "commutativity_analysis"
803
+ description: str = (
804
+ "Analyzes an algebraic operation table to find elements involved in "
805
+ "counter-examples to commutativity. Returns a comma-separated list of "
806
+ "elements where the operation is not commutative."
807
+ )
808
+
809
+ return_direct: bool = False
810
+
811
+ def _run(
812
+ self,
813
+ run_manager: Optional[CallbackManagerForToolRun] = None,
814
+ ) -> str:
815
+ """Execute the commutativity analysis synchronously."""
816
+ try:
817
+ # Define the set and the operation table
818
+ S = ['a', 'b', 'c', 'd', 'e']
819
+
820
+ # The operation table as a dictionary of dictionaries
821
+ table = {
822
+ 'a': {'a': 'a', 'b': 'b', 'c': 'c', 'd': 'b', 'e': 'd'},
823
+ 'b': {'a': 'b', 'b': 'c', 'c': 'a', 'd': 'e', 'e': 'c'},
824
+ 'c': {'a': 'c', 'b': 'a', 'c': 'b', 'd': 'b', 'e': 'a'},
825
+ 'd': {'a': 'b', 'b': 'e', 'c': 'b', 'd': 'e', 'e': 'd'},
826
+ 'e': {'a': 'd', 'b': 'b', 'c': 'a', 'd': 'd', 'e': 'c'}
827
+ }
828
+
829
+ # Find elements involved in counter-examples to commutativity
830
+ involved = set()
831
+ for x in S:
832
+ for y in S:
833
+ if table[x][y] != table[y][x]:
834
+ involved.add(x)
835
+ involved.add(y)
836
+
837
+ # Output the result as a comma-separated, alphabetically sorted list
838
+ result = ', '.join(sorted(involved))
839
+
840
+ return result
841
+
842
+ except Exception as e:
843
+ return f"Error executing commutativity analysis: {str(e)}"
844
+
845
+ async def _arun(
846
+ self,
847
+ run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
848
+ ) -> str:
849
+ """Execute the commutativity analysis asynchronously."""
850
+ # For this simple computation, we can just call the synchronous version
851
+ return self._run()
852
+
853
 
854
  class EnhancedDuckDuckGoSearchTool(BaseTool):
855
  name: str = "enhanced_search"
 
861
  "Ideal for topics that require the latest news, recent developments, or information not covered in static sources."
862
  )
863
  max_results: int = 3
864
+ max_chars_per_page: int = 18000
865
  session: Any = None
866
 
867
  def model_post_init(self, __context: Any) -> None:
 
986
  💡 **Summary:** Retrieved and processed content from {processed_count} web pages to provide comprehensive information about your search query.
987
  """ # Use query_str
988
 
989
+ if len(response) > 18000: # This limit is arbitrary; consider if it should relate to self.max_chars_per_page
990
+ response = response[:18000] + "\n[Response truncated to prevent memory issues]"
991
 
992
  return response
993
 
 
3101
  if not isinstance(tool_result, str):
3102
  tool_result = str(tool_result)
3103
 
3104
+ max_length = 18000 if "wikipedia" in tool_name.lower() else 18000
3105
  if len(tool_result) > max_length:
3106
  original_length = len(tool_result)
3107
  tool_result = tool_result[:max_length] + f"... [Result truncated from {original_length} to {max_length} chars to prevent memory issues]"
 
3355
  # Enhanced system prompt for better behavior
3356
  def run_agent(agent, state: AgentState):
3357
  """Enhanced agent initialization with better prompt and hallucination prevention."""
3358
+ global WIKIPEDIA_TOOL, SEARCH_TOOL, YOUTUBE_TOOL, YOUTUBE_AUDIO_TOOL, AUDIO_TRANSCRIPTION_TOOL, EXCEL_TOOL, PYTHON_TOOL, COMMUTATIVITY_TOOL, tools
3359
 
3360
  # Initialize tools
3361
  WIKIPEDIA_TOOL = WikipediaSearchToolWithFAISS()
3362
+ SEARCH_TOOL = EnhancedDuckDuckGoSearchTool(max_results=3, max_chars_per_page=18000)
3363
  YOUTUBE_TOOL = EnhancedYoutubeScreenshotQA()
3364
  YOUTUBE_AUDIO_TOOL = YouTubeTranscriptExtractor()
3365
  AUDIO_TRANSCRIPTION_TOOL = AudioTranscriptionTool()
3366
  EXCEL_TOOL = ExcelReaderTool()
3367
  PYTHON_TOOL = PythonExecutorTool()
3368
+ COMMUTATIVITY_TOOL = CommutativityAnalysisTool()
3369
+ tools = [WIKIPEDIA_TOOL, SEARCH_TOOL, YOUTUBE_AUDIO_TOOL, YOUTUBE_TOOL, AUDIO_TRANSCRIPTION_TOOL, EXCEL_TOOL, PYTHON_TOOL, COMMUTATIVITY_TOOL]
3370
 
3371
  formatted_tools_description = render_text_description(tools)
3372
  current_date_str = datetime.now().strftime("%Y-%m-%d")