phil71x commited on
Commit
6f77f6e
Β·
1 Parent(s): 48a7f49

feat: Enhance MCP sentiment analysis with dynamic smolagents import

Browse files

- Added a try-except block to conditionally import `MCPClient` from `smolagents`, improving error handling for its availability.
- Updated the `test_mcp_sentiment_analysis` function to check for `smolagents` availability before proceeding with sentiment analysis.
- Simplified the `check_smolagents` function to utilize the new availability check, enhancing code clarity and maintainability.

Files changed (1) hide show
  1. usage/sentiment_mcp.py +19 -17
usage/sentiment_mcp.py CHANGED
@@ -20,6 +20,14 @@ https://huggingface.co/learn/mcp-course/unit2/gradio-client
20
 
21
  import time
22
 
 
 
 
 
 
 
 
 
23
 
24
  def test_mcp_sentiment_analysis():
25
  """Test MCP connection using smolagents MCPClient."""
@@ -29,16 +37,13 @@ def test_mcp_sentiment_analysis():
29
  print("Based on: https://huggingface.co/learn/mcp-course/unit2/gradio-client")
30
  print()
31
 
32
- try:
33
- # Import here to handle import errors gracefully
34
- from smolagents.mcp_client import MCPClient
35
-
36
- print("βœ… smolagents imported successfully")
37
- except ImportError as e:
38
- print(f"❌ Failed to import smolagents: {e}")
39
  print("Install with: pdm add 'smolagents[mcp]'")
40
  return False
41
 
 
 
42
  # Test texts
43
  test_texts = [
44
  "I love this product! It's amazing!",
@@ -97,7 +102,7 @@ def test_mcp_sentiment_analysis():
97
  print(f" βœ… Result: {result}")
98
  print(f" ⏱️ Time: {elapsed:.2f}s")
99
 
100
- except Exception as e:
101
  elapsed = time.time() - start_time
102
  print(f" ❌ Error after {elapsed:.2f}s: {e}")
103
 
@@ -106,7 +111,7 @@ def test_mcp_sentiment_analysis():
106
  print("πŸŽ‰ MCP sentiment analysis completed!")
107
  return True
108
 
109
- except Exception as e:
110
  print(f"❌ Failed to connect with smolagents: {e}")
111
  print(f"Error type: {type(e).__name__}")
112
  print("\nTroubleshooting:")
@@ -120,21 +125,18 @@ def test_mcp_sentiment_analysis():
120
  try:
121
  mcp_client.disconnect()
122
  print("βœ… MCP client disconnected properly")
123
- except Exception as e:
124
  print(f"⚠️ Disconnect warning: {e}")
125
 
126
 
127
  def check_smolagents():
128
  """Check if smolagents is available."""
129
- try:
130
- import smolagents.mcp_client
131
-
132
  print("βœ… smolagents is available")
133
  return True
134
- except ImportError:
135
- print("❌ smolagents not found")
136
- print("Install with: pdm add 'smolagents[mcp]'")
137
- return False
138
 
139
 
140
  if __name__ == "__main__":
 
20
 
21
  import time
22
 
23
+ try:
24
+ from smolagents.mcp_client import MCPClient
25
+
26
+ SMOLAGENTS_AVAILABLE = True
27
+ except ImportError:
28
+ MCPClient = None
29
+ SMOLAGENTS_AVAILABLE = False
30
+
31
 
32
  def test_mcp_sentiment_analysis():
33
  """Test MCP connection using smolagents MCPClient."""
 
37
  print("Based on: https://huggingface.co/learn/mcp-course/unit2/gradio-client")
38
  print()
39
 
40
+ if not SMOLAGENTS_AVAILABLE:
41
+ print("❌ smolagents not available")
 
 
 
 
 
42
  print("Install with: pdm add 'smolagents[mcp]'")
43
  return False
44
 
45
+ print("βœ… smolagents imported successfully")
46
+
47
  # Test texts
48
  test_texts = [
49
  "I love this product! It's amazing!",
 
102
  print(f" βœ… Result: {result}")
103
  print(f" ⏱️ Time: {elapsed:.2f}s")
104
 
105
+ except Exception as e: # pylint: disable=broad-except
106
  elapsed = time.time() - start_time
107
  print(f" ❌ Error after {elapsed:.2f}s: {e}")
108
 
 
111
  print("πŸŽ‰ MCP sentiment analysis completed!")
112
  return True
113
 
114
+ except Exception as e: # pylint: disable=broad-except
115
  print(f"❌ Failed to connect with smolagents: {e}")
116
  print(f"Error type: {type(e).__name__}")
117
  print("\nTroubleshooting:")
 
125
  try:
126
  mcp_client.disconnect()
127
  print("βœ… MCP client disconnected properly")
128
+ except Exception as e: # pylint: disable=broad-except
129
  print(f"⚠️ Disconnect warning: {e}")
130
 
131
 
132
  def check_smolagents():
133
  """Check if smolagents is available."""
134
+ if SMOLAGENTS_AVAILABLE:
 
 
135
  print("βœ… smolagents is available")
136
  return True
137
+ print("❌ smolagents not found")
138
+ print("Install with: pdm add 'smolagents[mcp]'")
139
+ return False
 
140
 
141
 
142
  if __name__ == "__main__":