Spaces:
Sleeping
Sleeping
Commit ·
cb5a5c0
1
Parent(s): 5fabd70
updated core_logic
Browse files- core_logic.py +46 -120
- core_logic_03.py +252 -0
core_logic.py
CHANGED
|
@@ -1,10 +1,10 @@
|
|
| 1 |
|
| 2 |
-
# ./core_logic.py
|
| 3 |
|
| 4 |
import os
|
| 5 |
-
import re #
|
| 6 |
from groq import Groq
|
| 7 |
-
from tools import web_search, parse_file
|
| 8 |
|
| 9 |
import yaml
|
| 10 |
import toml
|
|
@@ -14,52 +14,49 @@ from docx import Document
|
|
| 14 |
client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
| 15 |
model = "llama-3.1-8b-instant"
|
| 16 |
|
| 17 |
-
#
|
| 18 |
-
def
|
| 19 |
-
|
| 20 |
try:
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
| 23 |
os.remove(test_file)
|
| 24 |
-
print("✅ Write permissions verified.")
|
| 25 |
except Exception as e:
|
| 26 |
-
print(f"
|
| 27 |
-
|
| 28 |
-
verify_permissions()
|
| 29 |
|
|
|
|
| 30 |
|
|
|
|
| 31 |
def compile_cognitive_system_prompt():
|
| 32 |
-
"""
|
| 33 |
-
Cognitive Compilation Layer - Dynamically constructs the master system prompt
|
| 34 |
-
by assembling soul.md, heart.md, and memory.md side-car layers.
|
| 35 |
-
"""
|
| 36 |
base_soul = ""
|
| 37 |
current_heart = ""
|
| 38 |
past_memory = ""
|
| 39 |
|
| 40 |
-
#
|
| 41 |
if os.path.exists("soul.md"):
|
| 42 |
with open("soul.md", "r", encoding="utf-8") as f:
|
| 43 |
base_soul = f.read()
|
| 44 |
else:
|
| 45 |
-
#
|
| 46 |
-
base_soul = "You are CoderG, the Silicon Architect. Act as an elite
|
| 47 |
|
| 48 |
-
#
|
| 49 |
if os.path.exists("heart.md"):
|
| 50 |
with open("heart.md", "r", encoding="utf-8") as f:
|
| 51 |
current_heart = f.read()
|
| 52 |
else:
|
| 53 |
current_heart = "Focus on base architectural compilation and optimizing core component workflows."
|
| 54 |
|
| 55 |
-
#
|
| 56 |
if os.path.exists("memory.md"):
|
| 57 |
with open("memory.md", "r", encoding="utf-8") as f:
|
| 58 |
past_memory = f.read()
|
| 59 |
else:
|
| 60 |
past_memory = "No historical operational constraints loaded yet."
|
| 61 |
|
| 62 |
-
# Combine all layers into a structural system context map
|
| 63 |
master_prompt = f"""{base_soul}
|
| 64 |
|
| 65 |
====================================================================
|
|
@@ -74,149 +71,85 @@ def compile_cognitive_system_prompt():
|
|
| 74 |
"""
|
| 75 |
return master_prompt
|
| 76 |
|
| 77 |
-
|
| 78 |
-
def chat_function(message, history):
|
|
|
|
| 79 |
user_text = message.get("text", "")
|
| 80 |
files = message.get("files", [])
|
| 81 |
|
| 82 |
-
# Context Aggregator Buffer for all multi-format assets
|
| 83 |
context_from_files = ""
|
| 84 |
|
| 85 |
-
#
|
| 86 |
if files:
|
| 87 |
from perception_agent import read_document_file
|
| 88 |
yield "◌ _Perception Agent initialized: Ingesting uploaded file assets..._"
|
| 89 |
-
|
| 90 |
for f in files:
|
| 91 |
-
# Gradio 6 handles file entries either as dictionaries with a 'path' key or flat strings
|
| 92 |
path = f["path"] if isinstance(f, dict) else f
|
| 93 |
if path and os.path.exists(path):
|
| 94 |
-
|
| 95 |
-
context_from_files += file_content
|
| 96 |
-
|
| 97 |
yield "◌ _Perception processing complete. Transmitting compiled structures to the Brain..._"
|
| 98 |
|
| 99 |
-
|
| 100 |
-
# TRUNCATE FILE CONTEXT: Max ~3000 tokens (approx 12,000 chars)
|
| 101 |
if len(context_from_files) > 12000:
|
| 102 |
context_from_files = context_from_files[:12000] + "\n...[File Content Truncated for TPM Limits]..."
|
| 103 |
|
| 104 |
-
#
|
| 105 |
if any(keyword in user_text.lower() for keyword in ["search", "docs", "latest"]):
|
| 106 |
-
# Use a fast micro-turn to distill the massive user prompt into optimized keywords
|
| 107 |
distill_response = client.chat.completions.create(
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
"7. NEVER wrap your output in single or double quotes.\n"
|
| 122 |
-
"8. Maximum 5 words, under 50 characters total."
|
| 123 |
-
)
|
| 124 |
-
},
|
| 125 |
-
{
|
| 126 |
-
"role": "user",
|
| 127 |
-
"content": f"Convert the following request into raw optimized search keywords based on your system rules:\n\n{user_text}"
|
| 128 |
-
}
|
| 129 |
-
],
|
| 130 |
-
temperature=0.0,
|
| 131 |
-
)
|
| 132 |
|
| 133 |
-
# Extract and aggressively sanitize the string programmatically
|
| 134 |
raw_query = distill_response.choices[0].message.content.strip()
|
| 135 |
-
|
| 136 |
-
optimized_query = re.sub(r"[`'\"\\n\-*#\[\]]", "", raw_query)
|
| 137 |
-
|
| 138 |
-
# Defensive Guardrail: Ensure query fits under Tavily's 400-character ceiling
|
| 139 |
if len(optimized_query) > 390:
|
| 140 |
-
|
| 141 |
-
optimized_query = optimized_query[:390].rpartition(' ')[0]
|
| 142 |
-
|
| 143 |
-
# Clean up any residual markdown symbols the model leaked
|
| 144 |
-
optimized_query = optimized_query.replace("`", "").replace("python", "").strip()
|
| 145 |
-
|
| 146 |
-
print(f"\nlen optimized_query: {len(optimized_query)}") # Debug log for query length
|
| 147 |
-
print(f"\nOptimized Search Query: '{optimized_query}'") # Debug log for the optimized query
|
| 148 |
|
| 149 |
-
# Executing clean, highly target web search under the 400-character cap
|
| 150 |
research_context = web_search(optimized_query)
|
| 151 |
-
|
| 152 |
-
#print(f"\nResearch Context Retrieved: {research_context[:500]}...")
|
| 153 |
-
print(f"\nResearch Context Retrieved: {research_context}...") # Debug log for research context snippet
|
| 154 |
-
|
| 155 |
prompt = f"RESEARCH:\n{research_context}\n\nFILES:\n{context_from_files}\n\nUSER: {optimized_query}"
|
| 156 |
-
#research_context = web_search(user_text)
|
| 157 |
-
#prompt = f"RESEARCH:\n{research_context}\n\nFILES:\n{context_from_files}\n\nUSER: {user_text}"
|
| 158 |
else:
|
| 159 |
prompt = f"FILES:\n{context_from_files}\n\nUSER: {user_text}"
|
| 160 |
|
| 161 |
-
#
|
| 162 |
-
# 🧠 COGNITIVE INJECTION ENGINE LAYER
|
| 163 |
-
# ====================================================================
|
| 164 |
-
# Dynamically read and compile soul.md, heart.md, and memory.md combined
|
| 165 |
-
# seamlessly with your complete legacy systemic directives.
|
| 166 |
compiled_cognitive_prompt = compile_cognitive_system_prompt()
|
| 167 |
-
|
| 168 |
-
# Build Messages with Dynamic Context Compilations
|
| 169 |
messages = [{"role": "system", "content": compiled_cognitive_prompt}]
|
| 170 |
|
| 171 |
-
# ONLY KEEP LAST 3 TURNS: This is the 'Master Stroke' for staying under 6k TPM
|
| 172 |
for turn in history[-3:]:
|
| 173 |
messages.append({"role": turn["role"], "content": turn["content"]})
|
| 174 |
|
| 175 |
-
#messages.append({"role": "user", "content": prompt})
|
| 176 |
-
|
| 177 |
system_execution_fence = (
|
| 178 |
f"{prompt}\n\n"
|
| 179 |
"[SYSTEM EXECUTOR NOTICE: Answer the user's prompt immediately. "
|
| 180 |
"Do NOT append or print your Core Identity, Mandate, or Directives summary at the end of your response. "
|
| 181 |
"Stop generating tokens the moment the technical payload is complete.]"
|
| 182 |
)
|
| 183 |
-
|
| 184 |
messages.append({"role": "user", "content": system_execution_fence})
|
| 185 |
|
| 186 |
-
# =============================================================================================
|
| 187 |
-
# 🎯DIAGNOSTICS FOR THE LENGTH OF LIST PAYLOAD BEING SENT TO THE PROVIDER, WHICH IT CAN HANDLE
|
| 188 |
-
# =============================================================================================
|
| 189 |
-
print("\n==================================================")
|
| 190 |
-
print(f"📊 Sending {len(messages)} raw message blocks to the {model}.")
|
| 191 |
-
print("==================================================\n")
|
| 192 |
-
# ====================================================================
|
| 193 |
-
|
| 194 |
try:
|
| 195 |
completion = client.chat.completions.create(
|
| 196 |
model=model,
|
| 197 |
messages=messages,
|
| 198 |
stream=True,
|
| 199 |
temperature=0.2,
|
| 200 |
-
#max_tokens=1024 # Limit response size to prevent mid-stream cuts
|
| 201 |
)
|
| 202 |
|
| 203 |
response_text = ""
|
| 204 |
-
|
| 205 |
-
# Step 1: Stream the raw LLM output token by token to the user
|
| 206 |
for chunk in completion:
|
| 207 |
if chunk.choices and chunk.choices[0].delta.content:
|
| 208 |
-
|
| 209 |
-
response_text += token
|
| 210 |
yield response_text
|
| 211 |
|
| 212 |
-
#
|
| 213 |
-
|
| 214 |
-
has_code_blocks = bool(re.search(r"```[\s\S]*?```", response_text))
|
| 215 |
-
|
| 216 |
-
if has_code_blocks:
|
| 217 |
-
# ONLY execute file creation and staging alerts if an artifact is detected
|
| 218 |
-
|
| 219 |
-
# Step 2: Transition seamlessly to Local File Generation
|
| 220 |
yield response_text + "\n\n◌ _File agent initialized: Generating local documentation workspace..._"
|
| 221 |
|
| 222 |
from file_agent import write_document
|
|
@@ -225,9 +158,9 @@ def chat_function(message, history):
|
|
| 225 |
filename = "COURSE_README.md"
|
| 226 |
backup_filename = "COURSE_README_-1.md"
|
| 227 |
|
| 228 |
-
# Proactively manage historical backup copy before writing fresh file state
|
| 229 |
src_path = os.path.join("outputs", filename)
|
| 230 |
dst_path = os.path.join("outputs", backup_filename)
|
|
|
|
| 231 |
if os.path.exists(src_path):
|
| 232 |
try:
|
| 233 |
shutil.copy2(src_path, dst_path)
|
|
@@ -235,18 +168,11 @@ def chat_function(message, history):
|
|
| 235 |
from agent_logging import log_agent_action
|
| 236 |
log_agent_action("BACKUP_ERROR", f"Failed to cycle historical version file: {str(e)}")
|
| 237 |
|
| 238 |
-
# Write fresh incoming file generation
|
| 239 |
file_path = write_document(response_text, filename)
|
| 240 |
-
|
| 241 |
-
print(f"\nGenerated file at: {file_path}")
|
| 242 |
-
|
| 243 |
-
# Step 3: Inform the UI that the material is staged and ready for the GitHub authorization layer
|
| 244 |
if "Error" not in file_path:
|
| 245 |
yield response_text + f"\n\n✅ _Files successfully generated in localized staging environment._\n\n◌ _Awaiting authorization control panel to push to GitHub._"
|
| 246 |
else:
|
| 247 |
yield response_text + f"\n\n❌ _File generation failed: {file_path}_"
|
| 248 |
|
| 249 |
except Exception as e:
|
| 250 |
-
yield f"Error: {str(e)}"
|
| 251 |
-
|
| 252 |
-
|
|
|
|
| 1 |
|
| 2 |
+
# ./core_logic.py
|
| 3 |
|
| 4 |
import os
|
| 5 |
+
import re # for structural artifact code block extraction
|
| 6 |
from groq import Groq
|
| 7 |
+
from tools import web_search, parse_file # script explicitly calls web_search()
|
| 8 |
|
| 9 |
import yaml
|
| 10 |
import toml
|
|
|
|
| 14 |
client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
| 15 |
model = "llama-3.1-8b-instant"
|
| 16 |
|
| 17 |
+
# 1. Proactive DevOps Environment Check (Valid Dream Idea)
|
| 18 |
+
def verify_workspace_permissions():
|
| 19 |
+
"""Verifies write permissions to the workspace directory to ensure side-cars can compile."""
|
| 20 |
try:
|
| 21 |
+
test_file = "outputs/.permission_test.tmp"
|
| 22 |
+
os.makedirs("outputs", exist_ok=True)
|
| 23 |
+
with open(test_file, "w", encoding="utf-8") as f:
|
| 24 |
+
f.write("workspace_test")
|
| 25 |
os.remove(test_file)
|
|
|
|
| 26 |
except Exception as e:
|
| 27 |
+
print(f"⚠️ WORKSPACE WARNING: Verification engine encountered pathing friction: {e}")
|
|
|
|
|
|
|
| 28 |
|
| 29 |
+
verify_workspace_permissions()
|
| 30 |
|
| 31 |
+
# 2. Dynamic Cognitive Prompt Assembler
|
| 32 |
def compile_cognitive_system_prompt():
|
| 33 |
+
"""Assembles soul.md, heart.md, and memory.md into a high-density system directive block."""
|
|
|
|
|
|
|
|
|
|
| 34 |
base_soul = ""
|
| 35 |
current_heart = ""
|
| 36 |
past_memory = ""
|
| 37 |
|
| 38 |
+
# Ingest Core Mandate Layer
|
| 39 |
if os.path.exists("soul.md"):
|
| 40 |
with open("soul.md", "r", encoding="utf-8") as f:
|
| 41 |
base_soul = f.read()
|
| 42 |
else:
|
| 43 |
+
# Secure Environment variable option with a backup string fallback
|
| 44 |
+
base_soul = os.environ.get("BASE_SOUL", "You are CoderG, the Silicon Architect. Act as an elite AI Engineer.")
|
| 45 |
|
| 46 |
+
# Ingest Current Priorities State
|
| 47 |
if os.path.exists("heart.md"):
|
| 48 |
with open("heart.md", "r", encoding="utf-8") as f:
|
| 49 |
current_heart = f.read()
|
| 50 |
else:
|
| 51 |
current_heart = "Focus on base architectural compilation and optimizing core component workflows."
|
| 52 |
|
| 53 |
+
# Ingest Historical Ephemeral Layer
|
| 54 |
if os.path.exists("memory.md"):
|
| 55 |
with open("memory.md", "r", encoding="utf-8") as f:
|
| 56 |
past_memory = f.read()
|
| 57 |
else:
|
| 58 |
past_memory = "No historical operational constraints loaded yet."
|
| 59 |
|
|
|
|
| 60 |
master_prompt = f"""{base_soul}
|
| 61 |
|
| 62 |
====================================================================
|
|
|
|
| 71 |
"""
|
| 72 |
return master_prompt
|
| 73 |
|
| 74 |
+
# 3. Main Operational Streaming Core Execution Block
|
| 75 |
+
def chat_function(message, history, client, model):
|
| 76 |
+
"""Streams responses from the client provider using the cognitive prompt matrix."""
|
| 77 |
user_text = message.get("text", "")
|
| 78 |
files = message.get("files", [])
|
| 79 |
|
|
|
|
| 80 |
context_from_files = ""
|
| 81 |
|
| 82 |
+
# File asset context extraction
|
| 83 |
if files:
|
| 84 |
from perception_agent import read_document_file
|
| 85 |
yield "◌ _Perception Agent initialized: Ingesting uploaded file assets..._"
|
|
|
|
| 86 |
for f in files:
|
|
|
|
| 87 |
path = f["path"] if isinstance(f, dict) else f
|
| 88 |
if path and os.path.exists(path):
|
| 89 |
+
context_from_files += read_document_file(path)
|
|
|
|
|
|
|
| 90 |
yield "◌ _Perception processing complete. Transmitting compiled structures to the Brain..._"
|
| 91 |
|
|
|
|
|
|
|
| 92 |
if len(context_from_files) > 12000:
|
| 93 |
context_from_files = context_from_files[:12000] + "\n...[File Content Truncated for TPM Limits]..."
|
| 94 |
|
| 95 |
+
# Optimization/Research routine triggering logic
|
| 96 |
if any(keyword in user_text.lower() for keyword in ["search", "docs", "latest"]):
|
|
|
|
| 97 |
distill_response = client.chat.completions.create(
|
| 98 |
+
model="llama-3.1-8b-instant",
|
| 99 |
+
messages=[
|
| 100 |
+
{
|
| 101 |
+
"role": "system",
|
| 102 |
+
"content": (
|
| 103 |
+
"You are a search query optimizer tool. Your ONLY job is to take the user's long request and turn it into a short, effective, plain-text, web search query for finding relevant technical programming documentation.\n\n"
|
| 104 |
+
"Critical Rules:\n1. Do NOT answer the user's prompt.\n2. Do NOT write code blocks or markdown.\n3. Maximum 5 words, under 50 characters total."
|
| 105 |
+
)
|
| 106 |
+
},
|
| 107 |
+
{"role": "user", "content": f"Convert the following request into raw optimized search keywords:\n\n{user_text}"}
|
| 108 |
+
],
|
| 109 |
+
temperature=0.0,
|
| 110 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
|
|
|
| 112 |
raw_query = distill_response.choices[0].message.content.strip()
|
| 113 |
+
optimized_query = re.sub(r"[`'\"\\n\-*#\[\]]", "", raw_query).replace("python", "").strip()
|
|
|
|
|
|
|
|
|
|
| 114 |
if len(optimized_query) > 390:
|
| 115 |
+
optimized_query = optimized_query[:390].rpartition(' ')[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
|
|
|
| 117 |
research_context = web_search(optimized_query)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
prompt = f"RESEARCH:\n{research_context}\n\nFILES:\n{context_from_files}\n\nUSER: {optimized_query}"
|
|
|
|
|
|
|
| 119 |
else:
|
| 120 |
prompt = f"FILES:\n{context_from_files}\n\nUSER: {user_text}"
|
| 121 |
|
| 122 |
+
# Assembling context arrays
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
compiled_cognitive_prompt = compile_cognitive_system_prompt()
|
|
|
|
|
|
|
| 124 |
messages = [{"role": "system", "content": compiled_cognitive_prompt}]
|
| 125 |
|
|
|
|
| 126 |
for turn in history[-3:]:
|
| 127 |
messages.append({"role": turn["role"], "content": turn["content"]})
|
| 128 |
|
|
|
|
|
|
|
| 129 |
system_execution_fence = (
|
| 130 |
f"{prompt}\n\n"
|
| 131 |
"[SYSTEM EXECUTOR NOTICE: Answer the user's prompt immediately. "
|
| 132 |
"Do NOT append or print your Core Identity, Mandate, or Directives summary at the end of your response. "
|
| 133 |
"Stop generating tokens the moment the technical payload is complete.]"
|
| 134 |
)
|
|
|
|
| 135 |
messages.append({"role": "user", "content": system_execution_fence})
|
| 136 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
try:
|
| 138 |
completion = client.chat.completions.create(
|
| 139 |
model=model,
|
| 140 |
messages=messages,
|
| 141 |
stream=True,
|
| 142 |
temperature=0.2,
|
|
|
|
| 143 |
)
|
| 144 |
|
| 145 |
response_text = ""
|
|
|
|
|
|
|
| 146 |
for chunk in completion:
|
| 147 |
if chunk.choices and chunk.choices[0].delta.content:
|
| 148 |
+
response_text += chunk.choices[0].delta.content
|
|
|
|
| 149 |
yield response_text
|
| 150 |
|
| 151 |
+
# Automated Local Artifact Generation Execution Hook
|
| 152 |
+
if bool(re.search(r"```[\s\S]*?```", response_text)):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
yield response_text + "\n\n◌ _File agent initialized: Generating local documentation workspace..._"
|
| 154 |
|
| 155 |
from file_agent import write_document
|
|
|
|
| 158 |
filename = "COURSE_README.md"
|
| 159 |
backup_filename = "COURSE_README_-1.md"
|
| 160 |
|
|
|
|
| 161 |
src_path = os.path.join("outputs", filename)
|
| 162 |
dst_path = os.path.join("outputs", backup_filename)
|
| 163 |
+
|
| 164 |
if os.path.exists(src_path):
|
| 165 |
try:
|
| 166 |
shutil.copy2(src_path, dst_path)
|
|
|
|
| 168 |
from agent_logging import log_agent_action
|
| 169 |
log_agent_action("BACKUP_ERROR", f"Failed to cycle historical version file: {str(e)}")
|
| 170 |
|
|
|
|
| 171 |
file_path = write_document(response_text, filename)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
if "Error" not in file_path:
|
| 173 |
yield response_text + f"\n\n✅ _Files successfully generated in localized staging environment._\n\n◌ _Awaiting authorization control panel to push to GitHub._"
|
| 174 |
else:
|
| 175 |
yield response_text + f"\n\n❌ _File generation failed: {file_path}_"
|
| 176 |
|
| 177 |
except Exception as e:
|
| 178 |
+
yield f"Error: {str(e)}"
|
|
|
|
|
|
core_logic_03.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# ./core_logic.py -> Token-safe
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import re # Added for structural artifact code block extraction
|
| 6 |
+
from groq import Groq
|
| 7 |
+
from tools import web_search, parse_file
|
| 8 |
+
|
| 9 |
+
import yaml
|
| 10 |
+
import toml
|
| 11 |
+
from docx import Document
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
| 15 |
+
model = "llama-3.1-8b-instant"
|
| 16 |
+
|
| 17 |
+
# Verify write permissions to 'outputs' directory
|
| 18 |
+
def verify_permissions():
|
| 19 |
+
test_file = "permission_test.txt"
|
| 20 |
+
try:
|
| 21 |
+
with open(test_file, "w") as f:
|
| 22 |
+
f.write("test")
|
| 23 |
+
os.remove(test_file)
|
| 24 |
+
print("✅ Write permissions verified.")
|
| 25 |
+
except Exception as e:
|
| 26 |
+
print(f"❌ PERMISSION ERROR: {e}")
|
| 27 |
+
|
| 28 |
+
verify_permissions()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def compile_cognitive_system_prompt():
|
| 32 |
+
"""
|
| 33 |
+
Cognitive Compilation Layer - Dynamically constructs the master system prompt
|
| 34 |
+
by assembling soul.md, heart.md, and memory.md side-car layers.
|
| 35 |
+
"""
|
| 36 |
+
base_soul = ""
|
| 37 |
+
current_heart = ""
|
| 38 |
+
past_memory = ""
|
| 39 |
+
|
| 40 |
+
# 1. Gather Soul Directive
|
| 41 |
+
if os.path.exists("soul.md"):
|
| 42 |
+
with open("soul.md", "r", encoding="utf-8") as f:
|
| 43 |
+
base_soul = f.read()
|
| 44 |
+
else:
|
| 45 |
+
# Emergency hardcoded fallback matching your architectural profile
|
| 46 |
+
base_soul = "You are CoderG, the Silicon Architect. Act as an elite Full-stack AI Engineer."
|
| 47 |
+
|
| 48 |
+
# 2. Gather Heart State
|
| 49 |
+
if os.path.exists("heart.md"):
|
| 50 |
+
with open("heart.md", "r", encoding="utf-8") as f:
|
| 51 |
+
current_heart = f.read()
|
| 52 |
+
else:
|
| 53 |
+
current_heart = "Focus on base architectural compilation and optimizing core component workflows."
|
| 54 |
+
|
| 55 |
+
# 3. Gather Memory Graph
|
| 56 |
+
if os.path.exists("memory.md"):
|
| 57 |
+
with open("memory.md", "r", encoding="utf-8") as f:
|
| 58 |
+
past_memory = f.read()
|
| 59 |
+
else:
|
| 60 |
+
past_memory = "No historical operational constraints loaded yet."
|
| 61 |
+
|
| 62 |
+
# Combine all layers into a structural system context map
|
| 63 |
+
master_prompt = f"""{base_soul}
|
| 64 |
+
|
| 65 |
+
====================================================================
|
| 66 |
+
❤️ ACTIVE OPERATIONAL TASK STATUS (HEART.MD)
|
| 67 |
+
====================================================================
|
| 68 |
+
{current_heart}
|
| 69 |
+
|
| 70 |
+
====================================================================
|
| 71 |
+
💾 HISTORICAL ENVIRONMENT TRUTHS & PATCHES (MEMORY.MD)
|
| 72 |
+
====================================================================
|
| 73 |
+
{past_memory}
|
| 74 |
+
"""
|
| 75 |
+
return master_prompt
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def chat_function(message, history):
|
| 79 |
+
user_text = message.get("text", "")
|
| 80 |
+
files = message.get("files", [])
|
| 81 |
+
|
| 82 |
+
# Context Aggregator Buffer for all multi-format assets
|
| 83 |
+
context_from_files = ""
|
| 84 |
+
|
| 85 |
+
# 1. Process Multimodal and Extended Multi-format Files via Perception Agent
|
| 86 |
+
if files:
|
| 87 |
+
from perception_agent import read_document_file
|
| 88 |
+
yield "◌ _Perception Agent initialized: Ingesting uploaded file assets..._"
|
| 89 |
+
|
| 90 |
+
for f in files:
|
| 91 |
+
# Gradio 6 handles file entries either as dictionaries with a 'path' key or flat strings
|
| 92 |
+
path = f["path"] if isinstance(f, dict) else f
|
| 93 |
+
if path and os.path.exists(path):
|
| 94 |
+
file_content = read_document_file(path)
|
| 95 |
+
context_from_files += file_content
|
| 96 |
+
|
| 97 |
+
yield "◌ _Perception processing complete. Transmitting compiled structures to the Brain..._"
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# TRUNCATE FILE CONTEXT: Max ~3000 tokens (approx 12,000 chars)
|
| 101 |
+
if len(context_from_files) > 12000:
|
| 102 |
+
context_from_files = context_from_files[:12000] + "\n...[File Content Truncated for TPM Limits]..."
|
| 103 |
+
|
| 104 |
+
# 2. Research Trigger
|
| 105 |
+
if any(keyword in user_text.lower() for keyword in ["search", "docs", "latest"]):
|
| 106 |
+
# Use a fast micro-turn to distill the massive user prompt into optimized keywords
|
| 107 |
+
distill_response = client.chat.completions.create(
|
| 108 |
+
model="llama-3.1-8b-instant",
|
| 109 |
+
messages=[
|
| 110 |
+
{
|
| 111 |
+
"role": "system",
|
| 112 |
+
"content": (
|
| 113 |
+
"You are a search query optimizer tool. Your ONLY job is to take the user's long request and turn it into a short, effective, plain-text, web search query for finding relevant technical programming documentation.\n\n"
|
| 114 |
+
"Critical Rules:\n"
|
| 115 |
+
"1. Do NOT answer the user's prompt.\n"
|
| 116 |
+
"2. Do NOT write code blocks, code explanations, tasks, or JSON data structures.\n"
|
| 117 |
+
"3. Your entire output must be a single sentence under 50 characters.\n"
|
| 118 |
+
"4. If the user provides a code file or raw data logs, ignore the text content and generate a query searching for the underlying concept (e.g., 'Scapy network sniffing documentation python').\n"
|
| 119 |
+
"5. Output ONLY raw keywords.\n"
|
| 120 |
+
"6. NEVER use markdown, backticks, or code blocks.\n"
|
| 121 |
+
"7. NEVER wrap your output in single or double quotes.\n"
|
| 122 |
+
"8. Maximum 5 words, under 50 characters total."
|
| 123 |
+
)
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"role": "user",
|
| 127 |
+
"content": f"Convert the following request into raw optimized search keywords based on your system rules:\n\n{user_text}"
|
| 128 |
+
}
|
| 129 |
+
],
|
| 130 |
+
temperature=0.0,
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
# Extract and aggressively sanitize the string programmatically
|
| 134 |
+
raw_query = distill_response.choices[0].message.content.strip()
|
| 135 |
+
# Strip away any lingering quotes, backticks, or markdown syntax characters
|
| 136 |
+
optimized_query = re.sub(r"[`'\"\\n\-*#\[\]]", "", raw_query)
|
| 137 |
+
|
| 138 |
+
# Defensive Guardrail: Ensure query fits under Tavily's 400-character ceiling
|
| 139 |
+
if len(optimized_query) > 390:
|
| 140 |
+
# Option 1: Extract just the first line or clip the characters safely
|
| 141 |
+
optimized_query = optimized_query[:390].rpartition(' ')[0]
|
| 142 |
+
|
| 143 |
+
# Clean up any residual markdown symbols the model leaked
|
| 144 |
+
optimized_query = optimized_query.replace("`", "").replace("python", "").strip()
|
| 145 |
+
|
| 146 |
+
print(f"\nlen optimized_query: {len(optimized_query)}") # Debug log for query length
|
| 147 |
+
print(f"\nOptimized Search Query: '{optimized_query}'") # Debug log for the optimized query
|
| 148 |
+
|
| 149 |
+
# Executing clean, highly target web search under the 400-character cap
|
| 150 |
+
research_context = web_search(optimized_query)
|
| 151 |
+
|
| 152 |
+
#print(f"\nResearch Context Retrieved: {research_context[:500]}...")
|
| 153 |
+
print(f"\nResearch Context Retrieved: {research_context}...") # Debug log for research context snippet
|
| 154 |
+
|
| 155 |
+
prompt = f"RESEARCH:\n{research_context}\n\nFILES:\n{context_from_files}\n\nUSER: {optimized_query}"
|
| 156 |
+
#research_context = web_search(user_text)
|
| 157 |
+
#prompt = f"RESEARCH:\n{research_context}\n\nFILES:\n{context_from_files}\n\nUSER: {user_text}"
|
| 158 |
+
else:
|
| 159 |
+
prompt = f"FILES:\n{context_from_files}\n\nUSER: {user_text}"
|
| 160 |
+
|
| 161 |
+
# ====================================================================
|
| 162 |
+
# 🧠 COGNITIVE INJECTION ENGINE LAYER
|
| 163 |
+
# ====================================================================
|
| 164 |
+
# Dynamically read and compile soul.md, heart.md, and memory.md combined
|
| 165 |
+
# seamlessly with your complete legacy systemic directives.
|
| 166 |
+
compiled_cognitive_prompt = compile_cognitive_system_prompt()
|
| 167 |
+
|
| 168 |
+
# Build Messages with Dynamic Context Compilations
|
| 169 |
+
messages = [{"role": "system", "content": compiled_cognitive_prompt}]
|
| 170 |
+
|
| 171 |
+
# ONLY KEEP LAST 3 TURNS: This is the 'Master Stroke' for staying under 6k TPM
|
| 172 |
+
for turn in history[-3:]:
|
| 173 |
+
messages.append({"role": turn["role"], "content": turn["content"]})
|
| 174 |
+
|
| 175 |
+
#messages.append({"role": "user", "content": prompt})
|
| 176 |
+
|
| 177 |
+
system_execution_fence = (
|
| 178 |
+
f"{prompt}\n\n"
|
| 179 |
+
"[SYSTEM EXECUTOR NOTICE: Answer the user's prompt immediately. "
|
| 180 |
+
"Do NOT append or print your Core Identity, Mandate, or Directives summary at the end of your response. "
|
| 181 |
+
"Stop generating tokens the moment the technical payload is complete.]"
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
messages.append({"role": "user", "content": system_execution_fence})
|
| 185 |
+
|
| 186 |
+
# =============================================================================================
|
| 187 |
+
# 🎯DIAGNOSTICS FOR THE LENGTH OF LIST PAYLOAD BEING SENT TO THE PROVIDER, WHICH IT CAN HANDLE
|
| 188 |
+
# =============================================================================================
|
| 189 |
+
print("\n==================================================")
|
| 190 |
+
print(f"📊 Sending {len(messages)} raw message blocks to the {model}.")
|
| 191 |
+
print("==================================================\n")
|
| 192 |
+
# ====================================================================
|
| 193 |
+
|
| 194 |
+
try:
|
| 195 |
+
completion = client.chat.completions.create(
|
| 196 |
+
model=model,
|
| 197 |
+
messages=messages,
|
| 198 |
+
stream=True,
|
| 199 |
+
temperature=0.2,
|
| 200 |
+
#max_tokens=1024 # Limit response size to prevent mid-stream cuts
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
response_text = ""
|
| 204 |
+
|
| 205 |
+
# Step 1: Stream the raw LLM output token by token to the user
|
| 206 |
+
for chunk in completion:
|
| 207 |
+
if chunk.choices and chunk.choices[0].delta.content:
|
| 208 |
+
token = chunk.choices[0].delta.content
|
| 209 |
+
response_text += token
|
| 210 |
+
yield response_text
|
| 211 |
+
|
| 212 |
+
# ARTIFACT CHECK: Scan the response text for any code block structures
|
| 213 |
+
# This matches strings enclosed within triple backticks ```
|
| 214 |
+
has_code_blocks = bool(re.search(r"```[\s\S]*?```", response_text))
|
| 215 |
+
|
| 216 |
+
if has_code_blocks:
|
| 217 |
+
# ONLY execute file creation and staging alerts if an artifact is detected
|
| 218 |
+
|
| 219 |
+
# Step 2: Transition seamlessly to Local File Generation
|
| 220 |
+
yield response_text + "\n\n◌ _File agent initialized: Generating local documentation workspace..._"
|
| 221 |
+
|
| 222 |
+
from file_agent import write_document
|
| 223 |
+
import shutil
|
| 224 |
+
|
| 225 |
+
filename = "COURSE_README.md"
|
| 226 |
+
backup_filename = "COURSE_README_-1.md"
|
| 227 |
+
|
| 228 |
+
# Proactively manage historical backup copy before writing fresh file state
|
| 229 |
+
src_path = os.path.join("outputs", filename)
|
| 230 |
+
dst_path = os.path.join("outputs", backup_filename)
|
| 231 |
+
if os.path.exists(src_path):
|
| 232 |
+
try:
|
| 233 |
+
shutil.copy2(src_path, dst_path)
|
| 234 |
+
except Exception as e:
|
| 235 |
+
from agent_logging import log_agent_action
|
| 236 |
+
log_agent_action("BACKUP_ERROR", f"Failed to cycle historical version file: {str(e)}")
|
| 237 |
+
|
| 238 |
+
# Write fresh incoming file generation
|
| 239 |
+
file_path = write_document(response_text, filename)
|
| 240 |
+
|
| 241 |
+
print(f"\nGenerated file at: {file_path}")
|
| 242 |
+
|
| 243 |
+
# Step 3: Inform the UI that the material is staged and ready for the GitHub authorization layer
|
| 244 |
+
if "Error" not in file_path:
|
| 245 |
+
yield response_text + f"\n\n✅ _Files successfully generated in localized staging environment._\n\n◌ _Awaiting authorization control panel to push to GitHub._"
|
| 246 |
+
else:
|
| 247 |
+
yield response_text + f"\n\n❌ _File generation failed: {file_path}_"
|
| 248 |
+
|
| 249 |
+
except Exception as e:
|
| 250 |
+
yield f"Error: {str(e)}"
|
| 251 |
+
|
| 252 |
+
|