Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,11 +1,8 @@
|
|
1 |
import gradio as gr
|
2 |
import requests
|
3 |
-
from smolagents import CodeAgent
|
4 |
-
import json
|
5 |
-
import re
|
6 |
import logging
|
7 |
from tenacity import retry, stop_after_attempt, wait_exponential
|
8 |
-
from duckduckgo_search import ddg
|
9 |
|
10 |
# Configure logging
|
11 |
logging.basicConfig(level=logging.INFO)
|
@@ -14,116 +11,74 @@ logger = logging.getLogger(__name__)
|
|
14 |
# Correct URL based on your Space
|
15 |
HF_SPACE_URL = "https://manavraj-troubleshoot-mcp.hf.space"
|
16 |
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
results = ddg(query, max_results=5)
|
39 |
-
if not results:
|
40 |
-
return f"No results found for '{query}'"
|
41 |
-
|
42 |
-
formatted_results = []
|
43 |
-
for i, result in enumerate(results, 1):
|
44 |
-
formatted_results.append(f"{i}. [{result['title']}]({result['href']})\n{result['body']}")
|
45 |
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
return f"Error performing web search: {str(e)}"
|
50 |
-
|
51 |
-
@tool
|
52 |
-
def format_steps(raw_steps: str) -> str:
|
53 |
-
"""Format raw steps into a numbered list."""
|
54 |
-
try:
|
55 |
-
if not raw_steps.strip():
|
56 |
-
return "Please enter some text to format."
|
57 |
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
logger.error(f"Formatting error: {str(e)}")
|
64 |
-
return f"Error formatting steps: {str(e)}"
|
65 |
-
|
66 |
-
# Initialize tools
|
67 |
-
tools = TroubleshootTools()
|
68 |
|
69 |
-
# Initialize CodeAgent with
|
70 |
agent = CodeAgent(
|
71 |
-
tools=[
|
72 |
model="microsoft/DialoGPT-medium",
|
73 |
-
system_prompt="""You are
|
74 |
-
1.
|
75 |
-
2.
|
76 |
-
3.
|
77 |
|
78 |
-
|
79 |
-
-
|
80 |
-
-
|
|
|
81 |
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
patterns = {
|
98 |
-
'thought': r'(?:THOUGHT|Thought):\s*(.*?)(?=(?:ACTION|Action|OBSERVATION|Observation|$))',
|
99 |
-
'action': r'(?:ACTION|Action):\s*(.*?)(?=(?:OBSERVATION|Observation|FINAL|Final|$))',
|
100 |
-
'observation': r'(?:OBSERVATION|Observation):\s*(.*?)(?=(?:FINAL|Final|$))'
|
101 |
-
}
|
102 |
-
|
103 |
-
for section, pattern in patterns.items():
|
104 |
-
match = re.search(pattern, response, re.DOTALL | re.IGNORECASE)
|
105 |
-
if match:
|
106 |
-
sections[section] = match.group(1).strip()
|
107 |
-
|
108 |
-
return sections
|
109 |
|
110 |
def chat_interface(message, history):
|
111 |
-
"""
|
112 |
try:
|
113 |
-
#
|
114 |
-
|
115 |
-
|
116 |
-
if not isinstance(agent_response, str):
|
117 |
-
agent_response = str(agent_response)
|
118 |
-
|
119 |
-
cycle_parts = extract_thought_action_observation(agent_response)
|
120 |
-
|
121 |
-
# Format the response for display
|
122 |
-
return f"""🤔 **THOUGHT:** {cycle_parts.get('thought', 'Analyzing your issue...')}
|
123 |
-
⚡ **ACTION:** {cycle_parts.get('action', 'Processing request')}
|
124 |
-
👁️ **OBSERVATION:** {cycle_parts.get('observation', 'Gathering information')[:200]}{'...' if len(cycle_parts.get('observation', '')) > 200 else ''}
|
125 |
-
✅ **SOLUTION:**\n{agent_response.split('FINAL RESPONSE:')[-1].strip() if 'FINAL RESPONSE:' in agent_response else agent_response}"""
|
126 |
-
|
127 |
except Exception as e:
|
128 |
logger.error(f"Chat error: {str(e)}")
|
129 |
return f"Error processing request: {str(e)}"
|
@@ -134,8 +89,8 @@ demo = gr.ChatInterface(
|
|
134 |
title="🔧 Technical Support Agent",
|
135 |
examples=[
|
136 |
"My wifi keeps disconnecting",
|
137 |
-
"
|
138 |
-
"Format
|
139 |
]
|
140 |
)
|
141 |
|
|
|
1 |
import gradio as gr
|
2 |
import requests
|
3 |
+
from smolagents import CodeAgent
|
|
|
|
|
4 |
import logging
|
5 |
from tenacity import retry, stop_after_attempt, wait_exponential
|
|
|
6 |
|
7 |
# Configure logging
|
8 |
logging.basicConfig(level=logging.INFO)
|
|
|
11 |
# Correct URL based on your Space
|
12 |
HF_SPACE_URL = "https://manavraj-troubleshoot-mcp.hf.space"
|
13 |
|
14 |
+
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
|
15 |
+
def call_mcp_server(message, tool_type="knowledge_base"):
|
16 |
+
"""Call MCP server with proper endpoint routing"""
|
17 |
+
try:
|
18 |
+
endpoint_map = {
|
19 |
+
"knowledge_base": "api/knowledge_base",
|
20 |
+
"web_search": "api/web_search",
|
21 |
+
"formatter": "api/formatter"
|
22 |
+
}
|
23 |
+
|
24 |
+
endpoint = endpoint_map.get(tool_type, "api/knowledge_base")
|
25 |
+
url = f"{HF_SPACE_URL}/{endpoint}"
|
26 |
+
|
27 |
+
response = requests.post(
|
28 |
+
url,
|
29 |
+
json={"data": [message]},
|
30 |
+
timeout=30
|
31 |
+
)
|
32 |
+
|
33 |
+
if response.status_code != 200:
|
34 |
+
raise Exception(f"MCP server returned {response.status_code}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
|
36 |
+
data = response.json()
|
37 |
+
if not isinstance(data, dict) or 'data' not in data:
|
38 |
+
raise Exception("Invalid MCP response format")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
40 |
+
return data['data'][0]
|
41 |
+
|
42 |
+
except Exception as e:
|
43 |
+
logger.error(f"MCP call failed: {str(e)}")
|
44 |
+
return f"Error: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
+
# Initialize CodeAgent with optimized system prompt
|
47 |
agent = CodeAgent(
|
48 |
+
tools=[], # No tools defined here as they're in MCP
|
49 |
model="microsoft/DialoGPT-medium",
|
50 |
+
system_prompt="""You are an advanced Technical Support Assistant with these capabilities:
|
51 |
+
1. Troubleshooting technical issues (wifi, hardware, software)
|
52 |
+
2. Finding information through web search
|
53 |
+
3. Formatting instructions into clear steps
|
54 |
|
55 |
+
Tools available via MCP server:
|
56 |
+
- knowledge_base: For technical issues (wifi, screen, sound problems)
|
57 |
+
- web_search: For finding latest information or non-technical queries
|
58 |
+
- formatter: To organize raw steps into numbered lists
|
59 |
|
60 |
+
Response Guidelines:
|
61 |
+
1. INTERNALLY follow THOUGHT/ACTION/OBSERVATION cycle
|
62 |
+
2. Use knowledge_base for technical troubleshooting
|
63 |
+
3. Use web_search for information lookup
|
64 |
+
4. Use formatter when user provides unorganized steps
|
65 |
+
5. Provide FINAL RESPONSE in clear, helpful language
|
66 |
|
67 |
+
Example workflow:
|
68 |
+
THOUGHT: User has wifi issue, should check knowledge base
|
69 |
+
ACTION: knowledge_base
|
70 |
+
OBSERVATION: Found 4 troubleshooting steps
|
71 |
+
FINAL RESPONSE: Here's how to fix your wifi: [steps]
|
72 |
+
|
73 |
+
Never show THOUGHT/ACTION/OBSERVATION to user - only final response."""
|
74 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
75 |
|
76 |
def chat_interface(message, history):
|
77 |
+
"""Simplified chat interface"""
|
78 |
try:
|
79 |
+
# Let agent handle the complete process
|
80 |
+
response = agent.run(message)
|
81 |
+
return str(response).split("FINAL RESPONSE:")[-1].strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
82 |
except Exception as e:
|
83 |
logger.error(f"Chat error: {str(e)}")
|
84 |
return f"Error processing request: {str(e)}"
|
|
|
89 |
title="🔧 Technical Support Agent",
|
90 |
examples=[
|
91 |
"My wifi keeps disconnecting",
|
92 |
+
"Find the latest Windows 11 update",
|
93 |
+
"Format: Restart. Check connections. Update drivers"
|
94 |
]
|
95 |
)
|
96 |
|