-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
289 lines (229 loc) · 9.27 KB
/
main.py
File metadata and controls
289 lines (229 loc) · 9.27 KB
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
"""
Email RAG Assistant - Main Entry Point
A real-time agentic AI system that:
1. Monitors Gmail inbox for new emails
2. Converts emails to embeddings and stores them in Pinecone
3. Allows natural language queries against the email knowledge base
Usage:
python main.py # Run with interactive query mode
python main.py --ingest # Run ingestion only (once)
python main.py --daemon # Run as background daemon with scheduler
"""
import asyncio
import sys
import argparse
from datetime import datetime
from config import validate_config, INGESTION_INTERVAL_SECONDS
from ai_agents.gmail_ingestion_agent import GmailIngestionAgent
from ai_agents.embedding_agent import EmbeddingAgent
from ai_agents.rag_query_agent import RAGQueryAgent
from utils.scheduler import Scheduler, GracefulShutdown
class EmailRAGAssistant:
"""
Main orchestrator for the Email RAG Assistant.
Coordinates all agents and services.
"""
def __init__(self):
"""Initialize the Email RAG Assistant."""
self.gmail_agent = GmailIngestionAgent()
self.embedding_agent = EmbeddingAgent()
self.rag_agent = RAGQueryAgent()
self.scheduler = None
self._initialized = False
async def initialize(self) -> bool:
"""
Initialize all components.
Returns:
True if initialization successful.
"""
print("\n" + "=" * 60)
print("🚀 Email RAG Assistant - Initializing...")
print("=" * 60)
try:
# Validate configuration
validate_config()
print("✓ Configuration validated")
# Initialize Gmail authentication
if not self.gmail_agent.authenticate():
print("⚠ Gmail authentication pending - will prompt on first use")
else:
print("✓ Gmail authenticated")
# Initialize embedding agent (loads model and Pinecone)
if not self.embedding_agent.initialize():
print("✗ Failed to initialize embedding agent")
return False
print("✓ Embedding agent initialized")
# Initialize RAG agent
if not self.rag_agent.initialize():
print("✗ Failed to initialize RAG agent")
return False
print("✓ RAG query agent initialized")
self._initialized = True
print("\n✓ All components initialized successfully!")
print("=" * 60)
return True
except Exception as e:
print(f"\n✗ Initialization error: {e}")
return False
async def run_ingestion(self) -> int:
"""
Run a single email ingestion cycle.
Returns:
Number of emails processed.
"""
print(f"\n[{datetime.now().strftime('%H:%M:%S')}] Starting email ingestion...")
try:
# Check for new emails
emails = await self.gmail_agent.check_inbox(max_emails=20)
if not emails:
print("No new emails found.")
return 0
print(f"Found {len(emails)} new email(s). Processing...")
# Process emails through embedding agent
processed = await self.embedding_agent.process_emails(emails)
print(f"Successfully processed {processed}/{len(emails)} emails.")
return processed
except Exception as e:
print(f"Error during ingestion: {e}")
return 0
async def query(self, question: str) -> str:
"""
Query the email knowledge base.
Args:
question: The user's question.
Returns:
The assistant's answer.
"""
return await self.rag_agent.query(question)
async def interactive_mode(self):
"""Run the interactive query mode."""
print("\n" + "=" * 60)
print("📧 Email RAG Assistant - Interactive Mode")
print("=" * 60)
print("\nCommands:")
print(" Type your question to search emails")
print(" 'ingest' - Run email ingestion")
print(" 'stats' - Show system statistics")
print(" 'help' - Show this help")
print(" 'quit' - Exit the program")
print("-" * 60)
while True:
try:
print()
user_input = input("You: ").strip()
if not user_input:
continue
command = user_input.lower()
if command in ['quit', 'exit', 'q']:
print("\nGoodbye! 👋")
break
elif command == 'help':
print("\nCommands:")
print(" - Type any question to search your emails")
print(" - 'ingest' - Check for new emails and process them")
print(" - 'stats' - Show system statistics")
print(" - 'quit' - Exit the program")
elif command == 'ingest':
processed = await self.run_ingestion()
print(f"\nIngestion complete. Processed {processed} emails.")
elif command == 'stats':
await self.show_stats()
else:
# Treat as a question
print("\nSearching emails...")
response = await self.query(user_input)
print(f"\nAssistant: {response}")
except KeyboardInterrupt:
print("\n\nInterrupted. Goodbye! 👋")
break
except EOFError:
print("\n\nGoodbye! 👋")
break
except Exception as e:
print(f"\nError: {e}")
async def show_stats(self):
"""Display system statistics."""
print("\n📊 System Statistics:")
print("-" * 40)
# Gmail stats
gmail_processed = self.gmail_agent.get_processed_count()
print(f"Emails processed (this session): {gmail_processed}")
# Embedding/Pinecone stats
pinecone_stats = self.embedding_agent.get_stats()
print(f"Total emails in knowledge base: {pinecone_stats.get('total_vectors', 'N/A')}")
# Scheduler stats if running
if self.scheduler:
status = self.scheduler.get_status()
print(f"Scheduler running: {status['running']}")
print(f"Ingestion interval: {status['interval_seconds']} seconds")
print(f"Total ingestion runs: {status['tick_count']}")
async def run_daemon(self):
"""Run as a background daemon with scheduled ingestion."""
print("\n" + "=" * 60)
print("📧 Email RAG Assistant - Daemon Mode")
print("=" * 60)
print(f"\nRunning email ingestion every {INGESTION_INTERVAL_SECONDS} seconds.")
print("Press Ctrl+C to stop.\n")
# Setup scheduler
self.scheduler = Scheduler(
interval_seconds=INGESTION_INTERVAL_SECONDS,
on_tick=self.run_ingestion
)
# Setup graceful shutdown
shutdown = GracefulShutdown()
shutdown.register_callback(self.scheduler.stop)
try:
# Run initial ingestion
await self.run_ingestion()
# Start scheduler
await self.scheduler.start()
# Keep running until interrupted
while True:
await asyncio.sleep(1)
except KeyboardInterrupt:
print("\n\nShutting down gracefully...")
finally:
await self.scheduler.stop()
print("Daemon stopped.")
async def main_async(args):
"""Async main function."""
assistant = EmailRAGAssistant()
# Initialize the system
if not await assistant.initialize():
print("\nFailed to initialize. Please check your configuration.")
sys.exit(1)
# Run based on mode
if args.ingest:
# Single ingestion run
processed = await assistant.run_ingestion()
print(f"\nIngestion complete. Processed {processed} emails.")
elif args.daemon:
# Daemon mode with scheduler
await assistant.run_daemon()
else:
# Interactive mode (default)
await assistant.interactive_mode()
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(
description="Email RAG Assistant - Query your emails with AI"
)
parser.add_argument(
"--ingest",
action="store_true",
help="Run email ingestion once and exit"
)
parser.add_argument(
"--daemon",
action="store_true",
help="Run as daemon with scheduled ingestion"
)
args = parser.parse_args()
# Run async main
try:
asyncio.run(main_async(args))
except KeyboardInterrupt:
print("\nInterrupted.")
sys.exit(0)
if __name__ == "__main__":
main()