Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -5,17 +5,17 @@ import json
|
|
5 |
from urllib.parse import quote_plus
|
6 |
import time
|
7 |
import logging
|
8 |
-
import re
|
9 |
-
from smolagents.tools import tool
|
10 |
|
11 |
# Configure logging
|
12 |
logging.basicConfig(level=logging.INFO)
|
13 |
logger = logging.getLogger(__name__)
|
14 |
|
15 |
-
@tool
|
16 |
def search_knowledge_base(issue: str) -> str:
|
17 |
"""
|
18 |
-
Search the knowledge base for solutions related to the provided
|
19 |
Args:
|
20 |
issue (str): The technical issue to search for
|
21 |
Returns:
|
@@ -23,12 +23,12 @@ def search_knowledge_base(issue: str) -> str:
|
|
23 |
"""
|
24 |
try:
|
25 |
issue = issue.lower()
|
26 |
-
if "wifi" in issue
|
27 |
-
return "
|
28 |
-
elif "screen" in issue
|
29 |
-
return "
|
30 |
elif "sound" in issue or "audio" in issue:
|
31 |
-
return "
|
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)}")
|
@@ -36,7 +36,7 @@ def search_knowledge_base(issue: str) -> str:
|
|
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:
|
@@ -49,27 +49,24 @@ def search_web_duckduckgo(query: str) -> str:
|
|
49 |
response.raise_for_status()
|
50 |
|
51 |
data = response.json()
|
|
|
52 |
results = []
|
53 |
|
54 |
if data.get('AbstractText'):
|
55 |
-
results.append(f"
|
56 |
|
57 |
if data.get('RelatedTopics'):
|
58 |
-
results.append("\
|
59 |
-
for i, topic in enumerate(data['RelatedTopics'][:
|
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('
|
66 |
-
results.append("\
|
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"
|
73 |
return search_web_scraper(query)
|
74 |
|
75 |
def search_web_scraper(query: str) -> str:
|
@@ -96,18 +93,17 @@ def search_web_scraper(query: str) -> str:
|
|
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}
|
102 |
|
103 |
if results:
|
104 |
-
return f"
|
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
|
111 |
def search_web(query: str) -> str:
|
112 |
"""
|
113 |
Main web search function that tries multiple methods.
|
@@ -124,7 +120,7 @@ def search_web(query: str) -> str:
|
|
124 |
logger.error(f"Error in main web search: {str(e)}")
|
125 |
return f"Error processing your search: {str(e)}"
|
126 |
|
127 |
-
@tool
|
128 |
def format_response(raw_steps: str) -> str:
|
129 |
"""
|
130 |
Format the raw steps into a numbered list.
|
@@ -137,18 +133,10 @@ def format_response(raw_steps: str) -> str:
|
|
137 |
if not raw_steps.strip():
|
138 |
return "Please enter some text to format."
|
139 |
|
140 |
-
steps = re.split(r'[.,;]\s
|
141 |
steps = [step.strip() for step in steps if step.strip()]
|
142 |
-
|
143 |
-
|
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)}"
|
@@ -156,31 +144,27 @@ def format_response(raw_steps: str) -> str:
|
|
156 |
# Knowledge Base Search Interface
|
157 |
demo1 = gr.Interface(
|
158 |
fn=search_knowledge_base,
|
159 |
-
inputs=[gr.Textbox(label="Technical Issue", placeholder="Enter your technical problem
|
160 |
outputs=[gr.Textbox(label="Solution")],
|
161 |
-
title="Knowledge Base Search"
|
162 |
-
description="Enter a technical issue to search for solutions in the knowledge base."
|
163 |
)
|
164 |
|
165 |
# Web Search Interface
|
166 |
demo2 = gr.Interface(
|
167 |
fn=search_web,
|
168 |
-
inputs=[gr.Textbox(label="Search Query", placeholder="Enter your search query
|
169 |
outputs=[gr.Textbox(label="Search Results")],
|
170 |
-
title="Web Search"
|
171 |
-
description="Enter a search query to get real web search results from DuckDuckGo."
|
172 |
)
|
173 |
|
174 |
# Response Formatter Interface
|
175 |
demo3 = gr.Interface(
|
176 |
fn=format_response,
|
177 |
-
inputs=[gr.Textbox(label="Raw Steps", placeholder="Enter steps separated by periods
|
178 |
outputs=[gr.Textbox(label="Formatted Steps")],
|
179 |
-
title="Response Formatter"
|
180 |
-
description="Enter raw steps separated by periods or semicolons to format them as a numbered list."
|
181 |
)
|
182 |
|
183 |
-
# Combine all interfaces using Tabs
|
184 |
demo = gr.TabbedInterface([demo1, demo2, demo3], ["Knowledge Base", "Web Search", "Formatter"])
|
185 |
|
186 |
if __name__ == "__main__":
|
|
|
5 |
from urllib.parse import quote_plus
|
6 |
import time
|
7 |
import logging
|
8 |
+
import re
|
9 |
+
from smolagents.tools import tool
|
10 |
|
11 |
# Configure logging
|
12 |
logging.basicConfig(level=logging.INFO)
|
13 |
logger = logging.getLogger(__name__)
|
14 |
|
15 |
+
@tool
|
16 |
def search_knowledge_base(issue: str) -> str:
|
17 |
"""
|
18 |
+
Search the knowledge base for solutions related to the provided 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:
|
27 |
+
return "1. 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:
|
29 |
+
return "1. 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 "1. 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)}")
|
|
|
36 |
|
37 |
def search_web_duckduckgo(query: str) -> str:
|
38 |
"""
|
39 |
+
Perform actual web search using DuckDuckGo API.
|
40 |
Args:
|
41 |
query (str): The search query
|
42 |
Returns:
|
|
|
49 |
response.raise_for_status()
|
50 |
|
51 |
data = response.json()
|
52 |
+
|
53 |
results = []
|
54 |
|
55 |
if data.get('AbstractText'):
|
56 |
+
results.append(f"Summary: {data['AbstractText']}")
|
57 |
|
58 |
if data.get('RelatedTopics'):
|
59 |
+
results.append("\nRelated Information:")
|
60 |
+
for i, topic in enumerate(data['RelatedTopics'][:3], 1):
|
61 |
if isinstance(topic, dict) and topic.get('Text'):
|
62 |
results.append(f"{i}. {topic['Text']}")
|
|
|
|
|
63 |
|
64 |
+
if data.get('Definition'):
|
65 |
+
results.append(f"\nDefinition: {data['Definition']}")
|
|
|
|
|
66 |
|
67 |
return "\n".join(results) if results else search_web_scraper(query)
|
68 |
except Exception as e:
|
69 |
+
logger.error(f"Web search API error: {str(e)}")
|
70 |
return search_web_scraper(query)
|
71 |
|
72 |
def search_web_scraper(query: str) -> str:
|
|
|
93 |
|
94 |
for i, link in enumerate(result_links, 1):
|
95 |
title = link.get_text(strip=True)
|
|
|
96 |
if title:
|
97 |
+
results.append(f"{i}. {title}")
|
98 |
|
99 |
if results:
|
100 |
+
return f"Search Results for '{query}':\n" + "\n".join(results)
|
101 |
return f"No results found for '{query}'. Try different keywords."
|
102 |
except Exception as e:
|
103 |
logger.error(f"Web scraping error: {str(e)}")
|
104 |
return f"Error in backup search: {str(e)}"
|
105 |
|
106 |
+
@tool
|
107 |
def search_web(query: str) -> str:
|
108 |
"""
|
109 |
Main web search function that tries multiple methods.
|
|
|
120 |
logger.error(f"Error in main web search: {str(e)}")
|
121 |
return f"Error processing your search: {str(e)}"
|
122 |
|
123 |
+
@tool
|
124 |
def format_response(raw_steps: str) -> str:
|
125 |
"""
|
126 |
Format the raw steps into a numbered list.
|
|
|
133 |
if not raw_steps.strip():
|
134 |
return "Please enter some text to format."
|
135 |
|
136 |
+
steps = re.split(r'[.,;]\s*', raw_steps)
|
137 |
steps = [step.strip() for step in steps if step.strip()]
|
138 |
+
steps = [f"{i+1}. {step}" for i, step in enumerate(steps)]
|
139 |
+
return "\n".join(steps)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
140 |
except Exception as e:
|
141 |
logger.error(f"Error formatting steps: {str(e)}")
|
142 |
return f"Error formatting your steps: {str(e)}"
|
|
|
144 |
# Knowledge Base Search Interface
|
145 |
demo1 = gr.Interface(
|
146 |
fn=search_knowledge_base,
|
147 |
+
inputs=[gr.Textbox(label="Technical Issue", placeholder="Enter your technical problem")],
|
148 |
outputs=[gr.Textbox(label="Solution")],
|
149 |
+
title="Knowledge Base Search"
|
|
|
150 |
)
|
151 |
|
152 |
# Web Search Interface
|
153 |
demo2 = gr.Interface(
|
154 |
fn=search_web,
|
155 |
+
inputs=[gr.Textbox(label="Search Query", placeholder="Enter your search query")],
|
156 |
outputs=[gr.Textbox(label="Search Results")],
|
157 |
+
title="Web Search"
|
|
|
158 |
)
|
159 |
|
160 |
# Response Formatter Interface
|
161 |
demo3 = gr.Interface(
|
162 |
fn=format_response,
|
163 |
+
inputs=[gr.Textbox(label="Raw Steps", placeholder="Enter steps separated by periods")],
|
164 |
outputs=[gr.Textbox(label="Formatted Steps")],
|
165 |
+
title="Response Formatter"
|
|
|
166 |
)
|
167 |
|
|
|
168 |
demo = gr.TabbedInterface([demo1, demo2, demo3], ["Knowledge Base", "Web Search", "Formatter"])
|
169 |
|
170 |
if __name__ == "__main__":
|