Spaces:
Sleeping
Sleeping
File size: 7,624 Bytes
0ea40d5 cb5a5c0 0ea40d5 cb5a5c0 b83d944 cb5a5c0 cf308ec f54201d b83d944 0ea40d5 cb5a5c0 f54201d cb5a5c0 f54201d cb5a5c0 f54201d cb5a5c0 9013c0e cb5a5c0 9013c0e cb5a5c0 9013c0e cb5a5c0 9013c0e cb5a5c0 9013c0e cb5a5c0 9013c0e cb5a5c0 9013c0e 931d9f1 9013c0e cb5a5c0 b5a0b96 0ea40d5 b5a0b96 aae6d78 cb5a5c0 aae6d78 cb5a5c0 aae6d78 3a187d4 b83d944 3a187d4 cb5a5c0 b5a0b96 e2d338a cb5a5c0 d003812 cb5a5c0 0a69020 cb5a5c0 890c54c e2d338a 0ea40d5 b5a0b96 0ea40d5 cb5a5c0 9013c0e fdc8455 3a187d4 fdc8455 e2d338a 8e09430 0ea40d5 fdc8455 3a187d4 1911701 3a187d4 aae6d78 3a187d4 b83d944 cb5a5c0 b83d944 f54201d cb5a5c0 5744898 cb5a5c0 5744898 f54201d fdc8455 cb5a5c0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 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 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 |
# ./core_logic.py
import os
import re # for structural artifact code block extraction
from groq import Groq
from tools import web_search, parse_file # script explicitly calls web_search()
import yaml
import toml
from docx import Document
client = Groq(api_key=os.getenv("GROQ_API_KEY"))
model = "llama-3.1-8b-instant"
# 1. Proactive DevOps Environment Check (Valid Dream Idea)
def verify_workspace_permissions():
"""Verifies write permissions to the workspace directory to ensure side-cars can compile."""
try:
test_file = "outputs/.permission_test.tmp"
os.makedirs("outputs", exist_ok=True)
with open(test_file, "w", encoding="utf-8") as f:
f.write("workspace_test")
os.remove(test_file)
except Exception as e:
print(f"⚠️ WORKSPACE WARNING: Verification engine encountered pathing friction: {e}")
verify_workspace_permissions()
# 2. Dynamic Cognitive Prompt Assembler
def compile_cognitive_system_prompt():
"""Assembles soul.md, heart.md, and memory.md into a high-density system directive block."""
base_soul = ""
current_heart = ""
past_memory = ""
# Ingest Core Mandate Layer
if os.path.exists("soul.md"):
with open("soul.md", "r", encoding="utf-8") as f:
base_soul = f.read()
else:
# Secure Environment variable option with a backup string fallback
base_soul = os.environ.get("BASE_SOUL", "You are CoderG, the Silicon Architect. Act as an elite AI Engineer.")
# Ingest Current Priorities State
if os.path.exists("heart.md"):
with open("heart.md", "r", encoding="utf-8") as f:
current_heart = f.read()
else:
current_heart = "Focus on base architectural compilation and optimizing core component workflows."
# Ingest Historical Ephemeral Layer
if os.path.exists("memory.md"):
with open("memory.md", "r", encoding="utf-8") as f:
past_memory = f.read()
else:
past_memory = "No historical operational constraints loaded yet."
master_prompt = f"""{base_soul}
====================================================================
❤️ ACTIVE OPERATIONAL TASK STATUS (HEART.MD)
====================================================================
{current_heart}
====================================================================
💾 HISTORICAL ENVIRONMENT TRUTHS & PATCHES (MEMORY.MD)
====================================================================
{past_memory}
"""
return master_prompt
# 3. Main Operational Streaming Core Execution Block
def chat_function(message, history, client, model):
"""Streams responses from the client provider using the cognitive prompt matrix."""
user_text = message.get("text", "")
files = message.get("files", [])
context_from_files = ""
# File asset context extraction
if files:
from perception_agent import read_document_file
yield "◌ _Perception Agent initialized: Ingesting uploaded file assets..._"
for f in files:
path = f["path"] if isinstance(f, dict) else f
if path and os.path.exists(path):
context_from_files += read_document_file(path)
yield "◌ _Perception processing complete. Transmitting compiled structures to the Brain..._"
if len(context_from_files) > 12000:
context_from_files = context_from_files[:12000] + "\n...[File Content Truncated for TPM Limits]..."
# Optimization/Research routine triggering logic
if any(keyword in user_text.lower() for keyword in ["search", "docs", "latest"]):
distill_response = client.chat.completions.create(
model="llama-3.1-8b-instant",
messages=[
{
"role": "system",
"content": (
"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"
"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."
)
},
{"role": "user", "content": f"Convert the following request into raw optimized search keywords:\n\n{user_text}"}
],
temperature=0.0,
)
raw_query = distill_response.choices[0].message.content.strip()
optimized_query = re.sub(r"[`'\"\\n\-*#\[\]]", "", raw_query).replace("python", "").strip()
if len(optimized_query) > 390:
optimized_query = optimized_query[:390].rpartition(' ')[0]
research_context = web_search(optimized_query)
prompt = f"RESEARCH:\n{research_context}\n\nFILES:\n{context_from_files}\n\nUSER: {optimized_query}"
else:
prompt = f"FILES:\n{context_from_files}\n\nUSER: {user_text}"
# Assembling context arrays
compiled_cognitive_prompt = compile_cognitive_system_prompt()
messages = [{"role": "system", "content": compiled_cognitive_prompt}]
for turn in history[-3:]:
messages.append({"role": turn["role"], "content": turn["content"]})
system_execution_fence = (
f"{prompt}\n\n"
"[SYSTEM EXECUTOR NOTICE: Answer the user's prompt immediately. "
"Do NOT append or print your Core Identity, Mandate, or Directives summary at the end of your response. "
"Stop generating tokens the moment the technical payload is complete.]"
)
messages.append({"role": "user", "content": system_execution_fence})
try:
completion = client.chat.completions.create(
model=model,
messages=messages,
stream=True,
temperature=0.2,
)
response_text = ""
for chunk in completion:
if chunk.choices and chunk.choices[0].delta.content:
response_text += chunk.choices[0].delta.content
yield response_text
# Automated Local Artifact Generation Execution Hook
if bool(re.search(r"```[\s\S]*?```", response_text)):
yield response_text + "\n\n◌ _File agent initialized: Generating local documentation workspace..._"
from file_agent import write_document
import shutil
filename = "COURSE_README.md"
backup_filename = "COURSE_README_-1.md"
src_path = os.path.join("outputs", filename)
dst_path = os.path.join("outputs", backup_filename)
if os.path.exists(src_path):
try:
shutil.copy2(src_path, dst_path)
except Exception as e:
from agent_logging import log_agent_action
log_agent_action("BACKUP_ERROR", f"Failed to cycle historical version file: {str(e)}")
file_path = write_document(response_text, filename)
if "Error" not in file_path:
yield response_text + f"\n\n✅ _Files successfully generated in localized staging environment._\n\n◌ _Awaiting authorization control panel to push to GitHub._"
else:
yield response_text + f"\n\n❌ _File generation failed: {file_path}_"
except Exception as e:
yield f"Error: {str(e)}" |