-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathSemanticCascadeProcessing.py
2329 lines (1993 loc) · 86.1 KB
/
SemanticCascadeProcessing.py
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
"""
Cascade of Semantically Integrated Layers (CaSIL) Module
This module implements the Cascade of Semantically Integrated Layers algorithm,
which combines computational semantic analysis with progressive multi-layer
processing for enhanced natural language understanding and response generation.
Key Components:
- Semantic Analysis: TF-IDF vectorization and cosine similarity
- Dynamic Temperature Adjustment: Based on semantic similarity
- Multi-layer Processing: Progressive understanding through structured layers
- Knowledge Base Integration: External knowledge incorporation
"""
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
from typing import List, Dict, Optional, Any, Tuple, Set
from dataclasses import dataclass, field
import requests
import json
import sseclient
import os
from datetime import datetime, timedelta
from nltk_utils import ensure_nltk_resources
from dotenv import load_dotenv
from pathlib import Path
import string
from functools import lru_cache
import concurrent.futures
import dataclasses
from networkx import Graph, pagerank
from sklearn.cluster import DBSCAN
import networkx as nx
from sklearn.decomposition import TruncatedSVD
from sklearn.neighbors import NearestNeighbors
from tabulate import tabulate
from collections import OrderedDict
from typing import TypeVar, Generic
# Load environment variables
load_dotenv()
class LLMConfig:
"""Configuration for LLM API calls."""
def __init__(
self,
url: str = os.getenv('LLM_URL', 'http://0.0.0.0:11434/v1/chat/completions'),
model: str = os.getenv('LLM_MODEL', 'hf.co/arcee-ai/SuperNova-Medius-GGUF:f16'),
context_window: int = int(os.getenv('LLM_CONTEXT_WINDOW', '8192')),
max_tokens: int = int(os.getenv('LLM_MAX_TOKENS', '4096')),
top_p: float = float(os.getenv('LLM_TOP_P', '0.9')),
frequency_penalty: float = float(os.getenv('LLM_FREQUENCY_PENALTY', '0.0')),
presence_penalty: float = float(os.getenv('LLM_PRESENCE_PENALTY', '0.0')),
repeat_penalty: float = float(os.getenv('LLM_REPEAT_PENALTY', '1.1')),
temperature: float = float(os.getenv('LLM_TEMPERATURE', '0.7')),
stream: bool = True,
stop_sequences: List[str] = None,
seed: Optional[int] = None
):
"""Initialize LLM configuration."""
self.url = url
self.model = model
self.context_window = context_window
self.max_tokens = max_tokens
self.top_p = top_p
self.frequency_penalty = frequency_penalty
self.presence_penalty = presence_penalty
self.repeat_penalty = repeat_penalty
self.temperature = temperature
self.stream = stream
self.stop_sequences = stop_sequences or []
self.seed = seed or None
# Handle seed properly
seed_env = os.getenv('LLM_SEED')
try:
self.seed = int(seed_env) if seed_env and seed_env.isdigit() else seed
except (ValueError, TypeError):
self.seed = None
def to_dict(self) -> Dict[str, Any]:
"""Convert config to dictionary format."""
return {
'url': self.url,
'model': self.model,
'context_window': self.context_window,
'temperature': self.temperature,
'max_tokens': self.max_tokens,
'stream': self.stream,
'top_p': self.top_p,
'frequency_penalty': self.frequency_penalty,
'presence_penalty': self.presence_penalty,
'stop_sequences': self.stop_sequences,
'repeat_penalty': self.repeat_penalty,
'seed': self.seed
}
def get_temperature(self) -> float:
"""Get current temperature setting."""
return self.temperature
def set_temperature(self, temp: float) -> None:
"""Set temperature value."""
self.temperature = max(0.0, min(2.0, float(temp)))
@dataclass
class CSILConfig:
"""Configuration for Cascade of Semantically Integrated Layers.
Args:
min_keywords: Minimum number of keywords to extract
max_keywords: Maximum number of keywords to extract
keyword_weight_threshold: Minimum weight threshold for keywords
similarity_threshold: Minimum similarity threshold
max_results: Maximum number of results to return
llm_config: LLM configuration settings
debug_mode: Enable debug output
use_external_knowledge: Enable external knowledge integration
layer_thresholds: Layer-specific similarity thresholds
adaptive_thresholds: Enable adaptive thresholds
min_threshold: Minimum threshold for adaptive thresholds
max_threshold: Maximum threshold for adaptive thresholds
threshold_step: Step size for adaptive thresholds
"""
min_keywords: int = 2
max_keywords: int = 20
keyword_weight_threshold: float = 0.1
similarity_threshold: float = 0.1
max_results: Optional[int] = None
llm_config: LLMConfig = field(
default_factory=lambda: LLMConfig(
temperature=0.6
)
)
debug_mode: bool = False
use_external_knowledge: bool = field(
default_factory=lambda: os.getenv('USE_EXTERNAL_KNOWLEDGE', 'false').lower() == 'true'
)
layer_thresholds: Dict[str, float] = field(
default_factory=lambda: {
"initial_understanding": 0.7,
"relationship_analysis": 0.7,
"contextual_integration": 0.9,
"synthesis": 0.8
}
)
adaptive_thresholds: bool = True
min_threshold: float = 0.1
max_threshold: float = 0.9
threshold_step: float = 0.05
def __post_init__(self):
"""Validate configuration after initialization."""
# Convert to bool if string value provided
if isinstance(self.use_external_knowledge, str):
self.use_external_knowledge = self.use_external_knowledge.lower() == 'true'
@dataclass
class Conversation:
"""Stores conversation history and context"""
messages: List[Dict[str, str]] = field(default_factory=list)
context: Dict[str, Any] = field(default_factory=dict)
def add_message(self, role: str, content: str):
self.messages.append({
"role": role,
"content": content,
"timestamp": datetime.now().isoformat()
})
def get_recent_context(self, n_messages: int = 5) -> str:
"""Get recent conversation context"""
return "\n".join([
f"{msg['role']}: {msg['content']}"
for msg in self.messages[-n_messages:]
])
@dataclass
class KnowledgeBase:
"""Dynamic knowledge base that can load from multiple sources"""
documents: Dict[str, List[str]] = field(default_factory=dict)
required_categories: List[str] = field(
default_factory=lambda: ['prompts', 'templates']
)
def load_from_json(self, filepath: str) -> None:
"""
Load structured knowledge from JSON file.
Args:
filepath: Path to JSON file
"""
try:
with open(filepath, 'r', encoding='utf-8') as f:
data = json.load(f)
category = Path(filepath).parent.name
if category not in self.documents:
self.documents[category] = []
self.documents[category].append(json.dumps(data))
except Exception as e:
raise RuntimeError(f"Failed to load JSON from {filepath}: {str(e)}")
def load_from_directory(self, directory: str) -> None:
"""
Load text files from a directory.
Args:
directory: Path to directory containing text files
"""
try:
dir_path = Path(directory)
category = dir_path.name
if category not in self.documents:
self.documents[category] = []
for file_path in dir_path.glob('*.txt'):
with open(file_path, 'r', encoding='utf-8') as f:
self.documents[category].append(f.read())
except Exception as e:
raise RuntimeError(f"Failed to load directory {directory}: {str(e)}")
def get_relevant_documents(self, category: Optional[str] = None) -> List[str]:
"""
Get documents, optionally filtered by category.
Args:
category: Optional category to filter by
Returns:
List of document contents
"""
if category:
return self.documents.get(category, [])
return [doc for docs in self.documents.values() for doc in docs]
def is_required(self, category: str) -> bool:
"""Check if a category is required"""
return category in self.required_categories
@dataclass
class CategoryConfig:
"""Configuration for category-specific processing."""
name: str
similarity_threshold: float
concept_weight: float
context_weight: float
knowledge_weight: float
@dataclass
class SessionContext:
"""Tracks session-specific learning context"""
conversation: Conversation = field(default_factory=Conversation)
session_graph: nx.DiGraph = field(default_factory=nx.DiGraph)
concept_cache: Dict[str, float] = field(default_factory=dict)
session_start: datetime = field(default_factory=datetime.now)
def reset(self):
"""Reset session context"""
self.conversation = Conversation()
self.session_graph = nx.DiGraph()
self.concept_cache.clear()
self.session_start = datetime.now()
@dataclass
class KnowledgeGraphContext:
"""Tracks persistent knowledge and concept relationships"""
knowledge_graph: nx.DiGraph = field(default_factory=nx.DiGraph)
concept_metadata: Dict[str, Dict[str, Any]] = field(default_factory=dict)
entity_relationships: Dict[str, Set[str]] = field(default_factory=dict)
# Add vector storage
vector_store: Dict[str, np.ndarray] = field(default_factory=dict)
def add_concept(self, concept: str, metadata: Dict[str, Any],
vector: Optional[np.ndarray] = None) -> None:
"""Add or update concept with vector embedding"""
try:
# Get existing node data if it exists
existing_data = (
self.knowledge_graph.nodes[concept]
if concept in self.knowledge_graph
else {}
)
# Merge existing data with new metadata
node_data = {
**existing_data,
'first_seen': existing_data.get(
'first_seen',
datetime.now().isoformat()
),
'frequency': existing_data.get('frequency', 0) + 1,
**metadata
}
# Add or update node with merged data
self.knowledge_graph.add_node(concept, **node_data)
self.concept_metadata[concept] = metadata
# Store vector embedding if provided
if vector is not None:
self.vector_store[concept] = vector
except Exception as e:
raise RuntimeError(f"Failed to add concept {concept}: {str(e)}")
def get_similar_concepts(self, query_vector: np.ndarray,
top_k: int = 5) -> List[Tuple[str, float]]:
"""Retrieve similar concepts using vector similarity"""
similarities = []
for concept, vector in self.vector_store.items():
similarity = cosine_similarity(
query_vector.reshape(1, -1),
vector.reshape(1, -1)
)[0][0]
similarities.append((concept, similarity))
# Sort by similarity score
return sorted(similarities, key=lambda x: x[1],
reverse=True)[:top_k]
T = TypeVar('T') # Type variable for cache values
class LRUCache(Generic[T]):
"""
Least Recently Used (LRU) cache implementation.
Args:
maxsize: Maximum number of items to store
on_evict: Optional callback when items are evicted
"""
def __init__(self, maxsize: int = 1000, on_evict=None):
self.maxsize = maxsize
self.cache = OrderedDict()
self.on_evict = on_evict
def get(self, key: str, default: T = None) -> T:
"""Get item from cache with optional default."""
try:
value = self.cache.pop(key)
self.cache[key] = value
return value
except KeyError:
return default
def put(self, key: str, value: T) -> None:
"""Add item to cache, evicting oldest if necessary."""
try:
self.cache.pop(key)
except KeyError:
if len(self.cache) >= self.maxsize:
# Get oldest item
oldest_key, oldest_value = self.cache.popitem(last=False)
if self.on_evict:
self.on_evict(oldest_key, oldest_value)
self.cache[key] = value
def __getitem__(self, key: str) -> T:
"""Get item using dictionary syntax."""
return self.get(key)
def __setitem__(self, key: str, value: T) -> None:
"""Set item using dictionary syntax."""
self.put(key, value)
def __contains__(self, key: str) -> bool:
"""Check if key exists in cache."""
return key in self.cache
def __len__(self) -> int:
"""Get number of items in cache."""
return len(self.cache)
def clear(self) -> None:
"""Clear all items from cache."""
self.cache.clear()
class CascadeSemanticLayerProcessor:
"""
Main processor implementing the Cascade of Semantically Integrated Layers
algorithm.
The CaSIL algorithm processes user input through multiple layers of analysis:
1. Initial Understanding: Basic concept extraction
2. Semantic Analysis: Relationship discovery
3. Context Integration: Broader implications
4. Response Synthesis: Final coherent response
"""
def __init__(self, config: CSILConfig = CSILConfig()):
"""Initialize Cascade of Semantically Integrated Layers with enhanced
semantic analysis."""
self.config = config
self.conversation = Conversation()
self.knowledge_base = KnowledgeBase()
self.last_query = ""
# Modify vectorizer settings to handle small document counts
self.vectorizer = TfidfVectorizer(
stop_words=None,
max_features=1000,
ngram_range=(1, 1),
min_df=1,
max_df=1.0,
strip_accents='unicode',
token_pattern=r'(?u)\b\w+\b'
)
ensure_nltk_resources()
self.is_vectorizer_fitted = False
self.corpus_texts = []
# Remove thread pool from __init__
# We'll create it when needed instead
self._thread_pool = None
# Add caching for vectorizer
self._vector_cache = {}
# Add category-specific configurations
self.category_configs = {
# Original categories
"puzzle": CategoryConfig(
"puzzle",
similarity_threshold=0.6,
concept_weight=0.7,
context_weight=0.2,
knowledge_weight=0.1
),
"spatial": CategoryConfig(
"spatial",
similarity_threshold=0.7,
concept_weight=0.6,
context_weight=0.3,
knowledge_weight=0.1
),
# Scientific domains
"physics": CategoryConfig(
"physics",
similarity_threshold=0.75,
concept_weight=0.8,
context_weight=0.1,
knowledge_weight=0.1
),
"mathematics": CategoryConfig(
"mathematics",
similarity_threshold=0.8,
concept_weight=0.85,
context_weight=0.1,
knowledge_weight=0.05
),
"chemistry": CategoryConfig(
"chemistry",
similarity_threshold=0.75,
concept_weight=0.75,
context_weight=0.15,
knowledge_weight=0.1
),
# Engineering & Technology
"engineering": CategoryConfig(
"engineering",
similarity_threshold=0.7,
concept_weight=0.65,
context_weight=0.25,
knowledge_weight=0.1
),
"computer_science": CategoryConfig(
"computer_science",
similarity_threshold=0.75,
concept_weight=0.7,
context_weight=0.2,
knowledge_weight=0.1
),
# Philosophy & Logic
"philosophy": CategoryConfig(
"philosophy",
similarity_threshold=0.65,
concept_weight=0.6,
context_weight=0.3,
knowledge_weight=0.1
),
"logic": CategoryConfig(
"logic",
similarity_threshold=0.8,
concept_weight=0.8,
context_weight=0.1,
knowledge_weight=0.1
),
# Creative & Inventive
"invention": CategoryConfig(
"invention",
similarity_threshold=0.6,
concept_weight=0.5,
context_weight=0.3,
knowledge_weight=0.2
),
"innovation": CategoryConfig(
"innovation",
similarity_threshold=0.65,
concept_weight=0.55,
context_weight=0.25,
knowledge_weight=0.2
),
# Natural Sciences
"biology": CategoryConfig(
"biology",
similarity_threshold=0.7,
concept_weight=0.7,
context_weight=0.2,
knowledge_weight=0.1
),
"astronomy": CategoryConfig(
"astronomy",
similarity_threshold=0.75,
concept_weight=0.75,
context_weight=0.15,
knowledge_weight=0.1
),
# Interdisciplinary
"systems_thinking": CategoryConfig(
"systems_thinking",
similarity_threshold=0.65,
concept_weight=0.6,
context_weight=0.3,
knowledge_weight=0.1
),
"pattern_recognition": CategoryConfig(
"pattern_recognition",
similarity_threshold=0.7,
concept_weight=0.7,
context_weight=0.2,
knowledge_weight=0.1
),
# General Knowledge
"general": CategoryConfig(
"general",
similarity_threshold=0.6,
concept_weight=0.6,
context_weight=0.2,
knowledge_weight=0.2
)
}
# Maintain both session and persistent knowledge contexts
self.session = SessionContext()
self.knowledge = KnowledgeGraphContext()
# Add tracking for processed queries
self.processed_queries = 0
# Enhance caching mechanism
self._similarity_cache = {}
self._concept_cache = {}
self._processed_pairs = set()
# Add deduplication tracking
self._concept_normalizer = {} # Maps variants to canonical forms
self._concept_metadata = {} # Stores metadata for canonical forms
# Initialize vector database with LRU cache
self.vector_db = {
'embeddings': LRUCache(maxsize=1000),
'metadata': {},
'timestamps': {}
}
# Add vector cache with size limit
self._vector_cache = LRUCache(maxsize=1000)
# Add embedding cache with decorator
self._get_embedding = lru_cache(maxsize=1000)(self._generate_embedding)
@property
def thread_pool(self):
"""Lazy initialization of thread pool."""
if self._thread_pool is None:
self._thread_pool = concurrent.futures.ThreadPoolExecutor(
max_workers=4
)
return self._thread_pool
def _normalize_concept(self, concept: str) -> str:
"""Normalize concept to canonical form."""
try:
# Basic normalization
normalized = concept.lower().strip()
# Return cached canonical form if exists
if normalized in self._concept_normalizer:
return self._concept_normalizer[normalized]
# Store new canonical form
self._concept_normalizer[normalized] = normalized
return normalized
except Exception as e:
if self.config.debug_mode:
print(f"Error normalizing concept: {str(e)}")
return concept
def _calculate_semantic_similarity(
self,
text1: str,
text2: str,
use_cache: bool = True
) -> float:
"""Calculate semantic similarity with improved caching and deduplication."""
try:
# Create cache key with normalized texts
cache_key = tuple(sorted([
self._normalize_concept(text1),
self._normalize_concept(text2)
]))
# Skip if already processed
if cache_key in self._processed_pairs:
return self._similarity_cache.get(cache_key, 0.0)
# Mark as processed
self._processed_pairs.add(cache_key)
# Calculate similarity only if needed
if use_cache and cache_key in self._similarity_cache:
return self._similarity_cache[cache_key]
# Perform calculation
vectors = self.vectorizer.transform([text1, text2])
cos_sim = cosine_similarity(vectors[0:1], vectors[1:2])[0][0]
words1 = set(word_tokenize(text1.lower()))
words2 = set(word_tokenize(text2.lower()))
jaccard = len(words1 & words2) / len(words1 | words2) if words1 | words2 else 0
combined_sim = (0.7 * cos_sim) + (0.3 * jaccard)
result = max(0.0, min(1.0, combined_sim))
# Cache result
self._similarity_cache[cache_key] = result
# Debug output only for new calculations
if self.config.debug_mode:
print(f"\nSimilarity Calculation (new for {cache_key}):")
print(f"- Cosine similarity: {cos_sim:.3f}")
print(f"- Jaccard similarity: {jaccard:.3f}")
print(f"- Combined similarity: {combined_sim:.3f}")
return result
except Exception as e:
if self.config.debug_mode:
print(f"Similarity calculation error: {str(e)}")
return 0.0
def _calculate_tfidf_weight(self, term: str, context: str) -> float:
"""
Calculate TF-IDF weight for a term in given context.
Args:
term: Term to calculate weight for
context: Context text
Returns:
float: TF-IDF weight
"""
try:
# Ensure vectorizer is fitted
if not self.is_vectorizer_fitted:
# Add context to corpus and fit vectorizer
if context not in self.corpus_texts:
self.corpus_texts.append(context)
self._fit_vectorizer()
if not self.is_vectorizer_fitted:
return 0.0
# Transform single document
vector = self.vectorizer.transform([context])
# Get term index
term_idx = None
feature_names = self.vectorizer.get_feature_names_out()
for idx, feature in enumerate(feature_names):
if feature == term.lower():
term_idx = idx
break
if term_idx is not None:
# Get weight from vector
return vector[0, term_idx]
return 0.0
except Exception as e:
if self.config.debug_mode:
print(f"Error calculating TF-IDF weight: {str(e)}")
return 0.0
def _calculate_position_weight(self, term: str, context: str) -> float:
"""
Calculate position-based weight for a term.
Args:
term: Term to calculate weight for
context: Context text
Returns:
float: Position-based weight (earlier positions get higher weight)
"""
try:
words = word_tokenize(context.lower())
term_lower = term.lower()
# Find first occurrence
for i, word in enumerate(words):
if word == term_lower:
# Exponential decay based on position
return np.exp(-i / len(words))
return 0.0
except Exception as e:
if self.config.debug_mode:
print(f"Error calculating position weight: {str(e)}")
return 0.0
def _weight_concepts_by_importance(
self,
concepts: List[str],
context: str
) -> List[Tuple[str, float]]:
"""Weight concepts by their importance in context."""
# Ensure vectorizer is fitted before processing
if not self.is_vectorizer_fitted:
if context not in self.corpus_texts:
self.corpus_texts.append(context)
self._fit_vectorizer()
weights = []
for concept in concepts:
try:
# Calculate TF-IDF weight
tfidf_weight = self._calculate_tfidf_weight(concept, context)
# Calculate position weight
position_weight = self._calculate_position_weight(concept, context)
# Calculate frequency weight
freq_weight = context.lower().count(concept.lower()) / len(context.split())
# Combine weights
combined_weight = (
0.5 * tfidf_weight +
0.3 * position_weight +
0.2 * freq_weight
)
weights.append((concept, combined_weight))
except Exception as e:
if self.config.debug_mode:
print(f"Error weighting concept {concept}: {str(e)}")
weights.append((concept, 0.0))
return sorted(weights, key=lambda x: x[1], reverse=True)
def _extract_key_concepts(self, text: str) -> List[str]:
"""Extract key concepts with improved error handling."""
if not text or not text.strip():
return []
try:
# Ensure vectorizer is fitted
if not self.is_vectorizer_fitted:
if text not in self.corpus_texts:
self.corpus_texts.append(text)
self._fit_vectorizer()
# Single-threaded processing to avoid thread pool issues
tokens = word_tokenize(text.lower())
stop_words = set(stopwords.words('english'))
# Enhanced filtering criteria
filtered_tokens = [
t for t in tokens
if (
len(t) > 1 and
not t.isnumeric() and
not t in stop_words and
not all(char in string.punctuation for char in t)
)
]
if not filtered_tokens:
return tokens[:self.config.min_keywords]
# Calculate weights and select terms
document = ' '.join(filtered_tokens)
weighted_terms = self._weight_concepts_by_importance(filtered_tokens, document)
# Apply limits
num_terms = max(
self.config.min_keywords,
min(len(weighted_terms), self.config.max_keywords)
)
selected_terms = weighted_terms[:num_terms]
if self.config.debug_mode:
print("\nExtracted concepts:")
for term, weight in selected_terms:
print(f" • {term}: {weight:.3f}")
return [term for term, _ in selected_terms]
except Exception as e:
if self.config.debug_mode:
print(f"Error in concept extraction: {str(e)}")
return text.split()[:self.config.min_keywords]
def __del__(self):
"""Cleanup thread pool on object deletion."""
if self._thread_pool is not None:
self._thread_pool.shutdown(wait=False)
def process_semantic_cascade(self, user_input: str) -> Dict[str, Any]:
"""Enhanced semantic cascade with adaptive processing."""
try:
self.last_query = user_input
# Initialize results dictionary
results = {
'initial_understanding': '',
'relationships': '',
'context_integration': '',
'final_response': '',
'metadata': {
'timestamp': datetime.now().isoformat(),
'concepts_extracted': [],
'similarity_scores': {}
}
}
if self.config.debug_mode:
print("\n🤔 Starting semantic cascade...")
print(f"Corpus size before: {len(self.corpus_texts)}")
# Add user input to corpus
if user_input not in self.corpus_texts:
self.corpus_texts.append(user_input)
# Add conversation context to corpus
context = self.conversation.get_recent_context()
if context and context not in self.corpus_texts:
self.corpus_texts.append(context)
# Add knowledge base documents to corpus
if self.config.use_external_knowledge:
relevant_docs = self.knowledge_base.get_relevant_documents()
self.corpus_texts.extend([doc for doc in relevant_docs
if doc not in self.corpus_texts])
# Extract and process concepts
concepts = self._extract_key_concepts(user_input)
# Update graphs with new concepts
self._update_graphs(concepts, user_input)
# Increment processed queries counter
self.processed_queries += 1
# Process each layer
results['initial_understanding'] = self._process_layer(
"initial_understanding",
user_input,
"", # No previous output for first layer
"Identify ONLY the fundamental concepts and questions."
)
results['relationships'] = self._process_layer(
"relationship_analysis",
user_input,
results['initial_understanding'],
"Discover NEW connections between the identified concepts."
)
results['context_integration'] = self._process_layer(
"contextual_integration",
user_input,
results['relationships'],
"Add BROADER context and implications not yet discussed."
)
results['final_response'] = self._process_layer(
"synthesis",
user_input,
results['context_integration'],
"Create a cohesive final response that builds upon all previous layers and directly answers the users query and/or intent. Make sure your response is readable and helpful to the user."
)
return results
except Exception as e:
if self.config.debug_mode:
print(f"Error in semantic cascade: {str(e)}")
# Return a structured error response
return {
'initial_understanding': '',
'relationships': '',
'context_integration': '',
'final_response': f"Error processing query: {str(e)}",
'error': str(e)
}
def _process_with_threshold(
self,
user_input: str,
threshold: float
) -> Dict[str, Any]:
"""Process with specific threshold."""
try:
temp_config = dataclasses.replace(
self.config,
similarity_threshold=threshold
)
# Process through semantic cascade
return self.process_semantic_cascade(user_input)
except Exception as e:
if self.config.debug_mode:
print(f"Error in threshold processing: {str(e)}")
return {
'error': str(e),
'threshold_used': threshold
}
def process_interaction(self, user_input: str) -> Dict[str, Any]:
"""Enhanced interaction processing with category detection."""
try:
# Detect category
category = self._detect_category(user_input)
# Get category-specific config
category_config = self.category_configs.get(category)
if category_config:
# Temporarily adjust config for this interaction
original_config = self.config
self.config = CSILConfig(
**{
**dataclasses.asdict(original_config),
"similarity_threshold": category_config.similarity_threshold
}
)
try:
# Process through semantic cascade directly
results = self.process_semantic_cascade(user_input)
finally:
# Restore original config
self.config = original_config
return results
else:
# Use default processing if no specific category config
return self.process_semantic_cascade(user_input)
except Exception as e:
if self.config.debug_mode:
print(f"Error in interaction processing: {str(e)}")
return {
'error': str(e),
'initial_understanding': '',
'relationships': '',
'context_integration': '',
'final_response': f"Error processing query: {str(e)}"
}
def _calculate_dynamic_temperature(
self,
novelty_score: float,
layer_name: str
) -> float:
"""Calculate dynamic temperature with more conservative scaling.
Args:
novelty_score: Score indicating content novelty (0.0-1.0)
layer_name: Name of current processing layer
Returns:
float: Calculated temperature value (0.1-1.0)
"""
try:
# Lower base temperature from config
base_temp = min(0.6, float(self.config.llm_config.temperature))
# Reduced layer-specific adjustments
layer_adjustments = {