Ashokdll's picture
Update app.py
72dabfb verified
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()