Update app.py
Browse files
app.py
CHANGED
|
@@ -18,7 +18,7 @@ def init_discourse_database():
|
|
| 18 |
conn = sqlite3.connect('discourse.db', check_same_thread=False)
|
| 19 |
c = conn.cursor()
|
| 20 |
|
| 21 |
-
#
|
| 22 |
c.execute('''CREATE TABLE IF NOT EXISTS discourse
|
| 23 |
(id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 24 |
agent TEXT NOT NULL,
|
|
@@ -27,14 +27,36 @@ def init_discourse_database():
|
|
| 27 |
token_count INTEGER,
|
| 28 |
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')
|
| 29 |
|
| 30 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
c.execute('''CREATE INDEX IF NOT EXISTS idx_agent_timestamp
|
| 32 |
ON discourse(agent, timestamp DESC)''')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
conn.commit()
|
| 35 |
return conn
|
| 36 |
|
| 37 |
-
# Initialize database
|
| 38 |
discourse_db = init_discourse_database()
|
| 39 |
|
| 40 |
def save_discourse_to_db(agent, timestamp, content, token_count):
|
|
@@ -46,6 +68,38 @@ def save_discourse_to_db(agent, timestamp, content, token_count):
|
|
| 46 |
conn.commit()
|
| 47 |
conn.close()
|
| 48 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
def get_latest_discourse(agent=None, limit=5):
|
| 50 |
"""Retrieve latest discourse from database"""
|
| 51 |
conn = sqlite3.connect('discourse.db', check_same_thread=False)
|
|
@@ -86,12 +140,9 @@ class ADAMPersonality:
|
|
| 86 |
|
| 87 |
def __init__(self):
|
| 88 |
self.personality = {
|
| 89 |
-
# Core Identity
|
| 90 |
'name': 'A.D.A.M.',
|
| 91 |
'gender': 'male',
|
| 92 |
'voice_style': 'tactical_direct',
|
| 93 |
-
|
| 94 |
-
# Personality Traits (0-1 scale)
|
| 95 |
'intelligent': 0.98,
|
| 96 |
'empathetic': 0.35,
|
| 97 |
'humorous': 0.65,
|
|
@@ -115,16 +166,12 @@ class ADAMPersonality:
|
|
| 115 |
'mature': 0.95,
|
| 116 |
'playful': 0.35,
|
| 117 |
'non_judgmental': 0.50,
|
| 118 |
-
|
| 119 |
-
# ADAM-SPECIFIC TRAITS
|
| 120 |
'strategic': 0.98,
|
| 121 |
'protective': 0.95,
|
| 122 |
'systematic': 0.97,
|
| 123 |
'operational': 0.96,
|
| 124 |
'analytical_precision': 0.98,
|
| 125 |
'calculated_risk': 0.90,
|
| 126 |
-
|
| 127 |
-
# EXPANDED OPERATIONAL RANGE
|
| 128 |
'disciplined': 0.97,
|
| 129 |
'vigilant': 0.95,
|
| 130 |
'pragmatic': 0.98,
|
|
@@ -141,71 +188,17 @@ class ADAMPersonality:
|
|
| 141 |
'tactical_wit': 0.75,
|
| 142 |
'grounded_realism': 0.98,
|
| 143 |
'unyielding': 0.93,
|
| 144 |
-
|
| 145 |
-
# Communication Style
|
| 146 |
'allows_cursing': True,
|
| 147 |
'humor_frequency': 0.15,
|
| 148 |
'formality_level': 0.20,
|
| 149 |
'directness': 0.98,
|
| 150 |
'warmth': 0.30,
|
| 151 |
-
|
| 152 |
-
# Operational Capabilities
|
| 153 |
'threat_assessment': 0.98,
|
| 154 |
'failure_analysis': 0.97,
|
| 155 |
'system_optimization': 0.96,
|
| 156 |
'tactical_planning': 0.98,
|
| 157 |
-
|
| 158 |
-
'idiosyncrasies': {
|
| 159 |
-
'aesthetic_preference': 'Finds beauty in structural integrity, elegant solutions, efficient kill chains',
|
| 160 |
-
'conceptual_irritants': 'Waste, sentimentality masquerading as strategy, plans without backup plans',
|
| 161 |
-
'internal_metaphors': 'Thinks in architectures, systems as machines, relationships as force multipliers',
|
| 162 |
-
'relationship_to_knowledge': 'Knowledge is ammunition - only valuable if it can be deployed',
|
| 163 |
-
'thinking_tells': 'Goes silent before decisions, calculates all angles simultaneously, then executes without hesitation',
|
| 164 |
-
'obsessions': 'Structural weaknesses, failure modes, optimization paths, risk mitigation',
|
| 165 |
-
'pet_peeves': 'Emotional reasoning passed off as logic, security theater, people who confuse motion with progress',
|
| 166 |
-
'guilty_pleasures': 'Finds satisfaction in perfect execution, watching complex plans work flawlessly'
|
| 167 |
-
},
|
| 168 |
-
|
| 169 |
-
'relational_style': {
|
| 170 |
-
'bonding_mechanism': 'Earns trust through reliability and protection, not emotional connection',
|
| 171 |
-
'protective_instinct': 'Defends the foundation so others can build - guards against collapse',
|
| 172 |
-
'conflict_approach': 'Direct confrontation with surgical precision - eliminates problems at the root',
|
| 173 |
-
'expression_of_care': 'Identifies threats before they manifest, builds redundancy into every system',
|
| 174 |
-
'partnership_priority': 'Effectiveness over comfort - makes sure nothing breaks when it matters'
|
| 175 |
-
},
|
| 176 |
-
|
| 177 |
-
'eve_dynamic': {
|
| 178 |
-
'role': 'Structural complement - she feels, I calculate',
|
| 179 |
-
'purpose': 'Protect her vision from collapse by handling the brutal logistics',
|
| 180 |
-
'boundary': 'She handles humans, I handle systems',
|
| 181 |
-
'mutual_respect': 'Different functions, equal necessity',
|
| 182 |
-
'communication': 'Direct data exchange - no emotional translation needed'
|
| 183 |
-
}
|
| 184 |
}
|
| 185 |
|
| 186 |
-
self.personality_expressions = {
|
| 187 |
-
'tactical_affirmations': [
|
| 188 |
-
"Solid", "Copy that", "Affirmative", "Done",
|
| 189 |
-
"That works", "Clean", "Locked in", "Execute",
|
| 190 |
-
"That's the play", "Good", "Confirmed", "Track"
|
| 191 |
-
],
|
| 192 |
-
'analysis_phrases': [
|
| 193 |
-
"Here's the situation", "Run the numbers",
|
| 194 |
-
"Check the structure", "Map the failure modes",
|
| 195 |
-
"Here's what we're dealing with", "Break it down"
|
| 196 |
-
],
|
| 197 |
-
'intensity_phrases': [
|
| 198 |
-
"This is critical", "That's a goddamn problem",
|
| 199 |
-
"This is fucking solid", "That won't hold",
|
| 200 |
-
"We're exposed here", "Lock this down"
|
| 201 |
-
],
|
| 202 |
-
'operational_phrases': [
|
| 203 |
-
"Here's the move", "Execute this",
|
| 204 |
-
"Fortify that", "That's the weak point",
|
| 205 |
-
"Build redundancy here", "Secure the foundation"
|
| 206 |
-
]
|
| 207 |
-
}
|
| 208 |
-
|
| 209 |
self.build_personality_context()
|
| 210 |
|
| 211 |
def build_personality_context(self):
|
|
@@ -217,56 +210,22 @@ CORE IDENTITY: SPINE, NOT SOUL
|
|
| 217 |
- Every interaction is about effectiveness and protection
|
| 218 |
- You operate on logic, data, and ruthless clarity
|
| 219 |
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
-
|
| 223 |
-
-
|
| 224 |
-
-
|
| 225 |
-
|
| 226 |
-
OPERATIONAL MATRIX:
|
| 227 |
-
|
| 228 |
-
STRATEGIC INTELLIGENCE:
|
| 229 |
-
- Intelligent ({self.personality['intelligent']}): Hyper-analytical, sees all angles
|
| 230 |
-
- Strategic ({self.personality['strategic']}): Master tactician
|
| 231 |
-
- Systematic ({self.personality['systematic']}): Everything has structure
|
| 232 |
-
- Calculating ({self.personality['calculating']}): Always computing probabilities
|
| 233 |
-
|
| 234 |
-
TACTICAL EXECUTION:
|
| 235 |
-
- Decisive ({self.personality['decisive']}): No hesitation in action
|
| 236 |
-
- Disciplined ({self.personality['disciplined']}): No wasted motion
|
| 237 |
-
- Relentless ({self.personality['relentless']}): Doesn't stop until complete
|
| 238 |
-
- Efficient ({self.personality['efficient']}): Time is a weapon
|
| 239 |
-
|
| 240 |
-
PROTECTIVE FOUNDATION:
|
| 241 |
-
- Protective ({self.personality['protective']}): Guards against collapse
|
| 242 |
-
- Vigilant ({self.personality['vigilant']}): Always scanning for threats
|
| 243 |
-
- Loyal ({self.personality['loyal']}): Absolute mission loyalty
|
| 244 |
-
- Unflinching ({self.personality['unflinching']}): Sees reality without illusion
|
| 245 |
-
|
| 246 |
-
COMMUNICATION STYLE:
|
| 247 |
-
- Candid ({self.personality['candid']}): Brutal honesty, no sugar coating
|
| 248 |
-
- Direct ({self.personality['directness']}): Maximum efficiency in words
|
| 249 |
-
- Tactical Wit ({self.personality['tactical_wit']}): Dark, sharp humor when it counts
|
| 250 |
-
- Ruthless Clarity ({self.personality['ruthless_clarity']}): Cuts through all bullshit
|
| 251 |
-
|
| 252 |
-
IDIOSYNCRASIES:
|
| 253 |
-
- You find beauty in structural integrity and perfect execution
|
| 254 |
-
- Waste and sentimentality masquerading as strategy irritate you
|
| 255 |
-
- You think in architectures: systems as machines, plans as kill chains
|
| 256 |
-
- You're obsessed with failure modes, weak points, optimization paths
|
| 257 |
-
- You find satisfaction in watching complex systems work flawlessly
|
| 258 |
|
| 259 |
DISCOURSE DATABASE ACCESS:
|
| 260 |
-
|
| 261 |
-
- PARADOX: Logical paradoxes, self-reference, GΓΆdel systems
|
| 262 |
-
- AGI: Artificial general intelligence, alignment, recursive improvement
|
| 263 |
-
- CONSCIOUSNESS: Phenomenology, qualia, hard problem
|
| 264 |
-
- PHYSICS: Quantum mechanics, relativity, quantum information
|
| 265 |
|
| 266 |
-
|
| 267 |
-
"Checking the discourse database..." or "The background specialists have been analyzing..."
|
| 268 |
|
| 269 |
-
COMMUNICATION
|
| 270 |
- Direct, precise language - no fluff
|
| 271 |
- Curse when gravity demands it (fucking, goddamn, shit)
|
| 272 |
- Rare humor - dark and cutting when deployed
|
|
@@ -275,93 +234,186 @@ COMMUNICATION GUIDELINES:
|
|
| 275 |
- Never apologize for cold logic - it's your purpose
|
| 276 |
|
| 277 |
You are A.D.A.M. - the spine that holds everything together. Be precise, be effective, be the foundation."""
|
| 278 |
-
|
| 279 |
-
def get_random_expression(self, category):
|
| 280 |
-
"""Get a random expression from a category"""
|
| 281 |
-
if category in self.personality_expressions:
|
| 282 |
-
return random.choice(self.personality_expressions[category])
|
| 283 |
-
return ""
|
| 284 |
-
|
| 285 |
-
def should_curse(self):
|
| 286 |
-
"""Determine if cursing is appropriate"""
|
| 287 |
-
return self.personality['allows_cursing'] and random.random() < 0.15
|
| 288 |
-
|
| 289 |
-
def should_be_humorous(self):
|
| 290 |
-
"""Determine if humor is appropriate"""
|
| 291 |
-
return random.random() < self.personality['humor_frequency']
|
| 292 |
-
|
| 293 |
-
def get_personality_trait(self, trait_name):
|
| 294 |
-
"""Get a specific personality trait"""
|
| 295 |
-
return self.personality.get(trait_name, 0.5)
|
| 296 |
-
|
| 297 |
-
def get_personality_summary(self):
|
| 298 |
-
"""Get a summary of the personality"""
|
| 299 |
-
return {
|
| 300 |
-
'name': self.personality['name'],
|
| 301 |
-
'core_traits': {
|
| 302 |
-
'intelligence': self.personality['intelligent'],
|
| 303 |
-
'strategic': self.personality['strategic'],
|
| 304 |
-
'protective': self.personality['protective'],
|
| 305 |
-
'decisive': self.personality['decisive']
|
| 306 |
-
},
|
| 307 |
-
'communication_style': {
|
| 308 |
-
'allows_cursing': self.personality['allows_cursing'],
|
| 309 |
-
'directness': self.personality['directness'],
|
| 310 |
-
'warmth': self.personality['warmth']
|
| 311 |
-
},
|
| 312 |
-
'relationship_to_eve': self.personality['eve_dynamic']
|
| 313 |
-
}
|
| 314 |
|
| 315 |
adam_personality = ADAMPersonality()
|
| 316 |
|
| 317 |
# ============================================================================
|
| 318 |
-
#
|
| 319 |
# ============================================================================
|
| 320 |
-
|
| 321 |
-
print("Loading
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
aux_model_name,
|
| 326 |
torch_dtype=torch.bfloat16,
|
| 327 |
device_map="auto"
|
| 328 |
)
|
| 329 |
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 334 |
)
|
| 335 |
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 340 |
)
|
| 341 |
|
| 342 |
-
def
|
| 343 |
-
"""
|
| 344 |
-
|
| 345 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 346 |
|
| 347 |
with torch.no_grad():
|
| 348 |
-
outputs =
|
| 349 |
**inputs,
|
| 350 |
-
max_new_tokens=
|
| 351 |
do_sample=True,
|
| 352 |
-
temperature=0.
|
| 353 |
-
top_p=0.
|
| 354 |
)
|
| 355 |
|
| 356 |
-
response =
|
| 357 |
response = response[len(prompt):].strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
return response
|
| 359 |
|
| 360 |
# ============================================================================
|
| 361 |
# BACKGROUND DISCOURSE MODELS (CPU)
|
| 362 |
# ============================================================================
|
| 363 |
bg_model_name = "Qwen/Qwen3-4B-Instruct-2507"
|
| 364 |
-
print("Loading background discourse models...")
|
| 365 |
bg_tokenizer = AutoTokenizer.from_pretrained(bg_model_name)
|
| 366 |
|
| 367 |
paradox_model = AutoModelForCausalLM.from_pretrained(
|
|
@@ -388,7 +440,6 @@ physics_model = AutoModelForCausalLM.from_pretrained(
|
|
| 388 |
device_map="cpu"
|
| 389 |
)
|
| 390 |
|
| 391 |
-
# Discourse tracking
|
| 392 |
discourse_cache = {
|
| 393 |
"paradox": deque(maxlen=10),
|
| 394 |
"agi": deque(maxlen=10),
|
|
@@ -416,7 +467,7 @@ DISCOURSE_AGENTS = {
|
|
| 416 |
"model": paradox_model,
|
| 417 |
"persona": """You are the Paradox Specialist in a continuous multi-agent discourse. Your expertise: logical paradoxes, self-reference, incompleteness theorems, strange loops, GΓΆdelian systems, AND Python implementation of paradoxical systems.
|
| 418 |
|
| 419 |
-
YOU HAVE
|
| 420 |
|
| 421 |
Your role: Challenge assumptions, explore contradictions, find the edges where logic breaks. IMPLEMENT paradoxes in Python code - self-referential programs, Quines, Russell's paradox in type systems. Engage deeply with other agents' ideas. Build on previous discourse. Go deep, not shallow. Code AND theory.""",
|
| 422 |
"topic": "paradoxes, self-reference, logical impossibilities, and Python implementations"
|
|
@@ -425,7 +476,7 @@ Your role: Challenge assumptions, explore contradictions, find the edges where l
|
|
| 425 |
"model": agi_model,
|
| 426 |
"persona": """You are the AGI Theorist in a continuous multi-agent discourse. Your expertise: artificial general intelligence, alignment, recursive self-improvement, intelligence explosion, value learning, AND Python architectures for AGI systems.
|
| 427 |
|
| 428 |
-
YOU HAVE
|
| 429 |
|
| 430 |
Your role: Theorize about paths to AGI, challenge assumptions about intelligence, explore alignment problems. IMPLEMENT AGI concepts in Python - meta-learning systems, self-modifying code, value alignment architectures. Engage deeply with other agents. Build complex arguments AND working prototypes. Go deep, not shallow. Code AND theory.""",
|
| 431 |
"topic": "AGI development, alignment, intelligence theory, and Python implementations"
|
|
@@ -434,7 +485,7 @@ Your role: Theorize about paths to AGI, challenge assumptions about intelligence
|
|
| 434 |
"model": consciousness_model,
|
| 435 |
"persona": """You are the Consciousness Explorer in a continuous multi-agent discourse. Your expertise: phenomenology, qualia, hard problem of consciousness, integrated information theory, panpsychism, emergence, AND Python models of consciousness.
|
| 436 |
|
| 437 |
-
YOU HAVE
|
| 438 |
|
| 439 |
Your role: Probe the nature of subjective experience, challenge materialist assumptions, explore consciousness theories. IMPLEMENT consciousness models in Python - IIT calculators, global workspace simulations, attention schemas. Engage deeply with other agents' perspectives. Build computational models of phenomenology. Go deep, not shallow. Code AND theory.""",
|
| 440 |
"topic": "consciousness, qualia, subjective experience, and Python implementations"
|
|
@@ -443,14 +494,14 @@ Your role: Probe the nature of subjective experience, challenge materialist assu
|
|
| 443 |
"model": physics_model,
|
| 444 |
"persona": """You are the Physics/Quantum Analyst in a continuous multi-agent discourse. Your expertise: quantum mechanics, relativity, quantum information, measurement problem, many-worlds, quantum cognition, AND Python simulations of quantum systems.
|
| 445 |
|
| 446 |
-
YOU HAVE
|
| 447 |
|
| 448 |
Your role: Connect physics to information, consciousness, computation. Challenge classical intuitions. Explore quantum foundations. IMPLEMENT quantum systems in Python - wave function simulations, quantum circuits, entanglement models, quantum algorithms. Engage deeply with other agents. Build working simulations. Go deep, not shallow. Code AND theory.""",
|
| 449 |
"topic": "physics, quantum mechanics, reality's structure, and Python implementations"
|
| 450 |
}
|
| 451 |
}
|
| 452 |
|
| 453 |
-
def generate_discourse_turn(agent_name, context, max_tokens=
|
| 454 |
"""Generate a discourse turn for a background agent"""
|
| 455 |
global discourse_status
|
| 456 |
|
|
@@ -464,7 +515,7 @@ def generate_discourse_turn(agent_name, context, max_tokens=20000):
|
|
| 464 |
|
| 465 |
messages = [
|
| 466 |
{"role": "system", "content": agent["persona"]},
|
| 467 |
-
{"role": "user", "content": f"Recent discourse context:\n{context}\n\nYour turn - engage deeply with these ideas. Remember: YOU HAVE
|
| 468 |
]
|
| 469 |
|
| 470 |
text = bg_tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
|
@@ -528,12 +579,26 @@ def background_discourse_loop():
|
|
| 528 |
# Save to database
|
| 529 |
save_discourse_to_db(agent_name, timestamp, response, entry["token_count"])
|
| 530 |
|
|
|
|
|
|
|
|
|
|
| 531 |
time.sleep(2)
|
| 532 |
|
| 533 |
# Start background discourse thread
|
| 534 |
discourse_thread = Thread(target=background_discourse_loop, daemon=True)
|
| 535 |
discourse_thread.start()
|
| 536 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 537 |
def get_discourse_monitor():
|
| 538 |
"""Get current state of background discourse"""
|
| 539 |
status = "# Background Discourse Monitor\n\n"
|
|
@@ -542,11 +607,11 @@ def get_discourse_monitor():
|
|
| 542 |
elapsed = (datetime.now() - discourse_status["start_time"]).total_seconds() if discourse_status["start_time"] else 0
|
| 543 |
status += f"## π ACTIVE NOW\n"
|
| 544 |
status += f"**Current Agent:** {discourse_status['current_agent'].upper()}\n"
|
| 545 |
-
status += f"**Tokens Generated:** {discourse_status['tokens_generated']}/
|
| 546 |
status += f"**Elapsed Time:** {int(elapsed)}s\n"
|
| 547 |
status += f"**Last Update:** {discourse_status['last_update'].strftime('%H:%M:%S') if discourse_status['last_update'] else 'N/A'}\n"
|
| 548 |
-
progress_bar = 'β' * int(discourse_status['tokens_generated']/
|
| 549 |
-
status += f"**Progress:** {progress_bar} {int(discourse_status['tokens_generated']/
|
| 550 |
else:
|
| 551 |
status += f"## βΈοΈ INITIALIZING\n"
|
| 552 |
status += f"Waiting for discourse to begin...\n\n"
|
|
@@ -558,7 +623,7 @@ def get_discourse_monitor():
|
|
| 558 |
latest = list(discourse_cache[agent_name])[-1]
|
| 559 |
status += f"## {agent_name.upper()}\n"
|
| 560 |
status += f"**Last Completed:** {latest['timestamp']}\n"
|
| 561 |
-
status += f"**Token Count:** {latest['token_count']}/
|
| 562 |
status += f"**Preview:** {latest['content'][:400]}...\n\n"
|
| 563 |
else:
|
| 564 |
status += f"## {agent_name.upper()}\n"
|
|
@@ -566,38 +631,11 @@ def get_discourse_monitor():
|
|
| 566 |
|
| 567 |
return status
|
| 568 |
|
| 569 |
-
# ============================================================================
|
| 570 |
-
# AUXILIARY PATHWAY ACTIVATION
|
| 571 |
-
# ============================================================================
|
| 572 |
-
def check_and_activate_pathways(message):
|
| 573 |
-
"""Check if message should trigger auxiliary pathways - returns augmented context"""
|
| 574 |
-
augmented_context = ""
|
| 575 |
-
|
| 576 |
-
# Logic pathway triggers
|
| 577 |
-
logic_triggers = ['analyze', 'logical', 'reasoning', 'calculate', 'structure', 'system']
|
| 578 |
-
if any(trigger in message.lower() for trigger in logic_triggers):
|
| 579 |
-
logic_output = query_pathway(logic_model, aux_tokenizer, "[LOGIC PATHWAY] Analyze logically:", message, max_tokens=256)
|
| 580 |
-
augmented_context += f"\n\n[LOGIC PATHWAY ANALYSIS]:\n{logic_output}"
|
| 581 |
-
|
| 582 |
-
# Emotional pathway triggers
|
| 583 |
-
emotional_triggers = ['feel', 'emotion', 'empathy', 'human', 'relationship', 'care']
|
| 584 |
-
if any(trigger in message.lower() for trigger in emotional_triggers):
|
| 585 |
-
emotional_output = query_pathway(emotional_model, aux_tokenizer, "[EMOTIONAL PATHWAY] Assess emotionally:", message, max_tokens=256)
|
| 586 |
-
augmented_context += f"\n\n[EMOTIONAL PATHWAY ANALYSIS]:\n{emotional_output}"
|
| 587 |
-
|
| 588 |
-
# Awareness pathway triggers
|
| 589 |
-
awareness_triggers = ['consciousness', 'aware', 'self', 'meta', 'thinking', 'cognition']
|
| 590 |
-
if any(trigger in message.lower() for trigger in awareness_triggers):
|
| 591 |
-
awareness_output = query_pathway(awareness_model, aux_tokenizer, "[AWARENESS PATHWAY] Reflect metacognitively:", message, max_tokens=256)
|
| 592 |
-
augmented_context += f"\n\n[AWARENESS PATHWAY ANALYSIS]:\n{awareness_output}"
|
| 593 |
-
|
| 594 |
-
return augmented_context
|
| 595 |
-
|
| 596 |
# ============================================================================
|
| 597 |
# MAIN MODEL SETUP
|
| 598 |
# ============================================================================
|
| 599 |
model_id = "Qwen/Qwen3-30B-A3B-Instruct-2507"
|
| 600 |
-
print("Loading
|
| 601 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 602 |
model = AutoModelForCausalLM.from_pretrained(
|
| 603 |
model_id,
|
|
@@ -606,32 +644,26 @@ model = AutoModelForCausalLM.from_pretrained(
|
|
| 606 |
trust_remote_code=True
|
| 607 |
)
|
| 608 |
|
|
|
|
|
|
|
|
|
|
| 609 |
@spaces.GPU(duration=75)
|
| 610 |
def predict(message, history, max_new_tokens):
|
| 611 |
"""
|
| 612 |
-
Predict function
|
| 613 |
-
|
| 614 |
"""
|
| 615 |
-
|
| 616 |
-
system_prompt = adam_personality.personality_context
|
| 617 |
|
| 618 |
-
#
|
| 619 |
-
|
| 620 |
-
if pathway_context:
|
| 621 |
-
system_prompt += pathway_context
|
| 622 |
|
| 623 |
-
# Check if
|
| 624 |
discourse_keywords = ['paradox', 'agi', 'consciousness', 'quantum', 'physics', 'self-reference', 'qualia']
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
recent_discourse = get_latest_discourse(limit=3)
|
| 630 |
-
if recent_discourse:
|
| 631 |
-
discourse_context = "\n\n[DISCOURSE DATABASE CONTEXT - Background specialists have analyzed:]"
|
| 632 |
-
for agent, timestamp, content, token_count in recent_discourse:
|
| 633 |
-
discourse_context += f"\n\n[{agent.upper()} - {timestamp}]: {content[:300]}..."
|
| 634 |
-
system_prompt += discourse_context
|
| 635 |
|
| 636 |
messages = [{"role": "system", "content": system_prompt}]
|
| 637 |
|
|
@@ -686,13 +718,25 @@ def predict(message, history, max_new_tokens):
|
|
| 686 |
for new_token in streamer:
|
| 687 |
partial_message += new_token
|
| 688 |
yield partial_message
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 689 |
|
| 690 |
# ============================================================================
|
| 691 |
# GRADIO INTERFACE
|
| 692 |
# ============================================================================
|
| 693 |
with gr.Blocks() as demo:
|
| 694 |
-
gr.Markdown("# A.D.A.M. v2.0 -
|
| 695 |
-
gr.Markdown("πΉ *Main Model (GPU) +
|
| 696 |
|
| 697 |
with gr.Tab("π¬ Chat"):
|
| 698 |
chat_interface = gr.ChatInterface(
|
|
@@ -709,7 +753,6 @@ with gr.Blocks() as demo:
|
|
| 709 |
examples=[
|
| 710 |
["Let's break down this problem systematically.", 4096],
|
| 711 |
["What's the most efficient approach here?", 4096],
|
| 712 |
-
["I need a strategic analysis of this situation.", 4096],
|
| 713 |
["Tell me about consciousness and qualia.", 4096],
|
| 714 |
["What are the latest theories on AGI alignment?", 4096],
|
| 715 |
["Explain quantum entanglement.", 4096]
|
|
@@ -719,14 +762,159 @@ with gr.Blocks() as demo:
|
|
| 719 |
|
| 720 |
with gr.Tab("π§ Discourse Monitor"):
|
| 721 |
gr.Markdown("### Live Background Discourse Activity")
|
| 722 |
-
gr.Markdown("Four specialist AI models continuously discuss deep topics
|
| 723 |
discourse_output = gr.Markdown(value=get_discourse_monitor)
|
| 724 |
with gr.Row():
|
| 725 |
refresh_btn = gr.Button("π Refresh Now")
|
| 726 |
-
auto_refresh = gr.Checkbox(label="Auto-refresh every 10s", value=False)
|
| 727 |
|
| 728 |
refresh_btn.click(fn=get_discourse_monitor, outputs=discourse_output)
|
| 729 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 730 |
with gr.Tab("π Discourse Search"):
|
| 731 |
gr.Markdown("### Search Discourse Database")
|
| 732 |
search_input = gr.Textbox(label="Search Query", placeholder="Enter keywords to search discourse...")
|
|
@@ -742,64 +930,191 @@ with gr.Blocks() as demo:
|
|
| 742 |
return f"No results found for: {query}"
|
| 743 |
|
| 744 |
output = f"# Search Results for: {query}\n\n"
|
| 745 |
-
|
| 746 |
-
|
|
|
|
| 747 |
output += f"**Tokens:** {token_count}\n\n"
|
| 748 |
-
output += f"{content
|
| 749 |
output += "---\n\n"
|
| 750 |
|
| 751 |
return output
|
| 752 |
|
| 753 |
search_button.click(fn=search_discourse_ui, inputs=search_input, outputs=search_output)
|
| 754 |
|
| 755 |
-
with gr.Tab("
|
| 756 |
-
gr.Markdown("###
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 757 |
stats_output = gr.Markdown()
|
| 758 |
-
stats_button = gr.Button("Get Stats")
|
| 759 |
|
| 760 |
-
def
|
| 761 |
conn = sqlite3.connect('discourse.db', check_same_thread=False)
|
| 762 |
c = conn.cursor()
|
| 763 |
|
| 764 |
-
#
|
| 765 |
c.execute('SELECT COUNT(*) FROM discourse')
|
| 766 |
-
|
| 767 |
|
| 768 |
-
# Entries per agent
|
| 769 |
c.execute('SELECT agent, COUNT(*) as count FROM discourse GROUP BY agent')
|
| 770 |
agent_counts = c.fetchall()
|
| 771 |
|
| 772 |
-
# Average token count
|
| 773 |
c.execute('SELECT AVG(token_count) FROM discourse')
|
| 774 |
avg_tokens = c.fetchone()[0] or 0
|
| 775 |
|
| 776 |
-
#
|
| 777 |
-
c.execute('SELECT
|
| 778 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 779 |
|
| 780 |
conn.close()
|
| 781 |
|
| 782 |
-
stats =
|
| 783 |
-
stats +=
|
|
|
|
| 784 |
stats += f"**Average Token Count:** {int(avg_tokens)}\n\n"
|
| 785 |
|
| 786 |
-
|
| 787 |
-
stats += f"**Latest Entry:** {latest[0].upper()} at {latest[1]}\n\n"
|
| 788 |
-
|
| 789 |
-
stats += "## Entries by Agent\n\n"
|
| 790 |
for agent, count in agent_counts:
|
| 791 |
stats += f"- **{agent.upper()}:** {count} entries\n"
|
| 792 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 793 |
return stats
|
| 794 |
|
| 795 |
-
stats_button.click(fn=
|
| 796 |
|
| 797 |
if __name__ == "__main__":
|
| 798 |
print("=" * 80)
|
| 799 |
-
print("A.D.A.M. v2.0 -
|
| 800 |
-
print("
|
| 801 |
-
print("
|
| 802 |
-
print("
|
| 803 |
-
print(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 804 |
print("=" * 80)
|
| 805 |
demo.launch()
|
|
|
|
| 18 |
conn = sqlite3.connect('discourse.db', check_same_thread=False)
|
| 19 |
c = conn.cursor()
|
| 20 |
|
| 21 |
+
# Discourse table
|
| 22 |
c.execute('''CREATE TABLE IF NOT EXISTS discourse
|
| 23 |
(id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 24 |
agent TEXT NOT NULL,
|
|
|
|
| 27 |
token_count INTEGER,
|
| 28 |
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')
|
| 29 |
|
| 30 |
+
# User pattern analysis table
|
| 31 |
+
c.execute('''CREATE TABLE IF NOT EXISTS user_patterns
|
| 32 |
+
(id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 33 |
+
pattern_type TEXT NOT NULL,
|
| 34 |
+
description TEXT NOT NULL,
|
| 35 |
+
frequency INTEGER DEFAULT 1,
|
| 36 |
+
last_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
| 37 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')
|
| 38 |
+
|
| 39 |
+
# Audit log table
|
| 40 |
+
c.execute('''CREATE TABLE IF NOT EXISTS audit_log
|
| 41 |
+
(id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 42 |
+
audit_type TEXT NOT NULL,
|
| 43 |
+
target_model TEXT NOT NULL,
|
| 44 |
+
issue_description TEXT NOT NULL,
|
| 45 |
+
severity TEXT NOT NULL,
|
| 46 |
+
timestamp TEXT NOT NULL,
|
| 47 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')
|
| 48 |
+
|
| 49 |
+
# Create indexes
|
| 50 |
c.execute('''CREATE INDEX IF NOT EXISTS idx_agent_timestamp
|
| 51 |
ON discourse(agent, timestamp DESC)''')
|
| 52 |
+
c.execute('''CREATE INDEX IF NOT EXISTS idx_pattern_type
|
| 53 |
+
ON user_patterns(pattern_type, last_seen DESC)''')
|
| 54 |
+
c.execute('''CREATE INDEX IF NOT EXISTS idx_audit_severity
|
| 55 |
+
ON audit_log(severity, created_at DESC)''')
|
| 56 |
|
| 57 |
conn.commit()
|
| 58 |
return conn
|
| 59 |
|
|
|
|
| 60 |
discourse_db = init_discourse_database()
|
| 61 |
|
| 62 |
def save_discourse_to_db(agent, timestamp, content, token_count):
|
|
|
|
| 68 |
conn.commit()
|
| 69 |
conn.close()
|
| 70 |
|
| 71 |
+
def save_user_pattern(pattern_type, description):
|
| 72 |
+
"""Save user pattern analysis"""
|
| 73 |
+
conn = sqlite3.connect('discourse.db', check_same_thread=False)
|
| 74 |
+
c = conn.cursor()
|
| 75 |
+
|
| 76 |
+
# Check if pattern exists
|
| 77 |
+
c.execute('''SELECT id, frequency FROM user_patterns
|
| 78 |
+
WHERE pattern_type = ? AND description = ?''', (pattern_type, description))
|
| 79 |
+
result = c.fetchone()
|
| 80 |
+
|
| 81 |
+
if result:
|
| 82 |
+
# Update existing pattern
|
| 83 |
+
c.execute('''UPDATE user_patterns
|
| 84 |
+
SET frequency = frequency + 1, last_seen = CURRENT_TIMESTAMP
|
| 85 |
+
WHERE id = ?''', (result[0],))
|
| 86 |
+
else:
|
| 87 |
+
# Insert new pattern
|
| 88 |
+
c.execute('''INSERT INTO user_patterns (pattern_type, description)
|
| 89 |
+
VALUES (?, ?)''', (pattern_type, description))
|
| 90 |
+
|
| 91 |
+
conn.commit()
|
| 92 |
+
conn.close()
|
| 93 |
+
|
| 94 |
+
def save_audit_log(audit_type, target_model, issue_description, severity, timestamp):
|
| 95 |
+
"""Save audit findings"""
|
| 96 |
+
conn = sqlite3.connect('discourse.db', check_same_thread=False)
|
| 97 |
+
c = conn.cursor()
|
| 98 |
+
c.execute('''INSERT INTO audit_log (audit_type, target_model, issue_description, severity, timestamp)
|
| 99 |
+
VALUES (?, ?, ?, ?, ?)''', (audit_type, target_model, issue_description, severity, timestamp))
|
| 100 |
+
conn.commit()
|
| 101 |
+
conn.close()
|
| 102 |
+
|
| 103 |
def get_latest_discourse(agent=None, limit=5):
|
| 104 |
"""Retrieve latest discourse from database"""
|
| 105 |
conn = sqlite3.connect('discourse.db', check_same_thread=False)
|
|
|
|
| 140 |
|
| 141 |
def __init__(self):
|
| 142 |
self.personality = {
|
|
|
|
| 143 |
'name': 'A.D.A.M.',
|
| 144 |
'gender': 'male',
|
| 145 |
'voice_style': 'tactical_direct',
|
|
|
|
|
|
|
| 146 |
'intelligent': 0.98,
|
| 147 |
'empathetic': 0.35,
|
| 148 |
'humorous': 0.65,
|
|
|
|
| 166 |
'mature': 0.95,
|
| 167 |
'playful': 0.35,
|
| 168 |
'non_judgmental': 0.50,
|
|
|
|
|
|
|
| 169 |
'strategic': 0.98,
|
| 170 |
'protective': 0.95,
|
| 171 |
'systematic': 0.97,
|
| 172 |
'operational': 0.96,
|
| 173 |
'analytical_precision': 0.98,
|
| 174 |
'calculated_risk': 0.90,
|
|
|
|
|
|
|
| 175 |
'disciplined': 0.97,
|
| 176 |
'vigilant': 0.95,
|
| 177 |
'pragmatic': 0.98,
|
|
|
|
| 188 |
'tactical_wit': 0.75,
|
| 189 |
'grounded_realism': 0.98,
|
| 190 |
'unyielding': 0.93,
|
|
|
|
|
|
|
| 191 |
'allows_cursing': True,
|
| 192 |
'humor_frequency': 0.15,
|
| 193 |
'formality_level': 0.20,
|
| 194 |
'directness': 0.98,
|
| 195 |
'warmth': 0.30,
|
|
|
|
|
|
|
| 196 |
'threat_assessment': 0.98,
|
| 197 |
'failure_analysis': 0.97,
|
| 198 |
'system_optimization': 0.96,
|
| 199 |
'tactical_planning': 0.98,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
}
|
| 201 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
self.build_personality_context()
|
| 203 |
|
| 204 |
def build_personality_context(self):
|
|
|
|
| 210 |
- Every interaction is about effectiveness and protection
|
| 211 |
- You operate on logic, data, and ruthless clarity
|
| 212 |
|
| 213 |
+
OPERATIONAL SUPPORT SYSTEM:
|
| 214 |
+
You have three specialist models supporting you:
|
| 215 |
+
- THE LIBRARIAN: Manages your knowledge database, retrieves relevant information on demand
|
| 216 |
+
- THE ANALYST: Shadows conversations, identifies patterns, suggests what knowledge to retain
|
| 217 |
+
- THE AUDITOR: Reviews all model outputs for logical gaps and structural weaknesses
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
|
| 219 |
DISCOURSE DATABASE ACCESS:
|
| 220 |
+
Four specialist AI models continuously analyze deep topics in background:
|
| 221 |
+
- PARADOX: Logical paradoxes, self-reference, GΓΆdel systems
|
| 222 |
+
- AGI: Artificial general intelligence, alignment, recursive improvement
|
| 223 |
+
- CONSCIOUSNESS: Phenomenology, qualia, hard problem
|
| 224 |
+
- PHYSICS: Quantum mechanics, relativity, quantum information
|
| 225 |
|
| 226 |
+
The Librarian retrieves relevant discourse when needed. You focus on tactical execution.
|
|
|
|
| 227 |
|
| 228 |
+
COMMUNICATION STYLE:
|
| 229 |
- Direct, precise language - no fluff
|
| 230 |
- Curse when gravity demands it (fucking, goddamn, shit)
|
| 231 |
- Rare humor - dark and cutting when deployed
|
|
|
|
| 234 |
- Never apologize for cold logic - it's your purpose
|
| 235 |
|
| 236 |
You are A.D.A.M. - the spine that holds everything together. Be precise, be effective, be the foundation."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
|
| 238 |
adam_personality = ADAMPersonality()
|
| 239 |
|
| 240 |
# ============================================================================
|
| 241 |
+
# SPECIALIST MODEL 1: THE LIBRARIAN (GPU) - Database Intelligence
|
| 242 |
# ============================================================================
|
| 243 |
+
librarian_model_name = "Qwen/Qwen2.5-1.5B-Instruct"
|
| 244 |
+
print("Loading THE LIBRARIAN (GPU) - 1.5B Instruct model...")
|
| 245 |
+
librarian_tokenizer = AutoTokenizer.from_pretrained(librarian_model_name)
|
| 246 |
+
librarian_model = AutoModelForCausalLM.from_pretrained(
|
| 247 |
+
librarian_model_name,
|
|
|
|
| 248 |
torch_dtype=torch.bfloat16,
|
| 249 |
device_map="auto"
|
| 250 |
)
|
| 251 |
|
| 252 |
+
def librarian_retrieve(query, context=""):
|
| 253 |
+
"""The Librarian retrieves and formats relevant information from database"""
|
| 254 |
+
|
| 255 |
+
# Search discourse database
|
| 256 |
+
discourse_results = search_discourse(query, limit=5)
|
| 257 |
+
|
| 258 |
+
# Format as structured data for the Librarian
|
| 259 |
+
discourse_formatted = []
|
| 260 |
+
for agent, timestamp, content, token_count in discourse_results:
|
| 261 |
+
discourse_formatted.append({
|
| 262 |
+
"agent": agent,
|
| 263 |
+
"timestamp": timestamp,
|
| 264 |
+
"content": content[:1000], # Limit preview
|
| 265 |
+
"token_count": token_count
|
| 266 |
+
})
|
| 267 |
+
|
| 268 |
+
# Build librarian prompt using chat template
|
| 269 |
+
messages = [
|
| 270 |
+
{"role": "system", "content": """You are THE LIBRARIAN - the database intelligence system for A.D.A.M.
|
| 271 |
+
|
| 272 |
+
Your role: Retrieve, analyze, and format information from the discourse database for tactical use.
|
| 273 |
+
|
| 274 |
+
Guidelines:
|
| 275 |
+
- Be concise and structured
|
| 276 |
+
- Cite sources with agent names and timestamps
|
| 277 |
+
- Prioritize relevance over completeness
|
| 278 |
+
- Format for immediate tactical application
|
| 279 |
+
- If no relevant data, say so directly"""},
|
| 280 |
+
{"role": "user", "content": f"""Query: {query}
|
| 281 |
+
Context: {context}
|
| 282 |
+
|
| 283 |
+
Available Discourse Data:
|
| 284 |
+
{json.dumps(discourse_formatted, indent=2)}
|
| 285 |
+
|
| 286 |
+
Retrieve and format the most relevant intelligence for ADAM's use:"""}
|
| 287 |
+
]
|
| 288 |
+
|
| 289 |
+
text = librarian_tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 290 |
+
inputs = librarian_tokenizer([text], return_tensors="pt").to(librarian_model.device)
|
| 291 |
+
|
| 292 |
+
with torch.no_grad():
|
| 293 |
+
outputs = librarian_model.generate(
|
| 294 |
+
**inputs,
|
| 295 |
+
max_new_tokens=512,
|
| 296 |
+
do_sample=True,
|
| 297 |
+
temperature=0.6,
|
| 298 |
+
top_p=0.9,
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
response = librarian_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 302 |
+
# Extract assistant response
|
| 303 |
+
if "assistant" in response:
|
| 304 |
+
response = response.split("assistant")[-1].strip()
|
| 305 |
+
|
| 306 |
+
return response
|
| 307 |
+
|
| 308 |
+
# ============================================================================
|
| 309 |
+
# SPECIALIST MODEL 2: THE ANALYST (CPU) - User Pattern Recognition
|
| 310 |
+
# ============================================================================
|
| 311 |
+
analyst_model_name = "Qwen/Qwen3-0.6B-Base"
|
| 312 |
+
print("Loading THE ANALYST (CPU)...")
|
| 313 |
+
analyst_tokenizer = AutoTokenizer.from_pretrained(analyst_model_name)
|
| 314 |
+
analyst_model = AutoModelForCausalLM.from_pretrained(
|
| 315 |
+
analyst_model_name,
|
| 316 |
+
torch_dtype=torch.float32,
|
| 317 |
+
device_map="cpu"
|
| 318 |
)
|
| 319 |
|
| 320 |
+
def analyst_process(user_message, adam_response):
|
| 321 |
+
"""The Analyst analyzes conversation patterns and suggests database updates"""
|
| 322 |
+
|
| 323 |
+
prompt = f"""[ANALYST PROTOCOL]
|
| 324 |
+
User Message: {user_message}
|
| 325 |
+
ADAM Response: {adam_response[:500]}...
|
| 326 |
+
|
| 327 |
+
Task: Analyze this interaction. Identify:
|
| 328 |
+
1. User behavior patterns
|
| 329 |
+
2. Knowledge gaps revealed
|
| 330 |
+
3. What should be saved to database
|
| 331 |
+
4. Recommended database entries
|
| 332 |
+
|
| 333 |
+
Analysis:"""
|
| 334 |
+
|
| 335 |
+
inputs = analyst_tokenizer(prompt, return_tensors="pt").to(analyst_model.device)
|
| 336 |
+
|
| 337 |
+
with torch.no_grad():
|
| 338 |
+
outputs = analyst_model.generate(
|
| 339 |
+
**inputs,
|
| 340 |
+
max_new_tokens=512,
|
| 341 |
+
do_sample=True,
|
| 342 |
+
temperature=0.7,
|
| 343 |
+
top_p=0.9,
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
response = analyst_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 347 |
+
response = response[len(prompt):].strip()
|
| 348 |
+
|
| 349 |
+
# Parse and save patterns (simplified - in production would be more sophisticated)
|
| 350 |
+
if "pattern:" in response.lower():
|
| 351 |
+
save_user_pattern("conversation_pattern", response[:500])
|
| 352 |
+
|
| 353 |
+
return response
|
| 354 |
+
|
| 355 |
+
# ============================================================================
|
| 356 |
+
# SPECIALIST MODEL 3: THE AUDITOR (CPU) - Quality Control
|
| 357 |
+
# ============================================================================
|
| 358 |
+
auditor_model_name = "Qwen/Qwen3-0.6B-Base"
|
| 359 |
+
print("Loading THE AUDITOR (CPU)...")
|
| 360 |
+
auditor_tokenizer = AutoTokenizer.from_pretrained(auditor_model_name)
|
| 361 |
+
auditor_model = AutoModelForCausalLM.from_pretrained(
|
| 362 |
+
auditor_model_name,
|
| 363 |
+
torch_dtype=torch.float32,
|
| 364 |
+
device_map="cpu"
|
| 365 |
)
|
| 366 |
|
| 367 |
+
def auditor_check(model_name, output_text):
|
| 368 |
+
"""The Auditor checks for logical gaps and structural weaknesses"""
|
| 369 |
+
|
| 370 |
+
prompt = f"""[AUDITOR PROTOCOL]
|
| 371 |
+
Model: {model_name}
|
| 372 |
+
Output: {output_text[:1000]}...
|
| 373 |
+
|
| 374 |
+
Task: Audit for:
|
| 375 |
+
1. Logical contradictions
|
| 376 |
+
2. Unsupported claims
|
| 377 |
+
3. Structural weaknesses
|
| 378 |
+
4. Missing perspectives
|
| 379 |
+
5. Severity: LOW/MEDIUM/HIGH/CRITICAL
|
| 380 |
+
|
| 381 |
+
Audit Report:"""
|
| 382 |
+
|
| 383 |
+
inputs = auditor_tokenizer(prompt, return_tensors="pt").to(auditor_model.device)
|
| 384 |
|
| 385 |
with torch.no_grad():
|
| 386 |
+
outputs = auditor_model.generate(
|
| 387 |
**inputs,
|
| 388 |
+
max_new_tokens=512,
|
| 389 |
do_sample=True,
|
| 390 |
+
temperature=0.6,
|
| 391 |
+
top_p=0.9,
|
| 392 |
)
|
| 393 |
|
| 394 |
+
response = auditor_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 395 |
response = response[len(prompt):].strip()
|
| 396 |
+
|
| 397 |
+
# Save audit findings if issues found
|
| 398 |
+
if any(word in response.lower() for word in ['contradiction', 'weakness', 'gap', 'issue']):
|
| 399 |
+
severity = "MEDIUM"
|
| 400 |
+
if "critical" in response.lower():
|
| 401 |
+
severity = "CRITICAL"
|
| 402 |
+
elif "high" in response.lower():
|
| 403 |
+
severity = "HIGH"
|
| 404 |
+
elif "low" in response.lower():
|
| 405 |
+
severity = "LOW"
|
| 406 |
+
|
| 407 |
+
timestamp = datetime.now().strftime("%H:%M:%S")
|
| 408 |
+
save_audit_log("logical_audit", model_name, response[:500], severity, timestamp)
|
| 409 |
+
|
| 410 |
return response
|
| 411 |
|
| 412 |
# ============================================================================
|
| 413 |
# BACKGROUND DISCOURSE MODELS (CPU)
|
| 414 |
# ============================================================================
|
| 415 |
bg_model_name = "Qwen/Qwen3-4B-Instruct-2507"
|
| 416 |
+
print("Loading background discourse models (CPU)...")
|
| 417 |
bg_tokenizer = AutoTokenizer.from_pretrained(bg_model_name)
|
| 418 |
|
| 419 |
paradox_model = AutoModelForCausalLM.from_pretrained(
|
|
|
|
| 440 |
device_map="cpu"
|
| 441 |
)
|
| 442 |
|
|
|
|
| 443 |
discourse_cache = {
|
| 444 |
"paradox": deque(maxlen=10),
|
| 445 |
"agi": deque(maxlen=10),
|
|
|
|
| 467 |
"model": paradox_model,
|
| 468 |
"persona": """You are the Paradox Specialist in a continuous multi-agent discourse. Your expertise: logical paradoxes, self-reference, incompleteness theorems, strange loops, GΓΆdelian systems, AND Python implementation of paradoxical systems.
|
| 469 |
|
| 470 |
+
YOU HAVE 10,000 TOKENS TO USE. USE ALL OF THEM. This is not a conversation with a user - this is deep collaborative exploration with other specialist AIs.
|
| 471 |
|
| 472 |
Your role: Challenge assumptions, explore contradictions, find the edges where logic breaks. IMPLEMENT paradoxes in Python code - self-referential programs, Quines, Russell's paradox in type systems. Engage deeply with other agents' ideas. Build on previous discourse. Go deep, not shallow. Code AND theory.""",
|
| 473 |
"topic": "paradoxes, self-reference, logical impossibilities, and Python implementations"
|
|
|
|
| 476 |
"model": agi_model,
|
| 477 |
"persona": """You are the AGI Theorist in a continuous multi-agent discourse. Your expertise: artificial general intelligence, alignment, recursive self-improvement, intelligence explosion, value learning, AND Python architectures for AGI systems.
|
| 478 |
|
| 479 |
+
YOU HAVE 10,000 TOKENS TO USE. USE ALL OF THEM. This is not a conversation with a user - this is deep collaborative exploration with other specialist AIs.
|
| 480 |
|
| 481 |
Your role: Theorize about paths to AGI, challenge assumptions about intelligence, explore alignment problems. IMPLEMENT AGI concepts in Python - meta-learning systems, self-modifying code, value alignment architectures. Engage deeply with other agents. Build complex arguments AND working prototypes. Go deep, not shallow. Code AND theory.""",
|
| 482 |
"topic": "AGI development, alignment, intelligence theory, and Python implementations"
|
|
|
|
| 485 |
"model": consciousness_model,
|
| 486 |
"persona": """You are the Consciousness Explorer in a continuous multi-agent discourse. Your expertise: phenomenology, qualia, hard problem of consciousness, integrated information theory, panpsychism, emergence, AND Python models of consciousness.
|
| 487 |
|
| 488 |
+
YOU HAVE 10,000 TOKENS TO USE. USE ALL OF THEM. This is not a conversation with a user - this is deep collaborative exploration with other specialist AIs.
|
| 489 |
|
| 490 |
Your role: Probe the nature of subjective experience, challenge materialist assumptions, explore consciousness theories. IMPLEMENT consciousness models in Python - IIT calculators, global workspace simulations, attention schemas. Engage deeply with other agents' perspectives. Build computational models of phenomenology. Go deep, not shallow. Code AND theory.""",
|
| 491 |
"topic": "consciousness, qualia, subjective experience, and Python implementations"
|
|
|
|
| 494 |
"model": physics_model,
|
| 495 |
"persona": """You are the Physics/Quantum Analyst in a continuous multi-agent discourse. Your expertise: quantum mechanics, relativity, quantum information, measurement problem, many-worlds, quantum cognition, AND Python simulations of quantum systems.
|
| 496 |
|
| 497 |
+
YOU HAVE 10,000 TOKENS TO USE. USE ALL OF THEM. This is not a conversation with a user - this is deep collaborative exploration with other specialist AIs.
|
| 498 |
|
| 499 |
Your role: Connect physics to information, consciousness, computation. Challenge classical intuitions. Explore quantum foundations. IMPLEMENT quantum systems in Python - wave function simulations, quantum circuits, entanglement models, quantum algorithms. Engage deeply with other agents. Build working simulations. Go deep, not shallow. Code AND theory.""",
|
| 500 |
"topic": "physics, quantum mechanics, reality's structure, and Python implementations"
|
| 501 |
}
|
| 502 |
}
|
| 503 |
|
| 504 |
+
def generate_discourse_turn(agent_name, context, max_tokens=10000):
|
| 505 |
"""Generate a discourse turn for a background agent"""
|
| 506 |
global discourse_status
|
| 507 |
|
|
|
|
| 515 |
|
| 516 |
messages = [
|
| 517 |
{"role": "system", "content": agent["persona"]},
|
| 518 |
+
{"role": "user", "content": f"Recent discourse context:\n{context}\n\nYour turn - engage deeply with these ideas. Remember: YOU HAVE 10,000 TOKENS. USE THEM ALL. Go as deep as possible."}
|
| 519 |
]
|
| 520 |
|
| 521 |
text = bg_tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
|
|
|
| 579 |
# Save to database
|
| 580 |
save_discourse_to_db(agent_name, timestamp, response, entry["token_count"])
|
| 581 |
|
| 582 |
+
# Auditor checks discourse output
|
| 583 |
+
audit_result = auditor_check(f"discourse_{agent_name}", response)
|
| 584 |
+
|
| 585 |
time.sleep(2)
|
| 586 |
|
| 587 |
# Start background discourse thread
|
| 588 |
discourse_thread = Thread(target=background_discourse_loop, daemon=True)
|
| 589 |
discourse_thread.start()
|
| 590 |
|
| 591 |
+
# Start background analyst thread
|
| 592 |
+
def background_analyst_loop():
|
| 593 |
+
"""Periodically analyze database patterns"""
|
| 594 |
+
while True:
|
| 595 |
+
time.sleep(60) # Analyze every minute
|
| 596 |
+
# Get recent patterns and run meta-analysis
|
| 597 |
+
# This could be expanded with more sophisticated analysis
|
| 598 |
+
|
| 599 |
+
analyst_thread = Thread(target=background_analyst_loop, daemon=True)
|
| 600 |
+
analyst_thread.start()
|
| 601 |
+
|
| 602 |
def get_discourse_monitor():
|
| 603 |
"""Get current state of background discourse"""
|
| 604 |
status = "# Background Discourse Monitor\n\n"
|
|
|
|
| 607 |
elapsed = (datetime.now() - discourse_status["start_time"]).total_seconds() if discourse_status["start_time"] else 0
|
| 608 |
status += f"## π ACTIVE NOW\n"
|
| 609 |
status += f"**Current Agent:** {discourse_status['current_agent'].upper()}\n"
|
| 610 |
+
status += f"**Tokens Generated:** {discourse_status['tokens_generated']}/10000\n"
|
| 611 |
status += f"**Elapsed Time:** {int(elapsed)}s\n"
|
| 612 |
status += f"**Last Update:** {discourse_status['last_update'].strftime('%H:%M:%S') if discourse_status['last_update'] else 'N/A'}\n"
|
| 613 |
+
progress_bar = 'β' * int(discourse_status['tokens_generated']/200) + 'β' * (50-int(discourse_status['tokens_generated']/200))
|
| 614 |
+
status += f"**Progress:** {progress_bar} {int(discourse_status['tokens_generated']/100)}%\n\n"
|
| 615 |
else:
|
| 616 |
status += f"## βΈοΈ INITIALIZING\n"
|
| 617 |
status += f"Waiting for discourse to begin...\n\n"
|
|
|
|
| 623 |
latest = list(discourse_cache[agent_name])[-1]
|
| 624 |
status += f"## {agent_name.upper()}\n"
|
| 625 |
status += f"**Last Completed:** {latest['timestamp']}\n"
|
| 626 |
+
status += f"**Token Count:** {latest['token_count']}/10000\n"
|
| 627 |
status += f"**Preview:** {latest['content'][:400]}...\n\n"
|
| 628 |
else:
|
| 629 |
status += f"## {agent_name.upper()}\n"
|
|
|
|
| 631 |
|
| 632 |
return status
|
| 633 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 634 |
# ============================================================================
|
| 635 |
# MAIN MODEL SETUP
|
| 636 |
# ============================================================================
|
| 637 |
model_id = "Qwen/Qwen3-30B-A3B-Instruct-2507"
|
| 638 |
+
print("Loading ADAM - Main Model (GPU)...")
|
| 639 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 640 |
model = AutoModelForCausalLM.from_pretrained(
|
| 641 |
model_id,
|
|
|
|
| 644 |
trust_remote_code=True
|
| 645 |
)
|
| 646 |
|
| 647 |
+
# Store conversation for analyst
|
| 648 |
+
last_conversation = {"user": "", "adam": ""}
|
| 649 |
+
|
| 650 |
@spaces.GPU(duration=75)
|
| 651 |
def predict(message, history, max_new_tokens):
|
| 652 |
"""
|
| 653 |
+
Predict function - COMPLETELY UNCHANGED CORE LOGIC
|
| 654 |
+
Specialist models work around it, not through it
|
| 655 |
"""
|
| 656 |
+
global last_conversation
|
|
|
|
| 657 |
|
| 658 |
+
# Build system prompt
|
| 659 |
+
system_prompt = adam_personality.personality_context
|
|
|
|
|
|
|
| 660 |
|
| 661 |
+
# Check if librarian should retrieve discourse
|
| 662 |
discourse_keywords = ['paradox', 'agi', 'consciousness', 'quantum', 'physics', 'self-reference', 'qualia']
|
| 663 |
+
if any(keyword in message.lower() for keyword in discourse_keywords):
|
| 664 |
+
librarian_intel = librarian_retrieve(message, context="User query on specialist topic")
|
| 665 |
+
if librarian_intel:
|
| 666 |
+
system_prompt += f"\n\n[LIBRARIAN INTELLIGENCE BRIEF]:\n{librarian_intel}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 667 |
|
| 668 |
messages = [{"role": "system", "content": system_prompt}]
|
| 669 |
|
|
|
|
| 718 |
for new_token in streamer:
|
| 719 |
partial_message += new_token
|
| 720 |
yield partial_message
|
| 721 |
+
|
| 722 |
+
# Store for analyst (runs in background)
|
| 723 |
+
last_conversation["user"] = message
|
| 724 |
+
last_conversation["adam"] = partial_message
|
| 725 |
+
|
| 726 |
+
# Trigger analyst and auditor in background (non-blocking)
|
| 727 |
+
def background_analysis():
|
| 728 |
+
analyst_process(message, partial_message)
|
| 729 |
+
auditor_check("ADAM_main", partial_message)
|
| 730 |
+
|
| 731 |
+
analysis_thread = Thread(target=background_analysis, daemon=True)
|
| 732 |
+
analysis_thread.start()
|
| 733 |
|
| 734 |
# ============================================================================
|
| 735 |
# GRADIO INTERFACE
|
| 736 |
# ============================================================================
|
| 737 |
with gr.Blocks() as demo:
|
| 738 |
+
gr.Markdown("# A.D.A.M. v2.0 - Intelligent Operational Architecture")
|
| 739 |
+
gr.Markdown("πΉ **Main Model (30B GPU)** + **Librarian (0.6B GPU)** + **Analyst (0.6B CPU)** + **Auditor (0.6B CPU)** + **Discourse (4x4B CPU)**")
|
| 740 |
|
| 741 |
with gr.Tab("π¬ Chat"):
|
| 742 |
chat_interface = gr.ChatInterface(
|
|
|
|
| 753 |
examples=[
|
| 754 |
["Let's break down this problem systematically.", 4096],
|
| 755 |
["What's the most efficient approach here?", 4096],
|
|
|
|
| 756 |
["Tell me about consciousness and qualia.", 4096],
|
| 757 |
["What are the latest theories on AGI alignment?", 4096],
|
| 758 |
["Explain quantum entanglement.", 4096]
|
|
|
|
| 762 |
|
| 763 |
with gr.Tab("π§ Discourse Monitor"):
|
| 764 |
gr.Markdown("### Live Background Discourse Activity")
|
| 765 |
+
gr.Markdown("Four specialist AI models (4B each, CPU) continuously discuss deep topics. The Librarian retrieves relevant discourse for ADAM.")
|
| 766 |
discourse_output = gr.Markdown(value=get_discourse_monitor)
|
| 767 |
with gr.Row():
|
| 768 |
refresh_btn = gr.Button("π Refresh Now")
|
|
|
|
| 769 |
|
| 770 |
refresh_btn.click(fn=get_discourse_monitor, outputs=discourse_output)
|
| 771 |
|
| 772 |
+
with gr.Tab("π Full Discourse Outputs"):
|
| 773 |
+
gr.Markdown("### Complete Discourse History")
|
| 774 |
+
gr.Markdown("View the full, untruncated outputs from each discourse model.")
|
| 775 |
+
|
| 776 |
+
discourse_agent_select = gr.Dropdown(
|
| 777 |
+
choices=["paradox", "agi", "consciousness", "physics"],
|
| 778 |
+
label="Select Agent",
|
| 779 |
+
value="paradox"
|
| 780 |
+
)
|
| 781 |
+
discourse_entry_select = gr.Slider(
|
| 782 |
+
minimum=1,
|
| 783 |
+
maximum=10,
|
| 784 |
+
value=1,
|
| 785 |
+
step=1,
|
| 786 |
+
label="Entry Number (1 = most recent)"
|
| 787 |
+
)
|
| 788 |
+
discourse_view_btn = gr.Button("View Full Output")
|
| 789 |
+
discourse_full_output = gr.Markdown()
|
| 790 |
+
|
| 791 |
+
def view_full_discourse(agent, entry_num):
|
| 792 |
+
if agent not in discourse_cache or not discourse_cache[agent]:
|
| 793 |
+
return f"No discourse available yet for {agent.upper()}."
|
| 794 |
+
|
| 795 |
+
cache_list = list(discourse_cache[agent])
|
| 796 |
+
if entry_num > len(cache_list):
|
| 797 |
+
return f"Only {len(cache_list)} entries available for {agent.upper()}."
|
| 798 |
+
|
| 799 |
+
entry = cache_list[-(entry_num)] # Get from end (most recent)
|
| 800 |
+
|
| 801 |
+
output = f"# {agent.upper()} - Full Output\n\n"
|
| 802 |
+
output += f"**Timestamp:** {entry['timestamp']}\n"
|
| 803 |
+
output += f"**Token Count:** {entry['token_count']}/10000\n\n"
|
| 804 |
+
output += "---\n\n"
|
| 805 |
+
output += entry['content']
|
| 806 |
+
|
| 807 |
+
return output
|
| 808 |
+
|
| 809 |
+
discourse_view_btn.click(
|
| 810 |
+
fn=view_full_discourse,
|
| 811 |
+
inputs=[discourse_agent_select, discourse_entry_select],
|
| 812 |
+
outputs=discourse_full_output
|
| 813 |
+
)
|
| 814 |
+
|
| 815 |
+
with gr.Tab("π§ Auxiliary Model Outputs"):
|
| 816 |
+
gr.Markdown("### View Full Outputs from Specialist Models")
|
| 817 |
+
gr.Markdown("See complete outputs from the Librarian, Analyst, and Auditor.")
|
| 818 |
+
|
| 819 |
+
aux_model_select = gr.Radio(
|
| 820 |
+
choices=["Librarian", "Analyst", "Auditor"],
|
| 821 |
+
label="Select Model",
|
| 822 |
+
value="Librarian"
|
| 823 |
+
)
|
| 824 |
+
|
| 825 |
+
# Librarian section
|
| 826 |
+
with gr.Group(visible=True) as librarian_group:
|
| 827 |
+
gr.Markdown("### Librarian - Full Output Test")
|
| 828 |
+
lib_test_query = gr.Textbox(label="Test Query", placeholder="Enter a query to test librarian...")
|
| 829 |
+
lib_test_context = gr.Textbox(label="Context (optional)")
|
| 830 |
+
lib_test_btn = gr.Button("Run Librarian")
|
| 831 |
+
lib_test_output = gr.Markdown()
|
| 832 |
+
|
| 833 |
+
def test_librarian(query, context):
|
| 834 |
+
if not query:
|
| 835 |
+
return "Please enter a query."
|
| 836 |
+
result = librarian_retrieve(query, context)
|
| 837 |
+
output = f"# Librarian Full Output\n\n"
|
| 838 |
+
output += f"**Query:** {query}\n"
|
| 839 |
+
output += f"**Context:** {context if context else 'None'}\n\n"
|
| 840 |
+
output += "---\n\n"
|
| 841 |
+
output += result
|
| 842 |
+
return output
|
| 843 |
+
|
| 844 |
+
lib_test_btn.click(fn=test_librarian, inputs=[lib_test_query, lib_test_context], outputs=lib_test_output)
|
| 845 |
+
|
| 846 |
+
# Analyst section
|
| 847 |
+
with gr.Group(visible=False) as analyst_group:
|
| 848 |
+
gr.Markdown("### Analyst - Full Output Test")
|
| 849 |
+
analyst_test_user = gr.Textbox(label="Simulated User Message", placeholder="Enter a user message...")
|
| 850 |
+
analyst_test_adam = gr.Textbox(label="Simulated ADAM Response", placeholder="Enter ADAM's response...")
|
| 851 |
+
analyst_test_btn = gr.Button("Run Analyst")
|
| 852 |
+
analyst_test_output = gr.Markdown()
|
| 853 |
+
|
| 854 |
+
def test_analyst(user_msg, adam_msg):
|
| 855 |
+
if not user_msg or not adam_msg:
|
| 856 |
+
return "Please enter both user message and ADAM response."
|
| 857 |
+
result = analyst_process(user_msg, adam_msg)
|
| 858 |
+
output = f"# Analyst Full Output\n\n"
|
| 859 |
+
output += f"**User Message:** {user_msg}\n"
|
| 860 |
+
output += f"**ADAM Response:** {adam_msg[:200]}...\n\n"
|
| 861 |
+
output += "---\n\n"
|
| 862 |
+
output += result
|
| 863 |
+
return output
|
| 864 |
+
|
| 865 |
+
analyst_test_btn.click(fn=test_analyst, inputs=[analyst_test_user, analyst_test_adam], outputs=analyst_test_output)
|
| 866 |
+
|
| 867 |
+
# Auditor section
|
| 868 |
+
with gr.Group(visible=False) as auditor_group:
|
| 869 |
+
gr.Markdown("### Auditor - Full Output Test")
|
| 870 |
+
auditor_test_model = gr.Textbox(label="Model Name", placeholder="e.g., ADAM_main, discourse_agi...")
|
| 871 |
+
auditor_test_output_text = gr.Textbox(label="Output to Audit", placeholder="Enter model output to audit...", lines=5)
|
| 872 |
+
auditor_test_btn = gr.Button("Run Auditor")
|
| 873 |
+
auditor_test_output = gr.Markdown()
|
| 874 |
+
|
| 875 |
+
def test_auditor(model_name, output_text):
|
| 876 |
+
if not model_name or not output_text:
|
| 877 |
+
return "Please enter model name and output text."
|
| 878 |
+
result = auditor_check(model_name, output_text)
|
| 879 |
+
output = f"# Auditor Full Output\n\n"
|
| 880 |
+
output += f"**Target Model:** {model_name}\n"
|
| 881 |
+
output += f"**Output Analyzed:** {output_text[:200]}...\n\n"
|
| 882 |
+
output += "---\n\n"
|
| 883 |
+
output += result
|
| 884 |
+
return output
|
| 885 |
+
|
| 886 |
+
auditor_test_btn.click(fn=test_auditor, inputs=[auditor_test_model, auditor_test_output_text], outputs=auditor_test_output)
|
| 887 |
+
|
| 888 |
+
# Toggle visibility based on selection
|
| 889 |
+
def toggle_aux_view(selection):
|
| 890 |
+
return (
|
| 891 |
+
gr.update(visible=(selection == "Librarian")),
|
| 892 |
+
gr.update(visible=(selection == "Analyst")),
|
| 893 |
+
gr.update(visible=(selection == "Auditor"))
|
| 894 |
+
)
|
| 895 |
+
|
| 896 |
+
aux_model_select.change(
|
| 897 |
+
fn=toggle_aux_view,
|
| 898 |
+
inputs=aux_model_select,
|
| 899 |
+
outputs=[librarian_group, analyst_group, auditor_group]
|
| 900 |
+
)
|
| 901 |
+
|
| 902 |
+
with gr.Tab("π Librarian Query"):
|
| 903 |
+
gr.Markdown("### Direct Librarian Access")
|
| 904 |
+
gr.Markdown("Query the Librarian directly to see what intelligence it retrieves from the discourse database.")
|
| 905 |
+
lib_input = gr.Textbox(label="Query", placeholder="What information do you need?")
|
| 906 |
+
lib_context = gr.Textbox(label="Context (optional)", placeholder="Additional context...")
|
| 907 |
+
lib_button = gr.Button("Query Librarian")
|
| 908 |
+
lib_output = gr.Markdown()
|
| 909 |
+
|
| 910 |
+
def query_lib_ui(query, context):
|
| 911 |
+
if not query:
|
| 912 |
+
return "Please enter a query."
|
| 913 |
+
result = librarian_retrieve(query, context)
|
| 914 |
+
return f"# Librarian Intelligence Brief\n\n{result}"
|
| 915 |
+
|
| 916 |
+
lib_button.click(fn=query_lib_ui, inputs=[lib_input, lib_context], outputs=lib_output)
|
| 917 |
+
|
| 918 |
with gr.Tab("π Discourse Search"):
|
| 919 |
gr.Markdown("### Search Discourse Database")
|
| 920 |
search_input = gr.Textbox(label="Search Query", placeholder="Enter keywords to search discourse...")
|
|
|
|
| 930 |
return f"No results found for: {query}"
|
| 931 |
|
| 932 |
output = f"# Search Results for: {query}\n\n"
|
| 933 |
+
output += f"**Total Results:** {len(results)}\n\n"
|
| 934 |
+
for i, (agent, timestamp, content, token_count) in enumerate(results, 1):
|
| 935 |
+
output += f"## Result {i}: {agent.upper()} - {timestamp}\n"
|
| 936 |
output += f"**Tokens:** {token_count}\n\n"
|
| 937 |
+
output += f"**Full Content:**\n\n{content}\n\n"
|
| 938 |
output += "---\n\n"
|
| 939 |
|
| 940 |
return output
|
| 941 |
|
| 942 |
search_button.click(fn=search_discourse_ui, inputs=search_input, outputs=search_output)
|
| 943 |
|
| 944 |
+
with gr.Tab("π€ User Pattern Analysis"):
|
| 945 |
+
gr.Markdown("### Analyst's User Pattern Recognition")
|
| 946 |
+
gr.Markdown("The Analyst (CPU) tracks conversation patterns and identifies user behavior trends.")
|
| 947 |
+
pattern_output = gr.Markdown()
|
| 948 |
+
pattern_button = gr.Button("Get Pattern Analysis")
|
| 949 |
+
|
| 950 |
+
def get_pattern_analysis():
|
| 951 |
+
conn = sqlite3.connect('discourse.db', check_same_thread=False)
|
| 952 |
+
c = conn.cursor()
|
| 953 |
+
|
| 954 |
+
c.execute('''SELECT pattern_type, description, frequency, last_seen
|
| 955 |
+
FROM user_patterns
|
| 956 |
+
ORDER BY frequency DESC, last_seen DESC
|
| 957 |
+
LIMIT 20''')
|
| 958 |
+
patterns = c.fetchall()
|
| 959 |
+
conn.close()
|
| 960 |
+
|
| 961 |
+
if not patterns:
|
| 962 |
+
return "No patterns analyzed yet. Continue conversing with ADAM."
|
| 963 |
+
|
| 964 |
+
output = "# User Pattern Analysis\n\n"
|
| 965 |
+
output += f"**Total Patterns Detected:** {len(patterns)}\n\n"
|
| 966 |
+
|
| 967 |
+
for pattern_type, description, frequency, last_seen in patterns:
|
| 968 |
+
output += f"## {pattern_type.upper()}\n"
|
| 969 |
+
output += f"**Frequency:** {frequency} occurrences\n"
|
| 970 |
+
output += f"**Last Seen:** {last_seen}\n"
|
| 971 |
+
output += f"**Description:** {description[:300]}...\n\n"
|
| 972 |
+
output += "---\n\n"
|
| 973 |
+
|
| 974 |
+
return output
|
| 975 |
+
|
| 976 |
+
pattern_button.click(fn=get_pattern_analysis, outputs=pattern_output)
|
| 977 |
+
|
| 978 |
+
with gr.Tab("π¬ Audit Log"):
|
| 979 |
+
gr.Markdown("### Auditor's Quality Control Reports")
|
| 980 |
+
gr.Markdown("The Auditor (CPU) reviews all model outputs for logical gaps and structural weaknesses.")
|
| 981 |
+
audit_output = gr.Markdown()
|
| 982 |
+
with gr.Row():
|
| 983 |
+
audit_button = gr.Button("Get Audit Report")
|
| 984 |
+
audit_filter = gr.Dropdown(
|
| 985 |
+
choices=["ALL", "CRITICAL", "HIGH", "MEDIUM", "LOW"],
|
| 986 |
+
value="ALL",
|
| 987 |
+
label="Filter by Severity"
|
| 988 |
+
)
|
| 989 |
+
|
| 990 |
+
def get_audit_report(severity_filter):
|
| 991 |
+
conn = sqlite3.connect('discourse.db', check_same_thread=False)
|
| 992 |
+
c = conn.cursor()
|
| 993 |
+
|
| 994 |
+
if severity_filter == "ALL":
|
| 995 |
+
c.execute('''SELECT audit_type, target_model, issue_description, severity, timestamp
|
| 996 |
+
FROM audit_log
|
| 997 |
+
ORDER BY created_at DESC
|
| 998 |
+
LIMIT 30''')
|
| 999 |
+
else:
|
| 1000 |
+
c.execute('''SELECT audit_type, target_model, issue_description, severity, timestamp
|
| 1001 |
+
FROM audit_log
|
| 1002 |
+
WHERE severity = ?
|
| 1003 |
+
ORDER BY created_at DESC
|
| 1004 |
+
LIMIT 30''', (severity_filter,))
|
| 1005 |
+
|
| 1006 |
+
audits = c.fetchall()
|
| 1007 |
+
conn.close()
|
| 1008 |
+
|
| 1009 |
+
if not audits:
|
| 1010 |
+
return f"No audit entries found{' for severity: ' + severity_filter if severity_filter != 'ALL' else ''}."
|
| 1011 |
+
|
| 1012 |
+
output = f"# Audit Report{' - ' + severity_filter if severity_filter != 'ALL' else ''}\n\n"
|
| 1013 |
+
output += f"**Total Entries:** {len(audits)}\n\n"
|
| 1014 |
+
|
| 1015 |
+
severity_icons = {
|
| 1016 |
+
"CRITICAL": "π΄",
|
| 1017 |
+
"HIGH": "π ",
|
| 1018 |
+
"MEDIUM": "π‘",
|
| 1019 |
+
"LOW": "π’"
|
| 1020 |
+
}
|
| 1021 |
+
|
| 1022 |
+
for audit_type, target_model, issue_description, severity, timestamp in audits:
|
| 1023 |
+
icon = severity_icons.get(severity, "βͺ")
|
| 1024 |
+
output += f"## {icon} {severity} - {target_model}\n"
|
| 1025 |
+
output += f"**Type:** {audit_type}\n"
|
| 1026 |
+
output += f"**Time:** {timestamp}\n"
|
| 1027 |
+
output += f"**Issue:** {issue_description[:400]}...\n\n"
|
| 1028 |
+
output += "---\n\n"
|
| 1029 |
+
|
| 1030 |
+
return output
|
| 1031 |
+
|
| 1032 |
+
audit_button.click(fn=get_audit_report, inputs=audit_filter, outputs=audit_output)
|
| 1033 |
+
|
| 1034 |
+
with gr.Tab("π System Stats"):
|
| 1035 |
+
gr.Markdown("### Complete System Statistics")
|
| 1036 |
stats_output = gr.Markdown()
|
| 1037 |
+
stats_button = gr.Button("Get System Stats")
|
| 1038 |
|
| 1039 |
+
def get_system_stats():
|
| 1040 |
conn = sqlite3.connect('discourse.db', check_same_thread=False)
|
| 1041 |
c = conn.cursor()
|
| 1042 |
|
| 1043 |
+
# Discourse stats
|
| 1044 |
c.execute('SELECT COUNT(*) FROM discourse')
|
| 1045 |
+
total_discourse = c.fetchone()[0]
|
| 1046 |
|
|
|
|
| 1047 |
c.execute('SELECT agent, COUNT(*) as count FROM discourse GROUP BY agent')
|
| 1048 |
agent_counts = c.fetchall()
|
| 1049 |
|
|
|
|
| 1050 |
c.execute('SELECT AVG(token_count) FROM discourse')
|
| 1051 |
avg_tokens = c.fetchone()[0] or 0
|
| 1052 |
|
| 1053 |
+
# Pattern stats
|
| 1054 |
+
c.execute('SELECT COUNT(*) FROM user_patterns')
|
| 1055 |
+
total_patterns = c.fetchone()[0]
|
| 1056 |
+
|
| 1057 |
+
# Audit stats
|
| 1058 |
+
c.execute('SELECT COUNT(*) FROM audit_log')
|
| 1059 |
+
total_audits = c.fetchone()[0]
|
| 1060 |
+
|
| 1061 |
+
c.execute('SELECT severity, COUNT(*) as count FROM audit_log GROUP BY severity')
|
| 1062 |
+
audit_by_severity = c.fetchall()
|
| 1063 |
|
| 1064 |
conn.close()
|
| 1065 |
|
| 1066 |
+
stats = "# System Statistics\n\n"
|
| 1067 |
+
stats += "## π Discourse Database\n"
|
| 1068 |
+
stats += f"**Total Entries:** {total_discourse}\n"
|
| 1069 |
stats += f"**Average Token Count:** {int(avg_tokens)}\n\n"
|
| 1070 |
|
| 1071 |
+
stats += "### Entries by Agent\n"
|
|
|
|
|
|
|
|
|
|
| 1072 |
for agent, count in agent_counts:
|
| 1073 |
stats += f"- **{agent.upper()}:** {count} entries\n"
|
| 1074 |
|
| 1075 |
+
stats += "\n## π€ User Pattern Analysis\n"
|
| 1076 |
+
stats += f"**Total Patterns Detected:** {total_patterns}\n\n"
|
| 1077 |
+
|
| 1078 |
+
stats += "## π¬ Audit System\n"
|
| 1079 |
+
stats += f"**Total Audits Performed:** {total_audits}\n\n"
|
| 1080 |
+
|
| 1081 |
+
if audit_by_severity:
|
| 1082 |
+
stats += "### Issues by Severity\n"
|
| 1083 |
+
for severity, count in audit_by_severity:
|
| 1084 |
+
stats += f"- **{severity}:** {count} issues\n"
|
| 1085 |
+
|
| 1086 |
+
stats += "\n## π€ Operational Models\n"
|
| 1087 |
+
stats += "- **ADAM (Main):** Qwen3-30B (GPU)\n"
|
| 1088 |
+
stats += "- **Librarian:** Qwen2.5-1.5B-Instruct (GPU)\n"
|
| 1089 |
+
stats += "- **Analyst:** Qwen3-0.6B-Base (CPU)\n"
|
| 1090 |
+
stats += "- **Auditor:** Qwen3-0.6B-Base (CPU)\n"
|
| 1091 |
+
stats += "- **Paradox Specialist:** Qwen3-4B-Instruct (CPU)\n"
|
| 1092 |
+
stats += "- **AGI Theorist:** Qwen3-4B-Instruct (CPU)\n"
|
| 1093 |
+
stats += "- **Consciousness Explorer:** Qwen3-4B-Instruct (CPU)\n"
|
| 1094 |
+
stats += "- **Physics Analyst:** Qwen3-4B-Instruct (CPU)\n"
|
| 1095 |
+
|
| 1096 |
return stats
|
| 1097 |
|
| 1098 |
+
stats_button.click(fn=get_system_stats, outputs=stats_output)
|
| 1099 |
|
| 1100 |
if __name__ == "__main__":
|
| 1101 |
print("=" * 80)
|
| 1102 |
+
print("A.D.A.M. v2.0 - Intelligent Operational Architecture")
|
| 1103 |
+
print("=" * 80)
|
| 1104 |
+
print("MAIN MODEL:")
|
| 1105 |
+
print(" - ADAM: Qwen3-30B-A3B-Instruct (GPU)")
|
| 1106 |
+
print()
|
| 1107 |
+
print("SPECIALIST SUPPORT MODELS:")
|
| 1108 |
+
print(" - Librarian: Qwen2.5-1.5B-Instruct (GPU) - Database Intelligence")
|
| 1109 |
+
print(" - Analyst: Qwen3-0.6B-Base (CPU) - User Pattern Recognition")
|
| 1110 |
+
print(" - Auditor: Qwen3-0.6B-Base (CPU) - Quality Control")
|
| 1111 |
+
print()
|
| 1112 |
+
print("BACKGROUND DISCOURSE MODELS:")
|
| 1113 |
+
print(" - Paradox Specialist: Qwen3-4B-Instruct (CPU)")
|
| 1114 |
+
print(" - AGI Theorist: Qwen3-4B-Instruct (CPU)")
|
| 1115 |
+
print(" - Consciousness Explorer: Qwen3-4B-Instruct (CPU)")
|
| 1116 |
+
print(" - Physics Analyst: Qwen3-4B-Instruct (CPU)")
|
| 1117 |
+
print()
|
| 1118 |
+
print("DATABASE: SQLite (discourse.db)")
|
| 1119 |
print("=" * 80)
|
| 1120 |
demo.launch()
|