Spaces:
Sleeping
Sleeping
Update app.py
Browse files123445567891011121314151617181920212223242526272829303132333435891011123637383940414243444546474849505152531415545556575859606162171819202122236364656667686970717273747576777879252627808182import gradio as grimport osfrom smolagents import InferenceClientModel, CodeAgent, MCPClient
from mcp import StdioServerParametersfrom smolagents import InferenceClientModel, CodeAgent, ToolCollection, MCPClient# ConfigurationMCP_SERVER_URL = "https://ashokdll-mcp-sentiment.hf.space/gradio_api/mcp/sse" # Replace with your actual URLmcp_client = Noneagent = 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)
try: mcp_client = MCPClient( {"url": "http://localhost:7860/gradio_api/mcp/sse"} # This is the MCP Server we created in the previous section ) tools = mcp_client.get_tools()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)}"
model = InferenceClientModel(token=os.getenv("HUGGINGFACE_API_TOKEN")) agent = CodeAgent(tools=[*tools], model=model)def cleanup(): """Cleanup function to disconnect MCP client""" global mcp_client if mcp_client: try: mcp_client.disconnect() except: pass
demo = gr.ChatInterface( fn=lambda message, history: str(agent.run(message)), type="messages", examples=["Prime factorization of 68"], title="Agent with MCP Tools", description="This is a simple agent that uses MCP tools to answer questions.", )# Create the Gradio interfacedemo = 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 interfaceif __name__ == "__main__": try: demo.launch()finally: mcp_client.disconnect() demo.launch() finally: cleanup()app.py+74-19