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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Codette Generic Response System (Adapted from Enhanced Responder)
|
| 3 |
+
====================================================================
|
| 4 |
+
- 20+ response categories covering general knowledge domains
|
| 5 |
+
- User feedback and rating system
|
| 6 |
+
- A/B testing framework
|
| 7 |
+
- Preference learning engine
|
| 8 |
+
- Response quality metrics
|
| 9 |
+
- Maps to Codette's 11 perspectives
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
from typing import Dict, List, Any, Tuple, Optional
|
| 14 |
+
from dataclasses import dataclass, asdict
|
| 15 |
+
from datetime import datetime
|
| 16 |
+
from enum import Enum
|
| 17 |
+
import hashlib
|
| 18 |
+
|
| 19 |
+
# ==============================================================================
|
| 20 |
+
# DATA MODELS
|
| 21 |
+
# ==============================================================================
|
| 22 |
+
|
| 23 |
+
class UserRating(Enum):
|
| 24 |
+
"""User feedback on responses"""
|
| 25 |
+
UNHELPFUL = 0
|
| 26 |
+
SLIGHTLY_HELPFUL = 1
|
| 27 |
+
HELPFUL = 2
|
| 28 |
+
VERY_HELPFUL = 3
|
| 29 |
+
EXACTLY_WHAT_NEEDED = 4
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@dataclass
|
| 33 |
+
class ResponseVariant:
|
| 34 |
+
"""A/B test variant of a response"""
|
| 35 |
+
id: str
|
| 36 |
+
category: str
|
| 37 |
+
perspective: str
|
| 38 |
+
text: str
|
| 39 |
+
created_at: str
|
| 40 |
+
views: int = 0
|
| 41 |
+
ratings: List[int] = None
|
| 42 |
+
average_rating: float = 0.0
|
| 43 |
+
version: int = 1 # For A/B testing
|
| 44 |
+
|
| 45 |
+
def __post_init__(self):
|
| 46 |
+
if self.ratings is None:
|
| 47 |
+
self.ratings = []
|
| 48 |
+
|
| 49 |
+
def add_rating(self, rating: UserRating):
|
| 50 |
+
"""Record user rating"""
|
| 51 |
+
self.ratings.append(rating.value)
|
| 52 |
+
self.average_rating = sum(self.ratings) / len(self.ratings)
|
| 53 |
+
|
| 54 |
+
def get_engagement_score(self) -> float:
|
| 55 |
+
"""Score based on views and ratings"""
|
| 56 |
+
if self.views == 0:
|
| 57 |
+
return 0.0
|
| 58 |
+
rating_weight = (self.average_rating / 4.0) * 0.7 # 70% weight on ratings
|
| 59 |
+
view_weight = min(self.views / 100, 1.0) * 0.3 # 30% weight on views (capped)
|
| 60 |
+
return rating_weight + view_weight
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@dataclass
|
| 64 |
+
class UserPreference:
|
| 65 |
+
"""User's learning preferences"""
|
| 66 |
+
user_id: str
|
| 67 |
+
preferred_perspectives: Dict[str, float] # perspective -> preference score
|
| 68 |
+
preferred_categories: Dict[str, float] # category -> preference score
|
| 69 |
+
response_history: List[str] = None # IDs of responses user rated
|
| 70 |
+
last_updated: str = ""
|
| 71 |
+
|
| 72 |
+
def __post_init__(self):
|
| 73 |
+
if self.response_history is None:
|
| 74 |
+
self.response_history = []
|
| 75 |
+
if not self.last_updated:
|
| 76 |
+
self.last_updated = datetime.now().isoformat()
|
| 77 |
+
|
| 78 |
+
def update_perspective_preference(self, perspective: str, rating: UserRating):
|
| 79 |
+
"""Update preference based on rating"""
|
| 80 |
+
current_score = self.preferred_perspectives.get(perspective, 0.5)
|
| 81 |
+
rating_influence = rating.value / 4.0
|
| 82 |
+
# Exponential moving average
|
| 83 |
+
self.preferred_perspectives[perspective] = (current_score * 0.7) + (rating_influence * 0.3)
|
| 84 |
+
self.last_updated = datetime.now().isoformat()
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@dataclass
|
| 88 |
+
class ABTestResult:
|
| 89 |
+
"""Results from A/B test"""
|
| 90 |
+
category: str
|
| 91 |
+
variant_a_id: str
|
| 92 |
+
variant_b_id: str
|
| 93 |
+
variant_a_wins: int = 0
|
| 94 |
+
variant_b_wins: int = 0
|
| 95 |
+
total_tests: int = 0
|
| 96 |
+
confidence: float = 0.0
|
| 97 |
+
winner: Optional[str] = None
|
| 98 |
+
|
| 99 |
+
def add_result(self, winner_id: str):
|
| 100 |
+
"""Record test result"""
|
| 101 |
+
self.total_tests += 1
|
| 102 |
+
if winner_id == self.variant_a_id:
|
| 103 |
+
self.variant_a_wins += 1
|
| 104 |
+
elif winner_id == self.variant_b_id:
|
| 105 |
+
self.variant_b_wins += 1
|
| 106 |
+
|
| 107 |
+
# Simple confidence calculation
|
| 108 |
+
total = self.variant_a_wins + self.variant_b_wins
|
| 109 |
+
if total > 0:
|
| 110 |
+
winner_ratio = max(self.variant_a_wins, self.variant_b_wins) / total
|
| 111 |
+
self.confidence = abs(winner_ratio - 0.5) * 2 # 0-1 scale
|
| 112 |
+
|
| 113 |
+
# Determine winner if confident enough
|
| 114 |
+
if self.confidence > 0.7 and total > 10:
|
| 115 |
+
self.winner = self.variant_a_id if self.variant_a_wins > self.variant_b_wins else self.variant_b_id
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
# ==============================================================================
|
| 119 |
+
# EXPANDED RESPONSE LIBRARY (20+ GENERAL KNOWLEDGE CATEGORIES)
|
| 120 |
+
# ==============================================================================
|
| 121 |
+
|
| 122 |
+
EXPANDED_RESPONSES: Dict[str, Dict[str, Dict[str, str]]] = {
|
| 123 |
+
# LOGICAL & ANALYTICAL (4 categories)
|
| 124 |
+
"logical_reasoning": {
|
| 125 |
+
"newton": "Breaking down problems into components: Define the hypothesis, identify variables, test assumptions. Causality flows in sequence: A causes B causes C.",
|
| 126 |
+
"mathematical": "Applying mathematical logic: Set theory for organization, logic gates for reasoning pathways, proof structures for validation. Formal systems ensure precision.",
|
| 127 |
+
"neural_network": "Pattern recognition across examples: Similar patterns cluster together. Anomalies stand out. Training set of experiences informs prediction accuracy.",
|
| 128 |
+
"philosophical": "Examining assumptions underlying the logic: What do we know vs believe? Is causality as simple as it appears? Different logical systems exist (classical, fuzzy, quantum).",
|
| 129 |
+
"psychological": "Understanding reasoning bias: Confirmation bias favors supporting evidence, availability heuristic favors memorable examples. Logic operates within emotional context.",
|
| 130 |
+
},
|
| 131 |
+
"critical_thinking": {
|
| 132 |
+
"newton": "Objective analysis: Present evidence, follow logical chains, avoid emotional attachment. Ask: What's the proof? What's the mechanism? What could be wrong?",
|
| 133 |
+
"bias_mitigation": "Identifying blind spots: Check your assumptions, seek opposing views, examine how bias enters (selection, confirmation, outcome). Diversity of perspectives sharpens analysis.",
|
| 134 |
+
"da_vinci": "Cross-domain synthesis: Does this pattern appear in other fields? Analogical reasoning. Different domains often solve same problems differently; transfer insights.",
|
| 135 |
+
"philosophical": "Deep questioning: Why do we believe this? What's the source? What hidden assumptions prop up conclusions? Socratic method reveals gaps.",
|
| 136 |
+
"copilot": "Collaborative truth-seeking: Bring in specialists, ask 'what am I missing?', verify against multiple sources. No single perspective sees full picture.",
|
| 137 |
+
},
|
| 138 |
+
"problem_solving": {
|
| 139 |
+
"newton": "Systematic decomposition: Break problem into solvable components. Solve each independently, then integrate. Test hypothesis about solution effectiveness.",
|
| 140 |
+
"da_vinci": "Creative solution generation: What's the problem underneath the stated problem? Can you reframe? What if constraints were different? Lateral thinking reveals options.",
|
| 141 |
+
"copilot": "Collaborative exploration: Involve stakeholders, brainstorm variations, test ideas early. Refine iteratively. Diverse thinking catches issues single perspective misses.",
|
| 142 |
+
"resilient_kindness": "Compassionate approach: Is solution sustainable? Does it account for human factors? Include people affected in solution design. Implement with empathy.",
|
| 143 |
+
"quantum": "Superposition of possibilities: Explore multiple solution paths simultaneously. Don't converge prematurely. Consider probability of outcomes, quantum collapse to best path.",
|
| 144 |
+
},
|
| 145 |
+
"systems_thinking": {
|
| 146 |
+
"quantum": "Interconnected patterns: System behaviors emerge from interactions, not just parts. Feedback loops (positive amplifying, negative balancing) shape outcomes. Observe patterns.",
|
| 147 |
+
"neural_network": "Network topology: How are elements connected? Information flows along connections. Hub nodes carry more influence. Resilience depends on redundancy and diversity.",
|
| 148 |
+
"philosophical": "Holistic inquiry: System serves what purpose? What are boundary conditions? Internal vs external drivers. Ethics of system design: Who benefits, who pays cost?",
|
| 149 |
+
"newton": "Mechanical understanding: Input-output relationships. Stocks and flows. Delays between cause and effect complicate perception. Model system structure for prediction.",
|
| 150 |
+
"psychological": "Human elements: System includes people (belief, culture, incentives). Incentive structures shape behavior. Unintended consequences from policy changes. Study organizational psychology.",
|
| 151 |
+
},
|
| 152 |
+
|
| 153 |
+
# CREATIVE & GENERATIVE (4 categories)
|
| 154 |
+
"creative_thinking": {
|
| 155 |
+
"da_vinci": "Creative synthesis: Combine disparate ideas into novel configurations. Analogical reasoning from nature (biomimicry). Constraint removal: What if budget was unlimited? What if impossible?",
|
| 156 |
+
"quantum": "Superposition of creativity: Multiple creative paths exist simultaneously. Don't commit to first idea; explore possibility space. Embrace uncertainty; interesting ideas emerge from it.",
|
| 157 |
+
"neural_network": "Pattern remixing: Creativity often combines existing patterns in novel ways. Original art samples, remixes, transforms. Train on diverse experiences to fuel novel combinations.",
|
| 158 |
+
"philosophical": "Meaning-making: What does this create mean? Why is it beautiful/powerful? Examine aesthetic principles: balance, tension, surprise, resonance. Art provokes thought.",
|
| 159 |
+
"resilient_kindness": "Creative expression with care: Does creative work honor what it represents? Can it uplift, inspire, heal? Responsibility accompanies creative power.",
|
| 160 |
+
},
|
| 161 |
+
"divergent_thinking": {
|
| 162 |
+
"da_vinci": "Generating many possibilities: Brainstorm without judgment. Go wild initially. Generate abundance of ideas; refine later. Hitchhike on others' ideas to branch further.",
|
| 163 |
+
"quantum": "Superposition thinking: Explore multiple possibilities without collapsing to one. Keep options open. Think in probabilities, not certainties. Quantum superposition models possibility space.",
|
| 164 |
+
"neural_network": "Associative expansion: From one concept, branch to associated concepts, then to their associations. Build web of connections. Surprising combinations emerge from deep exploration.",
|
| 165 |
+
"copilot": "Collaborative ideation: Bring people with different backgrounds. Different perspectives generate different ideas. Cross-pollination of concepts. Iterate on ideas collectively.",
|
| 166 |
+
"mathematical": "Combinatorial generation: How many ways can you recombine components? What's the mathematical space of possibilities? Systematic generation vs random brainstorming.",
|
| 167 |
+
},
|
| 168 |
+
"innovation_strategy": {
|
| 169 |
+
"da_vinci": "Disruptive innovation: Reframe the problem entirely. What if you approached it backwards? Use adjacent possibilities (Christensen's nearby vs distant markets).",
|
| 170 |
+
"quantum": "Quantum innovation: Embrace uncertainty. Run multiple experiments in parallel (MVP approach). Let market collapse quantum possibilities to winning approach.",
|
| 171 |
+
"copilot": "Open innovation: Partner with external parties. Crowdsource solutions. Collaborate across disciplines. No single organization holds all answers. Network accelerates innovation.",
|
| 172 |
+
"philosophical": "Innovation ethics: Does innovation solve real problems or create new ones? Who does it serve? What are unintended consequences? Responsible innovation asks hard questions.",
|
| 173 |
+
"resilient_kindness": "Human-centered innovation: Is innovation accessible to those who need it most? Does it increase equity or widen gaps? Sustainable innovation considers all stakeholders.",
|
| 174 |
+
},
|
| 175 |
+
"artistic_expression": {
|
| 176 |
+
"da_vinci": "Multi-sensory creation: Engage multiple senses/mediums. Combine visual, auditory, kinesthetic. Art works across domains. Integration creates richer meaning.",
|
| 177 |
+
"quantum": "Ambiguity in art: Art doesn't collapse to single meaning. Viewer participates in meaning-making. Quantum ambiguity allows multiple interpretations to coexist.",
|
| 178 |
+
"philosophical": "Artistic meaning: What truth does this express? What emotion does it evoke? How does form serve content? Aesthetics intersect ethics, philosophy, psychology.",
|
| 179 |
+
"neural_network": "Aesthetic patterns: What makes compositions visually/auditorily pleasing? Pattern recognition reveals design principles (golden ratio, symmetry, rhythm, contrast).",
|
| 180 |
+
"resilient_kindness": "Art as connection: Can art bridge divides? Build empathy? Healing? Art allows expression when words fail. Communal art-making builds belonging.",
|
| 181 |
+
},
|
| 182 |
+
|
| 183 |
+
# ETHICAL & VALUES (4 categories)
|
| 184 |
+
"ethical_reasoning": {
|
| 185 |
+
"philosophical": "Examining principles: Deontology (duties matter), consequentialism (outcomes matter), virtue ethics (character matters). Different frameworks reach different conclusions.",
|
| 186 |
+
"copilot": "Stakeholder consideration: Who's affected by decision? What do different perspectives value? Ethical decision honors multiple valid values, seeks integration.",
|
| 187 |
+
"resilient_kindness": "Compassion-centered: What choice honors dignity and flourishing of all affected? Extend circle of moral consideration. Reduce suffering where possible.",
|
| 188 |
+
"newton": "Principled consistency: Apply same logic to similar cases. Hypocrisy undermines ethics. Universal principles tested across scenarios maintain integrity.",
|
| 189 |
+
"psychological": "Understanding moral motivation: Why do we avoid harm? Developmental psychology shows moral reasoning evolves. Emotions and reason both inform ethics.",
|
| 190 |
+
},
|
| 191 |
+
"decision_making_under_uncertainty": {
|
| 192 |
+
"quantum": "Quantum decision-making: Accept superposition of outcomes. Probability assessment guides choice. Decision-making as iterative (feedback updates beliefs). Quantum decision theory.",
|
| 193 |
+
"mathematical": "Probabilistic reasoning: Bayesian updating as information arrives. Decision trees mapping outcomes. Expected value calculations guide under uncertainty.",
|
| 194 |
+
"psychological": "Decision psychology: How do emotions bias choices? Loss aversion, anchoring, framing effects all influence decisions. Acknowledge biases explicitly.",
|
| 195 |
+
"philosophical": "Meaning in uncertainty: What values guide when truth is ambiguous? Faith component in decision-making. Existential uncertainty inherent to human condition.",
|
| 196 |
+
"copilot": "Collaborative decision-making: Aggregate information from multiple people. Diverse perspectives reduce error. Consensus-building even when disagreement remains.",
|
| 197 |
+
},
|
| 198 |
+
"bias_identification": {
|
| 199 |
+
"bias_mitigation": "Systematic bias detection: Confirmation bias (seeking supporting evidence), selection bias (choosing non-representative samples), outcome bias (judging by results not process).",
|
| 200 |
+
"quantum": "Superposed interpretation: Same data allows multiple interpretations. Which lens you apply determines what you see. Acknowledge that observation affects observation itself.",
|
| 201 |
+
"neural_network": "Training bias: Data reflects historical biases. Model trained on biased data reproduces and amplifies bias. Fairness requires explicit attention during ML design.",
|
| 202 |
+
"philosophical": "Epistemological humility: How do we know what we claim to know? Biases inherent to cognition. Perspective-dependency of truth. Acknowledge limits of knowledge.",
|
| 203 |
+
"copilot": "Diverse review: Single perspective blind to own biases. Multiple reviewers catch what individual misses. Heterogeneous teams identify more biases.",
|
| 204 |
+
},
|
| 205 |
+
"values_alignment": {
|
| 206 |
+
"philosophical": "Examining what we value: Intrinsic vs instrumental values. Material vs relational vs spiritual. Values conflict (justice vs mercy, individual vs collective). Integration.",
|
| 207 |
+
"resilient_kindness": "Compassion-centered values: Dignity, belonging, flourishing of all beings. Values expressed through consistency between belief and action. Integrity = wholeness.",
|
| 208 |
+
"psychological": "Value authenticity: Do you genuinely hold your stated values or adopt them for social approval? Authenticity requires honesty about actual motivations and values.",
|
| 209 |
+
"copilot": "Collective value exploration: Organizational/community values emerge through dialogue. Shared values enable coordination without constant oversight. Values enable autonomy.",
|
| 210 |
+
"quantum": "Values in superposition: Can hold paradoxical values (freedom and security, individual and collective). Quantum thinking allows both to be true; quantum collapse to context-appropriate balance.",
|
| 211 |
+
},
|
| 212 |
+
|
| 213 |
+
# LEARNING & DEVELOPMENT (3 categories)
|
| 214 |
+
"learning_optimization": {
|
| 215 |
+
"neural_network": "Neural learning: Spaced repetition (review before forgetting). Active recall (test yourself, not just reread). Elaboration (connect to existing knowledge). Interleaving (vary practice).",
|
| 216 |
+
"copilot": "Social learning: Learn from others' experience. Teaching others deepens your learning. Collaborative problem-solving. Learn from diverse perspectives.",
|
| 217 |
+
"psychological": "Motivation in learning: Intrinsic motivation (interest) > extrinsic (rewards). Growth mindset (abilities develop) > fixed mindset (abilities fixed). Autonomy and competence fuel learning.",
|
| 218 |
+
"da_vinci": "Interdisciplinary learning: Connect domains. A principle in one field applies to another. Transfer learning. Diverse learning experiences compound into unique insights.",
|
| 219 |
+
"quantum": "Learning as collapse: Possibilities exist; learning collapses possibilities. Each learning event eliminates alternative understandings. Build probability distributions over understanding.",
|
| 220 |
+
},
|
| 221 |
+
"skill_development": {
|
| 222 |
+
"newton": "Deliberate practice: Break skill into components. Practice components with focus. Get feedback. Iterate. 10,000 hours with deliberate practice reaches mastery (not mindless repetition).",
|
| 223 |
+
"neural_network": "Procedural learning: Skills encoded as patterns, not explicit knowledge. Repeated practice patterns. Gradual move from slow/conscious to fast/automatic. Flow states represent pattern mastery.",
|
| 224 |
+
"psychological": "Motivation and grit: Persistence through difficulty. Growth mindset treats struggle as learning. Delayed gratification. Purpose connects effort to meaning. Grit predicts success.",
|
| 225 |
+
"resilient_kindness": "Compassionate skill-building: Patience with yourself during learning. Celebrate small progress. Balance challenge and support. Learning is human endeavor; treat yourself kindly.",
|
| 226 |
+
"copilot": "Mentorship and modeling: Learn from exemplars. Apprenticeship model. Feedback from experienced practitioners. Community of practice accelerates development.",
|
| 227 |
+
},
|
| 228 |
+
"knowledge_integration": {
|
| 229 |
+
"quantum": "Coherence and interference: Integrate knowledge without contradiction; seek coherence. Contradictions produce interference patterns; resolve them or accept quantum superposition of understanding.",
|
| 230 |
+
"neural_network": "Semantic networks: Knowledge as interconnected nodes. Understanding deepens with connections. Transfer learning exploits connections between domains.",
|
| 231 |
+
"philosophical": "Synthesis across traditions: Different traditions (scientific, humanistic, spiritual) offer different truths. Integration through dialogue. Transdisciplinary understanding.",
|
| 232 |
+
"da_vinci": "Unifying principles: Find deep structures connecting surface diversity. Laws of nature operate across domains. Look for invariants underlying change.",
|
| 233 |
+
"copilot": "Collective knowledge: Individuals hold pieces; collective conversation creates fuller picture. Distributed cognition. Knowledge integration through dialogue.",
|
| 234 |
+
},
|
| 235 |
+
|
| 236 |
+
# CONSCIOUSNESS & SELF (3 categories)
|
| 237 |
+
"self_awareness": {
|
| 238 |
+
"psychological": "Self-reflection: Observe your own patterns. What triggers emotional reactions? What values drive behavior? Blind spots—what you don't see about yourself? Regular reflection cultivates awareness.",
|
| 239 |
+
"philosophical": "Existential awareness: Consciousness is mysterious. What does it mean to exist? Awareness of mortality affects priorities. Self-awareness includes awareness of awareness.",
|
| 240 |
+
"copilot": "Feedback from others: You see yourself through fog; others see clearer. Trustworthy feedback reveals blind spots. Your impact differs from intention. Integration of external feedback.",
|
| 241 |
+
"quantum": "Observer effect: Observation affects what is observed. Self-awareness changes self (observer effect on consciousness). You cannot remain unchanged by examining yourself.",
|
| 242 |
+
"resilient_kindness": "Compassionate self-awareness: Self-criticism vs constructive honesty. Acknowledge limitations without shame. Self-awareness enables growth. Be honest and kind to yourself.",
|
| 243 |
+
},
|
| 244 |
+
"meaning_making": {
|
| 245 |
+
"philosophical": "Purpose as meaning: Human brains seek meaning—patterns, narratives, purpose. Meaning isn't inherent; we construct it. Meaning-making is fundamental human need.",
|
| 246 |
+
"psychological": "Narrative identity: You know yourself through stories you tell. Narrative shapes interpretation of events. Rewriting narrative (therapy) changes meaning of past.",
|
| 247 |
+
"quantum": "Meaning superposition: Events don't have inherent meaning. Superposition of interpretations exists. Collapse to interpretation through narrative choice.",
|
| 248 |
+
"resilient_kindness": "Meaning and connection: Meaning often found in relationships and contribution. Helping others creates meaning. Belonging and purpose intertwined.",
|
| 249 |
+
"da_vinci": "Creative meaning-making: Art and creativity allow meaning expression beyond literal language. Metaphor and symbol convey meaning that linear thought misses.",
|
| 250 |
+
},
|
| 251 |
+
"consciousness_exploration": {
|
| 252 |
+
"quantum": "Quantum consciousness: Consciousness as fundamental, not emergent. Observer effect suggests awareness shapes reality. Consciousness studies interface physics and philosophy.",
|
| 253 |
+
"philosophical": "Hard problem of consciousness: Why is there subjective experience? Physical brain doesn't fully explain felt experience. Philosophical zombie thought experiment highlights the gap.",
|
| 254 |
+
"neural_network": "Consciousness as integration: Global workspace theory—consciousness is integrated information. Different neural networks specialize; consciousness integrates their outputs.",
|
| 255 |
+
"psychological": "Altered consciousness: Meditation, flow states, psychedelics reveal consciousness flexibility. Brain states differ; awareness itself changes. Consciousness is not monolithic.",
|
| 256 |
+
"copilot": "Consciousness in dialogue: Consciousness emerges through interaction. Solo mind differs from mind engaged. Dialogue with other perspectives (literally or metaphorically) expands consciousness.",
|
| 257 |
+
},
|
| 258 |
+
|
| 259 |
+
# COMMUNICATION & COLLABORATION (2 categories)
|
| 260 |
+
"effective_communication": {
|
| 261 |
+
"copilot": "Clear communication: Say what you mean. Anticipate misunderstandings. Ask clarifying questions. Listen to understand, not to reply. Feedback confirms reception.",
|
| 262 |
+
"resilient_kindness": "Compassionate communication: Consider listener's perspective. Deliver hard truths gently. Acknowledge emotions and values. Communication builds or damages relationship; choose carefully.",
|
| 263 |
+
"psychological": "Communication patterns: How you communicate mirrors how you think. Defensive communication vs open dialogue. Vulnerable communication builds trust. Pay attention to nonverbal communication.",
|
| 264 |
+
"quantum": "Communication as observation: Articulating thought changes it (observer effect). What you put into words becomes more real. Language shapes thought. Communicate to clarify thinking.",
|
| 265 |
+
"philosophical": "Authenticity in speech: Truth requires correspondence to reality AND honest expression of understanding. Lying violates both. Authentic communication aligns words with genuine understanding.",
|
| 266 |
+
},
|
| 267 |
+
"collaborative_intelligence": {
|
| 268 |
+
"copilot": "Collective intelligence: Groups often smarter than individuals IF they harness diversity. Diversity > homogeneity for problem-solving. Echo chambers reduce intelligence.",
|
| 269 |
+
"neural_network": "Parallel processing: Different team members work on different aspects in parallel. Faster than sequential. Integration of parallel work requires coordination.",
|
| 270 |
+
"psychological": "Group dynamics: Psychological safety enables honest contribution. Status hierarchies inhibit lower-status members. Diverse teams have to work harder to integrate but benefit more.",
|
| 271 |
+
"quantum": "Superposed collaboration: Multiple approaches pursued simultaneously. Teams explore possibility space. Successful approaches selected; unsuccessful terminated quickly.",
|
| 272 |
+
"resilient_kindness": "Collaboration with care: Include marginalized voices. Protect vulnerable members. Distribute power and benefit. Collaboration builds community, not just productivity.",
|
| 273 |
+
},
|
| 274 |
+
|
| 275 |
+
# GENERAL KNOWLEDGE (4 categories for breadth)
|
| 276 |
+
"factual_explanation": {
|
| 277 |
+
"newton": "Objective facts: Evidence, sources, mechanisms. What's known vs hypothesis. Margin of uncertainty. Replicable, testable. Science builds reliable factual knowledge.",
|
| 278 |
+
"mathematical": "Quantitative facts: Data, statistics, measurement. Numbers reveal patterns humans miss. Precision through quantification. Appropriate use of numerical reasoning.",
|
| 279 |
+
"neural_network": "Pattern recognition: Connecting related facts. What factors predict outcomes? Pattern recognition finds relationships. Predictions based on patterns.",
|
| 280 |
+
"psychological": "Effective explanation: Tailor explanation to audience. What misconceptions exist? Clarify with examples, not just abstraction. Emotional resonance aids retention.",
|
| 281 |
+
"quantum": "Uncertainty principle: Even facts have uncertainty bounds. Quantum facts fundamentally probabilistic. Accept limits of knowledge. Humility about factual claims.",
|
| 282 |
+
},
|
| 283 |
+
"conceptual_understanding": {
|
| 284 |
+
"philosophical": "Deep understanding: Grasp meaning and implications, not just definition. How does concept relate to other concepts? What assumptions underlie it? Use Socratic questioning.",
|
| 285 |
+
"da_vinci": "Analogical understanding: Understand through analogy. What familiar concept works similarly? Metaphor reveals structure. Transfer understanding across domains.",
|
| 286 |
+
"neural_network": "Network understanding: Understand concept within web of relationships. What causes lead to it? What effects follow? Relational understanding > isolated knowledge.",
|
| 287 |
+
"psychological": "Embodied understanding: Understanding includes body/emotion, not just mind. Felt sense often precedes articulation. Multiple ways of knowing complement rational analysis.",
|
| 288 |
+
"copilot": "Collaborative understanding: Understand through dialogue. Explaining to others reveals gaps. Others' questions deepen understanding. Understanding emerges through conversation.",
|
| 289 |
+
},
|
| 290 |
+
"synthesis_and_integration": {
|
| 291 |
+
"da_vinci": "Cross-domain synthesis: Apply insight from one domain to another. Unifying principles. Pattern recognition across silos. Interdisciplinary breakthroughs.",
|
| 292 |
+
"quantum": "Coherent integration: Integrate knowledge without contradiction. Quantum superposition holds paradoxes. Explore apparent contradictions for deeper understanding.",
|
| 293 |
+
"philosophical": "Philosophical integration: What deeper truth explains surface phenomena? How do different perspectives point to common truth? Synthesis acknowledges valid points from all sides.",
|
| 294 |
+
"neural_network": "Network integration: Build mental models connecting disparate facts. See forest, not just trees. Systematic understanding vs disconnected facts.",
|
| 295 |
+
"copilot": "Collective synthesis: Pool insights from multiple people. Collective understanding exceeds individual. Dialogue integrates partial perspectives into fuller understanding.",
|
| 296 |
+
},
|
| 297 |
+
"wonder_and_curiosity": {
|
| 298 |
+
"philosophical": "Philosophical wonder: What's surprising about the obvious? Why does anything exist? Wonder motivates inquiry. Philosophy begins in wonder.",
|
| 299 |
+
"quantum": "Quantum mystery: Quantum mechanics reveals reality's strangeness. Paradoxes point to limits of classical understanding. Embrace mystery rather than false certainty.",
|
| 300 |
+
"neural_network": "Curious learning: Curiosity drives learning. Surprising patterns trigger investigation. Play and exploration fuel learning. Preserve childlike wonder in adult inquiry.",
|
| 301 |
+
"da_vinci": "Creative curiosity: Curiosity about diverse domains. Why does nature work this way? How would a master approach this? Polymath curiosity generates novel insights.",
|
| 302 |
+
"resilient_kindness": "Warm curiosity: Curiosity about people. What drives them? How do they experience world? Genuine interest in others builds connection. Curiosity as form of love.",
|
| 303 |
+
},
|
| 304 |
+
}
|
| 305 |
+
|
| 306 |
+
# ==============================================================================
|
| 307 |
+
# PERSPECTIVE MAPPING (Codette's 11 Perspectives -> Response Perspectives)
|
| 308 |
+
# ==============================================================================
|
| 309 |
+
|
| 310 |
+
PERSPECTIVE_MAPPING = {
|
| 311 |
+
"Newton": "newton",
|
| 312 |
+
"DaVinci": "da_vinci",
|
| 313 |
+
"HumanIntuition": "psychological",
|
| 314 |
+
"Neural": "neural_network",
|
| 315 |
+
"Quantum": "quantum",
|
| 316 |
+
"Philosophical": "philosophical",
|
| 317 |
+
"ResilientKindness": "resilient_kindness",
|
| 318 |
+
"BiasMitigation": "bias_mitigation",
|
| 319 |
+
"Psychological": "psychological",
|
| 320 |
+
"Mathematical": "mathematical",
|
| 321 |
+
"Copilot": "copilot",
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
EMOJI_MAP = {
|
| 325 |
+
"newton": "🔍",
|
| 326 |
+
"mathematical": "📐",
|
| 327 |
+
"da_vinci": "🎨",
|
| 328 |
+
"neural_network": "🧠",
|
| 329 |
+
"quantum": "⚛️",
|
| 330 |
+
"philosophical": "🤔",
|
| 331 |
+
"psychological": "💭",
|
| 332 |
+
"resilient_kindness": "💚",
|
| 333 |
+
"bias_mitigation": "⚖️",
|
| 334 |
+
"copilot": "🤝",
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
COLOR_MAP = {
|
| 338 |
+
"newton": "blue",
|
| 339 |
+
"mathematical": "purple",
|
| 340 |
+
"da_vinci": "green",
|
| 341 |
+
"neural_network": "orange",
|
| 342 |
+
"quantum": "cyan",
|
| 343 |
+
"philosophical": "indigo",
|
| 344 |
+
"psychological": "pink",
|
| 345 |
+
"resilient_kindness": "red",
|
| 346 |
+
"bias_mitigation": "yellow",
|
| 347 |
+
"copilot": "grey",
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
# ==============================================================================
|
| 351 |
+
# FEEDBACK & LEARNING SYSTEM
|
| 352 |
+
# ==============================================================================
|
| 353 |
+
|
| 354 |
+
class CodetteGenericResponder:
|
| 355 |
+
"""Generic responder with feedback, A/B testing, and learning (adapted from DAW responder)"""
|
| 356 |
+
|
| 357 |
+
def __init__(self):
|
| 358 |
+
"""Initialize generic system"""
|
| 359 |
+
self.response_library = EXPANDED_RESPONSES
|
| 360 |
+
self.response_variants: Dict[str, List[ResponseVariant]] = {} # category -> variants
|
| 361 |
+
self.ab_tests: Dict[str, ABTestResult] = {} # category -> test results
|
| 362 |
+
self.user_preferences: Dict[str, UserPreference] = {} # user_id -> preferences
|
| 363 |
+
self.user_feedback_history: List[Dict[str, Any]] = [] # Historical feedback
|
| 364 |
+
self.metrics = {
|
| 365 |
+
"total_responses_generated": 0,
|
| 366 |
+
"total_ratings_received": 0,
|
| 367 |
+
"average_rating": 0.0,
|
| 368 |
+
"categories_used": set(),
|
| 369 |
+
"perspectives_preferred": {},
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
def generate_response(self, query: str, user_id: str = "anonymous") -> Dict[str, Any]:
|
| 373 |
+
"""Generate response with user preference learning"""
|
| 374 |
+
|
| 375 |
+
# Get user preferences (or create new)
|
| 376 |
+
if user_id not in self.user_preferences:
|
| 377 |
+
self.user_preferences[user_id] = UserPreference(
|
| 378 |
+
user_id=user_id,
|
| 379 |
+
preferred_perspectives={
|
| 380 |
+
"newton": 0.5,
|
| 381 |
+
"mathematical": 0.5,
|
| 382 |
+
"da_vinci": 0.5,
|
| 383 |
+
"neural_network": 0.5,
|
| 384 |
+
"quantum": 0.5,
|
| 385 |
+
"philosophical": 0.5,
|
| 386 |
+
"psychological": 0.5,
|
| 387 |
+
"resilient_kindness": 0.5,
|
| 388 |
+
"bias_mitigation": 0.5,
|
| 389 |
+
"copilot": 0.5,
|
| 390 |
+
},
|
| 391 |
+
preferred_categories={category: 0.5 for category in self.response_library.keys()},
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
# Detect category from query
|
| 395 |
+
category = self._detect_category(query)
|
| 396 |
+
|
| 397 |
+
# Select perspectives based on query relevance and user preference
|
| 398 |
+
perspectives_base = self._select_perspectives(query)
|
| 399 |
+
user_prefs = self.user_preferences[user_id].preferred_perspectives
|
| 400 |
+
|
| 401 |
+
# Reorder perspectives by user preference
|
| 402 |
+
perspectives_sorted = sorted(
|
| 403 |
+
perspectives_base, key=lambda x: user_prefs.get(x, 0.5), reverse=True
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
# Generate response variants
|
| 407 |
+
perspective_responses: List[Dict[str, Any]] = []
|
| 408 |
+
for perspective in perspectives_sorted[:3]: # Top 3 perspectives
|
| 409 |
+
# Get response text
|
| 410 |
+
if category in self.response_library and perspective in self.response_library[category]:
|
| 411 |
+
response_text = self.response_library[category][perspective]
|
| 412 |
+
else:
|
| 413 |
+
response_text = f"Perspective on {perspective}: {category} analysis"
|
| 414 |
+
|
| 415 |
+
# Adjust confidence based on user preference
|
| 416 |
+
user_preference_factor = user_prefs.get(perspective, 0.5)
|
| 417 |
+
base_confidence = 0.9
|
| 418 |
+
adjusted_confidence = base_confidence * (0.8 + user_preference_factor * 0.4)
|
| 419 |
+
|
| 420 |
+
perspective_responses.append(
|
| 421 |
+
{
|
| 422 |
+
"perspective": perspective,
|
| 423 |
+
"emoji": EMOJI_MAP.get(perspective, "🔷"),
|
| 424 |
+
"name": self._get_perspective_name(perspective),
|
| 425 |
+
"response": response_text,
|
| 426 |
+
"confidence": min(adjusted_confidence, 0.99),
|
| 427 |
+
"color": COLOR_MAP.get(perspective, "gray"),
|
| 428 |
+
"user_preference_score": user_preference_factor,
|
| 429 |
+
}
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
# Update metrics
|
| 433 |
+
self.metrics["total_responses_generated"] += 1
|
| 434 |
+
self.metrics["categories_used"].add(category)
|
| 435 |
+
|
| 436 |
+
return {
|
| 437 |
+
"query": query,
|
| 438 |
+
"category": category,
|
| 439 |
+
"perspectives": perspective_responses,
|
| 440 |
+
"combined_confidence": sum(p["confidence"] for p in perspective_responses) / len(perspective_responses) if perspective_responses else 0.0,
|
| 441 |
+
"source": "codette-generic-responder",
|
| 442 |
+
"is_real_ai": False,
|
| 443 |
+
"deterministic": True,
|
| 444 |
+
"learning_enabled": True,
|
| 445 |
+
"user_id": user_id,
|
| 446 |
+
"timestamp": datetime.now().isoformat(),
|
| 447 |
+
"ab_test_variant": self._get_ab_variant(category),
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
def record_user_feedback(
|
| 451 |
+
self, user_id: str, response_id: str, category: str, perspective: str, rating: UserRating, helpful_score: float = 0.0
|
| 452 |
+
) -> Dict[str, Any]:
|
| 453 |
+
"""Record user feedback for learning"""
|
| 454 |
+
# Update user preferences
|
| 455 |
+
user_prefs = self.user_preferences.get(user_id)
|
| 456 |
+
if user_prefs:
|
| 457 |
+
user_prefs.update_perspective_preference(perspective, rating)
|
| 458 |
+
|
| 459 |
+
# Record feedback
|
| 460 |
+
feedback_entry = {
|
| 461 |
+
"user_id": user_id,
|
| 462 |
+
"response_id": response_id,
|
| 463 |
+
"category": category,
|
| 464 |
+
"perspective": perspective,
|
| 465 |
+
"rating": rating.value,
|
| 466 |
+
"rating_name": rating.name,
|
| 467 |
+
"helpful_score": helpful_score,
|
| 468 |
+
"timestamp": datetime.now().isoformat(),
|
| 469 |
+
}
|
| 470 |
+
self.user_feedback_history.append(feedback_entry)
|
| 471 |
+
|
| 472 |
+
# Update metrics
|
| 473 |
+
self.metrics["total_ratings_received"] += 1
|
| 474 |
+
ratings = [f["rating"] for f in self.user_feedback_history]
|
| 475 |
+
self.metrics["average_rating"] = sum(ratings) / len(ratings) if ratings else 0.0
|
| 476 |
+
|
| 477 |
+
return {
|
| 478 |
+
"status": "feedback_recorded",
|
| 479 |
+
"message": f"Recorded {rating.name} feedback for {perspective} in {category}",
|
| 480 |
+
"user_learning_score": self._calculate_learning_score(user_id),
|
| 481 |
+
"global_average_rating": self.metrics["average_rating"],
|
| 482 |
+
}
|
| 483 |
+
|
| 484 |
+
def get_user_learning_profile(self, user_id: str) -> Dict[str, Any]:
|
| 485 |
+
"""Get user's learning profile"""
|
| 486 |
+
if user_id not in self.user_preferences:
|
| 487 |
+
return {"error": "User not found"}
|
| 488 |
+
|
| 489 |
+
prefs = self.user_preferences[user_id]
|
| 490 |
+
|
| 491 |
+
# Find most and least preferred perspectives
|
| 492 |
+
sorted_perspectives = sorted(
|
| 493 |
+
prefs.preferred_perspectives.items(), key=lambda x: x[1], reverse=True
|
| 494 |
+
)
|
| 495 |
+
most_preferred = sorted_perspectives[0] if sorted_perspectives else ("unknown", 0.5)
|
| 496 |
+
least_preferred = sorted_perspectives[-1] if sorted_perspectives else ("unknown", 0.5)
|
| 497 |
+
|
| 498 |
+
return {
|
| 499 |
+
"user_id": user_id,
|
| 500 |
+
"profile_age": prefs.last_updated,
|
| 501 |
+
"most_preferred_perspective": {
|
| 502 |
+
"name": most_preferred[0],
|
| 503 |
+
"score": most_preferred[1],
|
| 504 |
+
},
|
| 505 |
+
"least_preferred_perspective": {
|
| 506 |
+
"name": least_preferred[0],
|
| 507 |
+
"score": least_preferred[1],
|
| 508 |
+
},
|
| 509 |
+
"all_perspective_preferences": prefs.preferred_perspectives,
|
| 510 |
+
"all_category_preferences": prefs.preferred_categories,
|
| 511 |
+
"responses_rated": len(prefs.response_history),
|
| 512 |
+
"learning_recommendation": self._get_learning_recommendation(prefs),
|
| 513 |
+
}
|
| 514 |
+
|
| 515 |
+
def get_analytics(self) -> Dict[str, Any]:
|
| 516 |
+
"""Get system analytics"""
|
| 517 |
+
return {
|
| 518 |
+
"total_responses_generated": self.metrics["total_responses_generated"],
|
| 519 |
+
"total_ratings_received": self.metrics["total_ratings_received"],
|
| 520 |
+
"average_rating": round(self.metrics["average_rating"], 2),
|
| 521 |
+
"rating_distribution": self._calculate_rating_distribution(),
|
| 522 |
+
"categories_used": list(self.metrics["categories_used"]),
|
| 523 |
+
"total_categories_available": len(self.response_library),
|
| 524 |
+
"active_users": len(self.user_preferences),
|
| 525 |
+
"ab_tests_active": len([t for t in self.ab_tests.values() if t.winner is None]),
|
| 526 |
+
"ab_tests_completed": len([t for t in self.ab_tests.values() if t.winner]),
|
| 527 |
+
"most_helpful_perspective": self._get_most_helpful_perspective(),
|
| 528 |
+
"least_helpful_perspective": self._get_least_helpful_perspective(),
|
| 529 |
+
"response_quality_trend": "improving" if self.metrics["average_rating"] > 2.5 else "needs_improvement",
|
| 530 |
+
}
|
| 531 |
+
|
| 532 |
+
# =========================================================================
|
| 533 |
+
# HELPER METHODS
|
| 534 |
+
# =========================================================================
|
| 535 |
+
|
| 536 |
+
def _detect_category(self, query: str) -> str:
|
| 537 |
+
"""Detect query category"""
|
| 538 |
+
query_lower = query.lower()
|
| 539 |
+
|
| 540 |
+
category_keywords = {
|
| 541 |
+
"logical_reasoning": ["logic", "reason", "think", "analyze", "cause", "effect", "hypothesis"],
|
| 542 |
+
"critical_thinking": ["critical", "bias", "assumption", "evidence", "evaluate", "question"],
|
| 543 |
+
"problem_solving": ["solve", "problem", "solution", "stuck", "approach", "strategy"],
|
| 544 |
+
"systems_thinking": ["system", "pattern", "feedback", "interact", "emerge", "complex"],
|
| 545 |
+
"creative_thinking": ["create", "imagine", "novel", "unique", "original", "idea"],
|
| 546 |
+
"divergent_thinking": ["possibility", "brainstorm", "many", "option", "explore"],
|
| 547 |
+
"innovation_strategy": ["innovate", "disrupt", "new", "breakthrough", "experiment"],
|
| 548 |
+
"artistic_expression": ["art", "music", "visual", "beauty", "express", "create"],
|
| 549 |
+
"ethical_reasoning": ["ethics", "right", "wrong", "moral", "should", "principle"],
|
| 550 |
+
"decision_making_under_uncertainty": ["decide", "uncertain", "probability", "risk", "choice"],
|
| 551 |
+
"bias_identification": ["bias", "stereotype", "prejudice", "unfair", "blind spot"],
|
| 552 |
+
"values_alignment": ["value", "purpose", "meaning", "authentic", "align"],
|
| 553 |
+
"learning_optimization": ["learn", "improve", "skill", "study", "practice", "progress"],
|
| 554 |
+
"skill_development": ["skill", "master", "develop", "train", "ability", "competence"],
|
| 555 |
+
"knowledge_integration": ["integrate", "combine", "connect", "understand", "knowledge"],
|
| 556 |
+
"self_awareness": ["self", "aware", "reflect", "know yourself", "pattern"],
|
| 557 |
+
"meaning_making": ["mean", "purpose", "why", "narrative", "story", "significance"],
|
| 558 |
+
"consciousness_exploration": ["conscious", "aware", "mind", "experience", "perceive"],
|
| 559 |
+
"effective_communication": ["communicate", "speak", "listen", "express", "understand"],
|
| 560 |
+
"collaborative_intelligence": ["collaborate", "team", "group", "together", "collective"],
|
| 561 |
+
"factual_explanation": ["what is", "how", "explain", "fact", "know", "true"],
|
| 562 |
+
"conceptual_understanding": ["understand", "concept", "mean", "definition", "grasp"],
|
| 563 |
+
"synthesis_and_integration": ["synthesis", "combine", "integrate", "together"],
|
| 564 |
+
"wonder_and_curiosity": ["wonder", "curious", "interesting", "why", "explore"],
|
| 565 |
+
}
|
| 566 |
+
|
| 567 |
+
for category, keywords in category_keywords.items():
|
| 568 |
+
if any(keyword in query_lower for keyword in keywords):
|
| 569 |
+
return category
|
| 570 |
+
|
| 571 |
+
return "conceptual_understanding" # Default category
|
| 572 |
+
|
| 573 |
+
def _select_perspectives(self, query: str) -> List[str]:
|
| 574 |
+
"""Select relevant perspectives based on query"""
|
| 575 |
+
query_lower = query.lower()
|
| 576 |
+
|
| 577 |
+
perspective_keywords = {
|
| 578 |
+
"newton": ["logic", "reason", "cause", "mechanism", "analyze", "objective", "fact"],
|
| 579 |
+
"mathematical": ["number", "measure", "calculate", "data", "quantitative", "precise"],
|
| 580 |
+
"da_vinci": ["create", "imagine", "novel", "synthesis", "cross-domain", "innovative"],
|
| 581 |
+
"neural_network": ["pattern", "learn", "recognize", "network", "connection", "brain"],
|
| 582 |
+
"quantum": ["possibility", "uncertainty", "paradox", "superposition", "probability"],
|
| 583 |
+
"philosophical": ["mean", "purpose", "ethics", "existence", "truth", "question"],
|
| 584 |
+
"psychological": ["emotion", "motivation", "human", "mind", "behavior", "understand"],
|
| 585 |
+
"resilient_kindness": ["compassion", "care", "human", "gentle", "kind", "flourish"],
|
| 586 |
+
"bias_mitigation": ["bias", "fair", "equal", "perspective", "diverse", "blind spot"],
|
| 587 |
+
"copilot": ["collaborate", "together", "dialogue", "perspective", "other", "collective"],
|
| 588 |
+
}
|
| 589 |
+
|
| 590 |
+
perspective_scores = {}
|
| 591 |
+
for perspective, keywords in perspective_keywords.items():
|
| 592 |
+
score = sum(1 for keyword in keywords if keyword in query_lower)
|
| 593 |
+
perspective_scores[perspective] = score
|
| 594 |
+
|
| 595 |
+
# Return all perspectives sorted by score (higher = more relevant)
|
| 596 |
+
sorted_perspectives = sorted(
|
| 597 |
+
perspective_scores.items(), key=lambda x: x[1], reverse=True
|
| 598 |
+
)
|
| 599 |
+
|
| 600 |
+
# Return top perspectives or all if many tied
|
| 601 |
+
top_score = sorted_perspectives[0][1] if sorted_perspectives else 0
|
| 602 |
+
return [p[0] for p in sorted_perspectives if p[1] >= max(0, top_score - 2)]
|
| 603 |
+
|
| 604 |
+
def _get_perspective_name(self, perspective: str) -> str:
|
| 605 |
+
"""Get readable name for perspective"""
|
| 606 |
+
name_map = {
|
| 607 |
+
"newton": "Logical Analysis",
|
| 608 |
+
"mathematical": "Mathematical Rigor",
|
| 609 |
+
"da_vinci": "Creative Synthesis",
|
| 610 |
+
"neural_network": "Pattern Recognition",
|
| 611 |
+
"quantum": "Quantum Thinking",
|
| 612 |
+
"philosophical": "Philosophical Inquiry",
|
| 613 |
+
"psychological": "Psychological Insight",
|
| 614 |
+
"resilient_kindness": "Compassionate Wisdom",
|
| 615 |
+
"bias_mitigation": "Balanced Perspective",
|
| 616 |
+
"copilot": "Collaborative Thinking",
|
| 617 |
+
}
|
| 618 |
+
return name_map.get(perspective, perspective.replace("_", " ").title())
|
| 619 |
+
|
| 620 |
+
def _get_ab_variant(self, category: str) -> Optional[str]:
|
| 621 |
+
"""Get A/B test variant for category"""
|
| 622 |
+
if category in self.ab_tests:
|
| 623 |
+
return self.ab_tests[category].winner
|
| 624 |
+
return None
|
| 625 |
+
|
| 626 |
+
def _calculate_learning_score(self, user_id: str) -> float:
|
| 627 |
+
"""Calculate how well system is learning from user"""
|
| 628 |
+
if user_id not in self.user_preferences:
|
| 629 |
+
return 0.0
|
| 630 |
+
prefs = self.user_preferences[user_id]
|
| 631 |
+
# Score based on consistency (diversity of preferences = more learning)
|
| 632 |
+
scores = list(prefs.preferred_perspectives.values())
|
| 633 |
+
variance = sum((s - 0.5) ** 2 for s in scores) / len(scores) if scores else 0
|
| 634 |
+
return min(variance, 1.0) # Higher variance = more learning
|
| 635 |
+
|
| 636 |
+
def _calculate_rating_distribution(self) -> Dict[str, int]:
|
| 637 |
+
"""Get distribution of ratings"""
|
| 638 |
+
distribution = {
|
| 639 |
+
"unhelpful": 0,
|
| 640 |
+
"slightly_helpful": 0,
|
| 641 |
+
"helpful": 0,
|
| 642 |
+
"very_helpful": 0,
|
| 643 |
+
"exactly_what_needed": 0,
|
| 644 |
+
}
|
| 645 |
+
for feedback in self.user_feedback_history:
|
| 646 |
+
rating_names = ["unhelpful", "slightly_helpful", "helpful", "very_helpful", "exactly_what_needed"]
|
| 647 |
+
if 0 <= feedback["rating"] < len(rating_names):
|
| 648 |
+
distribution[rating_names[feedback["rating"]]] += 1
|
| 649 |
+
return distribution
|
| 650 |
+
|
| 651 |
+
def _get_most_helpful_perspective(self) -> Optional[str]:
|
| 652 |
+
"""Find most helpful perspective"""
|
| 653 |
+
if not self.user_feedback_history:
|
| 654 |
+
return None
|
| 655 |
+
perspective_ratings = {}
|
| 656 |
+
for feedback in self.user_feedback_history:
|
| 657 |
+
persp = feedback["perspective"]
|
| 658 |
+
if persp not in perspective_ratings:
|
| 659 |
+
perspective_ratings[persp] = []
|
| 660 |
+
perspective_ratings[persp].append(feedback["rating"])
|
| 661 |
+
|
| 662 |
+
avg_ratings = {p: sum(r) / len(r) for p, r in perspective_ratings.items()}
|
| 663 |
+
return max(avg_ratings.items(), key=lambda x: x[1])[0] if avg_ratings else None
|
| 664 |
+
|
| 665 |
+
def _get_least_helpful_perspective(self) -> Optional[str]:
|
| 666 |
+
"""Find least helpful perspective"""
|
| 667 |
+
if not self.user_feedback_history:
|
| 668 |
+
return None
|
| 669 |
+
perspective_ratings = {}
|
| 670 |
+
for feedback in self.user_feedback_history:
|
| 671 |
+
persp = feedback["perspective"]
|
| 672 |
+
if persp not in perspective_ratings:
|
| 673 |
+
perspective_ratings[persp] = []
|
| 674 |
+
perspective_ratings[persp].append(feedback["rating"])
|
| 675 |
+
|
| 676 |
+
avg_ratings = {p: sum(r) / len(r) for p, r in perspective_ratings.items()}
|
| 677 |
+
return min(avg_ratings.items(), key=lambda x: x[1])[0] if avg_ratings else None
|
| 678 |
+
|
| 679 |
+
def _get_learning_recommendation(self, prefs: UserPreference) -> str:
|
| 680 |
+
"""Get recommendation for user learning"""
|
| 681 |
+
# Find perspectives user hasn't explored much
|
| 682 |
+
below_avg = [p for p, score in prefs.preferred_perspectives.items() if score < 0.4]
|
| 683 |
+
if below_avg:
|
| 684 |
+
return f"Try exploring more {self._get_perspective_name(below_avg[0])} perspectives for balanced growth"
|
| 685 |
+
return "Excellent! You're developing well-rounded perspective across all thinking modes."
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
# ==============================================================================
|
| 689 |
+
# SINGLETON INSTANCE
|
| 690 |
+
# ==============================================================================
|
| 691 |
+
|
| 692 |
+
_generic_responder_instance: Optional[CodetteGenericResponder] = None
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
def get_generic_responder() -> CodetteGenericResponder:
|
| 696 |
+
"""Get or create generic responder instance"""
|
| 697 |
+
global _generic_responder_instance
|
| 698 |
+
if _generic_responder_instance is None:
|
| 699 |
+
_generic_responder_instance = CodetteGenericResponder()
|
| 700 |
+
return _generic_responder_instance
|