JimmyBhoy commited on
Commit
a270769
Β·
verified Β·
1 Parent(s): 1afa151

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +122 -100
app.py CHANGED
@@ -1,115 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
 
2
- **Model**: {self.config.MODEL_NAME}
3
- **Available Tools**: {', '.join(tool_names)}
4
- **Max Iterations**: {self.config.MAX_ITERATIONS}
5
- **Status**: βœ… Ready
 
 
 
 
 
 
 
6
 
7
- **Capabilities**:
8
- - Web search for current information
9
- - Document retrieval from knowledge base
10
- - Weather information
11
- - Multi-step reasoning and planning
12
- - Source attribution
13
- """
14
-
15
- # Initialize the RAG agent
16
- rag_agent = ProductionRAGAgent()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- def chat_interface(message: str, history: List) -> str:
19
- """Gradio chat interface function"""
20
- return rag_agent.query(message, history)
 
 
21
 
22
- def get_info() -> str:
23
- """Get agent information"""
24
- return rag_agent.get_agent_info()
25
 
26
- # Create Gradio interface
27
- def create_interface():
28
- """Create the Gradio web interface"""
29
 
30
- with gr.Blocks(
31
- title="Production RAG Agent",
32
- theme=gr.themes.Soft(),
33
- css="""
34
- .container { max-width: 1200px; margin: auto; }
35
- .header { text-align: center; margin-bottom: 30px; }
36
- .info-box { background: #f8f9fa; padding: 20px; border-radius: 10px; margin: 10px 0; }
37
- """
38
- ) as demo:
39
-
40
- # Header
41
- with gr.Row():
42
- gr.HTML("""
43
- <div class="header">
44
- <h1>πŸš€ Production RAG Agent</h1>
45
- <p>Advanced Retrieval-Augmented Generation with Multi-Tool Support</p>
46
- </div>
47
- """)
48
-
49
- # Main interface
50
- with gr.Row():
51
- with gr.Column(scale=3):
52
- # Chat interface
 
 
 
 
53
  chatbot = gr.ChatInterface(
54
- fn=chat_interface,
55
- title="πŸ’¬ Chat with RAG Agent",
56
- description="Ask questions and get answers from multiple information sources",
57
  examples=[
58
- "What are the latest developments in AI?",
59
- "Explain how transformer models work",
60
- "What's the weather like today?",
61
- "Compare different machine learning algorithms",
62
- "Tell me about recent research in computer vision"
63
  ],
64
  retry_btn="πŸ”„ Retry",
65
  undo_btn="β†Ά Undo",
66
- clear_btn="πŸ—‘οΈ Clear",
67
- submit_btn="πŸ“€ Send"
68
  )
69
-
70
- with gr.Column(scale=1):
71
- # Agent information panel
72
- with gr.Group():
73
- gr.Markdown("### πŸ€– Agent Status")
74
- info_display = gr.Markdown(value=get_info())
75
- refresh_btn = gr.Button("πŸ”„ Refresh Status", size="sm")
76
- refresh_btn.click(fn=get_info, outputs=info_display)
77
-
78
- # Usage tips
79
- with gr.Group():
80
- gr.Markdown("""
81
- ### πŸ’‘ Usage Tips
82
-
83
- **Best Practices:**
84
- - Be specific in your questions
85
- - Ask for sources when needed
86
- - Use follow-up questions for clarification
87
-
88
- **Available Features:**
89
- - 🌐 Web search for current info
90
- - πŸ“š Document knowledge retrieval
91
- - 🌀️ Weather information
92
- - 🧠 Multi-step reasoning
93
- """)
94
 
95
- # Footer
96
- with gr.Row():
97
- gr.HTML("""
98
- <div style="text-align: center; margin-top: 30px; padding: 20px; background: #f1f3f4; border-radius: 10px;">
99
- <p><strong>Production RAG Agent</strong> - Powered by Hugging Face πŸ€—</p>
100
- <p>Built with smolagents, Gradio, and advanced retrieval techniques</p>
101
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  """)
103
-
104
- return demo
105
 
106
- # Create and launch the interface
107
- if __name__ == "__main__":
108
- demo = create_interface()
109
- demo.queue()
110
- demo.launch(
111
- share=True,
112
- server_name="0.0.0.0",
113
- server_port=7860,
114
- show_error=True
115
- )
 
1
+ import gradio as gr
2
+ import os
3
+
4
+ # Simple demo RAG system
5
+ class DemoRAG:
6
+ def __init__(self):
7
+ self.documents = {}
8
+ self.doc_count = 0
9
+
10
+ def process_files(self, files):
11
+ if not files:
12
+ return "No files uploaded."
13
 
14
+ processed = 0
15
+ for file in files:
16
+ try:
17
+ # Read file content
18
+ if hasattr(file, 'name'):
19
+ with open(file.name, 'r', encoding='utf-8', errors='ignore') as f:
20
+ content = f.read()
21
+ self.documents[file.name] = content
22
+ processed += 1
23
+ except Exception as e:
24
+ continue
25
 
26
+ self.doc_count = len(self.documents)
27
+ return f"βœ… Processed {processed} documents successfully!\n\nπŸ“„ Total documents: {self.doc_count}"
28
+
29
+ def answer_question(self, question, history):
30
+ if not question.strip():
31
+ return "Please ask a question."
32
+
33
+ if not self.documents:
34
+ return "❌ No documents uploaded yet. Please upload some documents first."
35
+
36
+ # Simple keyword search
37
+ relevant_docs = []
38
+ question_lower = question.lower()
39
+
40
+ for filename, content in self.documents.items():
41
+ if any(word in content.lower() for word in question_lower.split()):
42
+ snippet = content[:300] + "..." if len(content) > 300 else content
43
+ relevant_docs.append(f"**Source: {filename}**\n{snippet}")
44
+
45
+ if not relevant_docs:
46
+ return f"No direct matches found in {len(self.documents)} documents. Try different keywords."
47
+
48
+ response = f"Based on your {len(self.documents)} uploaded documents:\n\n"
49
+ response += "\n\n---\n\n".join(relevant_docs[:2])
50
+ response += f"\n\n*Found information in {len(relevant_docs)} document(s)*"
51
+
52
+ return response
53
+
54
+ def get_status(self):
55
+ return f"""
56
+ πŸ€– **RAG System Status**
57
 
58
+ **Status**: βœ… Running
59
+ **Documents**: {self.doc_count} uploaded
60
+ **Search**: Simple keyword matching
61
+ **Ready**: Upload docs and ask questions!
62
+ """
63
 
64
+ # Initialize system
65
+ rag = DemoRAG()
 
66
 
67
+ # Create interface
68
+ with gr.Blocks(title="Enterprise RAG System", theme=gr.themes.Soft()) as demo:
 
69
 
70
+ gr.HTML("""
71
+ <div style="text-align: center; padding: 20px; background: linear-gradient(45deg, #4f46e5, #7c3aed); color: white; border-radius: 10px; margin-bottom: 20px;">
72
+ <h1>πŸš€ Enterprise RAG System</h1>
73
+ <p>Upload documents β€’ Ask questions β€’ Get AI-powered answers</p>
74
+ </div>
75
+ """)
76
+
77
+ with gr.Row():
78
+ # Main content
79
+ with gr.Column(scale=3):
80
+ with gr.Tab("πŸ“ Upload Documents"):
81
+ gr.Markdown("### Upload Your Documents")
82
+ file_upload = gr.File(
83
+ file_count="multiple",
84
+ file_types=[".txt", ".md", ".pdf", ".docx", ".json"],
85
+ label="Choose files to upload"
86
+ )
87
+ upload_btn = gr.Button("πŸ“€ Process Documents", variant="primary", size="lg")
88
+ upload_result = gr.Markdown()
89
+
90
+ upload_btn.click(
91
+ fn=rag.process_files,
92
+ inputs=[file_upload],
93
+ outputs=[upload_result]
94
+ )
95
+
96
+ with gr.Tab("πŸ’¬ Ask Questions"):
97
  chatbot = gr.ChatInterface(
98
+ fn=rag.answer_question,
99
+ title="Chat with Your Documents",
 
100
  examples=[
101
+ "What are the main topics in the documents?",
102
+ "Can you summarize the key points?",
103
+ "What does it say about [your topic]?",
104
+ "Find information about [specific term]"
 
105
  ],
106
  retry_btn="πŸ”„ Retry",
107
  undo_btn="β†Ά Undo",
108
+ clear_btn="πŸ—‘οΈ Clear"
 
109
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
+ # Sidebar
112
+ with gr.Column(scale=1):
113
+ gr.Markdown("### πŸ“Š System Status")
114
+ status_display = gr.Markdown(value=rag.get_status())
115
+ gr.Button("πŸ”„ Refresh").click(fn=rag.get_status, outputs=[status_display])
116
+
117
+ gr.Markdown("""
118
+ ### πŸ’‘ Quick Guide
119
+
120
+ **1. Upload Documents**
121
+ - Support: TXT, PDF, DOCX, MD, JSON
122
+ - Multiple files at once
123
+
124
+ **2. Ask Questions**
125
+ - Natural language queries
126
+ - Get answers with sources
127
+ - Try different keywords
128
+
129
+ **3. Features**
130
+ - βœ… Document processing
131
+ - βœ… Keyword search
132
+ - βœ… Source attribution
133
+ - βœ… Multi-format support
134
  """)
 
 
135
 
136
+ # Launch
137
+ demo.launch()