Spaces:
Sleeping
Sleeping
Update modules/orchestrator.py
Browse files- modules/orchestrator.py +125 -126
modules/orchestrator.py
CHANGED
|
@@ -15,198 +15,197 @@ from typing import Dict, Any, List, Optional, Union, Callable
|
|
| 15 |
from dataclasses import dataclass, field
|
| 16 |
from fastapi import APIRouter, Form, Request
|
| 17 |
|
| 18 |
-
# Pygments for Colorful Coding
|
| 19 |
-
from pygments import highlight
|
| 20 |
-
from pygments.lexers import get_lexer_by_name, PythonLexer
|
| 21 |
-
from pygments.formatters import HtmlFormatter
|
| 22 |
-
|
| 23 |
# =================================================================
|
| 24 |
-
# 1.
|
| 25 |
# =================================================================
|
| 26 |
@dataclass
|
| 27 |
class MasterConfig:
|
| 28 |
-
version: str = "4.
|
| 29 |
max_workers: int = os.cpu_count() or 4
|
| 30 |
timeout: int = 150
|
| 31 |
memory_limit_mb: int = 1024
|
| 32 |
log_file: str = "logs/orchestrator_titan.log"
|
|
|
|
| 33 |
username: str = "AumCoreAI"
|
| 34 |
repo_name: str = "aumcore-m7b-docker"
|
| 35 |
-
|
| 36 |
-
code_style: str = "monokai"
|
| 37 |
|
| 38 |
# =================================================================
|
| 39 |
-
# 2.
|
| 40 |
# =================================================================
|
| 41 |
-
class
|
| 42 |
-
|
|
|
|
| 43 |
if not os.path.exists('logs'): os.makedirs('logs')
|
| 44 |
-
self.logger = logging.getLogger("
|
| 45 |
self.logger.setLevel(logging.DEBUG)
|
| 46 |
if not self.logger.handlers:
|
| 47 |
-
|
| 48 |
-
fh = logging.FileHandler(log_file)
|
| 49 |
-
fh.setFormatter(
|
| 50 |
self.logger.addHandler(fh)
|
| 51 |
ch = logging.StreamHandler()
|
| 52 |
-
ch.setFormatter(
|
| 53 |
self.logger.addHandler(ch)
|
| 54 |
|
| 55 |
-
def
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
elif level == "warn": self.logger.warning(msg)
|
| 59 |
-
|
| 60 |
-
# =================================================================
|
| 61 |
-
# 3. COLORFUL FORMATTING ENGINE (PYGMENTS INTEGRATION)
|
| 62 |
-
# =================================================================
|
| 63 |
-
class ColorfulFormatter:
|
| 64 |
-
"""The Engine that kills Black & White responses"""
|
| 65 |
-
def __init__(self, style: str):
|
| 66 |
-
self.formatter = HtmlFormatter(style=style, noclasses=True, nowrap=True)
|
| 67 |
-
self.style_defs = HtmlFormatter(style=style).get_style_defs('.highlight')
|
| 68 |
-
|
| 69 |
-
def inject_colors(self, text: str) -> str:
|
| 70 |
-
"""Finds markdown blocks and injects colorful HTML"""
|
| 71 |
-
# Pattern to match ```lang \n code \n ```
|
| 72 |
-
pattern = r"```(\w+)\n(.*?)\n```"
|
| 73 |
-
|
| 74 |
-
def replacer(match):
|
| 75 |
-
lang = match.group(1)
|
| 76 |
-
code = match.group(2)
|
| 77 |
-
try:
|
| 78 |
-
lexer = get_lexer_by_name(lang, stripall=True)
|
| 79 |
-
except:
|
| 80 |
-
lexer = PythonLexer(stripall=True)
|
| 81 |
-
|
| 82 |
-
colored_code = highlight(code, lexer, self.formatter)
|
| 83 |
-
return (
|
| 84 |
-
f'<div style="background-color: #272822; color: #f8f8f2; border-radius: 10px; '
|
| 85 |
-
f'padding: 15px; margin: 10px 0; font-family: Consolas, monospace; overflow-x: auto; '
|
| 86 |
-
f'border: 1px solid #444;">'
|
| 87 |
-
f'<div style="color: #66d9ef; margin-bottom: 5px; font-size: 0.8em; '
|
| 88 |
-
f'text-transform: uppercase;">{lang} Editor</div>'
|
| 89 |
-
f'<pre style="margin: 0;">{colored_code}</pre></div>'
|
| 90 |
-
)
|
| 91 |
-
|
| 92 |
-
return re.sub(pattern, replacer, text, flags=re.DOTALL)
|
| 93 |
|
| 94 |
# =================================================================
|
| 95 |
-
#
|
| 96 |
# =================================================================
|
| 97 |
-
class
|
| 98 |
-
|
|
|
|
| 99 |
self.client = client
|
| 100 |
-
self.
|
| 101 |
-
self.
|
| 102 |
|
| 103 |
-
async def
|
| 104 |
-
"""
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
"
|
| 124 |
-
"
|
| 125 |
-
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
)
|
|
|
|
| 128 |
try:
|
| 129 |
-
# Use executor for blocking Groq call
|
| 130 |
loop = asyncio.get_event_loop()
|
| 131 |
-
|
| 132 |
model="llama-3.3-70b-versatile",
|
| 133 |
-
messages=[
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
| 135 |
max_tokens=3000
|
| 136 |
))
|
| 137 |
-
return
|
| 138 |
except Exception as e:
|
| 139 |
-
|
| 140 |
-
return f"❌ System Error in Generation: {str(e)}"
|
| 141 |
|
| 142 |
async def _call_module(self, mod_name: str, method: str, data: str):
|
|
|
|
| 143 |
module = sys.modules.get(mod_name)
|
| 144 |
if module and hasattr(module, method):
|
| 145 |
try:
|
| 146 |
func = getattr(module, method)
|
| 147 |
-
|
|
|
|
|
|
|
| 148 |
except Exception as e:
|
| 149 |
-
self.
|
| 150 |
return None
|
| 151 |
|
| 152 |
# =================================================================
|
| 153 |
-
#
|
| 154 |
# =================================================================
|
| 155 |
-
class
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
|
|
|
|
|
|
|
|
|
| 159 |
return {
|
| 160 |
-
"
|
| 161 |
-
"
|
| 162 |
-
"
|
| 163 |
-
"
|
|
|
|
| 164 |
}
|
| 165 |
|
| 166 |
# =================================================================
|
| 167 |
-
#
|
| 168 |
# =================================================================
|
| 169 |
class AumCoreMaster:
|
| 170 |
-
|
|
|
|
| 171 |
self.config = MasterConfig()
|
| 172 |
-
self.audit =
|
| 173 |
-
self.pipeline =
|
|
|
|
| 174 |
self.is_running = True
|
| 175 |
-
|
| 176 |
-
async def handle_request(self, message: str) -> str:
|
| 177 |
-
# Check for code intent
|
| 178 |
-
coding_triggers = ["code", "python", "script", "build", "debug", "function"]
|
| 179 |
-
if any(word in message.lower() for word in coding_triggers):
|
| 180 |
-
return await self.pipeline.execute_workflow(message)
|
| 181 |
|
| 182 |
-
#
|
| 183 |
-
|
| 184 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
# =================================================================
|
| 187 |
-
#
|
| 188 |
# =================================================================
|
| 189 |
def register_module(app, client, username):
|
|
|
|
| 190 |
master = AumCoreMaster(client)
|
| 191 |
-
router = APIRouter(prefix="/system")
|
| 192 |
|
| 193 |
@router.post("/orchestrate")
|
| 194 |
-
async def
|
| 195 |
-
|
|
|
|
| 196 |
return {"response": response}
|
| 197 |
|
| 198 |
-
@router.get("/titan
|
| 199 |
-
async def
|
| 200 |
-
|
|
|
|
| 201 |
|
| 202 |
app.include_router(router)
|
| 203 |
app.state.orchestrator = master
|
| 204 |
|
| 205 |
print("\n" + "="*60)
|
| 206 |
-
print(f"🚀 TITAN ORCHESTRATOR v{master.config.version}
|
| 207 |
-
print(f"✅
|
| 208 |
-
print(f"✅
|
|
|
|
| 209 |
print("="*60 + "\n")
|
| 210 |
|
|
|
|
|
|
|
|
|
|
| 211 |
if __name__ == "__main__":
|
| 212 |
-
print("Orchestrator
|
|
|
|
| 15 |
from dataclasses import dataclass, field
|
| 16 |
from fastapi import APIRouter, Form, Request
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
# =================================================================
|
| 19 |
+
# 1. TITAN ENTERPRISE CONFIGURATION (2.0)
|
| 20 |
# =================================================================
|
| 21 |
@dataclass
|
| 22 |
class MasterConfig:
|
| 23 |
+
version: str = "4.2.0-Titan-Stable"
|
| 24 |
max_workers: int = os.cpu_count() or 4
|
| 25 |
timeout: int = 150
|
| 26 |
memory_limit_mb: int = 1024
|
| 27 |
log_file: str = "logs/orchestrator_titan.log"
|
| 28 |
+
diagnostics_log: str = "logs/titan_diagnostics.log"
|
| 29 |
username: str = "AumCoreAI"
|
| 30 |
repo_name: str = "aumcore-m7b-docker"
|
| 31 |
+
branch: str = "main"
|
|
|
|
| 32 |
|
| 33 |
# =================================================================
|
| 34 |
+
# 2. HIGH-LEVEL AUDIT SYSTEM
|
| 35 |
# =================================================================
|
| 36 |
+
class TitanAudit:
|
| 37 |
+
"""Enterprise logging for tracking every AI decision"""
|
| 38 |
+
def __init__(self, config: MasterConfig):
|
| 39 |
if not os.path.exists('logs'): os.makedirs('logs')
|
| 40 |
+
self.logger = logging.getLogger("TitanMaster")
|
| 41 |
self.logger.setLevel(logging.DEBUG)
|
| 42 |
if not self.logger.handlers:
|
| 43 |
+
fmt = logging.Formatter('%(asctime)s | [%(levelname)s] | %(message)s')
|
| 44 |
+
fh = logging.FileHandler(config.log_file)
|
| 45 |
+
fh.setFormatter(fmt)
|
| 46 |
self.logger.addHandler(fh)
|
| 47 |
ch = logging.StreamHandler()
|
| 48 |
+
ch.setFormatter(fmt)
|
| 49 |
self.logger.addHandler(ch)
|
| 50 |
|
| 51 |
+
def info(self, msg): self.logger.info(msg)
|
| 52 |
+
def error(self, msg): self.logger.error(msg)
|
| 53 |
+
def warn(self, msg): self.logger.warning(msg)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
# =================================================================
|
| 56 |
+
# 3. CORE LOGIC PIPELINE (The Brain)
|
| 57 |
# =================================================================
|
| 58 |
+
class TitanPipeline:
|
| 59 |
+
"""Manages AI Modules and ensures Professional Output"""
|
| 60 |
+
def __init__(self, client, config: MasterConfig, audit: TitanAudit):
|
| 61 |
self.client = client
|
| 62 |
+
self.config = config
|
| 63 |
+
self.audit = audit
|
| 64 |
|
| 65 |
+
async def execute_task(self, user_query: str) -> str:
|
| 66 |
+
"""The Master Sequence: Reason -> Gen -> Style"""
|
| 67 |
+
req_id = f"AUM-{uuid.uuid4().hex[:6].upper()}"
|
| 68 |
+
self.audit.info(f"Task {req_id} started: {user_query[:30]}")
|
| 69 |
+
|
| 70 |
+
try:
|
| 71 |
+
# Step 1: Intelligence Hook (Logic Check)
|
| 72 |
+
logic_data = await self._call_module("code_intelligence", "analyze_logic", user_query)
|
| 73 |
+
|
| 74 |
+
# Step 2: Expert Generation (With Hardcoded Persona)
|
| 75 |
+
# IMPORTANT: We use clean Markdown here to keep your COPY BUTTON active
|
| 76 |
+
final_response = await self._generate_with_expert_persona(logic_data or user_query)
|
| 77 |
+
|
| 78 |
+
# Step 3: Reviewer Hook (Bug detection)
|
| 79 |
+
reviewed_data = await self._call_module("code_reviewer", "review_code", final_response)
|
| 80 |
+
|
| 81 |
+
self.audit.info(f"Task {req_id} completed successfully.")
|
| 82 |
+
return reviewed_data or final_response
|
| 83 |
+
|
| 84 |
+
except Exception as e:
|
| 85 |
+
self.audit.error(f"Pipeline Crash on {req_id}: {str(e)}")
|
| 86 |
+
return f"❌ **System Error:** {str(e)}"
|
| 87 |
+
|
| 88 |
+
async def _generate_with_expert_persona(self, prompt: str) -> str:
|
| 89 |
+
"""Calls Groq with Strict Senior Developer Persona"""
|
| 90 |
+
if not self.client: return "Groq client is offline."
|
| 91 |
+
|
| 92 |
+
system_instruction = (
|
| 93 |
+
"YOU ARE A SENIOR PRINCIPAL ENGINEER AT AUMCORE AI. "
|
| 94 |
+
"YOUR GOAL: PROVIDE ENTERPRISE-GRADE PYTHON SOLUTIONS. "
|
| 95 |
+
"RULES: "
|
| 96 |
+
"1. ALWAYS USE STANDARD MARKDOWN CODE BLOCKS (```python ... ```). "
|
| 97 |
+
"2. NEVER CHIPKAO (STICK) IMPORTS; USE PROPER NEWLINES. "
|
| 98 |
+
"3. INCLUDE TYPE HINTS, DOCSTRINGS, AND TRY-EXCEPT BLOCKS. "
|
| 99 |
+
"4. DO NOT USE MANUAL HTML DIVS; KEEP IT NATIVE MARKDOWN FOR THE COPY BUTTON. "
|
| 100 |
+
"5. OUTPUT MUST BE CLEAN, WELL-SPACED, AND LOGICAL."
|
| 101 |
)
|
| 102 |
+
|
| 103 |
try:
|
|
|
|
| 104 |
loop = asyncio.get_event_loop()
|
| 105 |
+
response = await loop.run_in_executor(None, lambda: self.client.chat.completions.create(
|
| 106 |
model="llama-3.3-70b-versatile",
|
| 107 |
+
messages=[
|
| 108 |
+
{"role": "system", "content": system_instruction},
|
| 109 |
+
{"role": "user", "content": prompt}
|
| 110 |
+
],
|
| 111 |
+
temperature=0.2,
|
| 112 |
max_tokens=3000
|
| 113 |
))
|
| 114 |
+
return response.choices[0].message.content
|
| 115 |
except Exception as e:
|
| 116 |
+
raise Exception(f"Titan Generation Failed: {str(e)}")
|
|
|
|
| 117 |
|
| 118 |
async def _call_module(self, mod_name: str, method: str, data: str):
|
| 119 |
+
"""Dynamic cross-module communication"""
|
| 120 |
module = sys.modules.get(mod_name)
|
| 121 |
if module and hasattr(module, method):
|
| 122 |
try:
|
| 123 |
func = getattr(module, method)
|
| 124 |
+
if asyncio.iscoroutinefunction(func):
|
| 125 |
+
return await func(data)
|
| 126 |
+
return func(data)
|
| 127 |
except Exception as e:
|
| 128 |
+
self.audit.warn(f"Module {mod_name} execution error: {e}")
|
| 129 |
return None
|
| 130 |
|
| 131 |
# =================================================================
|
| 132 |
+
# 4. SYSTEM HEALTH & DIAGNOSTICS (Updated)
|
| 133 |
# =================================================================
|
| 134 |
+
class TitanMonitor:
|
| 135 |
+
def __init__(self, config: MasterConfig):
|
| 136 |
+
self.config = config
|
| 137 |
+
|
| 138 |
+
async def run_diagnostics(self) -> Dict:
|
| 139 |
+
"""Deep system check"""
|
| 140 |
+
process = psutil.Process(os.getpid())
|
| 141 |
return {
|
| 142 |
+
"uptime": f"{round(time.time() - psutil.boot_time())}s",
|
| 143 |
+
"memory_usage": f"{process.memory_info().rss / 1024 / 1024:.2f} MB",
|
| 144 |
+
"cpu_percent": f"{psutil.cpu_percent()}%",
|
| 145 |
+
"active_threads": threading.active_count(),
|
| 146 |
+
"python_env": sys.version.split()[0]
|
| 147 |
}
|
| 148 |
|
| 149 |
# =================================================================
|
| 150 |
+
# 5. THE MASTER ORCHESTRATOR CLASS
|
| 151 |
# =================================================================
|
| 152 |
class AumCoreMaster:
|
| 153 |
+
"""The Ultimate Controller of the AI Ecosystem"""
|
| 154 |
+
def __init__(self, client=None):
|
| 155 |
self.config = MasterConfig()
|
| 156 |
+
self.audit = TitanAudit(self.config)
|
| 157 |
+
self.pipeline = TitanPipeline(client, self.config, self.audit)
|
| 158 |
+
self.monitor = TitanMonitor(self.config)
|
| 159 |
self.is_running = True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
|
| 161 |
+
# OS Signal handling
|
| 162 |
+
signal.signal(signal.SIGINT, self._handle_exit)
|
| 163 |
+
|
| 164 |
+
def _handle_exit(self, sig, frame):
|
| 165 |
+
self.audit.warn("Titan is shutting down gracefully...")
|
| 166 |
+
self.is_running = False
|
| 167 |
+
|
| 168 |
+
async def process_request(self, message: str) -> str:
|
| 169 |
+
"""Public entry point for professional chat"""
|
| 170 |
+
# Detection logic
|
| 171 |
+
triggers = ["code", "script", "python", "build", "create", "fix"]
|
| 172 |
+
if any(t in message.lower() for t in triggers):
|
| 173 |
+
return await self.pipeline.execute_task(message)
|
| 174 |
+
|
| 175 |
+
# Fallback for normal conversation (Still runs through Titan Brain)
|
| 176 |
+
return await self.pipeline.execute_task(f"Chat mode: {message}")
|
| 177 |
|
| 178 |
# =================================================================
|
| 179 |
+
# 6. FASTAPI MODULE REGISTRATION
|
| 180 |
# =================================================================
|
| 181 |
def register_module(app, client, username):
|
| 182 |
+
"""Integrates Titan Orchestrator into the FastAPI Space"""
|
| 183 |
master = AumCoreMaster(client)
|
| 184 |
+
router = APIRouter(prefix="/system", tags=["Titan Core"])
|
| 185 |
|
| 186 |
@router.post("/orchestrate")
|
| 187 |
+
async def orchestrate_v2(message: str = Form(...)):
|
| 188 |
+
"""Primary endpoint for all AI logic"""
|
| 189 |
+
response = await master.process_request(message)
|
| 190 |
return {"response": response}
|
| 191 |
|
| 192 |
+
@router.get("/status/titan")
|
| 193 |
+
async def titan_status():
|
| 194 |
+
report = await master.monitor.run_diagnostics()
|
| 195 |
+
return {"status": "Titan Active", "report": report}
|
| 196 |
|
| 197 |
app.include_router(router)
|
| 198 |
app.state.orchestrator = master
|
| 199 |
|
| 200 |
print("\n" + "="*60)
|
| 201 |
+
print(f"🚀 TITAN ORCHESTRATOR v{master.config.version} DEPLOYED")
|
| 202 |
+
print(f"✅ Copy-Button Native Support: ACTIVE")
|
| 203 |
+
print(f"✅ Professional Coding Pipeline: ACTIVE")
|
| 204 |
+
print(f"✅ User: {username} | Repo: {master.config.repo_name}")
|
| 205 |
print("="*60 + "\n")
|
| 206 |
|
| 207 |
+
# =================================================================
|
| 208 |
+
# 7. BOOTSTRAP INITIALIZATION
|
| 209 |
+
# =================================================================
|
| 210 |
if __name__ == "__main__":
|
| 211 |
+
print("Titan Orchestrator standalone check...")
|