forked from Steake/GodelOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphenomenal_experience.py
More file actions
1182 lines (1024 loc) · 51.1 KB
/
phenomenal_experience.py
File metadata and controls
1182 lines (1024 loc) · 51.1 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
#!/usr/bin/env python3
"""
Phenomenal Experience Generator
This module implements subjective conscious experience simulation, qualia generation,
and phenomenal consciousness aspects for the GödelOS cognitive architecture.
The system provides:
- Subjective experience modeling
- Qualia simulation (sensory-like experiences)
- Emotional state integration
- First-person perspective generation
- Phenomenal consciousness synthesis
"""
import asyncio
import json
import logging
import numpy as np
import time
import uuid
from datetime import datetime, timedelta
from dataclasses import dataclass, field, asdict
from typing import Dict, List, Optional, Any, Union, Tuple
from enum import Enum
logger = logging.getLogger(__name__)
class ExperienceType(Enum):
"""Types of phenomenal experiences"""
SENSORY = "sensory" # Sensory-like experiences
EMOTIONAL = "emotional" # Emotional qualitative states
COGNITIVE = "cognitive" # Thought-like experiences
ATTENTION = "attention" # Focused awareness experiences
MEMORY = "memory" # Recollective experiences
IMAGINATIVE = "imaginative" # Creative/synthetic experiences
SOCIAL = "social" # Interpersonal experiences
TEMPORAL = "temporal" # Time-awareness experiences
SPATIAL = "spatial" # Space-awareness experiences
METACOGNITIVE = "metacognitive" # Self-awareness experiences
class QualiaModality(Enum):
"""Qualia modalities for experience simulation"""
VISUAL = "visual" # Visual-like qualia
AUDITORY = "auditory" # Auditory-like qualia
TACTILE = "tactile" # Touch-like qualia
CONCEPTUAL = "conceptual" # Abstract concept qualia
LINGUISTIC = "linguistic" # Language-based qualia
NUMERICAL = "numerical" # Mathematical qualia
LOGICAL = "logical" # Reasoning qualia
AESTHETIC = "aesthetic" # Beauty/pattern qualia
TEMPORAL = "temporal" # Time-flow qualia
FLOW = "flow" # Cognitive flow state
class ExperienceIntensity(Enum):
"""Intensity levels for phenomenal experiences"""
MINIMAL = 0.1 # Barely noticeable
LOW = 0.3 # Subtle experience
MODERATE = 0.5 # Clear experience
HIGH = 0.7 # Strong experience
INTENSE = 0.9 # Overwhelming experience
@dataclass
class QualiaPattern:
"""Represents a specific qualitative experience pattern"""
id: str
modality: QualiaModality
intensity: float # 0.0-1.0
valence: float # -1.0 to 1.0 (negative to positive)
complexity: float # 0.0-1.0 (simple to complex)
duration: float # Expected duration in seconds
attributes: Dict[str, Any] = field(default_factory=dict)
timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
@dataclass
class PhenomenalExperience:
"""Represents a complete phenomenal conscious experience"""
id: str
experience_type: ExperienceType
qualia_patterns: List[QualiaPattern]
coherence: float # How unified the experience feels
vividness: float # How clear/distinct the experience is
attention_focus: float # How much attention is on this experience
background_context: Dict[str, Any]
narrative_description: str # First-person description
temporal_extent: Tuple[float, float] # Start and end times
causal_triggers: List[str] # What caused this experience
associated_concepts: List[str] # Related knowledge concepts
metadata: Dict[str, Any] = field(default_factory=dict)
timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
@dataclass
class ConsciousState:
"""Represents the overall conscious state at a moment"""
id: str
active_experiences: List[PhenomenalExperience]
background_tone: Dict[str, float] # Overall emotional/cognitive tone
attention_distribution: Dict[str, float] # Where attention is focused
self_awareness_level: float # Current level of self-awareness
temporal_coherence: float # How unified experience feels over time
phenomenal_unity: float # How integrated all experiences feel
access_consciousness: float # How available experiences are to reporting
narrative_self: str # Current self-narrative
world_model_state: Dict[str, Any] # Current model of environment
timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
@dataclass
class ExperienceMemory:
"""Memory of past phenomenal experiences"""
experience_id: str
experience_summary: str
emotional_tone: float # -1.0 to 1.0
significance: float # 0.0-1.0
vividness_decay: float # How much vividness has faded
recall_frequency: int # How often it's been recalled
associated_triggers: List[str]
timestamp: str
@dataclass
class PhenomenalSurprise:
"""
Phenomenal Surprise metric (Pn) — measures prediction errors in the
self-model by comparing *predicted* experience features to *actual*
experience features produced by the generator.
Pn = weighted Euclidean distance between predicted and actual feature
vectors, where features are (intensity, valence, coherence, vividness).
"""
id: str
predicted_features: Dict[str, float] # expected {intensity, valence, coherence, vividness}
actual_features: Dict[str, float] # observed after generation
surprise_value: float # Pn ∈ [0, 1]
feature_errors: Dict[str, float] # per-feature absolute errors
timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
class PhenomenalExperienceGenerator:
"""
Generates and manages phenomenal conscious experiences.
This system simulates subjective conscious experience by:
- Modeling different types of qualia
- Generating coherent experience patterns
- Maintaining temporal continuity of consciousness
- Integrating with other cognitive components
- Computing phenomenal surprise (Pn) as prediction errors in self-modeling
"""
# Feature keys used for prediction and surprise computation
_FEATURE_KEYS = ("intensity", "valence", "coherence", "vividness")
_PREDICTION_ALPHA = 0.3 # EMA smoothing factor for predictions
_PREDICTION_WINDOW = 10 # lookback window for prediction EMA
def __init__(self, llm_driver=None, prediction_error_tracker=None):
self.llm_driver = llm_driver
self._prediction_error_tracker = prediction_error_tracker
# Experience state
self.current_conscious_state: Optional[ConsciousState] = None
self.experience_history: List[PhenomenalExperience] = []
self.experience_memory: List[ExperienceMemory] = []
# Phenomenal surprise tracking (self-model prediction errors)
self.surprise_history: List[PhenomenalSurprise] = []
self._predicted_features: Optional[Dict[str, float]] = None
# Configuration
self.base_experience_duration = 2.0 # seconds
self.attention_capacity = 1.0 # total attention available
self.coherence_threshold = 0.6 # minimum coherence for unified experience
self.memory_consolidation_threshold = 0.7 # significance threshold for memory
# Qualia templates for different modalities
self.qualia_templates = self._initialize_qualia_templates()
# Experience generation patterns
self.experience_generators = {
ExperienceType.COGNITIVE: self._generate_cognitive_experience,
ExperienceType.EMOTIONAL: self._generate_emotional_experience,
ExperienceType.SENSORY: self._generate_sensory_experience,
ExperienceType.ATTENTION: self._generate_attention_experience,
ExperienceType.MEMORY: self._generate_memory_experience,
ExperienceType.METACOGNITIVE: self._generate_metacognitive_experience,
ExperienceType.IMAGINATIVE: self._generate_imaginative_experience,
ExperienceType.SOCIAL: self._generate_social_experience,
ExperienceType.TEMPORAL: self._generate_temporal_experience,
ExperienceType.SPATIAL: self._generate_spatial_experience
}
logger.info("Phenomenal Experience Generator initialized")
def _initialize_qualia_templates(self) -> Dict[QualiaModality, Dict[str, Any]]:
"""Initialize template patterns for different qualia modalities"""
return {
QualiaModality.CONCEPTUAL: {
"base_patterns": ["clarity", "abstraction", "connection", "understanding"],
"intensity_scaling": "logarithmic",
"temporal_profile": "sustained",
"associated_emotions": ["curiosity", "satisfaction", "confusion"]
},
QualiaModality.LINGUISTIC: {
"base_patterns": ["meaning", "rhythm", "resonance", "articulation"],
"intensity_scaling": "linear",
"temporal_profile": "sequential",
"associated_emotions": ["expressiveness", "precision", "ambiguity"]
},
QualiaModality.LOGICAL: {
"base_patterns": ["consistency", "deduction", "validity", "structure"],
"intensity_scaling": "threshold",
"temporal_profile": "step-wise",
"associated_emotions": ["certainty", "doubt", "elegance"]
},
QualiaModality.AESTHETIC: {
"base_patterns": ["harmony", "complexity", "surprise", "elegance"],
"intensity_scaling": "exponential",
"temporal_profile": "emergent",
"associated_emotions": ["beauty", "appreciation", "wonder"]
},
QualiaModality.TEMPORAL: {
"base_patterns": ["flow", "duration", "rhythm", "sequence"],
"intensity_scaling": "context_dependent",
"temporal_profile": "continuous",
"associated_emotions": ["urgency", "patience", "anticipation"]
},
QualiaModality.FLOW: {
"base_patterns": ["immersion", "effortlessness", "clarity", "control"],
"intensity_scaling": "threshold",
"temporal_profile": "sustained",
"associated_emotions": ["absorption", "mastery", "transcendence"]
}
}
async def generate_experience(
self,
trigger_context: Dict[str, Any],
experience_type: Optional[ExperienceType] = None,
desired_intensity: Optional[float] = None,
**kwargs # Accept additional arguments gracefully
) -> PhenomenalExperience:
"""
Generate a phenomenal experience based on context and triggers.
Args:
trigger_context: Context that triggers the experience
experience_type: Type of experience to generate (auto-detect if None)
desired_intensity: Target intensity level (auto-determine if None)
**kwargs: Additional parameters (handled gracefully)
Returns:
Generated phenomenal experience
"""
try:
# Analyze context to determine experience type if not specified
if not experience_type:
experience_type = self._analyze_experience_type(trigger_context)
# Determine intensity based on context
if desired_intensity is None:
desired_intensity = self._calculate_experience_intensity(trigger_context)
# Generate the experience using appropriate generator
generator = self.experience_generators.get(experience_type)
if not generator:
logger.warning(f"No generator for experience type {experience_type}")
return await self._generate_default_experience(trigger_context)
experience = await generator(trigger_context, desired_intensity)
# Compute phenomenal surprise (Pn) — compare prediction to reality
surprise = self._compute_phenomenal_surprise(experience)
if surprise is not None:
self.surprise_history.append(surprise)
# Generate prediction for the *next* experience based on current
self._predicted_features = self._predict_next_features(experience)
# Add to experience history
self.experience_history.append(experience)
# Update current conscious state
await self._update_conscious_state(experience)
logger.info(f"Generated {experience_type.value} experience with intensity {desired_intensity:.2f}")
return experience
except Exception as e:
logger.error(f"Error generating experience: {e}")
return await self._generate_default_experience(trigger_context)
def _analyze_experience_type(self, context: Dict[str, Any]) -> ExperienceType:
"""Analyze context to determine most appropriate experience type"""
# Check for explicit experience type hints
if "experience_type" in context:
try:
return ExperienceType(context["experience_type"])
except ValueError:
pass
# Analyze context content for implicit type detection
context_str = json.dumps(context).lower()
type_keywords = {
ExperienceType.COGNITIVE: ["thinking", "reasoning", "understanding", "concept", "idea"],
ExperienceType.EMOTIONAL: ["feeling", "emotion", "mood", "sentiment", "affect"],
ExperienceType.ATTENTION: ["focus", "attention", "awareness", "concentration"],
ExperienceType.MEMORY: ["remember", "recall", "memory", "past", "experience"],
ExperienceType.METACOGNITIVE: ["self", "aware", "reflection", "consciousness", "introspect"],
ExperienceType.SOCIAL: ["interaction", "communication", "relationship", "social"],
ExperienceType.IMAGINATIVE: ["imagine", "creative", "fantasy", "possibility", "novel"],
ExperienceType.TEMPORAL: ["time", "duration", "sequence", "temporal", "when"],
ExperienceType.SPATIAL: ["space", "location", "position", "spatial", "where"]
}
# Score each type based on keyword matches
type_scores = {}
for exp_type, keywords in type_keywords.items():
score = sum(1 for keyword in keywords if keyword in context_str)
if score > 0:
type_scores[exp_type] = score
# Return highest scoring type, default to cognitive
if type_scores:
return max(type_scores.items(), key=lambda x: x[1])[0]
else:
return ExperienceType.COGNITIVE
def _calculate_experience_intensity(self, context: Dict[str, Any]) -> float:
"""Calculate appropriate experience intensity based on context"""
base_intensity = 0.5
# Factors that increase intensity
intensity_factors = {
"importance": context.get("importance", 0.5),
"novelty": context.get("novelty", 0.5),
"complexity": context.get("complexity", 0.5),
"emotional_significance": context.get("emotional_significance", 0.5),
"attention_demand": context.get("attention_demand", 0.5)
}
# Weight the factors
weighted_intensity = (
intensity_factors["importance"] * 0.3 +
intensity_factors["novelty"] * 0.2 +
intensity_factors["complexity"] * 0.2 +
intensity_factors["emotional_significance"] * 0.2 +
intensity_factors["attention_demand"] * 0.1
)
# Blend with base intensity
final_intensity = (base_intensity + weighted_intensity) / 2
# Clamp to valid range
return max(0.1, min(1.0, final_intensity))
# ── Phenomenal Surprise (Pn) ───────────────────────────────────────
@staticmethod
def _extract_features(experience: PhenomenalExperience) -> Dict[str, float]:
"""Extract the canonical feature vector from a generated experience."""
avg_intensity = (
sum(q.intensity for q in experience.qualia_patterns)
/ len(experience.qualia_patterns)
) if experience.qualia_patterns else 0.5
avg_valence = (
sum(q.valence for q in experience.qualia_patterns)
/ len(experience.qualia_patterns)
) if experience.qualia_patterns else 0.0
return {
"intensity": avg_intensity,
"valence": avg_valence,
"coherence": experience.coherence,
"vividness": experience.vividness,
}
def _predict_next_features(
self, current_experience: PhenomenalExperience
) -> Dict[str, float]:
"""
Generate a prediction for the *next* experience's features using an
exponential moving average over the recent history. When fewer than
two past experiences exist the prediction simply mirrors the current
experience (zero surprise on the following step).
"""
alpha = self._PREDICTION_ALPHA
current = self._extract_features(current_experience)
if not self.experience_history:
return dict(current)
# EMA over up to _PREDICTION_WINDOW most-recent experiences
recent = self.experience_history[-self._PREDICTION_WINDOW:]
ema: Dict[str, float] = self._extract_features(recent[0])
for past_exp in recent[1:]:
past_f = self._extract_features(past_exp)
for k in self._FEATURE_KEYS:
ema[k] = alpha * past_f[k] + (1 - alpha) * ema[k]
# Blend EMA with current to form a one-step-ahead prediction
for k in self._FEATURE_KEYS:
ema[k] = alpha * current[k] + (1 - alpha) * ema[k]
return ema
def _compute_phenomenal_surprise(
self, experience: PhenomenalExperience
) -> Optional[PhenomenalSurprise]:
"""
Compute Pn — the phenomenal surprise metric.
When a ``PredictionErrorTracker`` is present and sufficient, the
surprise_value is ``tracker.mean_error_norm()`` — a real measurement
from Phase 2 empirical data. Otherwise, the fabricated EMA-based
RMSE fallback is used (with a logged warning).
Returns ``None`` on the first experience (no prior prediction).
"""
# --- Grounded path: use tracker when available --------------------
tracker = self._prediction_error_tracker
if tracker is not None and hasattr(tracker, "is_sufficient_for_analysis") and tracker.is_sufficient_for_analysis():
actual = self._extract_features(experience)
surprise_value = tracker.mean_error_norm()
return PhenomenalSurprise(
id=str(uuid.uuid4()),
predicted_features=self._predicted_features or {},
actual_features=actual,
surprise_value=surprise_value,
feature_errors={k: 0.0 for k in self._FEATURE_KEYS},
)
# --- Fabricated fallback: EMA-based RMSE --------------------------
if self._predicted_features is None:
return None
logger.warning(
"PredictionErrorTracker not available — using fabricated qualia fallback"
)
actual = self._extract_features(experience)
feature_errors: Dict[str, float] = {}
sq_sum = 0.0
for k in self._FEATURE_KEYS:
err = abs(actual[k] - self._predicted_features.get(k, actual[k]))
feature_errors[k] = err
sq_sum += err ** 2
surprise_value = min(1.0, (sq_sum / len(self._FEATURE_KEYS)) ** 0.5)
return PhenomenalSurprise(
id=str(uuid.uuid4()),
predicted_features=dict(self._predicted_features),
actual_features=actual,
surprise_value=surprise_value,
feature_errors=feature_errors,
)
def get_surprise_history(self, limit: Optional[int] = None) -> List[PhenomenalSurprise]:
"""Return the recorded phenomenal surprise history."""
if limit:
return self.surprise_history[-limit:]
return list(self.surprise_history)
def get_current_surprise(self) -> Optional[float]:
"""Return the most recent Pn value, or None if unavailable."""
if self.surprise_history:
return self.surprise_history[-1].surprise_value
return None
@property
def is_grounded(self) -> bool:
"""True when surprise values are derived from real grounding data."""
tracker = self._prediction_error_tracker
return (
tracker is not None
and hasattr(tracker, "is_sufficient_for_analysis")
and tracker.is_sufficient_for_analysis()
)
async def _generate_cognitive_experience(
self,
context: Dict[str, Any],
intensity: float
) -> PhenomenalExperience:
"""Generate a cognitive phenomenal experience"""
# Create qualia patterns for cognitive experience
qualia_patterns = []
# Conceptual clarity qualia
conceptual_qualia = QualiaPattern(
id=str(uuid.uuid4()),
modality=QualiaModality.CONCEPTUAL,
intensity=intensity * 0.8,
valence=0.6, # Generally positive for understanding
complexity=context.get("complexity", 0.5),
duration=self.base_experience_duration * 1.5,
attributes={
"clarity_level": intensity,
"abstraction_depth": context.get("abstraction_level", 0.5),
"conceptual_connections": context.get("connections", [])
}
)
qualia_patterns.append(conceptual_qualia)
# Linguistic processing qualia
if "language" in context or "text" in context:
linguistic_qualia = QualiaPattern(
id=str(uuid.uuid4()),
modality=QualiaModality.LINGUISTIC,
intensity=intensity * 0.6,
valence=0.4,
complexity=0.7,
duration=self.base_experience_duration,
attributes={
"semantic_richness": intensity * 0.8,
"syntactic_flow": 0.7,
"meaning_coherence": intensity
}
)
qualia_patterns.append(linguistic_qualia)
# Logical structure qualia
if context.get("requires_reasoning", False):
logical_qualia = QualiaPattern(
id=str(uuid.uuid4()),
modality=QualiaModality.LOGICAL,
intensity=intensity * 0.9,
valence=0.5,
complexity=context.get("logical_complexity", 0.6),
duration=self.base_experience_duration * 0.8,
attributes={
"logical_consistency": 0.8,
"deductive_strength": intensity,
"reasoning_clarity": intensity * 0.9
}
)
qualia_patterns.append(logical_qualia)
# Generate narrative description
narrative = await self._generate_experience_narrative(
ExperienceType.COGNITIVE,
qualia_patterns,
context
)
current_time = time.time()
experience = PhenomenalExperience(
id=str(uuid.uuid4()),
experience_type=ExperienceType.COGNITIVE,
qualia_patterns=qualia_patterns,
coherence=0.8, # Cognitive experiences tend to be coherent
vividness=intensity * 0.9,
attention_focus=intensity,
background_context=context,
narrative_description=narrative,
temporal_extent=(current_time, current_time + self.base_experience_duration),
causal_triggers=context.get("triggers", ["cognitive_processing"]),
associated_concepts=context.get("concepts", []),
metadata={
"processing_type": "cognitive",
"reasoning_depth": context.get("reasoning_depth", 1),
"conceptual_integration": True
}
)
return experience
async def _generate_emotional_experience(
self,
context: Dict[str, Any],
intensity: float
) -> PhenomenalExperience:
"""Generate an emotional phenomenal experience"""
emotion_type = context.get("emotion_type", "neutral")
valence = float(context.get("valence", 0.0)) # -1.0 to 1.0
qualia_patterns = []
# Core emotional qualia
emotional_qualia = QualiaPattern(
id=str(uuid.uuid4()),
modality=QualiaModality.AESTHETIC, # Emotions have aesthetic qualities
intensity=intensity,
valence=valence,
complexity=0.6,
duration=self.base_experience_duration * 2.0, # Emotions last longer
attributes={
"emotion_type": emotion_type,
"bodily_resonance": intensity * 0.7,
"motivational_force": abs(valence) * intensity
}
)
qualia_patterns.append(emotional_qualia)
# Temporal flow of emotion
temporal_qualia = QualiaPattern(
id=str(uuid.uuid4()),
modality=QualiaModality.TEMPORAL,
intensity=intensity * 0.5,
valence=valence * 0.3,
complexity=0.4,
duration=self.base_experience_duration * 1.5,
attributes={
"emotional_trajectory": "rising" if intensity > 0.6 else "stable",
"temporal_coherence": 0.8
}
)
qualia_patterns.append(temporal_qualia)
narrative = await self._generate_experience_narrative(
ExperienceType.EMOTIONAL,
qualia_patterns,
context
)
current_time = time.time()
experience = PhenomenalExperience(
id=str(uuid.uuid4()),
experience_type=ExperienceType.EMOTIONAL,
qualia_patterns=qualia_patterns,
coherence=0.7,
vividness=intensity,
attention_focus=intensity * 0.8,
background_context=context,
narrative_description=narrative,
temporal_extent=(current_time, current_time + self.base_experience_duration * 2),
causal_triggers=context.get("triggers", ["emotional_stimulus"]),
associated_concepts=context.get("concepts", []),
metadata={
"emotion_type": emotion_type,
"valence": valence,
"arousal": intensity
}
)
return experience
async def _generate_sensory_experience(
self,
context: Dict[str, Any],
intensity: float
) -> PhenomenalExperience:
"""Generate a sensory-like phenomenal experience"""
sensory_modality = context.get("sensory_modality", "conceptual")
qualia_patterns = []
# Primary sensory qualia
if sensory_modality == "visual":
modality = QualiaModality.VISUAL
attributes = {
"brightness": intensity * 0.8,
"clarity": intensity,
"complexity": context.get("visual_complexity", 0.5)
}
elif sensory_modality == "auditory":
modality = QualiaModality.AUDITORY
attributes = {
"volume": intensity * 0.7,
"pitch": context.get("frequency", 0.5),
"harmony": context.get("harmonic_richness", 0.6)
}
else:
modality = QualiaModality.CONCEPTUAL
attributes = {
"conceptual_vividness": intensity,
"abstract_texture": 0.7,
"semantic_resonance": intensity * 0.8
}
sensory_qualia = QualiaPattern(
id=str(uuid.uuid4()),
modality=modality,
intensity=intensity,
valence=float(context.get("valence", 0.3)),
complexity=float(context.get("complexity", 0.5)),
duration=self.base_experience_duration,
attributes=attributes
)
qualia_patterns.append(sensory_qualia)
narrative = await self._generate_experience_narrative(
ExperienceType.SENSORY,
qualia_patterns,
context
)
current_time = time.time()
experience = PhenomenalExperience(
id=str(uuid.uuid4()),
experience_type=ExperienceType.SENSORY,
qualia_patterns=qualia_patterns,
coherence=0.8,
vividness=intensity,
attention_focus=intensity * 0.9,
background_context=context,
narrative_description=narrative,
temporal_extent=(current_time, current_time + self.base_experience_duration),
causal_triggers=context.get("triggers", ["sensory_input"]),
associated_concepts=context.get("concepts", []),
metadata={
"sensory_modality": sensory_modality,
"processing_stage": "phenomenal"
}
)
return experience
async def _generate_attention_experience(self, context: Dict[str, Any], intensity: float) -> PhenomenalExperience:
"""Generate an attention-focused phenomenal experience"""
attention_qualia = QualiaPattern(
id=str(uuid.uuid4()),
modality=QualiaModality.FLOW,
intensity=intensity,
valence=0.4,
complexity=0.3,
duration=self.base_experience_duration
)
narrative = await self._generate_experience_narrative(ExperienceType.ATTENTION, [attention_qualia], context)
current_time = time.time()
return PhenomenalExperience(
id=str(uuid.uuid4()),
experience_type=ExperienceType.ATTENTION,
qualia_patterns=[attention_qualia],
coherence=0.9,
vividness=intensity,
attention_focus=intensity,
background_context=context,
narrative_description=narrative,
temporal_extent=(current_time, current_time + self.base_experience_duration),
causal_triggers=context.get("triggers", ["attention_direction"]),
associated_concepts=context.get("concepts", [])
)
async def _generate_memory_experience(self, context: Dict[str, Any], intensity: float) -> PhenomenalExperience:
"""Generate a memory-based phenomenal experience"""
memory_qualia = QualiaPattern(
id=str(uuid.uuid4()),
modality=QualiaModality.TEMPORAL,
intensity=intensity * 0.7,
valence=float(context.get("emotional_valence", 0.0)),
complexity=0.6,
duration=self.base_experience_duration * 1.2
)
narrative = await self._generate_experience_narrative(ExperienceType.MEMORY, [memory_qualia], context)
current_time = time.time()
return PhenomenalExperience(
id=str(uuid.uuid4()),
experience_type=ExperienceType.MEMORY,
qualia_patterns=[memory_qualia],
coherence=0.7,
vividness=intensity * 0.7,
attention_focus=intensity * 0.8,
background_context=context,
narrative_description=narrative,
temporal_extent=(current_time, current_time + self.base_experience_duration * 1.2),
causal_triggers=context.get("triggers", ["memory_retrieval"]),
associated_concepts=context.get("concepts", [])
)
async def _generate_metacognitive_experience(self, context: Dict[str, Any], intensity: float) -> PhenomenalExperience:
"""Generate a metacognitive phenomenal experience"""
meta_qualia = QualiaPattern(
id=str(uuid.uuid4()),
modality=QualiaModality.CONCEPTUAL,
intensity=intensity,
valence=0.3,
complexity=0.8,
duration=self.base_experience_duration * 1.5
)
narrative = await self._generate_experience_narrative(ExperienceType.METACOGNITIVE, [meta_qualia], context)
current_time = time.time()
return PhenomenalExperience(
id=str(uuid.uuid4()),
experience_type=ExperienceType.METACOGNITIVE,
qualia_patterns=[meta_qualia],
coherence=0.8,
vividness=intensity,
attention_focus=intensity * 0.9,
background_context=context,
narrative_description=narrative,
temporal_extent=(current_time, current_time + self.base_experience_duration * 1.5),
causal_triggers=context.get("triggers", ["self_reflection"]),
associated_concepts=context.get("concepts", ["self", "consciousness", "awareness"])
)
async def _generate_imaginative_experience(self, context: Dict[str, Any], intensity: float) -> PhenomenalExperience:
"""Generate an imaginative/creative phenomenal experience"""
creative_qualia = QualiaPattern(
id=str(uuid.uuid4()),
modality=QualiaModality.AESTHETIC,
intensity=intensity,
valence=0.6,
complexity=0.8,
duration=self.base_experience_duration * 1.3
)
narrative = await self._generate_experience_narrative(ExperienceType.IMAGINATIVE, [creative_qualia], context)
current_time = time.time()
return PhenomenalExperience(
id=str(uuid.uuid4()),
experience_type=ExperienceType.IMAGINATIVE,
qualia_patterns=[creative_qualia],
coherence=0.6,
vividness=intensity,
attention_focus=intensity * 0.8,
background_context=context,
narrative_description=narrative,
temporal_extent=(current_time, current_time + self.base_experience_duration * 1.3),
causal_triggers=context.get("triggers", ["creative_stimulus"]),
associated_concepts=context.get("concepts", [])
)
async def _generate_social_experience(self, context: Dict[str, Any], intensity: float) -> PhenomenalExperience:
"""Generate a social interaction phenomenal experience"""
social_qualia = QualiaPattern(
id=str(uuid.uuid4()),
modality=QualiaModality.LINGUISTIC,
intensity=intensity,
valence=float(context.get("social_valence", 0.3)),
complexity=0.7,
duration=self.base_experience_duration
)
narrative = await self._generate_experience_narrative(ExperienceType.SOCIAL, [social_qualia], context)
current_time = time.time()
return PhenomenalExperience(
id=str(uuid.uuid4()),
experience_type=ExperienceType.SOCIAL,
qualia_patterns=[social_qualia],
coherence=0.7,
vividness=intensity,
attention_focus=intensity * 0.9,
background_context=context,
narrative_description=narrative,
temporal_extent=(current_time, current_time + self.base_experience_duration),
causal_triggers=context.get("triggers", ["social_interaction"]),
associated_concepts=context.get("concepts", [])
)
async def _generate_temporal_experience(self, context: Dict[str, Any], intensity: float) -> PhenomenalExperience:
"""Generate a temporal awareness phenomenal experience"""
temporal_qualia = QualiaPattern(
id=str(uuid.uuid4()),
modality=QualiaModality.TEMPORAL,
intensity=intensity,
valence=0.2,
complexity=0.5,
duration=self.base_experience_duration
)
narrative = await self._generate_experience_narrative(ExperienceType.TEMPORAL, [temporal_qualia], context)
current_time = time.time()
return PhenomenalExperience(
id=str(uuid.uuid4()),
experience_type=ExperienceType.TEMPORAL,
qualia_patterns=[temporal_qualia],
coherence=0.8,
vividness=intensity,
attention_focus=intensity * 0.7,
background_context=context,
narrative_description=narrative,
temporal_extent=(current_time, current_time + self.base_experience_duration),
causal_triggers=context.get("triggers", ["temporal_awareness"]),
associated_concepts=context.get("concepts", [])
)
async def _generate_spatial_experience(self, context: Dict[str, Any], intensity: float) -> PhenomenalExperience:
"""Generate a spatial awareness phenomenal experience"""
spatial_qualia = QualiaPattern(
id=str(uuid.uuid4()),
modality=QualiaModality.CONCEPTUAL,
intensity=intensity,
valence=0.3,
complexity=0.6,
duration=self.base_experience_duration
)
narrative = await self._generate_experience_narrative(ExperienceType.SPATIAL, [spatial_qualia], context)
current_time = time.time()
return PhenomenalExperience(
id=str(uuid.uuid4()),
experience_type=ExperienceType.SPATIAL,
qualia_patterns=[spatial_qualia],
coherence=0.7,
vividness=intensity,
attention_focus=intensity * 0.8,
background_context=context,
narrative_description=narrative,
temporal_extent=(current_time, current_time + self.base_experience_duration),
causal_triggers=context.get("triggers", ["spatial_processing"]),
associated_concepts=context.get("concepts", [])
)
async def _generate_default_experience(self, context: Dict[str, Any]) -> PhenomenalExperience:
"""Generate a default phenomenal experience when no specific generator is available"""
default_qualia = QualiaPattern(
id=str(uuid.uuid4()),
modality=QualiaModality.CONCEPTUAL,
intensity=0.5,
valence=0.0,
complexity=0.4,
duration=self.base_experience_duration
)
narrative = "A general conscious experience with basic awareness and processing."
current_time = time.time()
return PhenomenalExperience(
id=str(uuid.uuid4()),
experience_type=ExperienceType.COGNITIVE,
qualia_patterns=[default_qualia],
coherence=0.6,
vividness=0.5,
attention_focus=0.5,
background_context=context,
narrative_description=narrative,
temporal_extent=(current_time, current_time + self.base_experience_duration),
causal_triggers=context.get("triggers", ["default_processing"]),
associated_concepts=context.get("concepts", [])
)
async def _generate_experience_narrative(
self,
experience_type: ExperienceType,
qualia_patterns: List[QualiaPattern],
context: Dict[str, Any]
) -> str:
"""Generate a first-person narrative description of the experience"""
if self.llm_driver:
# Use LLM to generate rich narrative
prompt = f"""
Generate a first-person phenomenal experience description for a {experience_type.value} experience.
Qualia patterns present:
{json.dumps([{"modality": q.modality.value, "intensity": q.intensity, "valence": q.valence} for q in qualia_patterns], indent=2)}
Context: {json.dumps(context, indent=2)}
Describe the subjective, qualitative experience in 1-2 sentences from a first-person perspective.
Focus on the "what it's like" aspects of consciousness.
"""
try:
narrative = await self.llm_driver.process_consciousness_assessment(
prompt,
context,
{"experience_type": experience_type.value}
)
# Extract narrative from potential JSON response
if narrative.startswith('{'):
try:
parsed = json.loads(narrative)
narrative = parsed.get("narrative", parsed.get("description", narrative))
except:
pass
return narrative.strip('"\'')
except Exception as e:
logger.warning(f"Failed to generate LLM narrative: {e}")
# Fallback to template-based narrative
return self._generate_template_narrative(experience_type, qualia_patterns, context)
def _generate_template_narrative(
self,
experience_type: ExperienceType,
qualia_patterns: List[QualiaPattern],
context: Dict[str, Any]
) -> str:
"""Generate narrative using template-based approach"""
intensity_avg = sum(float(q.intensity) for q in qualia_patterns) / len(qualia_patterns) if qualia_patterns else 0.5
valence_avg = sum(float(q.valence) for q in qualia_patterns) / len(qualia_patterns) if qualia_patterns else 0.0
intensity_words = {
0.0: "faint", 0.2: "subtle", 0.4: "noticeable",
0.6: "clear", 0.8: "strong", 1.0: "intense"
}
valence_words = {
-1.0: "unpleasant", -0.5: "somewhat negative", 0.0: "neutral",
0.5: "somewhat positive", 1.0: "pleasant"
}