Spaces:
Runtime error
Runtime error
phil71x
commited on
Commit
Β·
23d394c
1
Parent(s):
38a6bb3
feat: Introduce new sentiment analysis scripts and rename other scripts . Enhance documentation
Browse files- Introduced `sentiment_mcp_gradio_usage.py` for a Gradio UI interface with MCP integration.
- Renamed `sentiment_mcp_core_usage.py` for optimized MCP sentiment analysis using smolagents.
- Renamed `sentiment_gradio_client_usage.py` as a reliable backup solution bypassing MCP.
- Updated `README.md` to reflect new script names, usage instructions, and added a section for Cursor AI integration.
- Enhanced performance comparison and clarified dependencies for better user guidance.
usage/README.md
CHANGED
@@ -1,51 +1,96 @@
|
|
1 |
# Usage Scripts
|
2 |
|
3 |
-
This folder contains
|
4 |
|
5 |
## π Working Solutions
|
6 |
|
7 |
-
### 1. `
|
8 |
- **What it does**: Uses smolagents MCPClient for proper MCP protocol connection
|
9 |
- **Performance**: ~0.11 seconds per request (fastest!)
|
10 |
- **Status**: β
Works perfectly
|
11 |
-
- **Usage**: `pdm run python usage/
|
12 |
- **Dependencies**: `smolagents[mcp]` (already installed)
|
13 |
- **Protocol**: Native MCP via smolagents
|
14 |
|
15 |
-
### 2. `
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
- **What it does**: Uses Gradio client to bypass MCP protocol entirely
|
17 |
- **Performance**: ~1.3 seconds per request
|
18 |
- **Status**: β
Works reliably as backup solution
|
19 |
-
- **Usage**: `pdm run python usage/
|
20 |
- **Dependencies**: `gradio_client` (already installed)
|
21 |
- **Protocol**: Direct Gradio API access
|
22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
## π§ Utilities
|
24 |
|
25 |
-
###
|
26 |
- **What it does**: Debugging utility to check MCP package imports
|
27 |
- **Usage**: `pdm run python usage/debug_imports.py`
|
28 |
- **Purpose**: Troubleshooting import issues
|
29 |
- **Dependencies**: `mcp` (for testing imports)
|
30 |
|
31 |
-
### 4. `access_mcp_using_python.ipynb`
|
32 |
-
- **What it does**: Jupyter notebook showing HTTP API approach
|
33 |
-
- **Purpose**: Alternative approach using direct HTTP requests
|
34 |
-
- **Status**: Educational/reference material
|
35 |
-
|
36 |
## Quick Start
|
37 |
|
38 |
-
For
|
|
|
|
|
|
|
39 |
|
|
|
40 |
```bash
|
41 |
# Primary solution (fastest)
|
42 |
-
pdm run python usage/
|
43 |
-
|
|
|
|
|
44 |
|
45 |
-
Or the backup solution:
|
46 |
-
```bash
|
47 |
# Backup solution (reliable)
|
48 |
-
pdm run python usage/
|
49 |
```
|
50 |
|
51 |
For troubleshooting:
|
@@ -56,49 +101,89 @@ pdm run python usage/debug_imports.py
|
|
56 |
|
57 |
## Performance Comparison
|
58 |
|
59 |
-
|
|
60 |
-
|
61 |
-
|
|
62 |
-
| `
|
|
|
|
|
63 |
|
64 |
## File Naming Convention
|
65 |
|
66 |
-
All scripts
|
67 |
-
- `sentiment_
|
68 |
- `debug_*.py` - Debugging and utility scripts
|
69 |
-
- Each script includes
|
70 |
|
71 |
## Dependencies
|
72 |
|
73 |
All required packages are already installed:
|
74 |
- `smolagents[mcp]` - For MCP protocol support
|
75 |
- `gradio_client` - For direct Gradio API access
|
|
|
76 |
- `mcp` - Base MCP package
|
77 |
|
78 |
-
## What Was Cleaned Up
|
79 |
-
|
80 |
-
The folder was cleaned from 17 files down to 5 essential files:
|
81 |
-
|
82 |
-
**Removed (12 obsolete files):**
|
83 |
-
- All hanging MCP test scripts
|
84 |
-
- Failed timeout and debugging attempts
|
85 |
-
- Redundant test files
|
86 |
-
- Empty or obsolete utilities
|
87 |
-
|
88 |
-
**Kept (5 essential files):**
|
89 |
-
- β Primary MCP solution
|
90 |
-
- β
Backup Gradio solution
|
91 |
-
- π§ Import debugging utility
|
92 |
-
- π Educational notebook
|
93 |
-
- π This documentation
|
94 |
-
|
95 |
## Troubleshooting
|
96 |
|
97 |
If you encounter issues:
|
98 |
|
99 |
1. **Import errors**: Run `pdm run python usage/debug_imports.py`
|
100 |
-
2. **MCP connection issues**: Try `pdm run python usage/
|
101 |
3. **Missing dependencies**: Check the Dependencies section above
|
102 |
-
4. **
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
103 |
|
104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
# Usage Scripts
|
2 |
|
3 |
+
This folder contains working solutions and utilities for MCP sentiment analysis with consistent naming and proper documentation.
|
4 |
|
5 |
## π Working Solutions
|
6 |
|
7 |
+
### 1. `sentiment_mcp_core_usage.py` β **RECOMMENDED**
|
8 |
- **What it does**: Uses smolagents MCPClient for proper MCP protocol connection
|
9 |
- **Performance**: ~0.11 seconds per request (fastest!)
|
10 |
- **Status**: β
Works perfectly
|
11 |
+
- **Usage**: `pdm run python usage/sentiment_mcp_core_usage.py`
|
12 |
- **Dependencies**: `smolagents[mcp]` (already installed)
|
13 |
- **Protocol**: Native MCP via smolagents
|
14 |
|
15 |
+
### 2. `sentiment_mcp_gradio_usage.py`
|
16 |
+
- **What it does**: Creates a Gradio UI that connects to MCP sentiment analysis server
|
17 |
+
- **Performance**: Fast UI-based sentiment analysis
|
18 |
+
- **Status**: β
Works with interactive web interface
|
19 |
+
- **Usage**: `pdm run python usage/sentiment_mcp_gradio_usage.py`
|
20 |
+
- **Dependencies**: `smolagents[mcp]`, `gradio[mcp]` (already installed)
|
21 |
+
- **Protocol**: Native MCP via smolagents with Gradio interface
|
22 |
+
|
23 |
+
### 3. `sentiment_gradio_client_usage.py`
|
24 |
- **What it does**: Uses Gradio client to bypass MCP protocol entirely
|
25 |
- **Performance**: ~1.3 seconds per request
|
26 |
- **Status**: β
Works reliably as backup solution
|
27 |
+
- **Usage**: `pdm run python usage/sentiment_gradio_client_usage.py`
|
28 |
- **Dependencies**: `gradio_client` (already installed)
|
29 |
- **Protocol**: Direct Gradio API access
|
30 |
|
31 |
+
## π― Cursor AI Integration β **BEST EXPERIENCE**
|
32 |
+
|
33 |
+
The most seamless way to use MCP sentiment analysis is directly within **Cursor AI** using the built-in MCP support:
|
34 |
+
|
35 |
+
### Setup
|
36 |
+
Add this configuration to your Cursor MCP servers (`~/.cursor/mcp.json`):
|
37 |
+
|
38 |
+
```json
|
39 |
+
{
|
40 |
+
"mcpServers": {
|
41 |
+
"sentiment-analysis": {
|
42 |
+
"command": "cmd",
|
43 |
+
"args": [
|
44 |
+
"/c",
|
45 |
+
"npx",
|
46 |
+
"-y",
|
47 |
+
"mcp-remote",
|
48 |
+
"https://freemansel-mcp-sentiment.hf.space/gradio_api/mcp/sse",
|
49 |
+
"--transport",
|
50 |
+
"sse-only"
|
51 |
+
]
|
52 |
+
}
|
53 |
+
}
|
54 |
+
}
|
55 |
+
```
|
56 |
+
|
57 |
+
### Usage in Cursor
|
58 |
+
Once configured, you can directly ask Cursor AI:
|
59 |
+
- "Analyze the sentiment of this text: 'I love this product!'"
|
60 |
+
- "What's the sentiment of: 'This is terrible'"
|
61 |
+
- "Check sentiment: 'It's okay, nothing special'"
|
62 |
+
|
63 |
+
**Benefits:**
|
64 |
+
- β
No separate scripts needed
|
65 |
+
- β
Integrated directly in your coding workflow
|
66 |
+
- β
Real-time sentiment analysis while coding
|
67 |
+
- β
Works with any text in your editor
|
68 |
+
|
69 |
## π§ Utilities
|
70 |
|
71 |
+
### 4. `debug_imports.py`
|
72 |
- **What it does**: Debugging utility to check MCP package imports
|
73 |
- **Usage**: `pdm run python usage/debug_imports.py`
|
74 |
- **Purpose**: Troubleshooting import issues
|
75 |
- **Dependencies**: `mcp` (for testing imports)
|
76 |
|
|
|
|
|
|
|
|
|
|
|
77 |
## Quick Start
|
78 |
|
79 |
+
### For Cursor AI Users (Recommended)
|
80 |
+
1. Add the MCP server configuration to `~/.cursor/mcp.json`
|
81 |
+
2. Restart Cursor AI
|
82 |
+
3. Ask Cursor directly for sentiment analysis
|
83 |
|
84 |
+
### For Standalone Usage
|
85 |
```bash
|
86 |
# Primary solution (fastest)
|
87 |
+
pdm run python usage/sentiment_mcp_core_usage.py
|
88 |
+
|
89 |
+
# Interactive UI solution
|
90 |
+
pdm run python usage/sentiment_mcp_gradio_usage.py
|
91 |
|
|
|
|
|
92 |
# Backup solution (reliable)
|
93 |
+
pdm run python usage/sentiment_gradio_client_usage.py
|
94 |
```
|
95 |
|
96 |
For troubleshooting:
|
|
|
101 |
|
102 |
## Performance Comparison
|
103 |
|
104 |
+
| Solution | Speed | Protocol | Interface | Reliability | Command |
|
105 |
+
|----------|-------|----------|-----------|-------------|---------|
|
106 |
+
| **Cursor AI MCP** | **Instant** | β
Native MCP | β
Integrated | β
Excellent | Built-in |
|
107 |
+
| `sentiment_mcp_core_usage.py` | **0.11s** | β
Native MCP | Terminal | β
Excellent | `pdm run python usage/sentiment_mcp_core_usage.py` |
|
108 |
+
| `sentiment_mcp_gradio_usage.py` | Fast | β
Native MCP | Web UI | β
Excellent | `pdm run python usage/sentiment_mcp_gradio_usage.py` |
|
109 |
+
| `sentiment_gradio_client_usage.py` | 1.3s | Direct API | Terminal | β
Very Good | `pdm run python usage/sentiment_gradio_client_usage.py` |
|
110 |
|
111 |
## File Naming Convention
|
112 |
|
113 |
+
All scripts follow a consistent naming pattern:
|
114 |
+
- `sentiment_*_usage.py` - Main functionality scripts
|
115 |
- `debug_*.py` - Debugging and utility scripts
|
116 |
+
- Each script includes comprehensive docstring with PDM commands
|
117 |
|
118 |
## Dependencies
|
119 |
|
120 |
All required packages are already installed:
|
121 |
- `smolagents[mcp]` - For MCP protocol support
|
122 |
- `gradio_client` - For direct Gradio API access
|
123 |
+
- `gradio[mcp]` - For Gradio UI with MCP integration
|
124 |
- `mcp` - Base MCP package
|
125 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
126 |
## Troubleshooting
|
127 |
|
128 |
If you encounter issues:
|
129 |
|
130 |
1. **Import errors**: Run `pdm run python usage/debug_imports.py`
|
131 |
+
2. **MCP connection issues**: Try `pdm run python usage/sentiment_gradio_client_usage.py`
|
132 |
3. **Missing dependencies**: Check the Dependencies section above
|
133 |
+
4. **Cursor AI issues**: Verify MCP server configuration in `~/.cursor/mcp.json`
|
134 |
+
|
135 |
+
## π Concepts and Technical Details
|
136 |
+
|
137 |
+
### Model Context Protocol (MCP)
|
138 |
+
MCP is a protocol that enables AI applications to securely connect to external data sources and tools. In our case, it provides a standardized way to access sentiment analysis capabilities.
|
139 |
+
|
140 |
+
**Key Benefits:**
|
141 |
+
- **Standardized Interface**: Consistent API across different tools
|
142 |
+
- **Security**: Controlled access to external resources
|
143 |
+
- **Composability**: Tools can be combined and chained
|
144 |
+
- **Real-time**: Live connections to external services
|
145 |
+
|
146 |
+
### Architecture Overview
|
147 |
+
|
148 |
+
```
|
149 |
+
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
|
150 |
+
β Client β β MCP Server β β Sentiment β
|
151 |
+
β (Cursor AI, βββββΊβ (Protocol βββββΊβ Analysis β
|
152 |
+
β smolagents, β β Handler) β β Engine β
|
153 |
+
β Gradio) β β β β (TextBlob) β
|
154 |
+
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
|
155 |
+
```
|
156 |
|
157 |
+
### Technical Implementation Details
|
158 |
+
|
159 |
+
#### 1. **smolagents MCPClient**
|
160 |
+
- **Transport**: Server-Sent Events (SSE)
|
161 |
+
- **Endpoint**: `https://freemansel-mcp-sentiment.hf.space/gradio_api/mcp/sse`
|
162 |
+
- **Protocol**: Native MCP with automatic tool discovery
|
163 |
+
- **Performance**: ~110ms per request
|
164 |
+
|
165 |
+
#### 2. **Cursor AI Integration**
|
166 |
+
- **Tool**: `mcp-remote` npm package
|
167 |
+
- **Transport**: SSE-only mode for reliability
|
168 |
+
- **Integration**: Native MCP support in Cursor AI
|
169 |
+
- **Benefits**: Zero-setup sentiment analysis in IDE
|
170 |
+
|
171 |
+
#### 3. **Gradio Client (Fallback)**
|
172 |
+
- **Transport**: Direct HTTP API calls
|
173 |
+
- **Endpoint**: `https://freemansel-mcp-sentiment.hf.space`
|
174 |
+
- **Protocol**: Gradio's native API (bypasses MCP)
|
175 |
+
- **Performance**: ~1.3s per request
|
176 |
+
|
177 |
+
### Sentiment Analysis Engine
|
178 |
+
The backend uses **TextBlob** for sentiment analysis, providing:
|
179 |
+
- **Polarity**: Range from -1 (negative) to +1 (positive)
|
180 |
+
- **Subjectivity**: Range from 0 (objective) to 1 (subjective)
|
181 |
+
- **Assessment**: Human-readable sentiment classification
|
182 |
+
|
183 |
+
### Error Handling and Reliability
|
184 |
+
- **Connection Timeouts**: Automatic retry mechanisms
|
185 |
+
- **Fallback Strategies**: Multiple transport methods
|
186 |
+
- **Graceful Degradation**: Backup solutions when MCP fails
|
187 |
+
- **Comprehensive Logging**: Detailed error reporting for debugging
|
188 |
+
|
189 |
+
The folder is now clean, organized, and ready for production use with multiple integration options! π
|
usage/{sentiment_gradio.py β sentiment_gradio_client_usage.py}
RENAMED
File without changes
|
usage/{sentiment_mcp.py β sentiment_mcp_core_usage.py}
RENAMED
File without changes
|
usage/sentiment_mcp_gradio_usage.py
ADDED
@@ -0,0 +1,246 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
"""
|
3 |
+
MCP Sentiment Analysis with Gradio UI using smolagents.
|
4 |
+
|
5 |
+
This script creates a Gradio interface that connects to an MCP sentiment analysis server
|
6 |
+
using the smolagents library, following the approach from the Hugging Face MCP Course.
|
7 |
+
|
8 |
+
Performance: Fast UI-based sentiment analysis
|
9 |
+
Protocol: Native MCP via smolagents with Gradio interface
|
10 |
+
|
11 |
+
To run this script:
|
12 |
+
pdm run python usage/sentiment_mcp_bis.py
|
13 |
+
|
14 |
+
Dependencies:
|
15 |
+
- smolagents[mcp] (install with: pdm add "smolagents[mcp]")
|
16 |
+
- gradio[mcp] (install with: pdm add "gradio[mcp]")
|
17 |
+
|
18 |
+
Based on Hugging Face MCP Course:
|
19 |
+
https://huggingface.co/learn/mcp-course/unit2/gradio-client
|
20 |
+
"""
|
21 |
+
|
22 |
+
import gradio as gr
|
23 |
+
|
24 |
+
try:
|
25 |
+
from smolagents import InferenceClientModel, CodeAgent
|
26 |
+
from smolagents.mcp_client import MCPClient
|
27 |
+
|
28 |
+
SMOLAGENTS_AVAILABLE = True
|
29 |
+
except ImportError as e:
|
30 |
+
print(f"β smolagents not available: {e}")
|
31 |
+
MCPClient = None
|
32 |
+
InferenceClientModel = None
|
33 |
+
CodeAgent = None
|
34 |
+
SMOLAGENTS_AVAILABLE = False
|
35 |
+
|
36 |
+
|
37 |
+
def create_sentiment_interface():
|
38 |
+
"""Create a Gradio interface for sentiment analysis using MCP."""
|
39 |
+
|
40 |
+
if not SMOLAGENTS_AVAILABLE:
|
41 |
+
# Create a simple error interface
|
42 |
+
def error_fn(message, history):
|
43 |
+
return (
|
44 |
+
"β smolagents not available. Install with: pdm add 'smolagents[mcp]'"
|
45 |
+
)
|
46 |
+
|
47 |
+
demo = gr.ChatInterface(
|
48 |
+
fn=error_fn,
|
49 |
+
type="messages",
|
50 |
+
title="β MCP Sentiment Analysis (Missing Dependencies)",
|
51 |
+
description="smolagents library is required but not installed.",
|
52 |
+
)
|
53 |
+
return demo
|
54 |
+
|
55 |
+
mcp_client = None
|
56 |
+
|
57 |
+
try:
|
58 |
+
print("β³ Connecting to MCP sentiment analysis server...")
|
59 |
+
|
60 |
+
# Connect to the MCP server
|
61 |
+
mcp_client = MCPClient(
|
62 |
+
{"url": "https://freemansel-mcp-sentiment.hf.space/gradio_api/mcp/sse"}
|
63 |
+
)
|
64 |
+
|
65 |
+
print("β
MCP client connected successfully!")
|
66 |
+
|
67 |
+
# Get available tools
|
68 |
+
tools = mcp_client.get_tools()
|
69 |
+
print(f"β
Found {len(tools)} tools:")
|
70 |
+
for tool in tools:
|
71 |
+
print(f" β’ {tool.name}: {tool.description}")
|
72 |
+
|
73 |
+
# Create an agent with the tools
|
74 |
+
# Skip LLM models and go directly to simple agent for reliability
|
75 |
+
print("βΉοΈ Using simple direct agent (most reliable for MCP tools)")
|
76 |
+
|
77 |
+
def simple_agent_run(message):
|
78 |
+
# If message asks for sentiment analysis, use the tool directly
|
79 |
+
if "sentiment" in message.lower() and tools:
|
80 |
+
# Extract text from message
|
81 |
+
if "'" in message or '"' in message:
|
82 |
+
# Try to extract quoted text
|
83 |
+
import re
|
84 |
+
|
85 |
+
quoted_text = re.findall(r"['\"]([^'\"]+)['\"]", message)
|
86 |
+
if quoted_text:
|
87 |
+
text_to_analyze = quoted_text[0]
|
88 |
+
try:
|
89 |
+
result = tools[0](text=text_to_analyze)
|
90 |
+
return f"β
Sentiment Analysis Result:\n{result}"
|
91 |
+
except Exception as e:
|
92 |
+
return f"β Error calling sentiment tool: {e}"
|
93 |
+
|
94 |
+
# If no quotes found, try to extract text after common patterns
|
95 |
+
patterns = [
|
96 |
+
r"sentiment of:?\s*(.+)",
|
97 |
+
r"analyze:?\s*(.+)",
|
98 |
+
r"sentiment for:?\s*(.+)",
|
99 |
+
]
|
100 |
+
for pattern in patterns:
|
101 |
+
match = re.search(pattern, message, re.IGNORECASE)
|
102 |
+
if match:
|
103 |
+
text_to_analyze = match.group(1).strip()
|
104 |
+
try:
|
105 |
+
result = tools[0](text=text_to_analyze)
|
106 |
+
return f"β
Sentiment Analysis Result:\n{result}"
|
107 |
+
except Exception as e:
|
108 |
+
return f"β Error calling sentiment tool: {e}"
|
109 |
+
|
110 |
+
return """π **MCP Sentiment Analysis Tool**
|
111 |
+
|
112 |
+
Please ask for sentiment analysis using one of these formats:
|
113 |
+
β’ "Analyze the sentiment of: 'your text here'"
|
114 |
+
β’ "What's the sentiment of: 'your text here'"
|
115 |
+
β’ "Sentiment analysis for: 'your text here'"
|
116 |
+
|
117 |
+
**Examples:**
|
118 |
+
β’ Analyze the sentiment of: 'I love this product!'
|
119 |
+
β’ What's the sentiment of: 'This is terrible'
|
120 |
+
β’ Sentiment analysis for: 'It's okay, nothing special'"""
|
121 |
+
|
122 |
+
# Create a simple agent object
|
123 |
+
class SimpleAgent:
|
124 |
+
def run(self, message):
|
125 |
+
return simple_agent_run(message)
|
126 |
+
|
127 |
+
agent = SimpleAgent()
|
128 |
+
|
129 |
+
print("β
Agent created successfully!")
|
130 |
+
|
131 |
+
# Check if we're using the simple fallback agent
|
132 |
+
if hasattr(agent, "__class__") and agent.__class__.__name__ == "SimpleAgent":
|
133 |
+
print("βΉοΈ Using simple direct agent (no LLM model required)")
|
134 |
+
print(" Format: 'Analyze the sentiment of: \"your text here\"'")
|
135 |
+
else:
|
136 |
+
print("βΉοΈ Using full agent with LLM capabilities")
|
137 |
+
|
138 |
+
def chat_fn(message, history):
|
139 |
+
"""Process chat messages through the MCP agent."""
|
140 |
+
try:
|
141 |
+
# Use the agent to process the message
|
142 |
+
result = agent.run(message)
|
143 |
+
return str(result)
|
144 |
+
except Exception as e:
|
145 |
+
return f"β Error processing message: {e}"
|
146 |
+
|
147 |
+
# Create the Gradio interface
|
148 |
+
demo = gr.ChatInterface(
|
149 |
+
fn=chat_fn,
|
150 |
+
type="messages",
|
151 |
+
examples=[
|
152 |
+
"Analyze the sentiment of: 'I love this product!'",
|
153 |
+
"What's the sentiment of: 'This is terrible'",
|
154 |
+
"Sentiment analysis for: 'It's okay, nothing special'",
|
155 |
+
"How positive is: 'The weather is beautiful today!'",
|
156 |
+
"Analyze: 'I'm feeling quite neutral about this'",
|
157 |
+
],
|
158 |
+
title="π MCP Sentiment Analysis with smolagents",
|
159 |
+
description="""
|
160 |
+
This interface uses the Model Context Protocol (MCP) to perform sentiment analysis.
|
161 |
+
|
162 |
+
**How to use:**
|
163 |
+
- Type a message asking for sentiment analysis
|
164 |
+
- Example: "Analyze the sentiment of: 'Your text here'"
|
165 |
+
- The agent will use MCP tools to provide detailed sentiment analysis
|
166 |
+
|
167 |
+
**Powered by:**
|
168 |
+
- smolagents MCP client
|
169 |
+
- Hugging Face MCP server
|
170 |
+
- Based on HF MCP Course documentation
|
171 |
+
""",
|
172 |
+
)
|
173 |
+
|
174 |
+
# Store the client for cleanup
|
175 |
+
demo.mcp_client = mcp_client
|
176 |
+
|
177 |
+
return demo
|
178 |
+
|
179 |
+
except Exception as e:
|
180 |
+
error_msg = str(e)
|
181 |
+
print(f"β Failed to create MCP interface: {error_msg}")
|
182 |
+
|
183 |
+
def connection_error_fn(message, history):
|
184 |
+
return f"β MCP connection failed: {error_msg}\n\nTroubleshooting:\n1. Check internet connection\n2. Verify MCP server is running\n3. Try again in a few moments"
|
185 |
+
|
186 |
+
demo = gr.ChatInterface(
|
187 |
+
fn=connection_error_fn,
|
188 |
+
type="messages",
|
189 |
+
title="β MCP Sentiment Analysis (Connection Failed)",
|
190 |
+
description=f"Failed to connect to MCP server: {error_msg}",
|
191 |
+
)
|
192 |
+
|
193 |
+
return demo
|
194 |
+
|
195 |
+
|
196 |
+
def main():
|
197 |
+
"""Main function to run the Gradio interface."""
|
198 |
+
print("π MCP Sentiment Analysis with Gradio + smolagents")
|
199 |
+
print("Based on: https://huggingface.co/learn/mcp-course/unit2/gradio-client")
|
200 |
+
print("=" * 70) # Print a separator line of 70 equals signs
|
201 |
+
|
202 |
+
if not SMOLAGENTS_AVAILABLE:
|
203 |
+
print("β smolagents not available")
|
204 |
+
print("Install with: pdm add 'smolagents[mcp]'")
|
205 |
+
print("Also install: pdm add 'gradio[mcp]'")
|
206 |
+
else:
|
207 |
+
print("\nπ‘ For full LLM capabilities, set your Hugging Face token:")
|
208 |
+
print(" Windows: set HF_TOKEN=your_token_here")
|
209 |
+
print(" Linux/Mac: export HF_TOKEN=your_token_here")
|
210 |
+
print(" Or the script will use a simple direct approach.")
|
211 |
+
|
212 |
+
# Create and launch the interface
|
213 |
+
demo = create_sentiment_interface()
|
214 |
+
|
215 |
+
try:
|
216 |
+
print("\nπ Starting Gradio interface...")
|
217 |
+
print("Once started, you can:")
|
218 |
+
print("1. Open the provided URL in your browser")
|
219 |
+
print("2. Type sentiment analysis requests")
|
220 |
+
print("3. Try the example prompts")
|
221 |
+
print("4. Press Ctrl+C to stop")
|
222 |
+
print()
|
223 |
+
|
224 |
+
demo.launch(
|
225 |
+
share=False, # Set to True if you want a public link
|
226 |
+
server_name="localhost", # Use localhost for Windows compatibility
|
227 |
+
server_port=7861, # Different port to avoid conflicts
|
228 |
+
show_error=True,
|
229 |
+
)
|
230 |
+
|
231 |
+
except KeyboardInterrupt:
|
232 |
+
print("\nβΉοΈ Stopping Gradio interface...")
|
233 |
+
except Exception as e:
|
234 |
+
print(f"\nβ Error launching Gradio: {e}")
|
235 |
+
finally:
|
236 |
+
# Clean up MCP client if it exists
|
237 |
+
if hasattr(demo, "mcp_client") and demo.mcp_client:
|
238 |
+
try:
|
239 |
+
demo.mcp_client.disconnect()
|
240 |
+
print("β
MCP client disconnected properly")
|
241 |
+
except Exception as e:
|
242 |
+
print(f"β οΈ Disconnect warning: {e}")
|
243 |
+
|
244 |
+
|
245 |
+
if __name__ == "__main__":
|
246 |
+
main()
|