Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -5,14 +5,17 @@ import json
|
|
5 |
from urllib.parse import quote_plus
|
6 |
import time
|
7 |
import logging
|
|
|
|
|
8 |
|
9 |
# Configure logging
|
10 |
logging.basicConfig(level=logging.INFO)
|
11 |
logger = logging.getLogger(__name__)
|
12 |
|
13 |
-
|
|
|
14 |
"""
|
15 |
-
Search the knowledge base for solutions related to the provided issue.
|
16 |
Args:
|
17 |
issue (str): The technical issue to search for
|
18 |
Returns:
|
@@ -20,64 +23,56 @@ def search_knowledge_base(issue):
|
|
20 |
"""
|
21 |
try:
|
22 |
issue = issue.lower()
|
23 |
-
if "wifi" in issue:
|
24 |
-
return "
|
25 |
-
elif "screen" in issue:
|
26 |
-
return "
|
27 |
elif "sound" in issue or "audio" in issue:
|
28 |
-
return "
|
29 |
return "No predefined solution found in the knowledge base. Please try our web search tool for more information."
|
30 |
except Exception as e:
|
31 |
logger.error(f"Error in knowledge base search: {str(e)}")
|
32 |
return f"Error searching knowledge base: {str(e)}"
|
33 |
|
34 |
-
def search_web_duckduckgo(query):
|
35 |
"""
|
36 |
-
Perform
|
37 |
Args:
|
38 |
query (str): The search query
|
39 |
Returns:
|
40 |
str: Formatted search results
|
41 |
"""
|
42 |
try:
|
43 |
-
# DuckDuckGo Instant Answer API
|
44 |
url = f"https://api.duckduckgo.com/?q={quote_plus(query)}&format=json&no_html=1&skip_disambig=1"
|
45 |
|
46 |
response = requests.get(url, timeout=10)
|
47 |
response.raise_for_status()
|
48 |
|
49 |
data = response.json()
|
50 |
-
|
51 |
results = []
|
52 |
|
53 |
-
# Get instant answer if available
|
54 |
if data.get('AbstractText'):
|
55 |
-
results.append(f"
|
56 |
|
57 |
-
# Get related topics
|
58 |
if data.get('RelatedTopics'):
|
59 |
-
results.append("\n
|
60 |
-
for i, topic in enumerate(data['RelatedTopics'][:
|
61 |
if isinstance(topic, dict) and topic.get('Text'):
|
62 |
results.append(f"{i}. {topic['Text']}")
|
|
|
|
|
63 |
|
64 |
-
|
65 |
-
|
66 |
-
|
|
|
67 |
|
68 |
-
if results
|
69 |
-
return "\n".join(results)
|
70 |
-
else:
|
71 |
-
return f"Search completed for '{query}' but no detailed results available. Try a more specific query."
|
72 |
-
|
73 |
-
except requests.RequestException as e:
|
74 |
-
logger.error(f"Web search API error: {str(e)}")
|
75 |
-
return f"Error performing web search: {str(e)}"
|
76 |
except Exception as e:
|
77 |
-
logger.error(f"
|
78 |
-
return
|
79 |
|
80 |
-
def search_web_scraper(query):
|
81 |
"""
|
82 |
Alternative web search using web scraping (backup method).
|
83 |
Args:
|
@@ -86,7 +81,6 @@ def search_web_scraper(query):
|
|
86 |
str: Formatted search results
|
87 |
"""
|
88 |
try:
|
89 |
-
# Use DuckDuckGo HTML search as backup
|
90 |
search_url = f"https://duckduckgo.com/html/?q={quote_plus(query)}"
|
91 |
|
92 |
headers = {
|
@@ -97,26 +91,24 @@ def search_web_scraper(query):
|
|
97 |
response.raise_for_status()
|
98 |
|
99 |
soup = BeautifulSoup(response.content, 'html.parser')
|
100 |
-
|
101 |
-
# Extract search results
|
102 |
results = []
|
103 |
-
result_links = soup.find_all('a', class_='result__a')[:5]
|
104 |
|
105 |
for i, link in enumerate(result_links, 1):
|
106 |
title = link.get_text(strip=True)
|
|
|
107 |
if title:
|
108 |
-
results.append(f"{i}. {title}")
|
109 |
|
110 |
if results:
|
111 |
-
return f"
|
112 |
-
|
113 |
-
return f"No results found for '{query}'. Try different keywords."
|
114 |
-
|
115 |
except Exception as e:
|
116 |
logger.error(f"Web scraping error: {str(e)}")
|
117 |
return f"Error in backup search: {str(e)}"
|
118 |
|
119 |
-
|
|
|
120 |
"""
|
121 |
Main web search function that tries multiple methods.
|
122 |
Args:
|
@@ -127,21 +119,13 @@ def search_web(query):
|
|
127 |
try:
|
128 |
if not query.strip():
|
129 |
return "Please enter a search query."
|
130 |
-
|
131 |
-
# Try DuckDuckGo API first
|
132 |
-
result = search_web_duckduckgo(query)
|
133 |
-
|
134 |
-
# If API fails, try scraping method
|
135 |
-
if "Error" in result:
|
136 |
-
logger.info("API method failed, trying scraping method...")
|
137 |
-
result = search_web_scraper(query)
|
138 |
-
|
139 |
-
return result
|
140 |
except Exception as e:
|
141 |
logger.error(f"Error in main web search: {str(e)}")
|
142 |
return f"Error processing your search: {str(e)}"
|
143 |
|
144 |
-
|
|
|
145 |
"""
|
146 |
Format the raw steps into a numbered list.
|
147 |
Args:
|
@@ -153,11 +137,18 @@ def format_response(raw_steps):
|
|
153 |
if not raw_steps.strip():
|
154 |
return "Please enter some text to format."
|
155 |
|
156 |
-
|
157 |
-
steps = re.split(r'[.,;]\s*', raw_steps)
|
158 |
steps = [step.strip() for step in steps if step.strip()]
|
159 |
-
|
160 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
161 |
except Exception as e:
|
162 |
logger.error(f"Error formatting steps: {str(e)}")
|
163 |
return f"Error formatting your steps: {str(e)}"
|
|
|
5 |
from urllib.parse import quote_plus
|
6 |
import time
|
7 |
import logging
|
8 |
+
import re # Added missing import
|
9 |
+
from smolagents.tools import tool # Added for tool decorators
|
10 |
|
11 |
# Configure logging
|
12 |
logging.basicConfig(level=logging.INFO)
|
13 |
logger = logging.getLogger(__name__)
|
14 |
|
15 |
+
@tool(name="knowledge_base")
|
16 |
+
def search_knowledge_base(issue: str) -> str:
|
17 |
"""
|
18 |
+
Search the knowledge base for solutions related to the provided technical issue.
|
19 |
Args:
|
20 |
issue (str): The technical issue to search for
|
21 |
Returns:
|
|
|
23 |
"""
|
24 |
try:
|
25 |
issue = issue.lower()
|
26 |
+
if "wifi" in issue or "internet" in issue or "network" in issue:
|
27 |
+
return "π§ WiFi Troubleshooting:\n1. Check if your router is powered on\n2. Restart your router\n3. Try connecting again\n4. If problem persists, contact your ISP"
|
28 |
+
elif "screen" in issue or "display" in issue:
|
29 |
+
return "π₯οΈ Display Issues:\n1. Adjust display cable connections\n2. Update graphics drivers\n3. Restart the system\n4. Try a different monitor if available"
|
30 |
elif "sound" in issue or "audio" in issue:
|
31 |
+
return "π Audio Problems:\n1. Check volume settings\n2. Verify audio output device selection\n3. Update audio drivers\n4. Test with headphones"
|
32 |
return "No predefined solution found in the knowledge base. Please try our web search tool for more information."
|
33 |
except Exception as e:
|
34 |
logger.error(f"Error in knowledge base search: {str(e)}")
|
35 |
return f"Error searching knowledge base: {str(e)}"
|
36 |
|
37 |
+
def search_web_duckduckgo(query: str) -> str:
|
38 |
"""
|
39 |
+
Perform web search using DuckDuckGo API.
|
40 |
Args:
|
41 |
query (str): The search query
|
42 |
Returns:
|
43 |
str: Formatted search results
|
44 |
"""
|
45 |
try:
|
|
|
46 |
url = f"https://api.duckduckgo.com/?q={quote_plus(query)}&format=json&no_html=1&skip_disambig=1"
|
47 |
|
48 |
response = requests.get(url, timeout=10)
|
49 |
response.raise_for_status()
|
50 |
|
51 |
data = response.json()
|
|
|
52 |
results = []
|
53 |
|
|
|
54 |
if data.get('AbstractText'):
|
55 |
+
results.append(f"π {data['AbstractText']}")
|
56 |
|
|
|
57 |
if data.get('RelatedTopics'):
|
58 |
+
results.append("\nπ Related Topics:")
|
59 |
+
for i, topic in enumerate(data['RelatedTopics'][:5], 1):
|
60 |
if isinstance(topic, dict) and topic.get('Text'):
|
61 |
results.append(f"{i}. {topic['Text']}")
|
62 |
+
elif hasattr(topic, 'FirstURL'):
|
63 |
+
results.append(f"{i}. {getattr(topic, 'Text', 'No description')} - {topic.FirstURL}")
|
64 |
|
65 |
+
if data.get('Results'):
|
66 |
+
results.append("\nπ Web Results:")
|
67 |
+
for i, result in enumerate(data['Results'][:3], 1):
|
68 |
+
results.append(f"{i}. {result.get('Text', 'No title')} - {result.get('FirstURL', 'No URL')}")
|
69 |
|
70 |
+
return "\n".join(results) if results else search_web_scraper(query)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
except Exception as e:
|
72 |
+
logger.error(f"DuckDuckGo API error: {str(e)}")
|
73 |
+
return search_web_scraper(query)
|
74 |
|
75 |
+
def search_web_scraper(query: str) -> str:
|
76 |
"""
|
77 |
Alternative web search using web scraping (backup method).
|
78 |
Args:
|
|
|
81 |
str: Formatted search results
|
82 |
"""
|
83 |
try:
|
|
|
84 |
search_url = f"https://duckduckgo.com/html/?q={quote_plus(query)}"
|
85 |
|
86 |
headers = {
|
|
|
91 |
response.raise_for_status()
|
92 |
|
93 |
soup = BeautifulSoup(response.content, 'html.parser')
|
|
|
|
|
94 |
results = []
|
95 |
+
result_links = soup.find_all('a', class_='result__a')[:5]
|
96 |
|
97 |
for i, link in enumerate(result_links, 1):
|
98 |
title = link.get_text(strip=True)
|
99 |
+
url = link['href'] if 'href' in link.attrs else '#'
|
100 |
if title:
|
101 |
+
results.append(f"{i}. {title} - {url}")
|
102 |
|
103 |
if results:
|
104 |
+
return f"π Search Results for '{query}':\n" + "\n".join(results)
|
105 |
+
return f"No results found for '{query}'. Try different keywords."
|
|
|
|
|
106 |
except Exception as e:
|
107 |
logger.error(f"Web scraping error: {str(e)}")
|
108 |
return f"Error in backup search: {str(e)}"
|
109 |
|
110 |
+
@tool(name="web_search")
|
111 |
+
def search_web(query: str) -> str:
|
112 |
"""
|
113 |
Main web search function that tries multiple methods.
|
114 |
Args:
|
|
|
119 |
try:
|
120 |
if not query.strip():
|
121 |
return "Please enter a search query."
|
122 |
+
return search_web_duckduckgo(query)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
123 |
except Exception as e:
|
124 |
logger.error(f"Error in main web search: {str(e)}")
|
125 |
return f"Error processing your search: {str(e)}"
|
126 |
|
127 |
+
@tool(name="formatter")
|
128 |
+
def format_response(raw_steps: str) -> str:
|
129 |
"""
|
130 |
Format the raw steps into a numbered list.
|
131 |
Args:
|
|
|
137 |
if not raw_steps.strip():
|
138 |
return "Please enter some text to format."
|
139 |
|
140 |
+
steps = re.split(r'[.,;]\s+|\n', raw_steps)
|
|
|
141 |
steps = [step.strip() for step in steps if step.strip()]
|
142 |
+
|
143 |
+
formatted_steps = []
|
144 |
+
for i, step in enumerate(steps, 1):
|
145 |
+
if step:
|
146 |
+
formatted_step = f"{i}. {step[0].upper()}{step[1:]}"
|
147 |
+
if not step.endswith('.'):
|
148 |
+
formatted_step += '.'
|
149 |
+
formatted_steps.append(formatted_step)
|
150 |
+
|
151 |
+
return "\n".join(formatted_steps)
|
152 |
except Exception as e:
|
153 |
logger.error(f"Error formatting steps: {str(e)}")
|
154 |
return f"Error formatting your steps: {str(e)}"
|