Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,54 +1,199 @@
|
|
1 |
import gradio as gr
|
2 |
import requests
|
3 |
from smolagents import CodeAgent
|
|
|
|
|
4 |
|
5 |
-
# Your HF Space URL - Replace with your actual space URL
|
6 |
HF_SPACE_URL = "https://Manavraj-Troubleshoot_MCP.hf.space"
|
7 |
|
8 |
-
def call_mcp_server(message):
|
9 |
"""Call your MCP server and let it handle tool selection"""
|
10 |
try:
|
11 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
response = requests.post(f"{HF_SPACE_URL}/api/predict",
|
13 |
-
json={"data": [message], "fn_index":
|
14 |
return response.json().get("data", ["No response"])[0]
|
15 |
except Exception as e:
|
16 |
return f"MCP server error: {str(e)}"
|
17 |
|
18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
agent = CodeAgent(
|
20 |
tools=[],
|
21 |
model="microsoft/DialoGPT-medium",
|
22 |
-
system_prompt="""You are a Technical Support AI Agent
|
23 |
|
24 |
-
|
|
|
25 |
|
26 |
-
|
|
|
|
|
|
|
27 |
|
28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
|
|
|
30 |
{{authorized_imports}}"""
|
31 |
)
|
32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
def chat_interface(message, history):
|
34 |
-
"""
|
35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
try:
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
|
42 |
# Create Gradio interface
|
43 |
demo = gr.ChatInterface(
|
44 |
fn=chat_interface,
|
45 |
-
title="π§ MCP Technical Support Agent",
|
46 |
-
description="Technical support powered by MCP server tools",
|
47 |
examples=[
|
48 |
"I have a wifi connection problem",
|
49 |
-
"My screen keeps flickering",
|
50 |
-
"Search for latest
|
51 |
-
|
|
|
|
|
52 |
)
|
53 |
|
54 |
if __name__ == "__main__":
|
|
|
1 |
import gradio as gr
|
2 |
import requests
|
3 |
from smolagents import CodeAgent
|
4 |
+
import json
|
5 |
+
import re
|
6 |
|
|
|
7 |
HF_SPACE_URL = "https://Manavraj-Troubleshoot_MCP.hf.space"
|
8 |
|
9 |
+
def call_mcp_server(message, tool_type="knowledge_base"):
|
10 |
"""Call your MCP server and let it handle tool selection"""
|
11 |
try:
|
12 |
+
# Determine which tool to use based on tool_type
|
13 |
+
fn_index_map = {
|
14 |
+
"knowledge_base": 0,
|
15 |
+
"web_search": 1,
|
16 |
+
"formatter": 2
|
17 |
+
}
|
18 |
+
|
19 |
+
fn_index = fn_index_map.get(tool_type, 0)
|
20 |
+
|
21 |
response = requests.post(f"{HF_SPACE_URL}/api/predict",
|
22 |
+
json={"data": [message], "fn_index": fn_index})
|
23 |
return response.json().get("data", ["No response"])[0]
|
24 |
except Exception as e:
|
25 |
return f"MCP server error: {str(e)}"
|
26 |
|
27 |
+
def extract_thought_action_observation(response):
|
28 |
+
"""Extract and format the thought-action-observation cycle from agent response"""
|
29 |
+
sections = {
|
30 |
+
'thought': '',
|
31 |
+
'action': '',
|
32 |
+
'observation': ''
|
33 |
+
}
|
34 |
+
|
35 |
+
# Try to extract sections using regex
|
36 |
+
thought_match = re.search(r'(?:THOUGHT|Thought):\s*(.*?)(?=(?:ACTION|Action|OBSERVATION|Observation|$))', response, re.DOTALL | re.IGNORECASE)
|
37 |
+
action_match = re.search(r'(?:ACTION|Action):\s*(.*?)(?=(?:OBSERVATION|Observation|FINAL|Final|$))', response, re.DOTALL | re.IGNORECASE)
|
38 |
+
observation_match = re.search(r'(?:OBSERVATION|Observation):\s*(.*?)(?=(?:FINAL|Final|$))', response, re.DOTALL | re.IGNORECASE)
|
39 |
+
|
40 |
+
if thought_match:
|
41 |
+
sections['thought'] = thought_match.group(1).strip()
|
42 |
+
if action_match:
|
43 |
+
sections['action'] = action_match.group(1).strip()
|
44 |
+
if observation_match:
|
45 |
+
sections['observation'] = observation_match.group(1).strip()
|
46 |
+
|
47 |
+
return sections
|
48 |
+
|
49 |
+
# Initialize CodeAgent with enhanced system prompt
|
50 |
agent = CodeAgent(
|
51 |
tools=[],
|
52 |
model="microsoft/DialoGPT-medium",
|
53 |
+
system_prompt="""You are a Technical Support AI Agent that uses a structured Thought-Action-Observation cycle to solve user queries effectively.
|
54 |
|
55 |
+
WORKFLOW:
|
56 |
+
For every user query, you MUST follow this exact structure:
|
57 |
|
58 |
+
THOUGHT: Analyze the user's problem and decide what action to take
|
59 |
+
- Identify the type of issue (technical problem, information request, formatting need)
|
60 |
+
- Determine which MCP server tool would be most appropriate
|
61 |
+
- Consider what information you need to provide a complete answer
|
62 |
|
63 |
+
ACTION: Specify exactly what action you will take
|
64 |
+
- "search_knowledge_base" for known technical issues (wifi, screen, hardware problems)
|
65 |
+
- "web_search" for current information, news, or unknown topics
|
66 |
+
- "format_response" for organizing or structuring information
|
67 |
+
- "direct_response" if you can answer without tools
|
68 |
+
|
69 |
+
OBSERVATION: Analyze the results and determine next steps
|
70 |
+
- Evaluate if the action provided sufficient information
|
71 |
+
- Identify if additional actions are needed
|
72 |
+
- Note any gaps in the information
|
73 |
+
|
74 |
+
FINAL RESPONSE: Provide a clear, helpful answer to the user
|
75 |
+
|
76 |
+
EXAMPLE:
|
77 |
+
User: "My wifi keeps disconnecting"
|
78 |
+
|
79 |
+
THOUGHT: The user has a wifi connectivity issue. This is a common technical problem that likely has solutions in our knowledge base. I should search the knowledge base first for wifi-related solutions.
|
80 |
+
|
81 |
+
ACTION: search_knowledge_base with query "wifi disconnecting problem"
|
82 |
+
|
83 |
+
OBSERVATION: The knowledge base provided basic wifi troubleshooting steps. These steps are helpful but I should also check for any recent wifi issues or advanced solutions via web search to provide comprehensive help.
|
84 |
+
|
85 |
+
FINAL RESPONSE: [Provide complete solution combining knowledge base and any additional insights]
|
86 |
+
|
87 |
+
Remember:
|
88 |
+
- Always use the THOUGHT-ACTION-OBSERVATION-FINAL RESPONSE structure
|
89 |
+
- Be specific about which tool you're using and why
|
90 |
+
- Provide actionable, clear solutions
|
91 |
+
- If one action isn't sufficient, explain what additional actions you'll take
|
92 |
|
93 |
+
{{managed_agents_descriptions}}
|
94 |
{{authorized_imports}}"""
|
95 |
)
|
96 |
|
97 |
+
def determine_tool_type(message):
|
98 |
+
"""Determine which MCP tool to use based on user message"""
|
99 |
+
message_lower = message.lower()
|
100 |
+
|
101 |
+
# Technical issues - use knowledge base
|
102 |
+
tech_keywords = ["wifi", "screen", "computer", "laptop", "error", "problem", "issue", "broken", "not working"]
|
103 |
+
if any(keyword in message_lower for keyword in tech_keywords):
|
104 |
+
return "knowledge_base"
|
105 |
+
|
106 |
+
# Search queries - use web search
|
107 |
+
search_keywords = ["search", "find", "news", "latest", "current", "what is", "how to", "information about"]
|
108 |
+
if any(keyword in message_lower for keyword in search_keywords):
|
109 |
+
return "web_search"
|
110 |
+
|
111 |
+
# Formatting requests - use formatter
|
112 |
+
format_keywords = ["format", "organize", "list", "steps", "number"]
|
113 |
+
if any(keyword in message_lower for keyword in format_keywords):
|
114 |
+
return "formatter"
|
115 |
+
|
116 |
+
# Default to knowledge base for technical support
|
117 |
+
return "knowledge_base"
|
118 |
+
|
119 |
def chat_interface(message, history):
|
120 |
+
"""Enhanced chat interface with thought-action-observation cycle"""
|
121 |
+
|
122 |
+
# Step 1: Let agent think about the problem
|
123 |
+
thinking_prompt = f"""
|
124 |
+
User Query: "{message}"
|
125 |
+
|
126 |
+
Follow the THOUGHT-ACTION-OBSERVATION cycle:
|
127 |
+
|
128 |
+
THOUGHT: Analyze this query and determine the best approach.
|
129 |
+
"""
|
130 |
+
|
131 |
try:
|
132 |
+
# Get agent's initial thought process
|
133 |
+
agent_response = agent.run(thinking_prompt)
|
134 |
+
|
135 |
+
# Extract thought and determine action
|
136 |
+
cycle_parts = extract_thought_action_observation(agent_response)
|
137 |
+
|
138 |
+
# Determine tool type based on message content and agent's thought
|
139 |
+
tool_type = determine_tool_type(message)
|
140 |
+
|
141 |
+
# Step 2: Execute the action via MCP server
|
142 |
+
mcp_response = call_mcp_server(message, tool_type)
|
143 |
+
|
144 |
+
# Step 3: Let agent observe and provide final response
|
145 |
+
final_prompt = f"""
|
146 |
+
User Query: "{message}"
|
147 |
+
|
148 |
+
THOUGHT: {cycle_parts.get('thought', 'Analyzing user query for appropriate technical support response.')}
|
149 |
+
|
150 |
+
ACTION: Used {tool_type} tool with query: "{message}"
|
151 |
+
|
152 |
+
OBSERVATION: The MCP server returned: "{mcp_response}"
|
153 |
+
|
154 |
+
FINAL RESPONSE: Based on the observation, provide a complete, helpful response to the user. If the MCP server response is insufficient, explain what additional steps might be needed.
|
155 |
+
"""
|
156 |
+
|
157 |
+
final_response = agent.run(final_prompt)
|
158 |
+
|
159 |
+
# Format the response to show the thinking process
|
160 |
+
formatted_response = f"""π€ **THOUGHT:** {cycle_parts.get('thought', 'Analyzing your query...')}
|
161 |
+
|
162 |
+
β‘ **ACTION:** Used {tool_type.replace('_', ' ')} tool
|
163 |
+
|
164 |
+
ποΈ **OBSERVATION:** {mcp_response[:200]}{'...' if len(mcp_response) > 200 else ''}
|
165 |
+
|
166 |
+
β
**SOLUTION:**
|
167 |
+
{final_response}"""
|
168 |
+
|
169 |
+
return formatted_response
|
170 |
+
|
171 |
+
except Exception as e:
|
172 |
+
# Fallback to direct MCP response with simple structure
|
173 |
+
tool_type = determine_tool_type(message)
|
174 |
+
mcp_response = call_mcp_server(message, tool_type)
|
175 |
+
|
176 |
+
return f"""π€ **THOUGHT:** You have a {tool_type.replace('_', ' ')} related query.
|
177 |
+
|
178 |
+
β‘ **ACTION:** Consulted the MCP server using {tool_type} tool.
|
179 |
+
|
180 |
+
ποΈ **OBSERVATION:** Found relevant information.
|
181 |
+
|
182 |
+
β
**SOLUTION:**
|
183 |
+
{mcp_response}"""
|
184 |
|
185 |
# Create Gradio interface
|
186 |
demo = gr.ChatInterface(
|
187 |
fn=chat_interface,
|
188 |
+
title="π§ MCP Technical Support Agent (TAO Cycle)",
|
189 |
+
description="Technical support powered by MCP server tools using Thought-Action-Observation methodology",
|
190 |
examples=[
|
191 |
"I have a wifi connection problem",
|
192 |
+
"My screen keeps flickering",
|
193 |
+
"Search for latest cybersecurity news",
|
194 |
+
"Format these steps: Install driver. Restart computer. Test connection"
|
195 |
+
],
|
196 |
+
chatbot=gr.Chatbot(height=600)
|
197 |
)
|
198 |
|
199 |
if __name__ == "__main__":
|