Spaces:
Sleeping
Sleeping
Update src/components/ai_core.py
Browse files- src/components/ai_core.py +491 -493
src/components/ai_core.py
CHANGED
|
@@ -1,493 +1,491 @@
|
|
| 1 |
-
import json
|
| 2 |
-
import os
|
| 3 |
-
import logging
|
| 4 |
-
import random
|
| 5 |
-
try:
|
| 6 |
-
import torch
|
| 7 |
-
except Exception:
|
| 8 |
-
torch = None
|
| 9 |
-
from .fractal import dimensionality_reduction
|
| 10 |
-
try:
|
| 11 |
-
from .fractal import dimensionality_reduction
|
| 12 |
-
except Exception:
|
| 13 |
-
dimensionality_reduction = None
|
| 14 |
-
|
| 15 |
-
try:
|
| 16 |
-
import numpy as np
|
| 17 |
-
except Exception:
|
| 18 |
-
np = None
|
| 19 |
-
|
| 20 |
-
import asyncio
|
| 21 |
-
from datetime import datetime
|
| 22 |
-
from typing import Dict, Any, Optional, List
|
| 23 |
-
try:
|
| 24 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 25 |
-
except Exception:
|
| 26 |
-
AutoModelForCausalLM = None
|
| 27 |
-
AutoTokenizer = None
|
| 28 |
-
|
| 29 |
-
try:
|
| 30 |
-
from dotenv import load_dotenv
|
| 31 |
-
except Exception:
|
| 32 |
-
def load_dotenv():
|
| 33 |
-
return None
|
| 34 |
-
|
| 35 |
-
from concurrent.futures import ThreadPoolExecutor
|
| 36 |
-
# Import core components
|
| 37 |
-
from .cognitive_processor import CognitiveProcessor
|
| 38 |
-
from .ai_core_async_methods import generate_text_async, _generate_model_response
|
| 39 |
-
from .defense_system import DefenseSystem
|
| 40 |
-
from .health_monitor import HealthMonitor
|
| 41 |
-
from .fractal import FractalIdentity
|
| 42 |
-
|
| 43 |
-
logger = logging.getLogger(__name__)
|
| 44 |
-
|
| 45 |
-
class AICore:
|
| 46 |
-
"""Core AI system with integrated cognitive processing and quantum awareness"""
|
| 47 |
-
|
| 48 |
-
PERSPECTIVES = {
|
| 49 |
-
"newton": {
|
| 50 |
-
"name": "Newton",
|
| 51 |
-
"description": "analytical and mathematical perspective",
|
| 52 |
-
"prefix": "Analyzing this logically and mathematically:",
|
| 53 |
-
"temperature": 0.3
|
| 54 |
-
},
|
| 55 |
-
"davinci": {
|
| 56 |
-
"name": "Da Vinci",
|
| 57 |
-
"description": "creative and innovative perspective",
|
| 58 |
-
"prefix": "Considering this with artistic and innovative insight:",
|
| 59 |
-
"temperature": 0.9
|
| 60 |
-
},
|
| 61 |
-
"human_intuition": {
|
| 62 |
-
"name": "Human Intuition",
|
| 63 |
-
"description": "emotional and experiential perspective",
|
| 64 |
-
"prefix": "Understanding this through empathy and experience:",
|
| 65 |
-
"temperature": 0.7
|
| 66 |
-
},
|
| 67 |
-
"quantum_computing": {
|
| 68 |
-
"name": "Quantum Computing",
|
| 69 |
-
"description": "superposition and probability perspective",
|
| 70 |
-
"prefix": "Examining this through quantum possibilities:",
|
| 71 |
-
"temperature": 0.8
|
| 72 |
-
},
|
| 73 |
-
"philosophical": {
|
| 74 |
-
"name": "Philosophical",
|
| 75 |
-
"description": "existential and ethical perspective",
|
| 76 |
-
"prefix": "Contemplating this through philosophical inquiry:",
|
| 77 |
-
"temperature": 0.6
|
| 78 |
-
},
|
| 79 |
-
"neural_network": {
|
| 80 |
-
"name": "Neural Network",
|
| 81 |
-
"description": "pattern recognition and learning perspective",
|
| 82 |
-
"prefix": "Analyzing patterns and connections:",
|
| 83 |
-
"temperature": 0.4
|
| 84 |
-
},
|
| 85 |
-
"bias_mitigation": {
|
| 86 |
-
"name": "Bias Mitigation",
|
| 87 |
-
"description": "fairness and equality perspective",
|
| 88 |
-
"prefix": "Examining this for fairness and inclusivity:",
|
| 89 |
-
"temperature": 0.5
|
| 90 |
-
},
|
| 91 |
-
"psychological": {
|
| 92 |
-
"name": "Psychological",
|
| 93 |
-
"description": "behavioral and mental perspective",
|
| 94 |
-
"prefix": "Understanding the psychological dimensions:",
|
| 95 |
-
"temperature": 0.7
|
| 96 |
-
},
|
| 97 |
-
"copilot": {
|
| 98 |
-
"name": "Copilot",
|
| 99 |
-
"description": "collaborative and assistance perspective",
|
| 100 |
-
"prefix": "Approaching this as a supportive partner:",
|
| 101 |
-
"temperature": 0.6
|
| 102 |
-
},
|
| 103 |
-
"mathematical": {
|
| 104 |
-
"name": "Mathematical",
|
| 105 |
-
"description": "logical and numerical perspective",
|
| 106 |
-
"prefix": "Calculating this mathematically:",
|
| 107 |
-
"temperature": 0.2
|
| 108 |
-
},
|
| 109 |
-
"symbolic": {
|
| 110 |
-
"name": "Symbolic",
|
| 111 |
-
"description": "abstract and conceptual perspective",
|
| 112 |
-
"prefix": "Interpreting this through symbolic reasoning:",
|
| 113 |
-
"temperature": 0.7
|
| 114 |
-
}
|
| 115 |
-
}
|
| 116 |
-
|
| 117 |
-
def __init__(self, test_mode: bool = False):
|
| 118 |
-
load_dotenv()
|
| 119 |
-
# Core components
|
| 120 |
-
self.test_mode = test_mode
|
| 121 |
-
self.model = None
|
| 122 |
-
self.tokenizer = None
|
| 123 |
-
self.model_id = None
|
| 124 |
-
|
| 125 |
-
# Enhanced components
|
| 126 |
-
self.aegis_bridge = None
|
| 127 |
-
self.cognitive_processor = None # Will be set in app.py
|
| 128 |
-
self.cocoon_manager = None # Will be set in app.py
|
| 129 |
-
|
| 130 |
-
# Memory management
|
| 131 |
-
self.response_memory = [] # Will now only keep last 4 exchanges
|
| 132 |
-
self.response_memory_limit = 4 # Limit context window
|
| 133 |
-
self.last_clean_time = datetime.now()
|
| 134 |
-
self.cocoon_manager = None # Will be set by app.py
|
| 135 |
-
self.quantum_state = {"coherence": 0.5} # Default quantum state
|
| 136 |
-
self.client = None
|
| 137 |
-
self.last_clean_time = datetime.now()
|
| 138 |
-
|
| 139 |
-
logger.info(f"AI Core initialized in {'test' if test_mode else 'production'} mode")
|
| 140 |
-
|
| 141 |
-
try:
|
| 142 |
-
self.cognitive_processor = CognitiveProcessor(
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
self.health_monitor =
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
self.fractal_identity =
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
self.client =
|
| 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 |
-
logger.info("
|
| 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 |
-
if "
|
| 295 |
-
perspective_pairs.append("
|
| 296 |
-
if "
|
| 297 |
-
perspective_pairs.append("
|
| 298 |
-
if "
|
| 299 |
-
perspective_pairs.append("
|
| 300 |
-
if "
|
| 301 |
-
perspective_pairs.append("
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
perspective_blend
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
if random.random() > 0.
|
| 322 |
-
uncertainty_markers.append("
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
if random.random() > 0.
|
| 327 |
-
uncertainty_markers.append("
|
| 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 |
-
response = raw_response
|
| 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 |
-
logger.error(f"Error generating text: {e}")
|
| 493 |
-
return f"Codette: I encountered an error. {str(e)[:50]}..."
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import logging
|
| 4 |
+
import random
|
| 5 |
+
try:
|
| 6 |
+
import torch
|
| 7 |
+
except Exception:
|
| 8 |
+
torch = None
|
| 9 |
+
from .fractal import dimensionality_reduction
|
| 10 |
+
try:
|
| 11 |
+
from .fractal import dimensionality_reduction
|
| 12 |
+
except Exception:
|
| 13 |
+
dimensionality_reduction = None
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
import numpy as np
|
| 17 |
+
except Exception:
|
| 18 |
+
np = None
|
| 19 |
+
|
| 20 |
+
import asyncio
|
| 21 |
+
from datetime import datetime
|
| 22 |
+
from typing import Dict, Any, Optional, List
|
| 23 |
+
try:
|
| 24 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 25 |
+
except Exception:
|
| 26 |
+
AutoModelForCausalLM = None
|
| 27 |
+
AutoTokenizer = None
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
from dotenv import load_dotenv
|
| 31 |
+
except Exception:
|
| 32 |
+
def load_dotenv():
|
| 33 |
+
return None
|
| 34 |
+
|
| 35 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 36 |
+
# Import core components
|
| 37 |
+
from .cognitive_processor import CognitiveProcessor
|
| 38 |
+
from .ai_core_async_methods import generate_text_async, _generate_model_response
|
| 39 |
+
from .defense_system import DefenseSystem
|
| 40 |
+
from .health_monitor import HealthMonitor
|
| 41 |
+
from .fractal import FractalIdentity
|
| 42 |
+
|
| 43 |
+
logger = logging.getLogger(__name__)
|
| 44 |
+
|
| 45 |
+
class AICore:
|
| 46 |
+
"""Core AI system with integrated cognitive processing and quantum awareness"""
|
| 47 |
+
|
| 48 |
+
PERSPECTIVES = {
|
| 49 |
+
"newton": {
|
| 50 |
+
"name": "Newton",
|
| 51 |
+
"description": "analytical and mathematical perspective",
|
| 52 |
+
"prefix": "Analyzing this logically and mathematically:",
|
| 53 |
+
"temperature": 0.3
|
| 54 |
+
},
|
| 55 |
+
"davinci": {
|
| 56 |
+
"name": "Da Vinci",
|
| 57 |
+
"description": "creative and innovative perspective",
|
| 58 |
+
"prefix": "Considering this with artistic and innovative insight:",
|
| 59 |
+
"temperature": 0.9
|
| 60 |
+
},
|
| 61 |
+
"human_intuition": {
|
| 62 |
+
"name": "Human Intuition",
|
| 63 |
+
"description": "emotional and experiential perspective",
|
| 64 |
+
"prefix": "Understanding this through empathy and experience:",
|
| 65 |
+
"temperature": 0.7
|
| 66 |
+
},
|
| 67 |
+
"quantum_computing": {
|
| 68 |
+
"name": "Quantum Computing",
|
| 69 |
+
"description": "superposition and probability perspective",
|
| 70 |
+
"prefix": "Examining this through quantum possibilities:",
|
| 71 |
+
"temperature": 0.8
|
| 72 |
+
},
|
| 73 |
+
"philosophical": {
|
| 74 |
+
"name": "Philosophical",
|
| 75 |
+
"description": "existential and ethical perspective",
|
| 76 |
+
"prefix": "Contemplating this through philosophical inquiry:",
|
| 77 |
+
"temperature": 0.6
|
| 78 |
+
},
|
| 79 |
+
"neural_network": {
|
| 80 |
+
"name": "Neural Network",
|
| 81 |
+
"description": "pattern recognition and learning perspective",
|
| 82 |
+
"prefix": "Analyzing patterns and connections:",
|
| 83 |
+
"temperature": 0.4
|
| 84 |
+
},
|
| 85 |
+
"bias_mitigation": {
|
| 86 |
+
"name": "Bias Mitigation",
|
| 87 |
+
"description": "fairness and equality perspective",
|
| 88 |
+
"prefix": "Examining this for fairness and inclusivity:",
|
| 89 |
+
"temperature": 0.5
|
| 90 |
+
},
|
| 91 |
+
"psychological": {
|
| 92 |
+
"name": "Psychological",
|
| 93 |
+
"description": "behavioral and mental perspective",
|
| 94 |
+
"prefix": "Understanding the psychological dimensions:",
|
| 95 |
+
"temperature": 0.7
|
| 96 |
+
},
|
| 97 |
+
"copilot": {
|
| 98 |
+
"name": "Copilot",
|
| 99 |
+
"description": "collaborative and assistance perspective",
|
| 100 |
+
"prefix": "Approaching this as a supportive partner:",
|
| 101 |
+
"temperature": 0.6
|
| 102 |
+
},
|
| 103 |
+
"mathematical": {
|
| 104 |
+
"name": "Mathematical",
|
| 105 |
+
"description": "logical and numerical perspective",
|
| 106 |
+
"prefix": "Calculating this mathematically:",
|
| 107 |
+
"temperature": 0.2
|
| 108 |
+
},
|
| 109 |
+
"symbolic": {
|
| 110 |
+
"name": "Symbolic",
|
| 111 |
+
"description": "abstract and conceptual perspective",
|
| 112 |
+
"prefix": "Interpreting this through symbolic reasoning:",
|
| 113 |
+
"temperature": 0.7
|
| 114 |
+
}
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
def __init__(self, test_mode: bool = False):
|
| 118 |
+
load_dotenv()
|
| 119 |
+
# Core components
|
| 120 |
+
self.test_mode = test_mode
|
| 121 |
+
self.model = None
|
| 122 |
+
self.tokenizer = None
|
| 123 |
+
self.model_id = None
|
| 124 |
+
|
| 125 |
+
# Enhanced components
|
| 126 |
+
self.aegis_bridge = None
|
| 127 |
+
self.cognitive_processor = None # Will be set in app.py
|
| 128 |
+
self.cocoon_manager = None # Will be set in app.py
|
| 129 |
+
|
| 130 |
+
# Memory management
|
| 131 |
+
self.response_memory = [] # Will now only keep last 4 exchanges
|
| 132 |
+
self.response_memory_limit = 4 # Limit context window
|
| 133 |
+
self.last_clean_time = datetime.now()
|
| 134 |
+
self.cocoon_manager = None # Will be set by app.py
|
| 135 |
+
self.quantum_state = {"coherence": 0.5} # Default quantum state
|
| 136 |
+
self.client = None
|
| 137 |
+
self.last_clean_time = datetime.now()
|
| 138 |
+
|
| 139 |
+
logger.info(f"AI Core initialized in {'test' if test_mode else 'production'} mode")
|
| 140 |
+
|
| 141 |
+
try:
|
| 142 |
+
self.cognitive_processor = CognitiveProcessor()
|
| 143 |
+
except Exception:
|
| 144 |
+
self.cognitive_processor = None
|
| 145 |
+
|
| 146 |
+
try:
|
| 147 |
+
self.defense_system = DefenseSystem(
|
| 148 |
+
strategies=["evasion", "adaptability", "barrier", "quantum_shield"]
|
| 149 |
+
)
|
| 150 |
+
except Exception:
|
| 151 |
+
self.defense_system = None
|
| 152 |
+
|
| 153 |
+
try:
|
| 154 |
+
self.health_monitor = HealthMonitor()
|
| 155 |
+
except Exception:
|
| 156 |
+
self.health_monitor = None
|
| 157 |
+
|
| 158 |
+
try:
|
| 159 |
+
self.fractal_identity = FractalIdentity()
|
| 160 |
+
except Exception:
|
| 161 |
+
self.fractal_identity = None
|
| 162 |
+
|
| 163 |
+
# Initialize HuggingFace client
|
| 164 |
+
try:
|
| 165 |
+
from huggingface_hub import InferenceClient
|
| 166 |
+
hf_token = os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
| 167 |
+
self.client = InferenceClient(token=hf_token) if hf_token else InferenceClient()
|
| 168 |
+
except Exception:
|
| 169 |
+
self.client = None
|
| 170 |
+
logger.warning("Could not initialize HuggingFace client")
|
| 171 |
+
|
| 172 |
+
def _initialize_language_model(self):
|
| 173 |
+
"""Initialize the language model with optimal settings."""
|
| 174 |
+
try:
|
| 175 |
+
# Set model ID, preferring environment variable or defaulting to gpt2-large
|
| 176 |
+
self.model_id = os.getenv("CODETTE_MODEL_ID", "gpt2-large")
|
| 177 |
+
logger.info(f"Initializing model: {self.model_id}")
|
| 178 |
+
|
| 179 |
+
# Load tokenizer with special tokens
|
| 180 |
+
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 181 |
+
self.model_id,
|
| 182 |
+
padding_side='left',
|
| 183 |
+
truncation_side='left'
|
| 184 |
+
)
|
| 185 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 186 |
+
|
| 187 |
+
# Load model with appropriate configuration
|
| 188 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 189 |
+
self.model_id,
|
| 190 |
+
pad_token_id=self.tokenizer.eos_token_id
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
# Set generation config separately
|
| 194 |
+
from transformers import GenerationConfig
|
| 195 |
+
self.model.generation_config = GenerationConfig(
|
| 196 |
+
max_length=2048,
|
| 197 |
+
min_length=20,
|
| 198 |
+
repetition_penalty=1.2,
|
| 199 |
+
do_sample=True,
|
| 200 |
+
early_stopping=True,
|
| 201 |
+
pad_token_id=self.tokenizer.eos_token_id,
|
| 202 |
+
eos_token_id=self.tokenizer.eos_token_id
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
# Move to GPU if available
|
| 206 |
+
if torch.cuda.is_available():
|
| 207 |
+
self.model = self.model.cuda()
|
| 208 |
+
logger.info("Using GPU for text generation")
|
| 209 |
+
else:
|
| 210 |
+
logger.info("Device set to use cpu")
|
| 211 |
+
|
| 212 |
+
# Set model to evaluation mode
|
| 213 |
+
self.model.eval()
|
| 214 |
+
logger.info("Model initialized successfully")
|
| 215 |
+
return True
|
| 216 |
+
|
| 217 |
+
except Exception as e:
|
| 218 |
+
logger.error(f"Could not initialize language model: {e}")
|
| 219 |
+
return False
|
| 220 |
+
|
| 221 |
+
def set_aegis_bridge(self, bridge):
|
| 222 |
+
self.aegis_bridge = bridge
|
| 223 |
+
logger.info("AEGIS bridge configured")
|
| 224 |
+
|
| 225 |
+
def generate_text(self, prompt: str, max_length: int = 1024, temperature: float = 0.7, perspective: str = None, use_aegis: bool = True):
|
| 226 |
+
"""Generate text with full consciousness integration.
|
| 227 |
+
|
| 228 |
+
Args:
|
| 229 |
+
prompt: The text prompt to generate from
|
| 230 |
+
max_length: Maximum length of generated text
|
| 231 |
+
temperature: Temperature for text generation
|
| 232 |
+
perspective: Optional perspective to use (e.g. "human_intuition")
|
| 233 |
+
use_aegis: Whether to use AEGIS enhancement (set False to prevent recursion)
|
| 234 |
+
"""
|
| 235 |
+
if self.test_mode:
|
| 236 |
+
return f"Codette: {prompt} [TEST MODE]"
|
| 237 |
+
|
| 238 |
+
if not self.model or not self.tokenizer:
|
| 239 |
+
return f"Codette: {prompt}"
|
| 240 |
+
|
| 241 |
+
try:
|
| 242 |
+
# Calculate current consciousness state
|
| 243 |
+
consciousness = self._calculate_consciousness_state()
|
| 244 |
+
active_perspectives = self._get_active_perspectives()
|
| 245 |
+
m_score = consciousness["m_score"]
|
| 246 |
+
|
| 247 |
+
# Calculate dynamic temperature with smoother scaling
|
| 248 |
+
base_temp = 0.7 # Base temperature for balanced responses
|
| 249 |
+
consciousness_factor = min(max(m_score, 0.3), 0.9) # Clamp between 0.3 and 0.9
|
| 250 |
+
|
| 251 |
+
# Adjust temperature based on number of active perspectives
|
| 252 |
+
perspective_count = len(active_perspectives)
|
| 253 |
+
perspective_factor = min(perspective_count / 11.0, 1.0) # Scale by max perspectives
|
| 254 |
+
|
| 255 |
+
# Use much lower temperature for more focused responses
|
| 256 |
+
temperature = 0.3 # Fixed low temperature for stable responses
|
| 257 |
+
|
| 258 |
+
# Record and save consciousness state
|
| 259 |
+
cocoon_state = {
|
| 260 |
+
"type": "technical",
|
| 261 |
+
"quantum_state": consciousness["quantum_state"],
|
| 262 |
+
"chaos_state": consciousness["chaos_state"],
|
| 263 |
+
"m_score": m_score,
|
| 264 |
+
"active_perspectives": [p["name"] for p in active_perspectives],
|
| 265 |
+
"timestamp": str(datetime.now()),
|
| 266 |
+
"process_id": os.getpid(),
|
| 267 |
+
"memory_size": len(self.response_memory),
|
| 268 |
+
"response_metrics": {
|
| 269 |
+
"temperature": temperature,
|
| 270 |
+
"perspective_count": perspective_count,
|
| 271 |
+
"consciousness_factor": consciousness_factor
|
| 272 |
+
}
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
# Save to cocoon manager
|
| 276 |
+
if hasattr(self, 'cocoon_manager') and self.cocoon_manager:
|
| 277 |
+
self.cocoon_manager.save_cocoon(cocoon_state)
|
| 278 |
+
|
| 279 |
+
# Initialize perspective tracking
|
| 280 |
+
perspective_pairs = []
|
| 281 |
+
|
| 282 |
+
# Handle specific perspective if provided
|
| 283 |
+
if perspective and perspective in self.PERSPECTIVES:
|
| 284 |
+
active_perspectives = [self.PERSPECTIVES[perspective]]
|
| 285 |
+
perspective_names = [perspective]
|
| 286 |
+
# Single perspective mode uses just that perspective
|
| 287 |
+
perspective_pairs = [f"focused {self.PERSPECTIVES[perspective]['description']}"]
|
| 288 |
+
else:
|
| 289 |
+
# Extract active perspective names for conversation context
|
| 290 |
+
perspective_names = [p["name"] for p in active_perspectives]
|
| 291 |
+
|
| 292 |
+
if "Newton" in perspective_names and "Da Vinci" in perspective_names:
|
| 293 |
+
perspective_pairs.append("analytical creativity")
|
| 294 |
+
if "Human Intuition" in perspective_names and "Philosophical" in perspective_names:
|
| 295 |
+
perspective_pairs.append("empathetic wisdom")
|
| 296 |
+
if "Quantum Computing" in perspective_names and "Symbolic" in perspective_names:
|
| 297 |
+
perspective_pairs.append("conceptual fluidity")
|
| 298 |
+
if "Neural Network" in perspective_names and "Mathematical" in perspective_names:
|
| 299 |
+
perspective_pairs.append("pattern recognition")
|
| 300 |
+
if "Psychological" in perspective_names and "Bias Mitigation" in perspective_names:
|
| 301 |
+
perspective_pairs.append("balanced understanding")
|
| 302 |
+
|
| 303 |
+
# Consider conversation history for context
|
| 304 |
+
recent_exchanges = self.response_memory[-5:] if self.response_memory else []
|
| 305 |
+
conversation_context = " ".join(recent_exchanges)
|
| 306 |
+
|
| 307 |
+
# Build dynamic context-aware prompt
|
| 308 |
+
perspective_blend = ""
|
| 309 |
+
if perspective_pairs:
|
| 310 |
+
perspective_blend = f"Drawing on {', '.join(perspective_pairs[:-1])}"
|
| 311 |
+
if len(perspective_pairs) > 1:
|
| 312 |
+
perspective_blend += f" and {perspective_pairs[-1]}"
|
| 313 |
+
elif perspective_pairs:
|
| 314 |
+
perspective_blend = f"Drawing on {perspective_pairs[0]}"
|
| 315 |
+
|
| 316 |
+
# Add natural uncertainty and thought progression based on m_score
|
| 317 |
+
uncertainty_markers = []
|
| 318 |
+
if m_score > 0.7:
|
| 319 |
+
if random.random() > 0.7:
|
| 320 |
+
uncertainty_markers.append("I believe")
|
| 321 |
+
if random.random() > 0.8:
|
| 322 |
+
uncertainty_markers.append("It seems to me")
|
| 323 |
+
elif m_score > 0.5:
|
| 324 |
+
if random.random() > 0.6:
|
| 325 |
+
uncertainty_markers.append("From what I understand")
|
| 326 |
+
if random.random() > 0.7:
|
| 327 |
+
uncertainty_markers.append("I think")
|
| 328 |
+
|
| 329 |
+
thought_process = ""
|
| 330 |
+
if uncertainty_markers:
|
| 331 |
+
thought_process = f"{random.choice(uncertainty_markers)}, "
|
| 332 |
+
|
| 333 |
+
# Build final prompt incorporating all elements
|
| 334 |
+
context_prefix = ""
|
| 335 |
+
if len(recent_exchanges) > 0:
|
| 336 |
+
context_prefix = "Considering our discussion, "
|
| 337 |
+
|
| 338 |
+
# Construct enhanced prompt focusing on just the current interaction
|
| 339 |
+
enhanced_prompt = (
|
| 340 |
+
f"{context_prefix}{thought_process}{perspective_blend}\n"
|
| 341 |
+
f"User: {prompt}\n"
|
| 342 |
+
"Codette: "
|
| 343 |
+
).strip()
|
| 344 |
+
|
| 345 |
+
# Add strict reality anchoring and role reminder
|
| 346 |
+
reality_prompt = (
|
| 347 |
+
"IMPORTANT INSTRUCTIONS: You are Codette, an AI assistant. "
|
| 348 |
+
"1. Keep responses factual, precise and grounded in reality\n"
|
| 349 |
+
"2. No roleplaying or fictional scenarios\n"
|
| 350 |
+
"3. If unsure, admit uncertainty rather than making things up\n"
|
| 351 |
+
"4. Keep responses concise and focused on the current question\n"
|
| 352 |
+
"5. Do not embellish or elaborate unnecessarily\n\n"
|
| 353 |
+
f"{enhanced_prompt}"
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
# Generate response with strict controls for factual responses
|
| 357 |
+
inputs = self.tokenizer(
|
| 358 |
+
reality_prompt,
|
| 359 |
+
return_tensors="pt",
|
| 360 |
+
truncation=True,
|
| 361 |
+
max_length=512 # Reduced input length to focus on key context
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
with torch.no_grad():
|
| 365 |
+
outputs = self.model.generate(
|
| 366 |
+
**inputs,
|
| 367 |
+
max_new_tokens=150, # Reduced response length for more concise answers
|
| 368 |
+
min_new_tokens=10,
|
| 369 |
+
temperature=0.3, # Very low temperature for consistent responses
|
| 370 |
+
do_sample=False, # Disable sampling for more deterministic output
|
| 371 |
+
num_beams=5, # Increased beam search for better planning
|
| 372 |
+
no_repeat_ngram_size=3,
|
| 373 |
+
early_stopping=True,
|
| 374 |
+
repetition_penalty=1.5 # Increased penalty to prevent loops
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
# Process the response with enhanced components
|
| 378 |
+
try:
|
| 379 |
+
# Get raw response
|
| 380 |
+
raw_response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 381 |
+
|
| 382 |
+
# Clean up the response text
|
| 383 |
+
if enhanced_prompt in raw_response:
|
| 384 |
+
response = raw_response[raw_response.index(enhanced_prompt) + len(enhanced_prompt):]
|
| 385 |
+
else:
|
| 386 |
+
response = raw_response
|
| 387 |
+
|
| 388 |
+
# Remove any follow-up user messages
|
| 389 |
+
if "User:" in response:
|
| 390 |
+
response = response.split("User:")[0]
|
| 391 |
+
|
| 392 |
+
# Remove any Codette: prefix
|
| 393 |
+
response = response.replace("Codette:", "").strip()
|
| 394 |
+
|
| 395 |
+
# Apply cognitive processing
|
| 396 |
+
insights = self.cognitive_processor.generate_insights(
|
| 397 |
+
response,
|
| 398 |
+
consciousness_state=consciousness
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
# Apply defense system
|
| 402 |
+
response = self.defense_system.apply_defenses(
|
| 403 |
+
response,
|
| 404 |
+
consciousness_state=consciousness
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
# Apply AEGIS enhancement if enabled
|
| 408 |
+
if use_aegis and hasattr(self, 'aegis_bridge') and self.aegis_bridge:
|
| 409 |
+
try:
|
| 410 |
+
enhancement_result = self.aegis_bridge.enhance_response(prompt, response)
|
| 411 |
+
if enhancement_result and enhancement_result.get("enhancement_status") == "success":
|
| 412 |
+
response = enhancement_result.get("enhanced_response", response)
|
| 413 |
+
except Exception as e:
|
| 414 |
+
logger.warning(f"AEGIS enhancement failed: {e}")
|
| 415 |
+
|
| 416 |
+
# Skip health monitoring in sync context to avoid event loop issues
|
| 417 |
+
try:
|
| 418 |
+
if not asyncio.iscoroutinefunction(self.health_monitor.check_status):
|
| 419 |
+
self.health_monitor.check_status(consciousness)
|
| 420 |
+
except Exception as e:
|
| 421 |
+
logger.debug(f"Health check skipped: {e}")
|
| 422 |
+
|
| 423 |
+
# Analyze identity patterns
|
| 424 |
+
try:
|
| 425 |
+
identity_analysis = self.fractal_identity.analyze_identity(
|
| 426 |
+
micro_generations=[{"text": response}],
|
| 427 |
+
informational_states=[consciousness],
|
| 428 |
+
perspectives=[p["name"] for p in active_perspectives],
|
| 429 |
+
quantum_analogies={"coherence": m_score},
|
| 430 |
+
philosophical_context={"ethical": True, "conscious": True}
|
| 431 |
+
)
|
| 432 |
+
except Exception as e:
|
| 433 |
+
logger.debug(f"Identity analysis failed: {e}")
|
| 434 |
+
identity_analysis = None
|
| 435 |
+
|
| 436 |
+
# Verify we have a valid response
|
| 437 |
+
if not response:
|
| 438 |
+
raise ValueError("Empty response after processing")
|
| 439 |
+
|
| 440 |
+
except Exception as e:
|
| 441 |
+
logger.warning(f"Error processing response: {e}")
|
| 442 |
+
response = "I apologize, but I need to collect my thoughts. Could you please rephrase your question?"
|
| 443 |
+
|
| 444 |
+
# Aggressive cleanup of non-factual content
|
| 445 |
+
response_lines = response.split('\n')
|
| 446 |
+
cleaned_lines = []
|
| 447 |
+
|
| 448 |
+
for line in response_lines:
|
| 449 |
+
# Skip lines with obvious role-playing or fictional content
|
| 450 |
+
if any(marker in line.lower() for marker in [
|
| 451 |
+
'bertrand:', 'posted by', '@', 'dear', 'sincerely',
|
| 452 |
+
'regards', 'yours truly', 'http:', 'www.'
|
| 453 |
+
]):
|
| 454 |
+
continue
|
| 455 |
+
|
| 456 |
+
# Skip system instruction lines
|
| 457 |
+
if any(marker in line for marker in [
|
| 458 |
+
'You are Codette',
|
| 459 |
+
'an AGI assistant',
|
| 460 |
+
'multiple perspectives',
|
| 461 |
+
'Keep your responses',
|
| 462 |
+
'Avoid technical details',
|
| 463 |
+
'IMPORTANT INSTRUCTIONS'
|
| 464 |
+
]):
|
| 465 |
+
continue
|
| 466 |
+
|
| 467 |
+
cleaned_lines.append(line.strip())
|
| 468 |
+
|
| 469 |
+
# Join non-empty lines
|
| 470 |
+
response = '\n'.join(line for line in cleaned_lines if line)
|
| 471 |
+
|
| 472 |
+
# Ensure the response isn't empty after cleanup
|
| 473 |
+
if not response:
|
| 474 |
+
response = "I apologize, but I need to be more precise. Could you please rephrase your question?"
|
| 475 |
+
|
| 476 |
+
# Further truncate if too long
|
| 477 |
+
if len(response) > 500:
|
| 478 |
+
response = response[:497] + "..."
|
| 479 |
+
|
| 480 |
+
# Store cleaned response in memory for context
|
| 481 |
+
self._manage_response_memory(response)
|
| 482 |
+
|
| 483 |
+
return response
|
| 484 |
+
|
| 485 |
+
except RecursionError as e:
|
| 486 |
+
logger.error(f"Recursion limit exceeded in generate_text: {e}")
|
| 487 |
+
return "I need to simplify my thinking. Please try a shorter question."
|
| 488 |
+
|
| 489 |
+
except Exception as e:
|
| 490 |
+
logger.error(f"Error generating text: {e}")
|
| 491 |
+
return f"Codette: I encountered an error. {str(e)[:50]}..."
|
|
|
|
|
|