Create app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,10 @@
|
|
| 1 |
import os
|
| 2 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 3 |
-
|
|
|
|
| 4 |
import torch
|
|
|
|
|
|
|
| 5 |
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
| 6 |
from threading import Thread
|
| 7 |
import time
|
|
@@ -10,17 +13,9 @@ from datetime import datetime
|
|
| 10 |
import warnings
|
| 11 |
warnings.filterwarnings("ignore", category=FutureWarning)
|
| 12 |
|
| 13 |
-
# LangChain imports
|
| 14 |
-
from langchain.agents import AgentExecutor, create_tool_calling_agent
|
| 15 |
-
from langchain_core.prompts import ChatPromptTemplate
|
| 16 |
-
from langchain_core.messages import HumanMessage, AIMessage
|
| 17 |
-
from langchain.tools import BaseTool
|
| 18 |
-
from langchain_community.tools import DuckDuckGoSearchRun, WikipediaQueryRun
|
| 19 |
-
from langchain_experimental.utilities import PythonREPL
|
| 20 |
-
|
| 21 |
# ====================== MODEL LOADING ======================
|
| 22 |
|
| 23 |
-
# Main
|
| 24 |
main_model_name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
|
| 25 |
main_tokenizer = AutoTokenizer.from_pretrained(main_model_name)
|
| 26 |
main_model = AutoModelForCausalLM.from_pretrained(
|
|
@@ -29,7 +24,7 @@ main_model = AutoModelForCausalLM.from_pretrained(
|
|
| 29 |
device_map="auto"
|
| 30 |
)
|
| 31 |
|
| 32 |
-
#
|
| 33 |
aux_model_name = "Qwen/Qwen3-0.6B-Base"
|
| 34 |
aux_tokenizer = AutoTokenizer.from_pretrained(aux_model_name)
|
| 35 |
logic_model = AutoModelForCausalLM.from_pretrained(
|
|
@@ -48,7 +43,7 @@ awareness_model = AutoModelForCausalLM.from_pretrained(
|
|
| 48 |
device_map="auto"
|
| 49 |
)
|
| 50 |
|
| 51 |
-
# Background
|
| 52 |
bg_model_name = "Qwen/Qwen3-4B-Thinking-2507"
|
| 53 |
bg_tokenizer = AutoTokenizer.from_pretrained(bg_model_name)
|
| 54 |
|
|
@@ -73,7 +68,7 @@ physics_model = AutoModelForCausalLM.from_pretrained(
|
|
| 73 |
device_map="cpu"
|
| 74 |
)
|
| 75 |
|
| 76 |
-
# ====================== DISCOURSE CACHE
|
| 77 |
|
| 78 |
discourse_cache = {
|
| 79 |
"paradox": deque(maxlen=10),
|
|
@@ -95,7 +90,7 @@ discourse_status = {
|
|
| 95 |
"last_update": None
|
| 96 |
}
|
| 97 |
|
| 98 |
-
# ====================== FULL
|
| 99 |
|
| 100 |
DISCOURSE_AGENTS = {
|
| 101 |
"paradox": {
|
|
@@ -184,9 +179,12 @@ Your role: Connect physics to information, consciousness, computation. Challenge
|
|
| 184 |
}
|
| 185 |
}
|
| 186 |
|
| 187 |
-
# ====================== BACKGROUND DISCOURSE
|
| 188 |
|
| 189 |
def generate_discourse_turn(agent_name, context, max_tokens=20000):
|
|
|
|
|
|
|
|
|
|
| 190 |
agent = DISCOURSE_AGENTS[agent_name]
|
| 191 |
model = agent["model"]
|
| 192 |
|
|
@@ -229,6 +227,9 @@ def generate_discourse_turn(agent_name, context, max_tokens=20000):
|
|
| 229 |
return response
|
| 230 |
|
| 231 |
def background_discourse_loop():
|
|
|
|
|
|
|
|
|
|
| 232 |
agent_names = list(DISCOURSE_AGENTS.keys())
|
| 233 |
|
| 234 |
while discourse_active:
|
|
@@ -259,181 +260,281 @@ def background_discourse_loop():
|
|
| 259 |
|
| 260 |
time.sleep(2)
|
| 261 |
|
| 262 |
-
# Start
|
| 263 |
discourse_thread = Thread(target=background_discourse_loop, daemon=True)
|
| 264 |
discourse_thread.start()
|
| 265 |
|
| 266 |
-
# ======================
|
| 267 |
|
| 268 |
-
def query_pathway(model, tokenizer, instruction,
|
| 269 |
-
prompt = f"{instruction}\n\
|
| 270 |
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
|
|
|
| 271 |
with torch.no_grad():
|
| 272 |
outputs = model.generate(
|
| 273 |
**inputs,
|
| 274 |
max_new_tokens=max_tokens,
|
| 275 |
do_sample=True,
|
| 276 |
temperature=0.8,
|
| 277 |
-
top_p=0.95
|
| 278 |
)
|
|
|
|
| 279 |
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 280 |
return response[len(prompt):].strip()
|
| 281 |
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
latest = list(discourse_cache[topic])[-1]
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
f"(Full: {latest['token_count']} tokens)"
|
| 298 |
-
)
|
| 299 |
-
return "\n\n".join(results) if results else "Background discourse is still initializing. Please wait a moment."
|
| 300 |
-
|
| 301 |
-
class LogicPathwayTool(BaseTool):
|
| 302 |
-
name = "logic_pathway"
|
| 303 |
-
description = "Activate pure logical and analytical reasoning pathway"
|
| 304 |
-
def _run(self, query: str) -> str:
|
| 305 |
-
return query_pathway(logic_model, aux_tokenizer, "[LOGIC PATHWAY] Analyze rigorously:", query)
|
| 306 |
-
|
| 307 |
-
class EmotionalPathwayTool(BaseTool):
|
| 308 |
-
name = "emotional_pathway"
|
| 309 |
-
description = "Activate empathetic and emotional understanding pathway"
|
| 310 |
-
def _run(self, query: str) -> str:
|
| 311 |
-
return query_pathway(emotional_model, aux_tokenizer, "[EMOTIONAL PATHWAY] Assess with empathy:", query)
|
| 312 |
-
|
| 313 |
-
class AwarenessPathwayTool(BaseTool):
|
| 314 |
-
name = "awareness_pathway"
|
| 315 |
-
description = "Activate metacognitive self-awareness pathway"
|
| 316 |
-
def _run(self, query: str) -> str:
|
| 317 |
-
return query_pathway(awareness_model, aux_tokenizer, "[AWARENESS PATHWAY] Reflect metacognitively:", query)
|
| 318 |
-
|
| 319 |
-
# ====================== LANGCHAIN TOOL LIST ======================
|
| 320 |
-
|
| 321 |
-
tools = [
|
| 322 |
-
DeepDiscourseTool(),
|
| 323 |
-
LogicPathwayTool(),
|
| 324 |
-
EmotionalPathwayTool(),
|
| 325 |
-
AwarenessPathwayTool(),
|
| 326 |
-
DuckDuckGoSearchRun(),
|
| 327 |
-
WikipediaQueryRun(),
|
| 328 |
-
PythonREPL(),
|
| 329 |
-
]
|
| 330 |
|
| 331 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
|
| 333 |
-
|
| 334 |
-
from langchain_core.outputs import LLMResult
|
| 335 |
-
from typing import List
|
| 336 |
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
)
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
|
| 382 |
-
|
| 383 |
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 390 |
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
|
| 400 |
# ====================== GRADIO INTERFACE ======================
|
| 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 |
-
clear.click(lambda: None, None, chatbot, queue=False)
|
| 438 |
|
| 439 |
-
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import spaces
|
| 5 |
import torch
|
| 6 |
+
import json
|
| 7 |
+
import re
|
| 8 |
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
| 9 |
from threading import Thread
|
| 10 |
import time
|
|
|
|
| 13 |
import warnings
|
| 14 |
warnings.filterwarnings("ignore", category=FutureWarning)
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
# ====================== MODEL LOADING ======================
|
| 17 |
|
| 18 |
+
# Main model (30B) - GPU
|
| 19 |
main_model_name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
|
| 20 |
main_tokenizer = AutoTokenizer.from_pretrained(main_model_name)
|
| 21 |
main_model = AutoModelForCausalLM.from_pretrained(
|
|
|
|
| 24 |
device_map="auto"
|
| 25 |
)
|
| 26 |
|
| 27 |
+
# Auxiliary models (0.6B each) - GPU - Neural Pathway Coordinators
|
| 28 |
aux_model_name = "Qwen/Qwen3-0.6B-Base"
|
| 29 |
aux_tokenizer = AutoTokenizer.from_pretrained(aux_model_name)
|
| 30 |
logic_model = AutoModelForCausalLM.from_pretrained(
|
|
|
|
| 43 |
device_map="auto"
|
| 44 |
)
|
| 45 |
|
| 46 |
+
# Background Cognition Models (4B each) - CPU - Continuous Discourse Engines
|
| 47 |
bg_model_name = "Qwen/Qwen3-4B-Thinking-2507"
|
| 48 |
bg_tokenizer = AutoTokenizer.from_pretrained(bg_model_name)
|
| 49 |
|
|
|
|
| 68 |
device_map="cpu"
|
| 69 |
)
|
| 70 |
|
| 71 |
+
# ====================== DISCOURSE CACHE ======================
|
| 72 |
|
| 73 |
discourse_cache = {
|
| 74 |
"paradox": deque(maxlen=10),
|
|
|
|
| 90 |
"last_update": None
|
| 91 |
}
|
| 92 |
|
| 93 |
+
# ====================== FULL DISCOURSE AGENTS (NOT SHORTENED) ======================
|
| 94 |
|
| 95 |
DISCOURSE_AGENTS = {
|
| 96 |
"paradox": {
|
|
|
|
| 179 |
}
|
| 180 |
}
|
| 181 |
|
| 182 |
+
# ====================== BACKGROUND DISCOURSE ======================
|
| 183 |
|
| 184 |
def generate_discourse_turn(agent_name, context, max_tokens=20000):
|
| 185 |
+
"""Generate a discourse turn for a background agent"""
|
| 186 |
+
global discourse_status
|
| 187 |
+
|
| 188 |
agent = DISCOURSE_AGENTS[agent_name]
|
| 189 |
model = agent["model"]
|
| 190 |
|
|
|
|
| 227 |
return response
|
| 228 |
|
| 229 |
def background_discourse_loop():
|
| 230 |
+
"""Continuous background discourse between specialist models"""
|
| 231 |
+
global discourse_active
|
| 232 |
+
|
| 233 |
agent_names = list(DISCOURSE_AGENTS.keys())
|
| 234 |
|
| 235 |
while discourse_active:
|
|
|
|
| 260 |
|
| 261 |
time.sleep(2)
|
| 262 |
|
| 263 |
+
# Start background discourse thread
|
| 264 |
discourse_thread = Thread(target=background_discourse_loop, daemon=True)
|
| 265 |
discourse_thread.start()
|
| 266 |
|
| 267 |
+
# ====================== TOOLS & PATHWAYS ======================
|
| 268 |
|
| 269 |
+
def query_pathway(model, tokenizer, instruction, context, max_tokens=256):
|
| 270 |
+
prompt = f"{instruction}\n\nContext: {context}\n\nCoordination Output:"
|
| 271 |
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 272 |
+
|
| 273 |
with torch.no_grad():
|
| 274 |
outputs = model.generate(
|
| 275 |
**inputs,
|
| 276 |
max_new_tokens=max_tokens,
|
| 277 |
do_sample=True,
|
| 278 |
temperature=0.8,
|
| 279 |
+
top_p=0.95,
|
| 280 |
)
|
| 281 |
+
|
| 282 |
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 283 |
return response[len(prompt):].strip()
|
| 284 |
|
| 285 |
+
TOOLS = [
|
| 286 |
+
{
|
| 287 |
+
"type": "function",
|
| 288 |
+
"function": {
|
| 289 |
+
"name": "logic_pathway",
|
| 290 |
+
"description": "Activate Logic Pathway for analytical reasoning",
|
| 291 |
+
"parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}
|
| 292 |
+
}
|
| 293 |
+
},
|
| 294 |
+
{
|
| 295 |
+
"type": "function",
|
| 296 |
+
"function": {
|
| 297 |
+
"name": "emotional_pathway",
|
| 298 |
+
"description": "Activate Emotional Pathway for empathetic understanding",
|
| 299 |
+
"parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}
|
| 300 |
+
}
|
| 301 |
+
},
|
| 302 |
+
{
|
| 303 |
+
"type": "function",
|
| 304 |
+
"function": {
|
| 305 |
+
"name": "awareness_pathway",
|
| 306 |
+
"description": "Activate Self-Awareness Pathway for metacognition",
|
| 307 |
+
"parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}
|
| 308 |
+
}
|
| 309 |
+
},
|
| 310 |
+
{
|
| 311 |
+
"type": "function",
|
| 312 |
+
"function": {
|
| 313 |
+
"name": "access_discourse_cache",
|
| 314 |
+
"description": "Access the background discourse cache from specialist models continuously discussing paradoxes, AGI, consciousness, and physics. Use this for deep theoretical insights.",
|
| 315 |
+
"parameters": {"type": "object", "properties": {"topics": {"type": "array", "items": {"type": "string"}, "description": "Topics to query: paradox, agi, consciousness, physics"}}, "required": ["topics"]}
|
| 316 |
+
}
|
| 317 |
+
}
|
| 318 |
+
]
|
| 319 |
|
| 320 |
+
def execute_tool_call(tool_name, arguments):
|
| 321 |
+
if tool_name == "logic_pathway":
|
| 322 |
+
instruction = "[LOGIC PATHWAY] Analyze logically:"
|
| 323 |
+
return query_pathway(logic_model, aux_tokenizer, instruction, arguments.get("query", ""))
|
| 324 |
+
|
| 325 |
+
elif tool_name == "emotional_pathway":
|
| 326 |
+
instruction = "[EMOTIONAL PATHWAY] Assess emotionally:"
|
| 327 |
+
return query_pathway(emotional_model, aux_tokenizer, instruction, arguments.get("query", ""))
|
| 328 |
+
|
| 329 |
+
elif tool_name == "awareness_pathway":
|
| 330 |
+
instruction = "[AWARENESS PATHWAY] Reflect metacognitively:"
|
| 331 |
+
return query_pathway(awareness_model, aux_tokenizer, instruction, arguments.get("query", ""))
|
| 332 |
+
|
| 333 |
+
elif tool_name == "access_discourse_cache":
|
| 334 |
+
topics = arguments.get("topics", [])
|
| 335 |
+
cache_content = []
|
| 336 |
+
for topic in topics:
|
| 337 |
+
if topic in discourse_cache and discourse_cache[topic]:
|
| 338 |
latest = list(discourse_cache[topic])[-1]
|
| 339 |
+
cache_content.append(f"[{topic.upper()} DISCOURSE - {latest['timestamp']}]:\n{latest['content'][:1000]}... ({latest['token_count']} tokens)")
|
| 340 |
+
return "\n\n".join(cache_content) if cache_content else "No discourse available yet."
|
| 341 |
+
|
| 342 |
+
return "Tool not found"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
|
| 344 |
+
def parse_tool_calls(text):
|
| 345 |
+
tool_calls = []
|
| 346 |
+
pattern = r'<tool_call>\s*\{[^}]+\}\s*</tool_call>'
|
| 347 |
+
matches = re.findall(pattern, text, re.DOTALL)
|
| 348 |
+
|
| 349 |
+
for match in matches:
|
| 350 |
+
try:
|
| 351 |
+
json_str = re.search(r'\{[^}]+\}', match, re.DOTALL).group()
|
| 352 |
+
tool_data = json.loads(json_str)
|
| 353 |
+
tool_calls.append(tool_data)
|
| 354 |
+
except:
|
| 355 |
+
continue
|
| 356 |
+
|
| 357 |
+
return tool_calls
|
| 358 |
|
| 359 |
+
# ====================== MAIN CHAT FUNCTION (FIXED STREAMING) ======================
|
|
|
|
|
|
|
| 360 |
|
| 361 |
+
@spaces.GPU
|
| 362 |
+
def chat(message, history, max_tokens):
|
| 363 |
+
messages = [
|
| 364 |
+
{"role": "system", "content": """You have access to:
|
| 365 |
+
1. Neural pathways: logic_pathway, emotional_pathway, awareness_pathway
|
| 366 |
+
2. Background discourse cache: access_discourse_cache (specialist AIs continuously discussing deep topics)
|
| 367 |
+
Use <tool_call>{"name": "tool_name", "arguments": {...}}</tool_call> format."""}
|
| 368 |
+
]
|
| 369 |
+
|
| 370 |
+
for item in history:
|
| 371 |
+
messages.append({"role": item["role"], "content": item["content"]})
|
| 372 |
+
|
| 373 |
+
messages.append({"role": "user", "content": message})
|
| 374 |
+
|
| 375 |
+
max_iterations = 5
|
| 376 |
+
iteration = 0
|
| 377 |
+
|
| 378 |
+
while iteration < max_iterations:
|
| 379 |
+
iteration += 1
|
| 380 |
+
|
| 381 |
+
text = main_tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 382 |
+
inputs = main_tokenizer([text], return_tensors="pt").to(main_model.device)
|
| 383 |
+
|
| 384 |
+
with torch.no_grad():
|
| 385 |
+
outputs = main_model.generate(
|
| 386 |
+
**inputs,
|
| 387 |
+
max_new_tokens=max_tokens,
|
| 388 |
+
do_sample=True,
|
| 389 |
+
temperature=0.7,
|
| 390 |
+
top_p=0.9
|
| 391 |
)
|
| 392 |
+
|
| 393 |
+
full_response = main_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 394 |
+
response = full_response[len(text):].strip()
|
| 395 |
+
|
| 396 |
+
tool_calls = parse_tool_calls(response)
|
| 397 |
+
|
| 398 |
+
if not tool_calls:
|
| 399 |
+
yield response
|
| 400 |
+
return
|
| 401 |
+
|
| 402 |
+
tool_results = []
|
| 403 |
+
for tool_call in tool_calls:
|
| 404 |
+
result = execute_tool_call(tool_call.get("name"), tool_call.get("arguments", {}))
|
| 405 |
+
tool_results.append(f"[{tool_call.get('name')}]: {result}")
|
| 406 |
+
|
| 407 |
+
intermediate = (
|
| 408 |
+
"Consulting Neural Pathways & Background Discourse...\n\n"
|
| 409 |
+
f"{response}\n\n"
|
| 410 |
+
"---\n\n"
|
| 411 |
+
"**Insights Gathered:**\n" +
|
| 412 |
+
"\n".join(tool_results) +
|
| 413 |
+
"\n\n*Synthesizing final response...*"
|
| 414 |
+
)
|
| 415 |
+
yield intermediate
|
| 416 |
+
|
| 417 |
+
messages.append({"role": "assistant", "content": response})
|
| 418 |
+
messages.append({"role": "user", "content": "\n\n".join(tool_results) + "\n\nNow provide a complete natural language response synthesizing these insights. Do NOT make any more tool calls, just give your final answer."})
|
| 419 |
+
|
| 420 |
+
yield response + "\n\n[Max iterations reached]"
|
| 421 |
+
|
| 422 |
+
# ====================== GRADIO RESPOND FUNCTION (FIXED) ======================
|
| 423 |
+
|
| 424 |
+
def respond(message, history, max_tokens):
|
| 425 |
+
if not history:
|
| 426 |
+
history = []
|
| 427 |
+
if history and isinstance(history[0], tuple):
|
| 428 |
+
new_history = []
|
| 429 |
+
for u, a in history:
|
| 430 |
+
if u: new_history.append({"role": "user", "content": u})
|
| 431 |
+
if a: new_history.append({"role": "assistant", "content": a})
|
| 432 |
+
history = new_history
|
| 433 |
+
|
| 434 |
+
history.append({"role": "user", "content": message})
|
| 435 |
+
history.append({"role": "assistant", "content": ""})
|
| 436 |
+
|
| 437 |
+
for partial_response in chat(message, history[:-1], max_tokens):
|
| 438 |
+
history[-1]["content"] = partial_response
|
| 439 |
+
yield history
|
| 440 |
|
| 441 |
+
# ====================== DISCOURSE MONITOR ======================
|
| 442 |
|
| 443 |
+
def get_discourse_monitor():
|
| 444 |
+
status = "# Background Discourse Monitor\n\n"
|
| 445 |
+
|
| 446 |
+
if discourse_status["current_agent"]:
|
| 447 |
+
elapsed = (datetime.now() - discourse_status["start_time"]).total_seconds() if discourse_status["start_time"] else 0
|
| 448 |
+
status += f"## ACTIVE NOW\n"
|
| 449 |
+
status += f"**Current Agent:** {discourse_status['current_agent'].upper()}\n"
|
| 450 |
+
status += f"**Tokens Generated:** {discourse_status['tokens_generated']}/20000\n"
|
| 451 |
+
status += f"**Elapsed Time:** {int(elapsed)}s\n"
|
| 452 |
+
status += f"**Last Update:** {discourse_status['last_update'].strftime('%H:%M:%S') if discourse_status['last_update'] else 'N/A'}\n"
|
| 453 |
+
progress = int(discourse_status['tokens_generated'] / 400)
|
| 454 |
+
status += f"**Progress:** {'█' * progress}{'░' * (50 - progress)} {int(discourse_status['tokens_generated']/200)}%\n\n"
|
| 455 |
+
else:
|
| 456 |
+
status += "## INITIALIZING\nWaiting for discourse to begin...\n\n"
|
| 457 |
+
|
| 458 |
+
status += "---\n\n"
|
| 459 |
+
|
| 460 |
+
for agent_name in DISCOURSE_AGENTS.keys():
|
| 461 |
+
if discourse_cache[agent_name]:
|
| 462 |
+
latest = list(discourse_cache[agent_name])[-1]
|
| 463 |
+
status += f"## {agent_name.upper()}\n"
|
| 464 |
+
status += f"**Last Completed:** {latest['timestamp']}\n"
|
| 465 |
+
status += f"**Token Count:** {latest['token_count']}/20000\n"
|
| 466 |
+
status += f"**Preview:** {latest['content'][:400]}...\n\n"
|
| 467 |
+
else:
|
| 468 |
+
status += f"## {agent_name.upper()}\n"
|
| 469 |
+
status += f"**Status:** Waiting for first turn...\n\n"
|
| 470 |
+
|
| 471 |
+
return status
|
| 472 |
|
| 473 |
+
def get_full_discourse(agent_name):
|
| 474 |
+
if agent_name not in discourse_cache or not discourse_cache[agent_name]:
|
| 475 |
+
return f"# {agent_name.upper()} - No discourse available yet\n\nWaiting for first turn..."
|
| 476 |
+
|
| 477 |
+
latest = list(discourse_cache[agent_name])[-1]
|
| 478 |
+
output = f"# {agent_name.upper()} - Full Discourse\n\n"
|
| 479 |
+
output += f"**Timestamp:** {latest['timestamp']}\n"
|
| 480 |
+
output += f"**Token Count:** {latest['token_count']}/20000\n"
|
| 481 |
+
output += f"**Agent Topic:** {DISCOURSE_AGENTS[agent_name]['topic']}\n\n"
|
| 482 |
+
output += "---\n\n"
|
| 483 |
+
output += latest['content']
|
| 484 |
+
|
| 485 |
+
return output
|
| 486 |
|
| 487 |
# ====================== GRADIO INTERFACE ======================
|
| 488 |
|
| 489 |
+
with gr.Blocks() as demo:
|
| 490 |
+
gr.Markdown("# Qwen3 Multi-Layer Cognitive Architecture")
|
| 491 |
+
gr.Markdown("Main model (GPU) + Neural Pathways (GPU) + Background Discourse (CPU)")
|
| 492 |
+
|
| 493 |
+
with gr.Tab("Chat"):
|
| 494 |
+
with gr.Row():
|
| 495 |
+
with gr.Column(scale=4):
|
| 496 |
+
chatbot = gr.Chatbot(height=600)
|
| 497 |
+
msg = gr.Textbox(label="Message", placeholder="Ask me anything...", scale=8)
|
| 498 |
+
with gr.Row():
|
| 499 |
+
submit = gr.Button("Send", variant="primary")
|
| 500 |
+
clear = gr.Button("Clear")
|
| 501 |
+
with gr.Column(scale=1):
|
| 502 |
+
max_tokens_slider = gr.Slider(
|
| 503 |
+
minimum=512,
|
| 504 |
+
maximum=32000,
|
| 505 |
+
value=2048,
|
| 506 |
+
step=512,
|
| 507 |
+
label="Max Tokens",
|
| 508 |
+
info="Response length"
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
msg.submit(respond, [msg, chatbot, max_tokens_slider], chatbot)
|
| 512 |
+
submit.click(respond, [msg, chatbot, max_tokens_slider], chatbot)
|
| 513 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
| 514 |
+
|
| 515 |
+
with gr.Tab("Discourse Monitor"):
|
| 516 |
+
gr.Markdown("### Live Background Discourse Activity")
|
| 517 |
+
discourse_output = gr.Markdown(value=get_discourse_monitor())
|
| 518 |
+
refresh_btn = gr.Button("Refresh Status")
|
| 519 |
+
|
| 520 |
+
gr.Markdown("### View Full Discourse Outputs")
|
| 521 |
+
with gr.Row():
|
| 522 |
+
paradox_btn = gr.Button("View Full PARADOX")
|
| 523 |
+
agi_btn = gr.Button("View Full AGI")
|
| 524 |
+
consciousness_btn = gr.Button("View Full CONSCIOUSNESS")
|
| 525 |
+
physics_btn = gr.Button("View Full PHYSICS")
|
| 526 |
+
|
| 527 |
+
full_discourse_output = gr.Markdown("Click a button above to view full discourse output")
|
| 528 |
+
|
| 529 |
+
refresh_btn.click(fn=get_discourse_monitor, outputs=discourse_output)
|
| 530 |
+
|
| 531 |
+
paradox_btn.click(fn=lambda: get_full_discourse("paradox"), outputs=full_discourse_output)
|
| 532 |
+
agi_btn.click(fn=lambda: get_full_discourse("agi"), outputs=full_discourse_output)
|
| 533 |
+
consciousness_btn.click(fn=lambda: get_full_discourse("consciousness"), outputs=full_discourse_output)
|
| 534 |
+
physics_btn.click(fn=lambda: get_full_discourse("physics"), outputs=full_discourse_output)
|
| 535 |
|
| 536 |
+
# Auto-refresh discourse monitor every 10 seconds
|
| 537 |
+
demo.load(get_discourse_monitor, None, discourse_output, every=10)
|
|
|
|
| 538 |
|
| 539 |
+
if __name__ == "__main__":
|
| 540 |
+
demo.launch()
|