AumCoreAI commited on
Commit
93650a4
·
verified ·
1 Parent(s): efe66b2

Update modules/orchestrator.py

Browse files
Files changed (1) hide show
  1. 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. ADVANCED ENTERPRISE CONFIGURATION
25
  # =================================================================
26
  @dataclass
27
  class MasterConfig:
28
- version: str = "4.0.0-Titan"
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
- # Styling for Colorful Output
36
- code_style: str = "monokai"
37
 
38
  # =================================================================
39
- # 2. PROFESSIONAL AUDIT & LOGGING SYSTEM
40
  # =================================================================
41
- class AumAuditSystem:
42
- def __init__(self, log_file: str):
 
43
  if not os.path.exists('logs'): os.makedirs('logs')
44
- self.logger = logging.getLogger("TitanOrchestrator")
45
  self.logger.setLevel(logging.DEBUG)
46
  if not self.logger.handlers:
47
- formatter = logging.Formatter('%(asctime)s | [%(levelname)s] | %(message)s')
48
- fh = logging.FileHandler(log_file)
49
- fh.setFormatter(formatter)
50
  self.logger.addHandler(fh)
51
  ch = logging.StreamHandler()
52
- ch.setFormatter(formatter)
53
  self.logger.addHandler(ch)
54
 
55
- def log_event(self, level: str, msg: str):
56
- if level == "info": self.logger.info(msg)
57
- elif level == "error": self.logger.error(msg)
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
- # 4. INTELLIGENT PIPELINE MANAGER
96
  # =================================================================
97
- class PipelineManager:
98
- def __init__(self, client, logger: AumAuditSystem):
 
99
  self.client = client
100
- self.logger = logger
101
- self.formatter = ColorfulFormatter("monokai")
102
 
103
- async def execute_workflow(self, message: str) -> str:
104
- """Main AI Flow: Reason -> Generate -> Review -> Colorize"""
105
- self.logger.log_event("info", f"Processing Request: {message[:50]}...")
106
-
107
- # 1. Logic Expansion (Call Intelligence if available)
108
- enhanced_prompt = await self._call_module("code_intelligence", "analyze_logic", message)
109
-
110
- # 2. Master Generation
111
- raw_ai_response = await self._generate_core_ai(enhanced_prompt or message)
112
-
113
- # 3. Code Review (Call Reviewer if available)
114
- reviewed_response = await self._call_module("code_reviewer", "review_code", raw_ai_response)
115
-
116
- # 4. Final Formatting (Injection of Colors)
117
- final_output = self.formatter.inject_colors(reviewed_response or raw_ai_response)
118
-
119
- return final_output
120
-
121
- async def _generate_core_ai(self, prompt: str) -> str:
122
- system_instructions = (
123
- "You are the Titan-Class AI Architect of AumCore. "
124
- "You write PRODUCTION-READY code with PEP 8 standards. "
125
- "Always wrap code in ```python blocks. Never use simple text for logic. "
126
- "Think step-by-step and provide clean, modular, and well-documented scripts."
 
 
 
 
 
 
 
 
 
 
 
 
127
  )
 
128
  try:
129
- # Use executor for blocking Groq call
130
  loop = asyncio.get_event_loop()
131
- res = await loop.run_in_executor(None, lambda: self.client.chat.completions.create(
132
  model="llama-3.3-70b-versatile",
133
- messages=[{"role": "system", "content": system_instructions}, {"role": "user", "content": prompt}],
134
- temperature=0.3,
 
 
 
135
  max_tokens=3000
136
  ))
137
- return res.choices[0].message.content
138
  except Exception as e:
139
- self.logger.log_event("error", f"LLM Crash: {e}")
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
- return await func(data) if asyncio.iscoroutinefunction(func) else func(data)
 
 
148
  except Exception as e:
149
- self.logger.log_event("warn", f"Module {mod_name} failed: {e}")
150
  return None
151
 
152
  # =================================================================
153
- # 5. DIAGNOSTICS & SYSTEM MONITOR
154
  # =================================================================
155
- class TitanDiagnostics:
156
- @staticmethod
157
- async def run_check():
158
- vmem = psutil.virtual_memory()
 
 
 
159
  return {
160
- "status": "Healthy",
161
- "cpu_load": f"{psutil.cpu_percent()}%",
162
- "memory": f"{vmem.percent}% used",
163
- "uptime": f"{round(time.time() - psutil.boot_time())}s"
 
164
  }
165
 
166
  # =================================================================
167
- # 6. MASTER ORCHESTRATOR INTERFACE
168
  # =================================================================
169
  class AumCoreMaster:
170
- def __init__(self, client):
 
171
  self.config = MasterConfig()
172
- self.audit = AumAuditSystem(self.config.log_file)
173
- self.pipeline = PipelineManager(client, self.audit)
 
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
- # Standard Chat with basic color injection
183
- raw_res = await self.pipeline._generate_core_ai(message)
184
- return self.pipeline.formatter.inject_colors(raw_res)
 
 
 
 
 
 
 
 
 
 
 
 
 
185
 
186
  # =================================================================
187
- # 7. FASTAPI REGISTRATION (THE BRIDGE)
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 process_task(message: str = Form(...)):
195
- response = await master.handle_request(message)
 
196
  return {"response": response}
197
 
198
- @router.get("/titan/health")
199
- async def health():
200
- return await TitanDiagnostics.run_check()
 
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} ONLINE")
207
- print(f"✅ Colorful Injection Engine: READY")
208
- print(f"✅ Expert Coding Pipeline: ACTIVE")
 
209
  print("="*60 + "\n")
210
 
 
 
 
211
  if __name__ == "__main__":
212
- print("Orchestrator testing mode...")
 
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...")