File size: 3,812 Bytes
44198e0
636f8ae
 
 
 
 
44198e0
636f8ae
 
 
 
 
 
 
 
 
 
 
 
3f90511
636f8ae
 
 
 
 
 
 
 
 
 
03649cb
 
 
 
 
44198e0
f2c01c1
636f8ae
03649cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44198e0
636f8ae
 
03649cb
 
 
44198e0
03649cb
44198e0
636f8ae
 
 
 
 
 
68c6844
636f8ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03649cb
 
 
 
636f8ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f90511
636f8ae
 
44198e0
68c6844
636f8ae
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import gradio as gr
from rag_engine import RAGEngine
import torch
import os
import logging
import traceback

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def safe_search(query, max_results):
    """Wrapper function to handle errors gracefully"""
    try:
        rag = RAGEngine()
        results = rag.search_and_process(query, max_results)
        
        if 'error' in results:
            return f"# ❌ Error\nSorry, an error occurred while processing your search:\n```\n{results['error']}\n```"
            
        return format_results(results)
    except Exception as e:
        error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
        logger.error(error_msg)
        return f"# ❌ Error\nSorry, an error occurred while processing your search:\n```\n{str(e)}\n```"

def format_results(results):
    """Format search results into a clean markdown output"""
    if 'error' in results:
        return f"❌ Error: {results['error']}"
        
    output = []
    
    # Add insights section
    if 'insights' in results:
        insights = results['insights']
        output.append("# 🎯 Key Insights\n")
        
        if 'summary' in insights:
            output.append(insights['summary'])
            output.append("\n")
            
        if 'key_points' in insights and len(insights['key_points']) > 5:
            output.append("\n## πŸ“Œ Additional Points\n")
            for point in insights['key_points'][5:]:
                output.append(f"β€’ {point}")
            output.append("\n")
    
    # Add sources section
    if 'insights' in results and 'sources' in results['insights']:
        output.append("\n# πŸ“š Sources\n")
        for idx, source in enumerate(results['insights']['sources'], 1):
            output.append(f"\n## {idx}. {source['title']}\n")
            if 'url' in source:
                output.append(f"πŸ”— [View Source]({source['url']})\n")
            if 'summary' in source:
                output.append(f"\n{source['summary']}\n")
    
    # Add follow-up questions
    if 'follow_up_questions' in results:
        output.append("\n# ❓ Suggested Questions\n")
        for question in results['follow_up_questions']:
            output.append(f"β€’ {question}\n")
    
    return "\n".join(output)

def create_demo():
    """Create the Gradio interface"""
    
    with gr.Blocks(title="Web Search + RAG") as demo:
        gr.Markdown("# πŸ” Intelligent Web Search")
        gr.Markdown("Search the web with AI-powered insights and analysis.")
        
        with gr.Row():
            with gr.Column():
                query = gr.Textbox(
                    label="Search Query",
                    placeholder="Enter your search query...",
                    lines=2
                )
                max_results = gr.Slider(
                    minimum=1,
                    maximum=10,
                    value=5,
                    step=1,
                    label="Number of Results"
                )
                search_button = gr.Button("πŸ” Search")
            
        output = gr.Markdown(
            label="Search Results",
            show_label=True
        )
        
        search_button.click(
            fn=safe_search,
            inputs=[query, max_results],
            outputs=output
        )
        
        gr.Examples(
            examples=[
                ["What is RAG in AI?", 5],
                ["Latest developments in quantum computing", 3],
                ["How does BERT work?", 5]
            ],
            inputs=[query, max_results]
        )
        
    return demo

# Create the demo
demo = create_demo()

# Launch for Spaces
demo.launch()