File size: 2,613 Bytes
7098f99
 
72dabfb
7098f99
72dabfb
 
 
 
7098f99
72dabfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7098f99
72dabfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7098f99
72dabfb
 
 
 
 
 
 
 
7098f99
72dabfb
 
 
 
 
 
 
 
 
 
 
 
 
7098f99
72dabfb
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import gradio as gr
import os
from smolagents import InferenceClientModel, CodeAgent, MCPClient

# Configuration
MCP_SERVER_URL = "https://ashokdll-mcp-sentiment.hf.space/gradio_api/mcp/sse"  # Replace with your actual URL
mcp_client = None
agent = None

def initialize_agent():
    """Initialize the MCP client and agent"""
    global mcp_client, agent
    
    try:
        # Connect to your MCP Server
        mcp_client = MCPClient({"url": MCP_SERVER_URL})
        tools = mcp_client.get_tools()
        
        # Debug: Print available tools
        print("Available tools:")
        for tool in tools:
            print(f"- {tool.name}: {tool.description}")
        
        # Create the model with HF token
        model = InferenceClientModel(token=os.getenv("HF_TOKEN"))
        
        # Create the agent with tools
        agent = CodeAgent(tools=[*tools], model=model)
        
        return True, "Agent initialized successfully"
    
    except Exception as e:
        print(f"Error initializing agent: {e}")
        return False, str(e)

def chat_function(message, history):
    """Handle chat messages"""
    global agent
    
    # Initialize agent if not already done
    if agent is None:
        success, error_msg = initialize_agent()
        if not success:
            return f"❌ Error connecting to MCP server: {error_msg}\n\nPlease check:\n1. Your MCP server URL is correct\n2. Your sentiment analysis space is running\n3. MCP server is enabled in your sentiment analysis app"
    
    try:
        # Run the agent with the user's message
        response = agent.run(message)
        return str(response)
    
    except Exception as e:
        return f"❌ Error running agent: {str(e)}"

def cleanup():
    """Cleanup function to disconnect MCP client"""
    global mcp_client
    if mcp_client:
        try:
            mcp_client.disconnect()
        except:
            pass

# Create the Gradio interface
demo = gr.ChatInterface(
    fn=chat_function,
    type="messages",
    examples=[
        "Analyze the sentiment of: 'I absolutely love this new product!'",
        "What's the sentiment of: 'This is terrible and I hate it'",
        "Check sentiment: 'The weather is okay today'",
        "Perform sentiment analysis on: 'Python programming is amazing!'"
    ],
    title="πŸ€– Sentiment Analysis Agent with MCP",
    description="This agent connects to your sentiment analysis MCP server and can analyze text sentiment using natural language commands.",
)

# Launch the interface
if __name__ == "__main__":
    try:
        demo.launch()
    finally:
        cleanup()