Spaces:
Sleeping
Sleeping
File size: 21,406 Bytes
90c6b42 | 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 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 | """
ATOM Communication Apps - LanceDB Ingestion Integration
Add LanceDB memory ingestion option to all communication apps
"""
from datetime import datetime, timedelta
import json
import logging
from typing import Any, Dict, List, Optional
from fastapi import APIRouter, BackgroundTasks, HTTPException, Request
from integrations.atom_communication_ingestion_pipeline import (
CommunicationAppType,
IngestionConfig,
ingestion_pipeline,
memory_manager,
)
logger = logging.getLogger(__name__)
class CommunicationAppIngestionIntegration:
"""Integration layer for all communication apps with LanceDB ingestion"""
def __init__(self):
self.router = APIRouter(prefix="/api/memory/ingestion", tags=["Communication Memory"])
self.setup_routes()
self._initialize_default_configs()
def _initialize_default_configs(self):
"""Initialize default ingestion configurations for all apps"""
default_configs = {
"whatsapp": IngestionConfig(
app_type=CommunicationAppType.WHATSAPP,
enabled=True,
real_time=True,
batch_size=50,
ingest_attachments=True,
embed_content=True,
retention_days=365,
vector_dim=768
),
"slack": IngestionConfig(
app_type=CommunicationAppType.SLACK,
enabled=True,
real_time=True,
batch_size=100,
ingest_attachments=True,
embed_content=True,
retention_days=365,
vector_dim=768
),
"email": IngestionConfig(
app_type=CommunicationAppType.EMAIL,
enabled=True,
real_time=False,
batch_size=200,
ingest_attachments=True,
embed_content=True,
retention_days=365,
vector_dim=768
),
"telegram": IngestionConfig(
app_type=CommunicationAppType.TELEGRAM,
enabled=True,
real_time=True,
batch_size=50,
ingest_attachments=True,
embed_content=True,
retention_days=365,
vector_dim=768
),
"discord": IngestionConfig(
app_type=CommunicationAppType.DISCORD,
enabled=True,
real_time=True,
batch_size=100,
ingest_attachments=True,
embed_content=True,
retention_days=365,
vector_dim=768
),
"sms": IngestionConfig(
app_type=CommunicationAppType.SMS,
enabled=True,
real_time=True,
batch_size=50,
ingest_attachments=False,
embed_content=True,
retention_days=180,
vector_dim=768
),
"calls": IngestionConfig(
app_type=CommunicationAppType.CALLS,
enabled=True,
real_time=True,
batch_size=50,
ingest_attachments=False,
embed_content=True,
retention_days=365,
vector_dim=768
),
"microsoft_teams": IngestionConfig(
app_type=CommunicationAppType.MICROSOFT_TEAMS,
enabled=True,
real_time=True,
batch_size=100,
ingest_attachments=True,
embed_content=True,
retention_days=365,
vector_dim=768
),
"zoom": IngestionConfig(
app_type=CommunicationAppType.ZOOM,
enabled=True,
real_time=False,
batch_size=50,
ingest_attachments=True,
embed_content=True,
retention_days=365,
vector_dim=768
),
"notion": IngestionConfig(
app_type=CommunicationAppType.NOTION,
enabled=True,
real_time=False,
batch_size=100,
ingest_attachments=True,
embed_content=True,
retention_days=365,
vector_dim=768
),
"linear": IngestionConfig(
app_type=CommunicationAppType.LINEAR,
enabled=True,
real_time=False,
batch_size=50,
ingest_attachments=False,
embed_content=True,
retention_days=365,
vector_dim=768
),
"outlook": IngestionConfig(
app_type=CommunicationAppType.OUTLOOK,
enabled=True,
real_time=False,
batch_size=200,
ingest_attachments=True,
embed_content=True,
retention_days=365,
vector_dim=768
),
"gmail": IngestionConfig(
app_type=CommunicationAppType.GMAIL,
enabled=True,
real_time=False,
batch_size=200,
ingest_attachments=True,
embed_content=True,
retention_days=365,
vector_dim=768
),
"salesforce": IngestionConfig(
app_type=CommunicationAppType.SALESFORCE,
enabled=True,
real_time=False,
batch_size=100,
ingest_attachments=True,
embed_content=True,
retention_days=365,
vector_dim=768
),
"asana": IngestionConfig(
app_type=CommunicationAppType.ASANA,
enabled=True,
real_time=False,
batch_size=50,
ingest_attachments=True,
embed_content=True,
retention_days=365,
vector_dim=768
),
"dropbox": IngestionConfig(
app_type=CommunicationAppType.DROPBOX,
enabled=True,
real_time=False,
batch_size=100,
ingest_attachments=True,
embed_content=True,
retention_days=365,
vector_dim=768
),
"box": IngestionConfig(
app_type=CommunicationAppType.BOX,
enabled=True,
real_time=False,
batch_size=100,
ingest_attachments=True,
embed_content=True,
retention_days=365,
vector_dim=768
),
"tableau": IngestionConfig(
app_type=CommunicationAppType.TABLEAU,
enabled=True,
real_time=False,
batch_size=50,
ingest_attachments=False,
embed_content=True,
retention_days=365,
vector_dim=768
),
"zoho": IngestionConfig(
app_type=CommunicationAppType.ZOHO,
enabled=True,
real_time=False,
batch_size=50,
ingest_attachments=True,
embed_content=True,
retention_days=365,
vector_dim=768
),
"xero": IngestionConfig(
app_type=CommunicationAppType.XERO,
enabled=True,
real_time=False,
batch_size=50,
ingest_attachments=True,
embed_content=True,
retention_days=365,
vector_dim=768
),
"quickbooks": IngestionConfig(
app_type=CommunicationAppType.QUICKBOOKS,
enabled=True,
real_time=False,
batch_size=50,
ingest_attachments=True,
embed_content=True,
retention_days=365,
vector_dim=768
)
}
# Configure all apps
for app_name, config in default_configs.items():
ingestion_pipeline.configure_app(config.app_type, config)
def setup_routes(self):
"""Setup API routes for communication ingestion"""
@self.router.get("/status")
async def get_ingestion_status():
"""Get overall ingestion status"""
try:
# Initialize memory manager if not already done
if not memory_manager.db:
memory_manager.initialize()
stats = ingestion_pipeline.get_ingestion_stats()
return {
"status": "active",
"timestamp": datetime.now().isoformat(),
"memory_database": "LanceDB",
"total_apps_configured": len(stats.get("configured_apps", [])),
"active_streams": stats.get("active_streams", []),
"total_messages_ingested": stats.get("total_messages", 0),
"app_statistics": stats.get("app_stats", {}),
"memory_database_path": str(memory_manager.db_path)
}
except Exception as e:
logger.error(f"Error getting ingestion status: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@self.router.get("/apps")
async def get_configured_apps():
"""Get list of configured communication apps"""
try:
apps = []
for app_type in CommunicationAppType:
apps.append({
"id": app_type.value,
"name": app_type.value.replace("_", " ").title(),
"type": "communication",
"supports_ingestion": True,
"supports_real_time": True,
"supports_embeddings": True
})
return {
"apps": apps,
"total": len(apps),
"timestamp": datetime.now().isoformat()
}
except Exception as e:
logger.error(f"Error getting configured apps: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@self.router.get("/apps/{app_id}")
async def get_app_ingestion_config(app_id: str):
"""Get ingestion configuration for specific app"""
try:
app_type = CommunicationAppType(app_id)
config = ingestion_pipeline.ingestion_configs.get(app_id)
if not config:
raise HTTPException(status_code=404, detail=f"App {app_id} not configured")
return {
"app_id": app_id,
"app_name": app_id.replace("_", " ").title(),
"config": config,
"timestamp": datetime.now().isoformat()
}
except ValueError:
raise HTTPException(status_code=404, detail=f"Invalid app_id: {app_id}")
except Exception as e:
logger.error(f"Error getting app config: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@self.router.post("/ingest/{app_id}")
async def ingest_message(app_id: str, message_data: Dict[str, Any]):
"""Ingest single message from communication app"""
try:
# Validate app_id
CommunicationAppType(app_id)
# Initialize memory manager if needed
if not memory_manager.db:
memory_manager.initialize()
# Ingest message
success = ingestion_pipeline.ingest_message(app_id, message_data)
if success:
return {
"success": True,
"message": f"Message from {app_id} ingested successfully",
"app_id": app_id,
"timestamp": datetime.now().isoformat()
}
else:
raise HTTPException(status_code=500, detail="Failed to ingest message")
except ValueError:
raise HTTPException(status_code=404, detail=f"Invalid app_id: {app_id}")
except Exception as e:
logger.error(f"Error ingesting message: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@self.router.post("/ingest/{app_id}/batch")
async def ingest_messages_batch(app_id: str, messages: List[Dict[str, Any]]):
"""Ingest batch of messages from communication app"""
try:
# Validate app_id
CommunicationAppType(app_id)
# Initialize memory manager if needed
if not memory_manager.db:
memory_manager.initialize()
# Ingest batch
success_count = 0
for message in messages:
if ingestion_pipeline.ingest_message(app_id, message):
success_count += 1
return {
"success": True,
"message": f"Batch ingestion completed for {app_id}",
"app_id": app_id,
"total_messages": len(messages),
"success_count": success_count,
"failure_count": len(messages) - success_count,
"timestamp": datetime.now().isoformat()
}
except ValueError:
raise HTTPException(status_code=404, detail=f"Invalid app_id: {app_id}")
except Exception as e:
logger.error(f"Error ingesting batch: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@self.router.post("/stream/start/{app_id}")
async def start_real_time_stream(app_id: str):
"""Start real-time ingestion stream for app"""
try:
# Validate app_id
CommunicationAppType(app_id)
# Initialize memory manager if needed
if not memory_manager.db:
memory_manager.initialize()
# Start stream
success = ingestion_pipeline.start_real_time_stream(app_id)
if success:
return {
"success": True,
"message": f"Real-time stream started for {app_id}",
"app_id": app_id,
"timestamp": datetime.now().isoformat()
}
else:
raise HTTPException(status_code=500, detail="Failed to start stream")
except ValueError:
raise HTTPException(status_code=404, detail=f"Invalid app_id: {app_id}")
except Exception as e:
logger.error(f"Error starting stream: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@self.router.get("/search")
async def search_memory(query: str, app_id: Optional[str] = None, limit: int = 10):
"""Search ingested communications"""
try:
# Initialize memory manager if needed
if not memory_manager.db:
memory_manager.initialize()
# Search communications
results = memory_manager.search_communications(query, limit, app_id)
return {
"success": True,
"query": query,
"app_filter": app_id,
"limit": limit,
"total_results": len(results),
"results": results,
"timestamp": datetime.now().isoformat()
}
except Exception as e:
logger.error(f"Error searching memory: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@self.router.get("/communications/{app_id}")
async def get_app_communications(app_id: str, limit: int = 100):
"""Get communications by app type"""
try:
# Validate app_id
CommunicationAppType(app_id)
# Initialize memory manager if needed
if not memory_manager.db:
memory_manager.initialize()
# Get communications
results = memory_manager.get_communications_by_app(app_id, limit)
return {
"success": True,
"app_id": app_id,
"limit": limit,
"total_results": len(results),
"communications": results,
"timestamp": datetime.now().isoformat()
}
except ValueError:
raise HTTPException(status_code=404, detail=f"Invalid app_id: {app_id}")
except Exception as e:
logger.error(f"Error getting communications: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@self.router.get("/communications/timeline")
async def get_communications_timeline(
start_date: str,
end_date: str,
app_id: Optional[str] = None
):
"""Get communications within time frame"""
try:
# Parse dates
start_dt = datetime.fromisoformat(start_date)
end_dt = datetime.fromisoformat(end_date)
# Initialize memory manager if needed
if not memory_manager.db:
memory_manager.initialize()
# Get communications
results = memory_manager.get_communications_by_timeframe(start_dt, end_dt)
# Filter by app if specified
if app_id:
results = [r for r in results if r.get("app_type") == app_id]
return {
"success": True,
"start_date": start_date,
"end_date": end_date,
"app_filter": app_id,
"total_results": len(results),
"communications": results,
"timestamp": datetime.now().isoformat()
}
except ValueError as e:
raise HTTPException(status_code=400, detail=f"Invalid date format: {str(e)}")
except Exception as e:
logger.error(f"Error getting timeline: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@self.router.get("/memory/stats")
async def get_memory_stats():
"""Get detailed memory statistics"""
try:
# Initialize memory manager if needed
if not memory_manager.db:
memory_manager.initialize()
stats = ingestion_pipeline.get_ingestion_stats()
# Get database statistics
db_stats = {
"database_type": "LanceDB",
"database_path": str(memory_manager.db_path),
"tables": memory_manager.db.table_names()
}
# Get table statistics
if memory_manager.connections_table:
comm_count = memory_manager.connections_table.to_pandas()
db_stats["total_communications"] = len(comm_count)
db_stats["app_distribution"] = comm_count["app_type"].value_counts().to_dict()
return {
"success": True,
"ingestion_stats": stats,
"database_stats": db_stats,
"timestamp": datetime.now().isoformat()
}
except Exception as e:
logger.error(f"Error getting memory stats: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
# Create global instance
communication_ingestion_integration = CommunicationAppIngestionIntegration()
communication_ingestion_router = communication_ingestion_integration.router
# Export for main app
__all__ = [
'communication_ingestion_integration',
'communication_ingestion_router'
] |