alfulanny commited on
Commit
dce7d2d
·
verified ·
1 Parent(s): 8304c16

Update smolagents_agent.py

Browse files
Files changed (1) hide show
  1. smolagents_agent.py +26 -14
smolagents_agent.py CHANGED
@@ -581,7 +581,6 @@ class OptimizedSmolagentsGAIAgent:
581
  print(f"Error initializing HuggingFace model: {e}")
582
  return None
583
 
584
-
585
  def classify_question(self, question: str) -> Dict[str, Any]:
586
  """Enhanced question classification with confidence scores"""
587
  q_lower = question.lower()
@@ -667,27 +666,37 @@ class OptimizedSmolagentsGAIAgent:
667
  result_str = str(result)
668
 
669
  # Format response for HuggingFace compatibility
670
- # Wrap any code blocks in <code> tags as expected by the parsing system
671
- if "```" in result_str or "def " in result_str or "import " in result_str:
672
- # Extract code blocks and wrap them properly
673
  import re
674
- # Find Python code blocks (either fenced with ```python or ``` or plain code)
675
- code_pattern = r'```(?:python)?\n(.*?)\n```|```\n(.*?)\n```|([a-zA-Z_][a-zA-Z0-9_]*\s*=\s*.*|def\s+\w+.*|import\s+\w+.*|from\s+\w+.*import.*)'
676
  matches = re.findall(code_pattern, result_str, re.DOTALL)
677
 
678
  if matches:
679
  formatted_result = result_str
680
  for match in matches:
681
- code_content = match[0] if match[0] else match[1] if match[1] else match[2]
682
- if code_content:
683
  # Wrap in <code> tags as expected by HuggingFace parser
684
  wrapped_code = f"<code>{code_content.strip()}</code>"
685
- formatted_result = formatted_result.replace(code_content.strip(), wrapped_code)
 
 
 
686
  result_str = formatted_result
687
- else:
688
- # If no code blocks found but response contains code-like patterns, wrap entire response
689
- if any(keyword in result_str.lower() for keyword in ['def ', 'import ', 'return ', 'print(', '# ']):
690
- result_str = f"<code>{result_str}</code>"
 
 
 
 
 
 
 
691
 
692
  # Cache the result
693
  self.cache.set(cache_key, result_str)
@@ -695,6 +704,10 @@ class OptimizedSmolagentsGAIAgent:
695
  return result_str
696
 
697
  except Exception as e:
 
 
 
 
698
  return f"Agent processing error: {str(e)}"
699
 
700
  def get_tool_recommendations(self, question: str) -> List[str]:
@@ -729,7 +742,6 @@ if __name__ == "__main__":
729
 
730
  print("=== OPTIMIZED SMOLAGENTS AGENT TEST ===\n")
731
 
732
-
733
  for i, question in enumerate(test_questions, 1):
734
  print(f"Test {i}: {question}")
735
  recommendations = agent.get_tool_recommendations(question)
 
581
  print(f"Error initializing HuggingFace model: {e}")
582
  return None
583
 
 
584
  def classify_question(self, question: str) -> Dict[str, Any]:
585
  """Enhanced question classification with confidence scores"""
586
  q_lower = question.lower()
 
666
  result_str = str(result)
667
 
668
  # Format response for HuggingFace compatibility
669
+ # Only wrap actual code blocks, not explanatory text
670
+ if "```" in result_str:
671
+ # Extract markdown code blocks and wrap them properly
672
  import re
673
+ # Find Python code blocks (either fenced with ```python or ```)
674
+ code_pattern = r'```(?:python)?\n(.*?)\n```|```\n(.*?)\n```'
675
  matches = re.findall(code_pattern, result_str, re.DOTALL)
676
 
677
  if matches:
678
  formatted_result = result_str
679
  for match in matches:
680
+ code_content = match[0] if match[0] else match[1]
681
+ if code_content and code_content.strip():
682
  # Wrap in <code> tags as expected by HuggingFace parser
683
  wrapped_code = f"<code>{code_content.strip()}</code>"
684
+ # Replace the original code block with wrapped version
685
+ formatted_result = formatted_result.replace(f"```{code_content.strip()}```", wrapped_code)
686
+ # Handle ```python variant
687
+ formatted_result = formatted_result.replace(f"```python\n{code_content.strip()}```", wrapped_code)
688
  result_str = formatted_result
689
+
690
+ # Only wrap if it's clearly actual code (function definitions, imports, etc.)
691
+ # and NOT explanatory text or thoughts
692
+ if (result_str.startswith(('def ', 'import ', 'from ', 'class ', '# ')) or
693
+ (result_str.count('\n') == 0 and ('=' in result_str or '(' in result_str))):
694
+ # Make sure it's actual code, not explanatory text
695
+ if not any(phrase in result_str.lower() for phrase in [
696
+ 'first thought', 'i need to', 'let me', 'here\'s', 'here is',
697
+ 'to solve', 'the answer is', 'result is', 'response is'
698
+ ]):
699
+ result_str = f"<code>{result_str}</code>"
700
 
701
  # Cache the result
702
  self.cache.set(cache_key, result_str)
 
704
  return result_str
705
 
706
  except Exception as e:
707
+ # Handle timeout errors gracefully
708
+ error_msg = str(e)
709
+ if "Gateway Time-out" in error_msg or "timeout" in error_msg.lower():
710
+ return f"Model timeout occurred. Please try again or simplify the question. Error: {error_msg}"
711
  return f"Agent processing error: {str(e)}"
712
 
713
  def get_tool_recommendations(self, question: str) -> List[str]:
 
742
 
743
  print("=== OPTIMIZED SMOLAGENTS AGENT TEST ===\n")
744
 
 
745
  for i, question in enumerate(test_questions, 1):
746
  print(f"Test {i}: {question}")
747
  recommendations = agent.get_tool_recommendations(question)