Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627import gradio as grimport osfrom mcp import StdioServerParametersfrom smolagents import InferenceClientModel, CodeAgent, ToolCollection, MCPClienttry: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()model = InferenceClientModel(token=os.getenv("HUGGINGFACE_API_TOKEN"))agent = CodeAgent(tools=[*tools], model=model)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.",)demo.launch()finally:mcp_client.disconnect()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182import gradio as grimport osfrom smolagents import InferenceClientModel, CodeAgent, MCPClient# ConfigurationMCP_SERVER_URL = "https://ashokdll-mcp-sentiment.hf.space/gradio_api/mcp/sse" # Replace with your actual URLmcp_client = Noneagent = Nonedef initialize_agent():"""Initialize the MCP client and agent"""global mcp_client, agenttry:# Connect to your MCP Servermcp_client = MCPClient({"url": MCP_SERVER_URL})tools = mcp_client.get_tools()# Debug: Print available toolsprint("Available tools:")for tool in tools:print(f"- {tool.name}: {tool.description}")# Create the model with HF tokenmodel = InferenceClientModel(token=os.getenv("HF_TOKEN"))# Create the agent with toolsagent = 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 doneif 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 messageresponse = 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_clientif mcp_client:try:mcp_client.disconnect()except:pass# 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:cleanup()
app.py+74-19