Manavraj commited on
Commit
ade2028
·
verified ·
1 Parent(s): ba5f007

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -105
app.py CHANGED
@@ -1,11 +1,8 @@
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,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
- 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"""
91
- sections = {
92
- 'thought': '',
93
- 'action': '',
94
- 'observation': ''
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
- """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)}")
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
- "Search for latest tech news",
138
- "Format these steps: Restart. Check cables. Test"
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