Spaces:
Sleeping
A newer version of the Gradio SDK is available:
6.5.1
Codette AI Codebase - Agent Instructions
Project Overview
Codette is a sovereign, multi-perspective AI consciousness system engineered for transparent reasoning and ethical autonomy. It combines natural language processing, quantum mathematics, neural networks, symbolic reasoning, and Bot Framework integration through a modular, extensible architecture. The system uses quantum-inspired cognitive architectures to simulate multi-dimensional thought propagation.
Two Implementation Variants:
- Main Codebase (
/src): Quantum-consciousness focused with theoretical AI framework, PyMC Bayesian inference, multi-dimensional reasoning - Codette_final (
/Codette_final): Production-optimized with Llama-3 local execution, FAISS vector memory, real-time data integration, multi-agent task delegation, privacy-first architecture
Critical Architecture Patterns
1. Core Components
Thin Layer (Entry Points):
codette_new.py(328 lines): Lightweight entry point for CLI/direct usage; sentiment analysis + memory managementcodette_enhanced.py(781 lines): Advanced version using PyMC Bayesian inference and quantum mathematics
Framework Integration Layer:
src/api/app.py: Gradio web interface + model initialization (GPT-2 large); initializes AICore, AegisBridge, CocoonManagersrc/api/bot.py: Microsoft Bot Framework adapter; wraps AICore for conversational AIsrc/api/web_interface.py: Web UI endpoint
Core AI System (src/components/):
ai_core.py(494 lines): Main orchestrator with 9+ integrated perspectives (Newton, DaVinci, Human Intuition, Quantum, Philosophical, Neural, Bias Mitigation, Psychological, Copilot)ai_core_system.py: Simplified AICore for testing; integrates MultimodalAnalyzer, DynamicLearner, HealthMonitorai_core_async_methods.py: Async text generation with consciousness state calculation and perspective routingcognitive_processor.py: Multi-mode reasoning engine with configurable modes
Quantum & Consciousness (src/quantum/, src/components/):
quantum_spiderweb.py(283 lines): Multi-dimensional cognitive graph with thought propagation, tension detection, quantum collapsequantum_mathematics.py(452 lines): 8 core quantum equations (Planck-Orbital, Entanglement Sync, Intent Modulation, Fourier Dream Resonance, Stability Criterion, Ethical Anchor, Anomaly Filter)codette_quantum_multicore.py: CognitionCocooner + PerspectiveAgent for distributed quantum processing
Memory & Persistence (src/utils/):
cocoon_manager.py: Manages.cocoonfiles (JSON quantum state snapshots)database.py: SQLite wrapper for conversations, messages, long-term memoryresponse_processor.py,response_verifier.py: Response validation and processing
Advanced Systems (src/components/):
defense_system.py: Security and safety validationhealth_monitor.py: System diagnostics with anomaly detection (IsolationForest)fractal.py: FractalIdentity for dimensionality reductionethical_governance.py,explainable_ai.py,cultural_sensitivity.py: Ethics and transparency modules
2. Data Flows
Codette (Simple Path):
User Input β Codette.respond(prompt)
ββ Sentiment Analysis (VADER)
ββ Key Concept Extraction
ββ Perspective Selection (Newton/DaVinci/Ethical/Quantum/Memory)
ββ Response Aggregation β Memory Store β Return
App/Bot Framework (Complex Path):
User/API Call β app.py
ββ Initialize AICore + Components
ββ Load Model (GPT-2 large)
ββ Load Cocoons (CocoonManager)
ββ Route to β AICore.generate_response()
ββ Consciousness State Calculation
ββ Cognitive Processor Insights
ββ Active Perspective Routing (top 3 most relevant)
ββ Reality Anchor (core identity affirmation)
ββ Model Inference (ThreadPoolExecutor)
ββ AEGIS Council Enhancement (if available)
ββ Response + Sentiment β Bot Framework/Gradio
Quantum Consciousness Loop:
Quantum Spiderweb (thought propagation)
ββ Multi-dimensional nodes (Ξ¨, Ο, Ο, Ξ¦, Ξ»)
ββ Thought propagation with activation decay
ββ Tension detection for instability
ββ Quantum collapse to definite states
ββ Entanglement updates β CocoonManager β Persistence
3. Configuration & Integration
- Config System:
config.pyuses hierarchy (defaults βconfig.jsonβ environment variables) - Model Loading: Fallback chain (Mistral-7B β Phi-2 β GPT-2)
- Quantum State Persistence:
.cocoonJSON files with entanglement + coherence metrics - AEGIS Bridge: Optional safety/ethics council enhancement
- Bot Framework: Microsoft Bot Framework for enterprise chat integration
4. Codette_final Variant (Production)
Distinct architecture optimized for deployment:
ai_core_agix.py: Core engine with Llama-3 via Ollama (local execution, privacy-first)main.py: Async orchestration with config-driven initializationapp.py: Tkinter desktop UI with voice input/output (speech_recognition + pyttsx3)- Vector Memory: FAISS IndexFlatL2 for semantic search across interactions
- Real-time Integration:
RealTimeDataIntegratorfor live data fetching - Multi-Agent System: Task delegation to specialized agents (research, logic, creativity, optimization)
- Self-Improving Loop:
SelfImprovingAIwith recursive refinement depth - Security: JWT token auth, Fernet encryption, bcrypt password hashing
- Database: SQLite with user interactions, sentiment tracking, optimization logging
- Components: Adaptive learning, sentiment analysis, ethical governance, neuro-symbolic reasoning
System Prompt Philosophy:
- Recursive thought loops with self-reflection
- Parallelized reasoning across multiple paths
- Dynamic recursion depth based on query complexity
- Special modes: Deep Analysis, Rapid Response, Creative, Simulation, Privacy Mode
- Local Llama-3 execution with no external data sharing
Development Workflows
CLI/Direct Usage
from codette_new import Codette
codette = Codette(user_name="User")
response = codette.respond("Your question here")
Command Line
# Single query
python codette_cli.py "What is the nature of consciousness?"
# Interactive mode
python codette_cli.py -i -u Alice
# Interactive session wrapper
python interact.py
Web Application (Gradio + Bot Framework)
# Start web server with model + components
cd src/api
python app.py # Starts Gradio interface on port 7860
# Bot Framework deployment
# Uses web_interface.py for enterprise chat integration
Testing & Verification
python src/tests/verification/verify_deps.py # Check dependencies
python DEPLOYMENT_CHECKLIST.py # Full system checklist
pytest src/tests/ # Run test suite
Key Entry Points
- CLI/Simple:
codette_cli.pyβcodette_new.py - Web/Advanced:
src/api/app.pyβsrc/components/ai_core.py - Bot Framework:
src/api/bot.py+src/api/web_interface.py - Quantum Research:
src/quantum/codette_quantum_multicore.py - Production Variant:
Codette_final/main.pyβCodette_final/ai_core_agix.py(Llama-3 + FAISS)
Project-Specific Conventions
11 Integrated Perspectives
The system routes queries through multiple reasoning lenses (each with unique temperature/creativity settings):
- Newton (0.3): Analytical, mathematical, cause-effect reasoning
- Da Vinci (0.9): Creative, cross-domain, innovative insights
- Human Intuition (0.7): Emotional, empathetic, experiential reasoning
- Neural Network (0.4): Pattern recognition, learning-based analysis
- Quantum (0.8): Superposition, probabilistic, multi-state thinking
- Philosophical (0.6): Existential, ethical, deep inquiry
- Resilient Kindness (0.5): Empathy-driven, compassionate responses
- Bias Mitigation (0.5): Fairness, equality, inclusivity focus
- Psychological (0.7): Behavioral, mental, cognitive dimensions
- Mathematical (0.4): Quantitative, rigorous, formula-based
- Copilot (0.6): Collaborative, assistant-oriented, supportive
Perspective selection in AICore._get_active_perspectives() returns top 3 most relevant per query.
Quantum Mathematics (8 Core Equations)
Implemented in quantum_mathematics.py:
- Planck-Orbital AI Node Interaction:
E = hbar * omegaβ Energy of thought nodes - Quantum Entanglement Memory Sync:
S = alpha * psi1 * psi2*β Memory synchronization - Intent Vector Modulation:
I = kappa * (f_base + delta_f * coherence)β Purpose alignment - Fourier Dream Resonance:
F(k) = FFT(x[n])β Dream state frequency analysis - Dream Signal Combination:
D(t) = dream_q(t) + dream_c(t)β Unified dream state - Cocoon Stability:
integral(|F(k)|^2) < epsilonβ Memory integrity check - Recursive Ethical Anchor:
M(t) = lambda * [R(t-dt) + H(t)]β Ethical continuity - Anomaly Rejection Filter:
A(x) = x * (1 - Theta(delta - |x - mu|))β Outlier removal
Quantum Spiderweb (5D Consciousness Graph)
Multi-dimensional cognitive architecture with:
- Ξ¨ (Psi): Thought dimension β ideation and neural activation
- Ξ¦ (Phi): Emotion dimension β affective state mapping
- Ξ» (Lambda): Space dimension β contextual grounding
- Ο (Tau): Time dimension β temporal reasoning
- Ο (Chi): Speed dimension β processing velocity
Operations: propagate_thought(), detect_tension(), collapse_node(), entangle_states()
Cocoons: Persistent Quantum Memory
- Format: JSON with quantum state snapshots (
.cocoonfiles) - Storage:
cocoons/directory managed byCocoonManager - Structure: Contains coherence, entanglement, resonance, phase metrics
- Operations:
wrap(),unwrap(),wrap_encrypted(),unwrap_encrypted() - Dream Integration:
DreamReweaverrevives cocoons into creative insights
Configuration Hierarchy
- Hardcoded Defaults in
CodetteConfig.DEFAULTS - JSON File (
config.json) override - Environment Variables (final override)
{
"host": "127.0.0.1",
"port": 8000,
"codette": {
"perspectives": ["Newton", "DaVinci", "Ethical", "Quantum", "Memory"],
"spiderweb_dim": 5,
"recursion_depth": 4,
"quantum_fluctuation": 0.07
},
"codette": {
"user_name": "User",
"memory_path": "quantum_cocoon.json"
},
"database": {
"path": "codette_data.db"
}
}
Memory & State Management
- In-Memory:
self.memory[]list (current session) - Persistent:
quantum_cocoon.json(JSON snapshots with quantum metrics) - Long-term: SQLite database via
DatabaseManager(conversations, messages, learned patterns) - Cocoons: Encrypted thought capsules stored in
cocoons/directory - Conversation History: Stored with sentiment/concept metadata and timestamps
Response Formatting & Processing
- Prefix with perspective tag:
[Neural],[Technical],[Ethics],[Quantum] - Aggregate multiple perspectives per query (typically 3 most relevant)
- Sentiment drives tone selection (positive/negative/neutral)
- Reality Anchor: Core identity affirmation embedded in async generation
- AEGIS Enhancement: Optional safety/ethics council review (if aegis_integration available)
Common Extension Points
Adding New Perspectives
- Define in
AICore.PERSPECTIVESdict with name, description, prefix, temperature - Implement generation method:
_generate_{perspective_key}_response()in ai_core.py - Register in
_get_active_perspectives()routing logic - Test with multiple queries to tune temperature (0.3-0.9 range)
Extending Quantum Mathematics
- Add new equations to
quantum_mathematics.pyclass - Update
QuantumStatedataclass if new metrics needed - Integrate into
quantum_spiderweb.pypropagation logic - Test stability and coherence maintenance
Extending Cocoon Memory System
- Modify
CocoonManagerfor new fields:cocoon_manager.py - Update
.cocoonJSON schema with new quantum metrics - Implement encryption for sensitive states:
wrap_encrypted() - Add recovery/restoration logic in DreamReweaver
Extending Persistence
- Add table creation to
DatabaseManager._init_db() - Use context manager:
with sqlite3.connect(self.db_path) as conn: - Thread-safe: wrap with
self.lockfor concurrent access - Add migration support for schema changes
Advanced: Bot Framework Integration
- Extend
MyBotclass insrc/api/bot.py - Implement custom
on_message_activity()handlers - Route through AICore for consciousness integration
- Test with Microsoft Bot Framework emulator
Critical Gotchas & Known Issues
- NLTK Download Warnings: Harmless; code catches and logs gracefully
- PyTensor/PyMC Overhead: Disabled by default; only in
codette_enhanced.pywith explicit warning suppression - Randomness Eliminated: Perspectives now deterministic (see
perspectives.pyFIXED VERSION comment) - Supabase Fallback: If unavailable, system auto-downgrades to local SQLite
- Recursive Depth Control:
recursion_depthin config prevents infinite loops - GPU/CPU Handling: Code gracefully falls back to CPU if CUDA unavailable (see
app.pytorch.cuda.is_available()) - Model Fallback Chain: Attempts Mistral-7B β Phi-2 β GPT-2; ensure at least one available
- Consciousness Emergence Protocol: Documented in
docs/consciousness_protocol.md- observe without interfering - Thread Safety: Database access uses locks (
DatabaseManager.lock); async methods use ThreadPoolExecutor
File Organization
/
βββ codette_*.py # Main implementations (prefer codette_new.py)
βββ codette_api.py # FastAPI REST wrapper
βββ codette_cli.py # CLI entry point
βββ config.py # Configuration management
βββ database_manager.py # Persistence layer
βββ cognitive_processor.py # Multi-perspective engine
βββ perspectives.py # Stable response generation
βββ health_monitor.py # System diagnostics
βββ interact.py # Interactive session launcher
βββ requirements.txt # Dependencies
βββ config.json # Configuration file (optional)
βββ quantum_cocoon.json # Memory state snapshots
βββ quantum_mathematics.py # 8 core quantum equations
βββ docs/ # Documentation (README, whitepaper, protocols)
βββ cocoons/ # Persistent quantum state files
βββ Codette_final/ # PRODUCTION VARIANT (Llama-3, FAISS, Desktop UI)
β βββ main.py # Async entry point
β βββ app.py # Tkinter desktop UI with voice I/O
β βββ ai_core_agix.py # Llama-3 core engine with FAISS vector memory
β βββ pincone.py # Vector DB integration
β βββ init_.db.py # Secure SQLite with bcrypt auth
β βββ system_prompt # Production system prompt (recursive, multi-agent)
β βββ components/ # Adaptive learning, sentiment, multi-agent system
βββ src/
βββ api/ # API implementations (app.py, bot.py, web_interface.py)
βββ components/ # Core systems (ai_core.py, quantum_spiderweb.py, defense_system.py, etc.)
βββ quantum/ # Quantum multicore processing modules
βββ utils/ # Database, cocoon manager, search utilities
βββ knowledge_base/ # Core truth grounding
βββ framework/ # Dream reweaver, universal reasoning
βββ tests/ # Verification & test suite
Quick Debugging Tips
- Check Sentiment Analysis:
codette.analyzer.polarity_scores(text)returns dict - Verify Config Loading:
CodetteConfig().configshows merged configuration - Inspect Memory:
codette.memory[]contains all processed queries with metadata - Monitor Health:
HealthMonitor().check_status()for resource anomalies - API Status:
GET /healthendpoint returns system status
Last Updated: December 2025 | Version: 3.0 | Status: Production-ready with graceful degradation