Manavraj commited on
Commit
ba5f007
Β·
verified Β·
1 Parent(s): 6c38b0b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -79
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
- @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
17
- def call_mcp_server(message, tool_type="knowledge_base"):
18
- """Call MCP server with proper endpoint routing"""
19
- try:
20
- # Map tool types to their respective API endpoints
21
- endpoint_map = {
22
- "knowledge_base": "api/knowledge_base",
23
- "web_search": "api/web_search",
24
- "formatter": "api/formatter"
25
- }
26
-
27
- endpoint = endpoint_map.get(tool_type, "api/knowledge_base")
28
- url = f"{HF_SPACE_URL}/{endpoint}"
29
-
30
- logger.info(f"Calling MCP endpoint: {url}")
31
-
32
- response = requests.post(
33
- url,
34
- json={"data": [message]},
35
- verify=False, # Temporary for debugging
36
- timeout=30
37
- )
38
-
39
- if response.status_code != 200:
40
- raise Exception(f"MCP server returned {response.status_code}")
41
 
42
- data = response.json()
43
- if not isinstance(data, dict) or 'data' not in data:
44
- raise Exception("Invalid MCP response format")
45
 
46
- return data['data'][0]
47
-
48
- except Exception as e:
49
- logger.error(f"MCP call failed: {str(e)}")
50
- return f"MCP server error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
- thinking_prompt = f"User Query: {message}\n\nTHOUGHT: Analyze this query"
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
- return f"""πŸ€” **THOUGHT:** {cycle_parts.get('thought', '')}
125
- ⚑ **ACTION:** Used {tool_type.replace('_', ' ')}
126
- πŸ‘οΈ **OBSERVATION:** {mcp_response[:200]}{'...' if len(mcp_response) > 200 else ''}
127
- βœ… **SOLUTION:**\n{final_response}"""
 
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)}")