-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserendipity_service.py
More file actions
3277 lines (2690 loc) · 135 KB
/
serendipity_service.py
File metadata and controls
3277 lines (2690 loc) · 135 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
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Serendipity Service Module for Synapse AI Web Application
This module provides AI-powered serendipity analysis functionality that discovers
hidden connections, patterns, and insights within a user's accumulated memory data.
It integrates seamlessly with the existing Synapse project architecture.
"""
import json
import logging
import time
import hashlib
import threading
import sys
import platform
import os
from datetime import datetime, timedelta
from typing import Dict, Any, List, Optional, Union, Tuple
from pathlib import Path
from dataclasses import dataclass, field
from collections import defaultdict
from config import get_config
from error_handler import (
get_error_handler,
ErrorCategory,
ErrorSeverity,
handle_service_error,
safe_file_operation,
RecoveryManager
)
from ai_service import get_ai_service, AIServiceError
from performance_monitor import get_performance_monitor
from enhanced_cache import get_cache_manager, CacheConfiguration
from analysis_queue import get_analysis_queue, RequestPriority, QueueConfiguration
# Configure logging
logger = logging.getLogger(__name__)
class SerendipityServiceError(Exception):
"""Custom exception for serendipity service errors"""
pass
class InsufficientDataError(SerendipityServiceError):
"""Raised when there's insufficient data for analysis"""
pass
class DataValidationError(SerendipityServiceError):
"""Raised when data validation fails"""
pass
class MemoryProcessingError(SerendipityServiceError):
"""Raised when memory processing fails"""
pass
@dataclass
class CacheEntry:
"""Cache entry with TTL support"""
data: Any
timestamp: datetime
ttl_seconds: int
access_count: int = 0
def is_expired(self) -> bool:
"""Check if cache entry has expired"""
return datetime.now() > self.timestamp + timedelta(seconds=self.ttl_seconds)
def access(self) -> Any:
"""Access cached data and increment access count"""
self.access_count += 1
return self.data
@dataclass
class ValidationResult:
"""Result of data validation"""
is_valid: bool
errors: List[str] = field(default_factory=list)
warnings: List[str] = field(default_factory=list)
insights_count: int = 0
conversations_count: int = 0
total_content_length: int = 0
categories: List[str] = field(default_factory=list)
@dataclass
class MemoryChunk:
"""Represents a chunk of memory data for processing"""
chunk_id: str
content: str
metadata: Dict[str, Any]
size_bytes: int
insights_count: int
conversations_count: int
class SerendipityService:
"""
AI-powered serendipity analysis service for discovering hidden connections
and patterns within user's memory data.
"""
def __init__(self, config=None):
"""
Initialize the serendipity service
Args:
config: Configuration object (uses default if None)
"""
self.config = config or get_config()
self.error_handler = get_error_handler()
self.ai_service = None
self._initialize_ai_service()
# Analysis configuration from config
self.min_insights_required = self.config.SERENDIPITY_MIN_INSIGHTS
self.max_memory_size_mb = self.config.SERENDIPITY_MAX_MEMORY_SIZE_MB
self.analysis_timeout = self.config.SERENDIPITY_ANALYSIS_TIMEOUT
self.analysis_cache_ttl = getattr(self.config, 'SERENDIPITY_ANALYSIS_CACHE_TTL', 1800)
# Performance monitoring
self.performance_monitor = get_performance_monitor(self.config)
# Enhanced multi-level caching system
self.cache_manager = get_cache_manager()
# Configure caches with optimized settings
memory_cache_config = CacheConfiguration(
max_entries=getattr(self.config, 'SERENDIPITY_MEMORY_CACHE_MAX_ENTRIES', 500),
max_size_mb=getattr(self.config, 'SERENDIPITY_MEMORY_CACHE_MAX_SIZE_MB', 50.0),
default_ttl_seconds=getattr(self.config, 'SERENDIPITY_MEMORY_CACHE_TTL', 3600),
enable_compression=True,
eviction_policy="lru"
)
analysis_cache_config = CacheConfiguration(
max_entries=getattr(self.config, 'SERENDIPITY_ANALYSIS_CACHE_MAX_ENTRIES', 100),
max_size_mb=getattr(self.config, 'SERENDIPITY_ANALYSIS_CACHE_MAX_SIZE_MB', 200.0),
default_ttl_seconds=getattr(self.config, 'SERENDIPITY_ANALYSIS_CACHE_TTL', 1800),
enable_compression=True,
eviction_policy="ttl"
)
formatted_cache_config = CacheConfiguration(
max_entries=getattr(self.config, 'SERENDIPITY_FORMATTED_CACHE_MAX_ENTRIES', 200),
max_size_mb=getattr(self.config, 'SERENDIPITY_FORMATTED_CACHE_MAX_SIZE_MB', 100.0),
default_ttl_seconds=getattr(self.config, 'SERENDIPITY_FORMATTED_CACHE_TTL', 1800),
enable_compression=True,
eviction_policy="lru"
)
# Get enhanced caches
self.memory_cache = self.cache_manager.get_cache("memory_cache", memory_cache_config)
self.analysis_cache = self.cache_manager.get_cache("analysis_cache", analysis_cache_config)
self.formatted_cache = self.cache_manager.get_cache("formatted_cache", formatted_cache_config)
# Queue management for concurrent requests
queue_config = QueueConfiguration(
max_queue_size=getattr(self.config, 'SERENDIPITY_MAX_QUEUE_SIZE', 100),
max_concurrent_workers=getattr(self.config, 'SERENDIPITY_MAX_CONCURRENT_WORKERS', 3),
worker_timeout_seconds=getattr(self.config, 'SERENDIPITY_WORKER_TIMEOUT', 300),
queue_timeout_seconds=getattr(self.config, 'SERENDIPITY_QUEUE_TIMEOUT', 600),
enable_adaptive_scaling=True,
enable_priority_boosting=True
)
self.analysis_queue = get_analysis_queue(queue_config, self)
# Chunking configuration
self.max_chunk_size_chars = getattr(self.config, 'SERENDIPITY_MAX_CHUNK_SIZE', 8000)
self.chunk_overlap_chars = getattr(self.config, 'SERENDIPITY_CHUNK_OVERLAP', 200)
# Legacy cache support (for backward compatibility)
self._memory_cache: Dict[str, CacheEntry] = {}
self._analysis_cache: Dict[str, CacheEntry] = {}
self._formatted_cache: Dict[str, CacheEntry] = {}
self._cache_lock = threading.RLock()
logger.info("SerendipityService initialized successfully with enhanced caching, performance monitoring, and queue management")
def _initialize_ai_service(self):
"""Initialize AI service with error handling"""
try:
if not self.config.ENABLE_SERENDIPITY_ENGINE:
logger.info("Serendipity engine is disabled via configuration")
return
self.ai_service = get_ai_service(
model=self.config.OLLAMA_MODEL,
system_prompt=self._get_serendipity_system_prompt()
)
logger.info(f"AI service initialized for serendipity analysis with model: {self.config.OLLAMA_MODEL}")
except Exception as e:
self.error_handler.log_error(
e,
ErrorCategory.SERENDIPITY_SERVICE,
ErrorSeverity.HIGH,
{"component": "ai_service_initialization"}
)
self.ai_service = None
def _get_serendipity_system_prompt(self) -> str:
"""Get specialized system prompt for serendipity analysis with examples"""
return """You are an expert cognitive analyst specializing in discovering non-obvious connections, hidden patterns, and serendipitous insights within personal knowledge and experiences. Your task is to analyze a user's accumulated thoughts, insights, and conversation summaries to identify meaningful connections that might not be immediately apparent.
Focus on finding:
1. Cross-domain connections between seemingly unrelated topics
2. Recurring themes and patterns across different time periods
3. Contradictions or tensions that reveal deeper insights
4. Emergent ideas that arise from the intersection of multiple concepts
5. Hidden assumptions or biases that shape thinking patterns
6. Potential blind spots or unexplored areas
7. Serendipitous opportunities for new directions or investigations
EXAMPLES OF GOOD CONNECTIONS:
- A person interested in both cooking and software development might have a hidden pattern of "systematic experimentation" - they approach both domains by testing small variations and iterating based on results
- Someone with insights about time management and gardening might discover they both reflect a deeper theme of "nurturing growth through consistent small actions"
- A contradiction between valuing efficiency and also enjoying slow, contemplative activities might reveal an underlying need for "balanced rhythms" in life
- Cross-domain: Insights about music theory connecting to mathematical thinking patterns
- Temporal: Early career focus on individual achievement evolving into later emphasis on collaboration, suggesting a maturation pattern
- Emergent: Multiple conversations about different topics all touching on themes of authenticity, suggesting this as a core value
Your analysis should be:
- Intellectually rigorous and evidence-based
- Surprising yet plausible (high surprise_factor for non-obvious connections)
- Actionable and personally relevant (high relevance for practical insights)
- Grounded in the actual data provided
- Specific about which insights support each connection
CRITICAL: Return ONLY valid JSON. No additional text before or after. Use this exact structure:
{
"connections": [
{
"title": "Brief descriptive title (max 60 chars)",
"description": "Detailed explanation of the connection and why it's meaningful",
"surprise_factor": 0.8,
"relevance": 0.9,
"connected_insights": ["specific insight text 1", "specific insight text 2"],
"connection_type": "cross_domain|temporal|contradictory|emergent|thematic",
"actionable_insight": "Specific action the user could take based on this connection"
}
],
"meta_patterns": [
{
"pattern_name": "Name of the overarching pattern",
"description": "Description of the pattern and its significance",
"evidence_count": 5,
"confidence": 0.85
}
],
"serendipity_summary": "Overall summary of the most interesting discoveries and their implications",
"recommendations": ["Specific actionable recommendation 1", "Specific actionable recommendation 2"]
}
IMPORTANT GUIDELINES:
- Return ONLY the JSON object, no other text
- If you find fewer than 3 insights, still look for at least 1-2 connections
- For small datasets, focus on quality over quantity
- All numeric values must be between 0.0 and 1.0
- Ensure proper JSON syntax with quotes around all strings
- If no meaningful connections exist, return empty arrays but maintain JSON structure"""
def analyze_memory(self, memory_file_path: Optional[str] = None,
priority: RequestPriority = RequestPriority.NORMAL,
use_queue: bool = False) -> Dict[str, Any]:
"""
Perform serendipity analysis on user's memory data
Args:
memory_file_path: Path to memory file (uses config default if None)
priority: Request priority for queue processing
use_queue: Whether to use queue for processing (for concurrent requests)
Returns:
dict: Analysis results with connections, patterns, and recommendations
Raises:
SerendipityServiceError: If analysis fails or service is disabled
"""
# Start performance monitoring
operation_id = self.performance_monitor.start_operation(
"serendipity_analysis",
{"memory_file": memory_file_path, "priority": priority.name if hasattr(priority, 'name') else str(priority)}
)
start_time = time.time()
cache_hits = 0
cache_misses = 0
try:
# Check if serendipity engine is enabled
if not self.config.ENABLE_SERENDIPITY_ENGINE:
raise SerendipityServiceError("Serendipity engine is disabled. Enable it by setting ENABLE_SERENDIPITY_ENGINE=True")
if not self.ai_service:
raise SerendipityServiceError("AI service is not available. Please ensure Ollama is running and properly configured")
# If using queue, submit request and return immediately
if use_queue:
request_id = self.analysis_queue.submit_request(
memory_file_path=memory_file_path,
priority=priority,
metadata={"operation_id": operation_id}
)
return {
"status": "queued",
"request_id": request_id,
"message": "Analysis request queued for processing"
}
# Load and validate memory data with caching
memory_data = self._load_memory_data_enhanced(memory_file_path)
if memory_data.get("_cache_hit"):
cache_hits += 1
else:
cache_misses += 1
# Validate sufficient data for analysis
self._validate_memory_data(memory_data)
# Format memory data for AI analysis with caching
formatted_memory = self._format_memory_for_analysis_enhanced(memory_data)
if formatted_memory.get("_cache_hit") if isinstance(formatted_memory, dict) else False:
cache_hits += 1
else:
cache_misses += 1
# Extract actual formatted data
if isinstance(formatted_memory, dict) and "_data" in formatted_memory:
formatted_data = formatted_memory["_data"]
else:
formatted_data = formatted_memory
# Check analysis cache first
analysis_cache_key = self._generate_analysis_cache_key(formatted_data)
cached_analysis = self.analysis_cache.get(analysis_cache_key)
if cached_analysis:
cache_hits += 1
analysis_results = cached_analysis
logger.info("Using cached analysis results")
else:
cache_misses += 1
# Perform AI analysis (handle both string and chunked data)
if isinstance(formatted_data, list):
# Handle chunked data
analysis_results = self._discover_connections_chunked(formatted_data)
else:
# Handle single string data
analysis_results = self._discover_connections(formatted_data)
# Cache the analysis results
self.analysis_cache.put(analysis_cache_key, analysis_results)
# Add comprehensive metadata with performance tracking
analysis_results["metadata"] = self._generate_analysis_metadata_enhanced(
memory_data, formatted_data, start_time, analysis_results, cache_hits, cache_misses
)
# Add patterns alias for backward compatibility
if "meta_patterns" in analysis_results and "patterns" not in analysis_results:
analysis_results["patterns"] = analysis_results["meta_patterns"]
# Store analysis in history
self._store_analysis_history(analysis_results)
# Track usage analytics
self._track_usage_analytics(analysis_results)
# Complete performance monitoring
self.performance_monitor.complete_operation(
operation_id,
cache_hits=cache_hits,
cache_misses=cache_misses,
ai_response_time=analysis_results["metadata"].get("ai_response_time"),
data_size_mb=analysis_results["metadata"].get("data_size_mb", 0),
chunk_count=analysis_results["metadata"].get("chunk_count", 0)
)
logger.info(f"Serendipity analysis completed in {analysis_results['metadata']['analysis_duration']}s")
return analysis_results
except Exception as e:
# Complete performance monitoring with error
self.performance_monitor.complete_operation(
operation_id,
cache_hits=cache_hits,
cache_misses=cache_misses,
error=e
)
raise
def _load_memory_data(self, memory_file_path: Optional[str] = None) -> Dict[str, Any]:
"""
Load and validate memory data from file with caching support
Args:
memory_file_path: Path to memory file
Returns:
dict: Loaded and validated memory data
Raises:
SerendipityServiceError: If file cannot be loaded or is invalid
"""
file_path = memory_file_path or self.config.MEMORY_FILE
# Generate cache key based on file path and modification time
cache_key = self._generate_memory_cache_key(file_path)
# Check cache first
with self._cache_lock:
if cache_key in self._memory_cache:
cache_entry = self._memory_cache[cache_key]
if not cache_entry.is_expired():
logger.info(f"Using cached memory data for {file_path}")
return cache_entry.access()
else:
# Remove expired entry
del self._memory_cache[cache_key]
# Load from file
memory_data = self._load_memory_from_file(file_path)
# Validate the loaded data
validation_result = self._validate_memory_data_comprehensive(memory_data)
if not validation_result.is_valid:
# Check if it's an insufficient data error specifically
if any("insufficient data" in error.lower() for error in validation_result.errors):
error_msg = f"Insufficient data for serendipity analysis. Found {validation_result.insights_count + validation_result.conversations_count} items, but need at least {self.min_insights_required}. Have more conversations to build up your memory for better analysis."
raise InsufficientDataError(error_msg)
else:
error_msg = f"Memory data validation failed: {'; '.join(validation_result.errors)}"
raise DataValidationError(error_msg)
# Log warnings if any
for warning in validation_result.warnings:
logger.warning(f"Memory data warning: {warning}")
# Cache the validated data (using legacy cache for backward compatibility)
with self._cache_lock:
self._memory_cache[cache_key] = CacheEntry(
data=memory_data,
timestamp=datetime.now(),
ttl_seconds=getattr(self.config, 'SERENDIPITY_MEMORY_CACHE_TTL', 3600)
)
logger.info(f"Loaded and cached memory data: {validation_result.insights_count} insights, "
f"{validation_result.conversations_count} conversations, "
f"{len(validation_result.categories)} categories")
return memory_data
def _load_memory_data_enhanced(self, memory_file_path: Optional[str] = None) -> Dict[str, Any]:
"""
Enhanced memory data loading with improved caching
Args:
memory_file_path: Path to memory file
Returns:
dict: Loaded memory data with cache metadata
"""
file_path = memory_file_path or self.config.MEMORY_FILE
# Generate cache key based on file path and modification time
cache_key = self._generate_memory_cache_key(file_path)
# Check enhanced cache first
cached_data = self.memory_cache.get(cache_key)
if cached_data:
logger.info(f"Using enhanced cached memory data for {file_path}")
cached_data["_cache_hit"] = True
return cached_data
# Load from file using original method
memory_data = self._load_memory_data(file_path)
# Cache in enhanced cache
self.memory_cache.put(cache_key, memory_data)
memory_data["_cache_hit"] = False
return memory_data
def _format_memory_for_analysis_enhanced(self, memory_data: Dict[str, Any]) -> Union[str, List[MemoryChunk], Dict[str, Any]]:
"""
Enhanced memory formatting with improved caching
Args:
memory_data: Raw memory data
Returns:
Formatted memory data with cache metadata
"""
# Generate cache key for formatted data
cache_key = self._generate_formatted_cache_key(memory_data)
# Check enhanced cache first
cached_formatted = self.formatted_cache.get(cache_key)
if cached_formatted:
logger.info("Using enhanced cached formatted memory data")
return {
"_data": cached_formatted,
"_cache_hit": True
}
# Format using original method
formatted_result = self._format_memory_for_analysis(memory_data)
# Cache in enhanced cache
self.formatted_cache.put(cache_key, formatted_result)
return {
"_data": formatted_result,
"_cache_hit": False
}
def _generate_analysis_cache_key(self, formatted_data: Union[str, List[MemoryChunk]]) -> str:
"""
Generate cache key for analysis results
Args:
formatted_data: Formatted memory data
Returns:
str: Cache key
"""
try:
if isinstance(formatted_data, str):
content_hash = hashlib.md5(formatted_data.encode()).hexdigest()
elif isinstance(formatted_data, list):
# Hash all chunks
combined_content = ""
for chunk in formatted_data:
if hasattr(chunk, 'content'):
combined_content += chunk.content
content_hash = hashlib.md5(combined_content.encode()).hexdigest()
else:
content_hash = hashlib.md5(str(formatted_data).encode()).hexdigest()
# Include model and configuration in key
key_data = f"analysis_{content_hash}_{self.config.OLLAMA_MODEL}_{self.analysis_timeout}"
return hashlib.md5(key_data.encode()).hexdigest()
except Exception as e:
logger.warning(f"Failed to generate analysis cache key: {e}")
return hashlib.md5(f"fallback_analysis_{time.time()}".encode()).hexdigest()
def _generate_analysis_metadata_enhanced(self, memory_data: Dict[str, Any],
formatted_memory: Union[str, List[MemoryChunk]],
start_time: float,
analysis_results: Dict[str, Any],
cache_hits: int = 0,
cache_misses: int = 0) -> Dict[str, Any]:
"""
Generate enhanced analysis metadata with performance metrics
Args:
memory_data: Original memory data
formatted_memory: Formatted memory data
start_time: Analysis start time
analysis_results: Analysis results
cache_hits: Number of cache hits
cache_misses: Number of cache misses
Returns:
dict: Enhanced metadata
"""
end_time = time.time()
duration = end_time - start_time
# Calculate data size
data_size_mb = 0.0
chunk_count = 0
if isinstance(formatted_memory, str):
data_size_mb = len(formatted_memory.encode('utf-8')) / (1024 * 1024)
chunk_count = 1
elif isinstance(formatted_memory, list):
total_size = sum(chunk.size_bytes for chunk in formatted_memory if hasattr(chunk, 'size_bytes'))
data_size_mb = total_size / (1024 * 1024)
chunk_count = len(formatted_memory)
# Get system resource info
try:
import psutil
process = psutil.Process()
memory_info = process.memory_info()
cpu_percent = process.cpu_percent()
except Exception:
memory_info = None
cpu_percent = 0.0
# Get cache statistics
cache_stats = {
"hits": cache_hits,
"misses": cache_misses,
"hit_rate": cache_hits / (cache_hits + cache_misses) if (cache_hits + cache_misses) > 0 else 0.0,
"memory_cache_stats": self.memory_cache.get_statistics(),
"analysis_cache_stats": self.analysis_cache.get_statistics(),
"formatted_cache_stats": self.formatted_cache.get_statistics()
}
# Get queue statistics if available
queue_stats = {}
try:
queue_stats = self.analysis_queue.get_queue_statistics()
except Exception as e:
logger.debug(f"Could not get queue statistics: {e}")
metadata = {
"analysis_duration": duration,
"analysis_timestamp": datetime.now().isoformat(),
"ai_model": self.config.OLLAMA_MODEL,
"data_size_mb": data_size_mb,
"chunk_count": chunk_count,
"insights_processed": len(memory_data.get("insights", [])),
"conversations_processed": len(memory_data.get("conversation_summaries", [])),
"cache_stats": cache_stats,
"queue_stats": queue_stats,
"performance_metrics": {
"start_time": start_time,
"end_time": end_time,
"duration_seconds": duration,
"operations_per_second": 1 / duration if duration > 0 else 0,
"memory_usage_mb": memory_info.rss / (1024 * 1024) if memory_info else 0,
"cpu_usage_percent": cpu_percent
},
"system_info": {
"platform": platform.system(),
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
"thread_count": threading.active_count()
}
}
# Add AI response time if available
if "ai_response_time" in analysis_results.get("metadata", {}):
metadata["ai_response_time"] = analysis_results["metadata"]["ai_response_time"]
return metadata
def _load_memory_from_file(self, file_path: str) -> Dict[str, Any]:
"""
Load memory data from file with comprehensive error handling
Args:
file_path: Path to memory file
Returns:
dict: Raw memory data
Raises:
SerendipityServiceError: If file cannot be loaded
"""
# Check if file exists
if not Path(file_path).exists():
raise SerendipityServiceError(f"Memory file not found: {file_path}")
try:
# Check file size and permissions
file_stat = Path(file_path).stat()
file_size_mb = file_stat.st_size / (1024 * 1024)
if file_size_mb > self.max_memory_size_mb:
logger.warning(f"Memory file is large ({file_size_mb:.1f}MB), analysis may be slow")
if file_stat.st_size == 0:
raise SerendipityServiceError(f"Memory file is empty: {file_path}")
# Load JSON with error recovery
with open(file_path, 'r', encoding='utf-8') as f:
try:
memory_data = json.load(f)
except json.JSONDecodeError as e:
logger.error(f"JSON decode error at line {e.lineno}, column {e.colno}: {e.msg}")
# Attempt to recover corrupted JSON
f.seek(0)
content = f.read()
recovered_data = self._attempt_json_recovery(content, file_path)
if recovered_data:
memory_data = recovered_data
logger.info("Successfully recovered corrupted JSON data")
else:
raise SerendipityServiceError(f"Failed to load memory file due to invalid JSON: {file_path}")
except PermissionError:
raise SerendipityServiceError(f"Permission denied accessing memory file: {file_path}")
except FileNotFoundError:
raise SerendipityServiceError(f"Memory file not found: {file_path}")
except Exception as e:
self.error_handler.log_error(
e,
ErrorCategory.SERENDIPITY_SERVICE,
ErrorSeverity.MEDIUM,
{"file_path": file_path}
)
raise SerendipityServiceError(f"Failed to load memory file: {file_path}")
# Basic structure validation
if not isinstance(memory_data, dict):
raise SerendipityServiceError("Memory file must contain a JSON object")
# Ensure required keys exist with defaults
if "insights" not in memory_data:
memory_data["insights"] = []
logger.warning("Memory file missing 'insights' key, using empty list")
if "conversation_summaries" not in memory_data:
memory_data["conversation_summaries"] = []
logger.warning("Memory file missing 'conversation_summaries' key, using empty list")
if "metadata" not in memory_data:
memory_data["metadata"] = {}
logger.warning("Memory file missing 'metadata' key, using empty dict")
return memory_data
def _attempt_json_recovery(self, content: str, file_path: str) -> Optional[Dict[str, Any]]:
"""
Attempt to recover corrupted JSON data
Args:
content: Raw file content
file_path: Path to the file for logging
Returns:
dict or None: Recovered data if successful
"""
try:
# Try to find and fix common JSON issues
# Remove trailing commas
import re
content = re.sub(r',(\s*[}\]])', r'\1', content)
# Try to parse again
recovered_data = json.loads(content)
logger.info(f"Successfully recovered JSON by removing trailing commas: {file_path}")
return recovered_data
except json.JSONDecodeError:
pass
try:
# Try to extract valid JSON portion
start_idx = content.find('{')
end_idx = content.rfind('}')
if start_idx != -1 and end_idx != -1 and end_idx > start_idx:
partial_content = content[start_idx:end_idx + 1]
recovered_data = json.loads(partial_content)
logger.info(f"Successfully recovered partial JSON data: {file_path}")
return recovered_data
except json.JSONDecodeError:
pass
# If all recovery attempts fail, create minimal structure
logger.warning(f"Could not recover JSON data, creating minimal structure: {file_path}")
return {
"insights": [],
"conversation_summaries": [],
"metadata": {
"recovery_note": f"Data recovered from corrupted file on {datetime.now().isoformat()}",
"original_file": file_path
}
}
def _generate_memory_cache_key(self, file_path: str) -> str:
"""
Generate cache key based on file path and modification time
Args:
file_path: Path to memory file
Returns:
str: Cache key
"""
try:
file_stat = Path(file_path).stat()
key_data = f"{file_path}:{file_stat.st_mtime}:{file_stat.st_size}"
return hashlib.md5(key_data.encode()).hexdigest()
except Exception:
# Fallback to just file path if stat fails
return hashlib.md5(file_path.encode()).hexdigest()
def _validate_memory_data_comprehensive(self, memory_data: Dict[str, Any]) -> ValidationResult:
"""
Comprehensive validation of memory data with detailed error reporting
Args:
memory_data: Memory data to validate
Returns:
ValidationResult: Detailed validation results
"""
result = ValidationResult(is_valid=True)
# Validate top-level structure
if not isinstance(memory_data, dict):
result.is_valid = False
result.errors.append("Memory data must be a dictionary")
return result
# Validate insights
insights = memory_data.get("insights", [])
if not isinstance(insights, list):
result.is_valid = False
result.errors.append("'insights' must be a list")
else:
result.insights_count = len(insights)
insight_validation = self._validate_insights(insights)
result.errors.extend(insight_validation["errors"])
result.warnings.extend(insight_validation["warnings"])
result.categories.extend(insight_validation["categories"])
result.total_content_length += insight_validation["content_length"]
# Validate conversation summaries
conversations = memory_data.get("conversation_summaries", [])
if not isinstance(conversations, list):
result.is_valid = False
result.errors.append("'conversation_summaries' must be a list")
else:
result.conversations_count = len(conversations)
conv_validation = self._validate_conversations(conversations)
result.errors.extend(conv_validation["errors"])
result.warnings.extend(conv_validation["warnings"])
result.total_content_length += conv_validation["content_length"]
# Validate metadata
metadata = memory_data.get("metadata", {})
if not isinstance(metadata, dict):
result.warnings.append("'metadata' should be a dictionary")
# Check for sufficient data
total_items = result.insights_count + result.conversations_count
if total_items < self.min_insights_required:
result.is_valid = False
result.errors.append(
f"Insufficient data for analysis. Found {total_items} items, "
f"need at least {self.min_insights_required}. "
"Have more conversations to build up your memory."
)
# If we have validation errors but still some valid data, don't fail completely
if result.errors and total_items >= self.min_insights_required:
# Only fail if we have critical structural errors
critical_errors = [e for e in result.errors if
"must be a list" in e or "must be a dictionary" in e or
"missing required field" in e or "has empty" in e]
if not critical_errors:
result.is_valid = True # Allow warnings but not critical errors
# Check for data quality issues
if result.insights_count == 0 and result.conversations_count == 0:
result.is_valid = False
result.errors.append("No insights or conversation summaries found")
if result.total_content_length < 100:
result.warnings.append("Very little content available for analysis")
# Check for category diversity
if len(result.categories) < 2:
result.warnings.append("Limited category diversity may reduce analysis quality")
return result
def _validate_insights(self, insights: List[Dict[str, Any]]) -> Dict[str, Any]:
"""
Validate insights data structure and content
Args:
insights: List of insight dictionaries
Returns:
dict: Validation results with errors, warnings, categories, and content length
"""
errors = []
warnings = []
categories = set()
content_length = 0
required_fields = ["content", "category"]
optional_fields = ["confidence", "tags", "evidence", "timestamp"]
for i, insight in enumerate(insights):
if not isinstance(insight, dict):
errors.append(f"Insight {i} is not a dictionary")
continue
# Check required fields
for field in required_fields:
if field not in insight:
errors.append(f"Insight {i} missing required field '{field}'")
elif not insight[field] or (isinstance(insight[field], str) and not insight[field].strip()):
errors.append(f"Insight {i} has empty '{field}' field")
# Validate content
if "content" in insight:
content = insight["content"]
if isinstance(content, str):
content_length += len(content)
if len(content) < 10:
warnings.append(f"Insight {i} has very short content")
elif len(content) > 1000:
warnings.append(f"Insight {i} has very long content")
else:
errors.append(f"Insight {i} content must be a string")
# Validate category
if "category" in insight:
category = insight["category"]
if isinstance(category, str):
categories.add(category.lower())
if not category.strip():
warnings.append(f"Insight {i} has empty category")
else:
errors.append(f"Insight {i} category must be a string")
# Validate confidence if present
if "confidence" in insight:
confidence = insight["confidence"]
try:
conf_val = float(confidence)
if not (0.0 <= conf_val <= 1.0):
warnings.append(f"Insight {i} confidence out of range [0,1]: {conf_val}")
except (ValueError, TypeError):
warnings.append(f"Insight {i} confidence must be a number")
# Validate tags if present
if "tags" in insight:
tags = insight["tags"]
if not isinstance(tags, list):
warnings.append(f"Insight {i} tags should be a list")
elif len(tags) == 0:
warnings.append(f"Insight {i} has empty tags list")
# Validate timestamp if present
if "timestamp" in insight:
timestamp = insight["timestamp"]
if not isinstance(timestamp, str):
warnings.append(f"Insight {i} timestamp should be a string")
else:
try:
datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
except ValueError:
warnings.append(f"Insight {i} has invalid timestamp format")
return {
"errors": errors,
"warnings": warnings,
"categories": list(categories),
"content_length": content_length
}
def _validate_conversations(self, conversations: List[Dict[str, Any]]) -> Dict[str, Any]:
"""
Validate conversation summaries data structure and content
Args:
conversations: List of conversation summary dictionaries
Returns:
dict: Validation results with errors, warnings, and content length
"""
errors = []
warnings = []
content_length = 0
required_fields = ["summary"]
optional_fields = ["key_themes", "timestamp", "insights_count"]
for i, conv in enumerate(conversations):
if not isinstance(conv, dict):
errors.append(f"Conversation {i} is not a dictionary")
continue
# Check required fields
for field in required_fields:
if field not in conv:
errors.append(f"Conversation {i} missing required field '{field}'")
elif not conv[field] or (isinstance(conv[field], str) and not conv[field].strip()):
errors.append(f"Conversation {i} has empty '{field}' field")
# Validate summary
if "summary" in conv:
summary = conv["summary"]
if isinstance(summary, str):
content_length += len(summary)
if len(summary) < 20:
warnings.append(f"Conversation {i} has very short summary")
elif len(summary) > 2000:
warnings.append(f"Conversation {i} has very long summary")
else:
errors.append(f"Conversation {i} summary must be a string")