Ashokdll commited on
Commit
72dabfb
·
verified ·
1 Parent(s): f1fecc3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -19
app.py CHANGED
@@ -1,27 +1,82 @@
1
  import gradio as gr
2
  import os
 
3
 
4
- from mcp import StdioServerParameters
5
- from smolagents import InferenceClientModel, CodeAgent, ToolCollection, MCPClient
 
 
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- try:
9
- mcp_client = MCPClient(
10
- {"url": "http://localhost:7860/gradio_api/mcp/sse"} # This is the MCP Server we created in the previous section
11
- )
12
- tools = mcp_client.get_tools()
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
- model = InferenceClientModel(token=os.getenv("HUGGINGFACE_API_TOKEN"))
15
- agent = CodeAgent(tools=[*tools], model=model)
 
 
 
 
 
 
16
 
17
- demo = gr.ChatInterface(
18
- fn=lambda message, history: str(agent.run(message)),
19
- type="messages",
20
- examples=["Prime factorization of 68"],
21
- title="Agent with MCP Tools",
22
- description="This is a simple agent that uses MCP tools to answer questions.",
23
- )
 
 
 
 
 
 
24
 
25
- demo.launch()
26
- finally:
27
- mcp_client.disconnect()
 
 
 
 
1
  import gradio as gr
2
  import os
3
+ from smolagents import InferenceClientModel, CodeAgent, MCPClient
4
 
5
+ # Configuration
6
+ MCP_SERVER_URL = "https://ashokdll-mcp-sentiment.hf.space/gradio_api/mcp/sse" # Replace with your actual URL
7
+ mcp_client = None
8
+ agent = None
9
 
10
+ def initialize_agent():
11
+ """Initialize the MCP client and agent"""
12
+ global mcp_client, agent
13
+
14
+ try:
15
+ # Connect to your MCP Server
16
+ mcp_client = MCPClient({"url": MCP_SERVER_URL})
17
+ tools = mcp_client.get_tools()
18
+
19
+ # Debug: Print available tools
20
+ print("Available tools:")
21
+ for tool in tools:
22
+ print(f"- {tool.name}: {tool.description}")
23
+
24
+ # Create the model with HF token
25
+ model = InferenceClientModel(token=os.getenv("HF_TOKEN"))
26
+
27
+ # Create the agent with tools
28
+ agent = CodeAgent(tools=[*tools], model=model)
29
+
30
+ return True, "Agent initialized successfully"
31
+
32
+ except Exception as e:
33
+ print(f"Error initializing agent: {e}")
34
+ return False, str(e)
35
 
36
+ def chat_function(message, history):
37
+ """Handle chat messages"""
38
+ global agent
39
+
40
+ # Initialize agent if not already done
41
+ if agent is None:
42
+ success, error_msg = initialize_agent()
43
+ if not success:
44
+ 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"
45
+
46
+ try:
47
+ # Run the agent with the user's message
48
+ response = agent.run(message)
49
+ return str(response)
50
+
51
+ except Exception as e:
52
+ return f"❌ Error running agent: {str(e)}"
53
 
54
+ def cleanup():
55
+ """Cleanup function to disconnect MCP client"""
56
+ global mcp_client
57
+ if mcp_client:
58
+ try:
59
+ mcp_client.disconnect()
60
+ except:
61
+ pass
62
 
63
+ # Create the Gradio interface
64
+ demo = gr.ChatInterface(
65
+ fn=chat_function,
66
+ type="messages",
67
+ examples=[
68
+ "Analyze the sentiment of: 'I absolutely love this new product!'",
69
+ "What's the sentiment of: 'This is terrible and I hate it'",
70
+ "Check sentiment: 'The weather is okay today'",
71
+ "Perform sentiment analysis on: 'Python programming is amazing!'"
72
+ ],
73
+ title="🤖 Sentiment Analysis Agent with MCP",
74
+ description="This agent connects to your sentiment analysis MCP server and can analyze text sentiment using natural language commands.",
75
+ )
76
 
77
+ # Launch the interface
78
+ if __name__ == "__main__":
79
+ try:
80
+ demo.launch()
81
+ finally:
82
+ cleanup()