Spaces:
Build error
Build error
fikird
commited on
Commit
Β·
53a521c
1
Parent(s):
d7b6953
Fix error handling and result formatting
Browse files- app.py +41 -70
- rag_engine.py +13 -9
app.py
CHANGED
@@ -4,7 +4,6 @@ import torch
|
|
4 |
import os
|
5 |
import logging
|
6 |
import traceback
|
7 |
-
import asyncio
|
8 |
|
9 |
# Configure logging
|
10 |
logging.basicConfig(
|
@@ -17,7 +16,11 @@ def safe_search(query, max_results):
|
|
17 |
"""Wrapper function to handle errors gracefully"""
|
18 |
try:
|
19 |
rag = RAGEngine()
|
20 |
-
results =
|
|
|
|
|
|
|
|
|
21 |
return format_results(results)
|
22 |
except Exception as e:
|
23 |
error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
|
@@ -26,7 +29,7 @@ def safe_search(query, max_results):
|
|
26 |
|
27 |
def format_results(results):
|
28 |
"""Format search results for display"""
|
29 |
-
if not results:
|
30 |
return "# β οΈ No Results\nNo search results were found. Please try a different query."
|
31 |
|
32 |
formatted = f"# π Search Results\n\n"
|
@@ -47,63 +50,39 @@ def format_results(results):
|
|
47 |
if 'results' in results:
|
48 |
formatted += "## π Detailed Results\n\n"
|
49 |
for i, result in enumerate(results['results'], 1):
|
|
|
|
|
|
|
50 |
formatted += f"### {i}. "
|
51 |
if 'url' in result:
|
52 |
-
|
53 |
-
|
54 |
-
|
|
|
55 |
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
# Add similar queries if available
|
72 |
-
if results.get('similar_queries'):
|
73 |
-
formatted += "## π Related Searches\n"
|
74 |
-
for query in results['similar_queries']:
|
75 |
-
if isinstance(query, dict) and 'query' in query:
|
76 |
-
formatted += f"- {query['query']}\n"
|
77 |
-
elif isinstance(query, str):
|
78 |
-
formatted += f"- {query}\n"
|
79 |
|
80 |
return formatted
|
81 |
|
82 |
def create_demo():
|
83 |
"""Create the Gradio interface"""
|
84 |
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
demo = gr.Blocks(
|
89 |
-
title="AI-Powered Search Engine",
|
90 |
-
css="""
|
91 |
-
.gradio-container {max-width: 1200px !important}
|
92 |
-
.markdown-text {font-size: 16px !important}
|
93 |
-
"""
|
94 |
-
)
|
95 |
-
|
96 |
-
with demo:
|
97 |
-
gr.Markdown("""
|
98 |
-
# π Intelligent Web Search Engine
|
99 |
-
|
100 |
-
This advanced search engine uses AI to provide deep understanding of search results:
|
101 |
-
- π§ Multi-model AI analysis
|
102 |
-
- π Semantic search and caching
|
103 |
-
- π‘ Automatic insights generation
|
104 |
-
- β Smart follow-up questions
|
105 |
-
- π Related searches
|
106 |
-
""")
|
107 |
|
108 |
with gr.Row():
|
109 |
with gr.Column():
|
@@ -113,21 +92,17 @@ def create_demo():
|
|
113 |
lines=2
|
114 |
)
|
115 |
max_results = gr.Slider(
|
116 |
-
minimum=
|
117 |
maximum=10,
|
118 |
value=5,
|
119 |
step=1,
|
120 |
-
label="
|
121 |
)
|
122 |
-
|
123 |
-
|
124 |
-
with gr.Column():
|
125 |
-
output = gr.Markdown(
|
126 |
-
label="Results",
|
127 |
-
show_label=False
|
128 |
-
)
|
129 |
|
130 |
-
|
|
|
|
|
131 |
fn=safe_search,
|
132 |
inputs=[query, max_results],
|
133 |
outputs=output
|
@@ -135,17 +110,13 @@ def create_demo():
|
|
135 |
|
136 |
gr.Examples(
|
137 |
examples=[
|
138 |
-
["What
|
139 |
-
["
|
140 |
-
["
|
141 |
-
["What are the environmental impacts of renewable energy?", 5]
|
142 |
],
|
143 |
-
inputs=[query, max_results]
|
144 |
-
outputs=output,
|
145 |
-
fn=safe_search,
|
146 |
-
cache_examples=True
|
147 |
)
|
148 |
-
|
149 |
return demo
|
150 |
|
151 |
# Create the demo
|
|
|
4 |
import os
|
5 |
import logging
|
6 |
import traceback
|
|
|
7 |
|
8 |
# Configure logging
|
9 |
logging.basicConfig(
|
|
|
16 |
"""Wrapper function to handle errors gracefully"""
|
17 |
try:
|
18 |
rag = RAGEngine()
|
19 |
+
results = rag.search_and_process(query, max_results)
|
20 |
+
|
21 |
+
if 'error' in results:
|
22 |
+
return f"# β Error\nSorry, an error occurred while processing your search:\n```\n{results['error']}\n```"
|
23 |
+
|
24 |
return format_results(results)
|
25 |
except Exception as e:
|
26 |
error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
|
|
|
29 |
|
30 |
def format_results(results):
|
31 |
"""Format search results for display"""
|
32 |
+
if not results or not results.get('results'):
|
33 |
return "# β οΈ No Results\nNo search results were found. Please try a different query."
|
34 |
|
35 |
formatted = f"# π Search Results\n\n"
|
|
|
50 |
if 'results' in results:
|
51 |
formatted += "## π Detailed Results\n\n"
|
52 |
for i, result in enumerate(results['results'], 1):
|
53 |
+
if not isinstance(result, dict):
|
54 |
+
continue
|
55 |
+
|
56 |
formatted += f"### {i}. "
|
57 |
if 'url' in result:
|
58 |
+
title = result.get('title', 'Untitled')
|
59 |
+
formatted += f"[{title}]({result['url']})\n"
|
60 |
+
if 'summary' in result:
|
61 |
+
formatted += f"\n{result['summary']}\n\n"
|
62 |
|
63 |
+
# Add similar chunks if available
|
64 |
+
if 'similar_chunks' in results:
|
65 |
+
formatted += "## π Related Content\n\n"
|
66 |
+
for i, chunk in enumerate(results['similar_chunks'], 1):
|
67 |
+
if not isinstance(chunk, dict):
|
68 |
+
continue
|
69 |
+
|
70 |
+
formatted += f"### Related {i}\n"
|
71 |
+
if 'metadata' in chunk:
|
72 |
+
meta = chunk['metadata']
|
73 |
+
if 'title' in meta and 'url' in meta:
|
74 |
+
formatted += f"From [{meta['title']}]({meta['url']})\n"
|
75 |
+
if 'content' in chunk:
|
76 |
+
formatted += f"\n{chunk['content'][:200]}...\n\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
|
78 |
return formatted
|
79 |
|
80 |
def create_demo():
|
81 |
"""Create the Gradio interface"""
|
82 |
|
83 |
+
with gr.Blocks(title="Web Search + RAG") as demo:
|
84 |
+
gr.Markdown("# π Intelligent Web Search")
|
85 |
+
gr.Markdown("Search the web with AI-powered insights and analysis.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
|
87 |
with gr.Row():
|
88 |
with gr.Column():
|
|
|
92 |
lines=2
|
93 |
)
|
94 |
max_results = gr.Slider(
|
95 |
+
minimum=1,
|
96 |
maximum=10,
|
97 |
value=5,
|
98 |
step=1,
|
99 |
+
label="Number of Results"
|
100 |
)
|
101 |
+
search_button = gr.Button("π Search")
|
|
|
|
|
|
|
|
|
|
|
|
|
102 |
|
103 |
+
output = gr.Markdown()
|
104 |
+
|
105 |
+
search_button.click(
|
106 |
fn=safe_search,
|
107 |
inputs=[query, max_results],
|
108 |
outputs=output
|
|
|
110 |
|
111 |
gr.Examples(
|
112 |
examples=[
|
113 |
+
["What is RAG in AI?", 5],
|
114 |
+
["Latest developments in quantum computing", 3],
|
115 |
+
["How does BERT work?", 5]
|
|
|
116 |
],
|
117 |
+
inputs=[query, max_results]
|
|
|
|
|
|
|
118 |
)
|
119 |
+
|
120 |
return demo
|
121 |
|
122 |
# Create the demo
|
rag_engine.py
CHANGED
@@ -46,22 +46,26 @@ class RAGEngine:
|
|
46 |
# Get web search results
|
47 |
web_results = self.web_search.search(query, max_results)
|
48 |
|
|
|
|
|
|
|
49 |
# Process and store new content
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
|
|
56 |
|
57 |
-
# Perform similarity search
|
58 |
if self.vector_store:
|
59 |
similar_docs = self.vector_store.similarity_search_with_score(
|
60 |
query,
|
61 |
k=similarity_k
|
62 |
)
|
63 |
|
64 |
-
# Add similarity results
|
65 |
web_results['similar_chunks'] = [
|
66 |
{
|
67 |
'content': doc[0].page_content,
|
@@ -75,7 +79,7 @@ class RAGEngine:
|
|
75 |
|
76 |
except Exception as e:
|
77 |
logger.error(f"Error in search_and_process: {str(e)}")
|
78 |
-
|
79 |
|
80 |
def get_relevant_context(self, query: str, k: int = 3) -> List[Dict]:
|
81 |
"""Get most relevant context from vector store"""
|
|
|
46 |
# Get web search results
|
47 |
web_results = self.web_search.search(query, max_results)
|
48 |
|
49 |
+
if 'error' in web_results:
|
50 |
+
return {'error': web_results['error']}
|
51 |
+
|
52 |
# Process and store new content
|
53 |
+
if 'results' in web_results and web_results['results']:
|
54 |
+
for result in web_results['results']:
|
55 |
+
if 'content' in result:
|
56 |
+
self.process_and_store_content(
|
57 |
+
result['content'],
|
58 |
+
metadata={'url': result.get('url'), 'title': result.get('title')}
|
59 |
+
)
|
60 |
|
61 |
+
# Perform similarity search if we have stored vectors
|
62 |
if self.vector_store:
|
63 |
similar_docs = self.vector_store.similarity_search_with_score(
|
64 |
query,
|
65 |
k=similarity_k
|
66 |
)
|
67 |
|
68 |
+
# Add similarity results to web results
|
69 |
web_results['similar_chunks'] = [
|
70 |
{
|
71 |
'content': doc[0].page_content,
|
|
|
79 |
|
80 |
except Exception as e:
|
81 |
logger.error(f"Error in search_and_process: {str(e)}")
|
82 |
+
return {'error': f"Search failed: {str(e)}"}
|
83 |
|
84 |
def get_relevant_context(self, query: str, k: int = 3) -> List[Dict]:
|
85 |
"""Get most relevant context from vector store"""
|