Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,10 +1,11 @@
|
|
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 |
|
9 |
# Configure logging
|
10 |
logging.basicConfig(level=logging.INFO)
|
@@ -13,41 +14,77 @@ logger = logging.getLogger(__name__)
|
|
13 |
# Correct URL based on your Space
|
14 |
HF_SPACE_URL = "https://manavraj-troubleshoot-mcp.hf.space"
|
15 |
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
"
|
23 |
-
|
24 |
-
"
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
raise Exception(f"MCP server returned {response.status_code}")
|
41 |
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
|
52 |
def extract_thought_action_observation(response):
|
53 |
"""Extract TAO cycle from response"""
|
@@ -70,61 +107,22 @@ def extract_thought_action_observation(response):
|
|
70 |
|
71 |
return sections
|
72 |
|
73 |
-
# Initialize CodeAgent
|
74 |
-
agent = CodeAgent(
|
75 |
-
tools=[],
|
76 |
-
model="microsoft/DialoGPT-medium",
|
77 |
-
system_prompt="""[Previous system prompt remains unchanged]"""
|
78 |
-
)
|
79 |
-
|
80 |
-
def determine_tool_type(message):
|
81 |
-
"""Determine which tool to use"""
|
82 |
-
message_lower = message.lower()
|
83 |
-
tech_keywords = ["wifi", "screen", "computer", "error"]
|
84 |
-
search_keywords = ["search", "find", "news", "how to"]
|
85 |
-
format_keywords = ["format", "organize", "steps"]
|
86 |
-
|
87 |
-
if any(k in message_lower for k in tech_keywords):
|
88 |
-
return "knowledge_base"
|
89 |
-
elif any(k in message_lower for k in search_keywords):
|
90 |
-
return "web_search"
|
91 |
-
elif any(k in message_lower for k in format_keywords):
|
92 |
-
return "formatter"
|
93 |
-
return "knowledge_base"
|
94 |
-
|
95 |
def chat_interface(message, history):
|
96 |
"""Enhanced chat interface with proper error handling"""
|
97 |
try:
|
98 |
# Get initial thought
|
99 |
-
|
100 |
-
agent_response = agent.run(thinking_prompt)
|
101 |
|
102 |
if not isinstance(agent_response, str):
|
103 |
agent_response = str(agent_response)
|
104 |
|
105 |
cycle_parts = extract_thought_action_observation(agent_response)
|
106 |
-
tool_type = determine_tool_type(message)
|
107 |
-
|
108 |
-
# Call MCP server
|
109 |
-
mcp_response = call_mcp_server(message, tool_type)
|
110 |
-
|
111 |
-
# Generate final response
|
112 |
-
final_prompt = f"""
|
113 |
-
User Query: {message}
|
114 |
-
THOUGHT: {cycle_parts.get('thought', 'Analysis complete')}
|
115 |
-
ACTION: Used {tool_type} tool
|
116 |
-
OBSERVATION: {mcp_response}
|
117 |
-
FINAL RESPONSE: Provide a complete solution
|
118 |
-
"""
|
119 |
-
|
120 |
-
final_response = agent.run(final_prompt)
|
121 |
-
if not isinstance(final_response, str):
|
122 |
-
final_response = str(final_response)
|
123 |
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
|
|
128 |
|
129 |
except Exception as e:
|
130 |
logger.error(f"Chat error: {str(e)}")
|
|
|
1 |
import gradio as gr
|
2 |
import requests
|
3 |
+
from smolagents import CodeAgent, tool
|
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 |
# Correct URL based on your Space
|
15 |
HF_SPACE_URL = "https://manavraj-troubleshoot-mcp.hf.space"
|
16 |
|
17 |
+
class TroubleshootTools:
|
18 |
+
@tool
|
19 |
+
def search_knowledge_base(issue: str) -> str:
|
20 |
+
"""Search the knowledge base for solutions to technical issues."""
|
21 |
+
try:
|
22 |
+
issue = issue.lower()
|
23 |
+
if "wifi" in issue:
|
24 |
+
return "1. Check if your router is powered on\n2. Restart your router\n3. Try connecting again\n4. If problem persists, contact your ISP"
|
25 |
+
elif "screen" in issue:
|
26 |
+
return "1. Adjust display cable connections\n2. Update graphics drivers\n3. Restart the system\n4. Try a different monitor if available"
|
27 |
+
elif "sound" in issue or "audio" in issue:
|
28 |
+
return "1. Check volume settings\n2. Verify audio output device selection\n3. Update audio drivers\n4. Test with headphones"
|
29 |
+
return "No predefined solution found in the knowledge base. Please try web search for more information."
|
30 |
+
except Exception as e:
|
31 |
+
logger.error(f"Knowledge base search error: {str(e)}")
|
32 |
+
return f"Error searching knowledge base: {str(e)}"
|
33 |
+
|
34 |
+
@tool
|
35 |
+
def web_search(query: str) -> str:
|
36 |
+
"""Perform web search using DuckDuckGo."""
|
37 |
+
try:
|
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 |
+
return "Search Results:\n" + "\n\n".join(formatted_results)
|
47 |
+
except Exception as e:
|
48 |
+
logger.error(f"Web search error: {str(e)}")
|
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 |
+
steps = re.split(r'[.,;]\s*', raw_steps)
|
59 |
+
steps = [step.strip() for step in steps if step.strip()]
|
60 |
+
steps = [f"{i+1}. {step}" for i, step in enumerate(steps)]
|
61 |
+
return "\n".join(steps)
|
62 |
+
except Exception as e:
|
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 proper system prompt
|
70 |
+
agent = CodeAgent(
|
71 |
+
tools=[tools.search_knowledge_base, tools.web_search, tools.format_steps],
|
72 |
+
model="microsoft/DialoGPT-medium",
|
73 |
+
system_prompt="""You are a technical support assistant. Your task is to help users with technical issues by:
|
74 |
+
1. Analyzing their problem
|
75 |
+
2. Selecting the appropriate tool (knowledge base, web search, or formatter)
|
76 |
+
3. Providing clear, step-by-step solutions
|
77 |
+
|
78 |
+
Authorized imports:
|
79 |
+
- from duckduckgo_search import ddg
|
80 |
+
- standard Python libraries
|
81 |
+
|
82 |
+
Always follow this response format:
|
83 |
+
THOUGHT: Your analysis of the problem
|
84 |
+
ACTION: The tool you're using (knowledge_base/web_search/format_steps)
|
85 |
+
OBSERVATION: The raw results from the tool
|
86 |
+
FINAL RESPONSE: The complete solution formatted for the user"""
|
87 |
+
)
|
88 |
|
89 |
def extract_thought_action_observation(response):
|
90 |
"""Extract TAO cycle from response"""
|
|
|
107 |
|
108 |
return sections
|
109 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
110 |
def chat_interface(message, history):
|
111 |
"""Enhanced chat interface with proper error handling"""
|
112 |
try:
|
113 |
# Get initial thought
|
114 |
+
agent_response = agent.run(message)
|
|
|
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)}")
|