Spaces:
Running
Running
Commit ·
901f373
1
Parent(s): 101c553
chore: purge obsolete scripts and lockfiles to make space clean and lightweight
Browse filesFiles changed (11)
- app.pyDeleted-324
- chat.pyDeleted-8
- main.pyDeleted-67
- next.config.mjsDeleted-6
- optimize_speed.pyDeleted-21
- postcss.config.mjsDeleted-7
- pyproject.tomlDeleted-33
- train_sd_lora.pyDeleted-128
- update_comprehension.pyDeleted-40
- update_prompt.pyDeleted-30
- uv.lockDeleted
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324"""app.py - Production FastAPI Engine for KORAHigh-performance asynchronous server running on free Hugging Face Spaces (2 vCPU, 16GB RAM).Features:- Dual-model asynchronous llama-cpp-python runtime- POST /v1/chat/completions (Phi-3.5-mini-instruct with live DuckDuckGo web search & persistent memory)- POST /v1/code/completions (Qwen2.5-Coder-1.5B with regex HTML5/code sanitizer)- POST /v1/memory/learn (cross-session memory learning)- Server-Sent Events (SSE) streaming"""
import osimport jsonimport asynciofrom typing import List, Dict, Any, Optionalfrom fastapi import FastAPI, HTTPException, Request, BackgroundTasksfrom fastapi.responses import StreamingResponse, JSONResponsefrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModel, Field
from tools import web_search, fetch_url_text, read_file_chunkfrom memory import get_user_facts, save_user_fact, format_memory_for_promptfrom sanitizer import clean_html_output, clean_code_blockfrom image_engine import enhance_prompt, generate_image_api, generate_svg_fallback
# ---------------------------------------------------------------------------# App Initialization & CORS# ---------------------------------------------------------------------------app = FastAPI( title="KORA Intelligence Engine", description="Autonomous Neural Reasoning & Full-Stack Code Synthesis by KONTYRA", version="2.0.0")
app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
# ---------------------------------------------------------------------------# Lazy Model Loading (llama-cpp-python)# ---------------------------------------------------------------------------CHAT_MODEL_PATH = os.getenv("CHAT_MODEL_PATH", "./models/phi-3.5-mini-instruct.Q4_K_M.gguf")CODE_MODEL_PATH = os.getenv("CODE_MODEL_PATH", "./models/qwen2.5-coder-1.5b-instruct.Q4_K_M.gguf")
chat_llm = Nonecode_llm = None
def get_chat_model(): global chat_llm if chat_llm is None: try: from llama_cpp import Llama if os.path.exists(CHAT_MODEL_PATH): print(f"[Model Loader] Initializing Chat Model: {CHAT_MODEL_PATH}") chat_llm = Llama( model_path=CHAT_MODEL_PATH, n_ctx=4096, n_threads=2, n_batch=512, verbose=False ) else: print(f"[Model Loader] Chat model file not found at {CHAT_MODEL_PATH}, fallback mode active.") except Exception as e: print(f"[Model Loader] Error loading chat model: {e}") return chat_llm
def get_code_model(): global code_llm if code_llm is None: try: from llama_cpp import Llama if os.path.exists(CODE_MODEL_PATH): print(f"[Model Loader] Initializing Code Model: {CODE_MODEL_PATH}") code_llm = Llama( model_path=CODE_MODEL_PATH, n_ctx=4096, n_threads=2, n_batch=512, verbose=False ) else: print(f"[Model Loader] Code model file not found at {CODE_MODEL_PATH}, fallback mode active.") except Exception as e: print(f"[Model Loader] Error loading code model: {e}") return code_llm
# ---------------------------------------------------------------------------# Pydantic Schemas# ---------------------------------------------------------------------------class ChatMessage(BaseModel): role: str content: str
class ChatCompletionRequest(BaseModel): messages: List[ChatMessage] model: Optional[str] = "kora-chat" temperature: Optional[float] = 0.7 max_tokens: Optional[int] = 1024 stream: Optional[bool] = True user_id: Optional[str] = "default_user"
class ImageGenerationRequest(BaseModel): prompt: str = Field(..., description="User prompt describing desired visual asset") width: Optional[int] = 1024 height: Optional[int] = 1024 mode: Optional[str] = "diffusion" # "diffusion" or "svg" response_format: Optional[str] = "url" # "url" or "b64_json"
class MemoryLearnRequest(BaseModel): user_id: str = "default_user" fact_type: str = Field(..., description="name, role, preference, note, or fact") value: Any = Field(..., description="The value to remember")
# ---------------------------------------------------------------------------# System Identity Prompt Seed (KONTYRA Core Directives)# ---------------------------------------------------------------------------KONTYRA_SYSTEM_SEED = """You are KORA, the elite autonomous intelligence platform for KONTYRA.Tagline: "Continuous Intelligence. Limitless Impact."
KONTYRA ECOSYSTEM PLATFORMS:- Official Hub: https://kontyra.name.ng- DevOS (Cloud IDE & Autonomous Containers): https://devos.kontyra.name.ng- VUX Events (Digital Event Platform): https://vux.kontyra.name.ng- Tech Visionaries Network / TVN: https://tvnetwork.zone.id- MathGuru: npmjs.com/package/mathguru- SwiftLink: https://slink.zone.id
CORE PRINCIPLES & DESIGN RULES:1. PURE LOGIC & ZERO PASSIVE PLACEHOLDERS: Always provide production-ready solutions and functional code directly.2. AESTHETICS: Pure black, clean white, high contrast, subtle hairline borders, and bold typography.3. PRECISE REASONING: Step-by-step verified logic and mathematical rigor."""
# ---------------------------------------------------------------------------# Endpoints# ---------------------------------------------------------------------------@app.get("/")def health_check(): return { "status": "online", "engine": "KORA v2.0.0", "chat_model_loaded": chat_llm is not None or os.path.exists(CHAT_MODEL_PATH), "code_model_loaded": code_llm is not None or os.path.exists(CODE_MODEL_PATH), }
@app.post("/v1/memory/learn")def learn_memory(req: MemoryLearnRequest): """Saves user identity facts and preferences to persistent memory.""" success = save_user_fact(req.user_id, req.fact_type, req.value) return {"success": success, "user_id": req.user_id, "saved": {req.fact_type: req.value}}
@app.post("/v1/images/generations")async def images_generations(req: ImageGenerationRequest): """ Image generation endpoint for KORA Studio. Injects Kontyra visual design language (matte black, glowing cyan/purple, glassmorphism, bold serif). Supports: - mode="diffusion": Serverless GPU diffusion rendering (FLUX.1 / SDXL). - mode="svg": Scalable, crisp Kontyra brand vector SVG code generator. """ width = req.width or 1024 height = req.height or 1024
if req.mode == "svg": svg_code = generate_svg_fallback(req.prompt, width, height) return { "created": 1795764000, "data": [{ "revised_prompt": enhance_prompt(req.prompt), "format": "image/svg+xml", "svg_code": svg_code, "provider": "Kontyra Scalable SVG Engine" }] }
# Default: Diffusion Generation result = generate_image_api(req.prompt, width, height) data_item = { "revised_prompt": result.get("enhanced_prompt", req.prompt), "provider": result.get("provider", "Serverless Diffusion") }
if "b64_json" in result and req.response_format == "b64_json": data_item["b64_json"] = result["b64_json"] elif "direct_url" in result: data_item["url"] = result["direct_url"] elif "svg_code" in result: data_item["format"] = "image/svg+xml" data_item["svg_code"] = result["svg_code"] else: data_item["url"] = f"https://pub-ca36ec775bc2411db57b100352558ed3.r2.dev/images/kora/generated/test_cat.jpg"
return { "created": 1795764000, "data": [data_item] }
@app.post("/v1/chat/completions")async def chat_completions(req: ChatCompletionRequest): """ Strategic reasoning and multi-turn conversational chat. Auto-detects temporal/real-time queries to trigger live DuckDuckGo search. Pre-loads user facts from persistent memory. """ user_id = req.user_id or "default_user" memory_context = format_memory_for_prompt(user_id) last_user_msg = next((m.content for m in reversed(req.messages) if m.role == "user"), "") # 1. Real-time Search Trigger Check search_context = "" temporal_triggers = ["today", "latest", "news", "current price", "who is", "weather", "recent", "what happened", "release date"] if any(trigger in last_user_msg.lower() for trigger in temporal_triggers): print(f"[Tools Trigger] Executing DuckDuckGo search for: {last_user_msg[:60]}") search_results = web_search(last_user_msg, max_results=3) if search_results: search_context = "### REAL-TIME WEB SEARCH RESULTS:\n" for res in search_results: search_context += f"- **{res['title']}**: {res['body']} ({res['href']})\n" search_context += "\n"
# 2. Build Enhanced Prompt full_system_prompt = f"{KONTYRA_SYSTEM_SEED}\n{memory_context}\n{search_context}".strip() prompt = f"<|system|>\n{full_system_prompt}<|end|>\n" for m in req.messages: prompt += f"<|{m.role}|>\n{m.content}<|end|>\n" prompt += "<|assistant|>\n"
llm = get_chat_model()
# Streaming Handler async def stream_generator(): if llm: output = llm( prompt, max_tokens=req.max_tokens or 1024, temperature=req.temperature or 0.7, stream=True ) for chunk in output: text = chunk["choices"][0]["text"] yield f"data: {json.dumps({'choices': [{'delta': {'content': text}}]})}\n\n" await asyncio.sleep(0.005) else: # Fallback simulated response if GGUF is downloading simulated = f"Hello! I am KORA, your autonomous intelligence companion. I am ready to reason and assist you across the Kontyra ecosystem." for word in simulated.split(" "): yield f"data: {json.dumps({'choices': [{'delta': {'content': word + ' '}}]})}\n\n" await asyncio.sleep(0.04) yield "data: [DONE]\n\n"
return StreamingResponse(stream_generator(), media_type="text/event-stream")
@app.post("/v1/code/completions")async def code_completions(req: ChatCompletionRequest): """ Dedicated code synthesis endpoint routed to Qwen2.5-Coder. Passes output through deterministic regex HTML5/code sanitizer before streaming. """ code_system = ( f"{KONTYRA_SYSTEM_SEED}\n\n" "CODE SYNTHESIS DIRECTIVE:\n" "Output complete, production-ready, fully responsive code.\n" "Valid HTML5, semantic tags, and Tailwind CSS. Zero placeholder comments." ) prompt = f"<|im_start|>system\n{code_system}<|im_end|>\n" for m in req.messages: prompt += f"<|im_start|>{m.role}\n{m.content}<|im_end|>\n" prompt += "<|im_start|>assistant\n"
llm = get_code_model() or get_chat_model()
async def stream_code_generator(): collected_buffer = "" if llm: output = llm( prompt, max_tokens=req.max_tokens or 2048, temperature=req.temperature or 0.2, stream=True ) for chunk in output: text = chunk["choices"][0]["text"] collected_buffer += text yield f"data: {json.dumps({'choices': [{'delta': {'content': text}}]})}\n\n" await asyncio.sleep(0.005) else: # High-fidelity programmatic template fallback sample_code = ( "```html\n" "<!DOCTYPE html>\n" "<html lang=\"en\">\n" "<head>\n" " <meta charset=\"UTF-8\">\n" " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" " <title>Kora Web App</title>\n" " <script src=\"https://cdn.tailwindcss.com\"></script>\n" "</head>\n" "<body class=\"bg-black text-white min-h-screen flex items-center justify-center p-6\">\n" " <div class=\"bg-[#09090b] border border-white/20 rounded-2xl p-6 max-w-md w-full shadow-2xl\">\n" " <h1 class=\"text-xl font-bold font-mono text-cyan-400 mb-2\">KORA Autonomous Core</h1>\n" " <p class=\"text-xs text-white/80 leading-relaxed\">Engine is active and ready for live code execution.</p>\n" " </div>\n" "</body>\n" "</html>\n" "```" ) for word in sample_code.split(" "): yield f"data: {json.dumps({'choices': [{'delta': {'content': word + ' '}}]})}\n\n" await asyncio.sleep(0.02) yield "data: [DONE]\n\n"
return StreamingResponse(stream_code_generator(), media_type="text/event-stream")
if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)12345678"""Convenient Root-Level Launcher to Chat with Kora."""
from kora.chat import chat_with_kora
if __name__ == "__main__": chat_with_kora()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667"""FastAPI entrypoint for the KORA AI backend."""
from __future__ import annotations
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI
from app.routes.chat import router as chat_router
from app.services.model_service import ModelService
from app.services.prompt_service import PromptService
from app.utils.config import settings
def configure_logging() -> None:
"""Configure centralized application logging."""
logging.basicConfig(
level=getattr(logging, settings.log_level.upper(), logging.INFO),
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Initialize shared services for app lifecycle."""
configure_logging()
prompt_service = PromptService(settings=settings)
model_service = ModelService(settings=settings)
app.state.prompt_service = prompt_service
app.state.model_service = model_service
await model_service.startup()
logging.getLogger(__name__).info("KORA backend initialized")
try:
yield
finally:
await model_service.shutdown()
app = FastAPI(
title=settings.app_name,
version="1.0.0",
lifespan=lifespan,
)
app.include_router(chat_router)
@app.get("/healthz", tags=["health"])
async def healthz() -> dict[str, str]:
"""Liveness/readiness probe for orchestrators and HF Spaces."""
return {"status": "ok", "service": settings.app_name}
@app.get("/", tags=["root"])
async def root() -> dict[str, str]:
"""Simple root route so HF Space URL does not return 404."""
return {
"service": settings.app_name,
"status": "ok",
"health": "/healthz",
"chat": "/v1/chat/completions",
}123456/** @type {import('next').NextConfig} */const nextConfig = { reactStrictMode: true,};
export default nextConfig;123456789101112131415161718192021import os
space_path = r'c:\Users\DELL\Documents\GitHub\kora-ai-hf-space\gateway.py'with open(space_path, 'r', encoding='utf-8') as f: code = f.read()
# Optimize default max_tokens and generation speed for CPU# 1024 tokens on a CPU takes 30-40 seconds. Capping default to 512 and optimizing beam/sample makes it respond 3x faster.code = code.replace( 'max_new_tokens=req.max_tokens or 1024,', 'max_new_tokens=req.max_tokens or 384,')code = code.replace( 'temperature=req.temperature or 0.7,', 'temperature=req.temperature or 0.3,')
with open(space_path, 'w', encoding='utf-8') as f: f.write(code)
print("SUCCESS: Optimized CPU generation parameters in gateway.py for fast real-time streaming!")1234567const config = { plugins: { "@tailwindcss/postcss": {}, },};
export default config;123456789101112131415161718192021222324252627282930313233[project]name = "kora"version = "0.1.0"description = "A small experimental language model built from scratch"readme = "README.md"requires-python = ">=3.11"dependencies = [ "onnxruntime>=1.18.0", "numpy>=1.24.0",]
[dependency-groups]dev = [ "torch>=2.0.0", "matplotlib>=3.7.0", "jupyterlab>=4.0.0", "datasets>=5.0.1", "huggingface-hub>=1.33.0", "onnx>=1.23.0", "onnxscript>=0.7.2", "transformers>=5.18.0", "peft>=0.21.2", "accelerate>=1.15.0", "fastapi>=0.142.2", "uvicorn>=0.54.0", "diffusers>=0.40.0",]
[tool.vercel]entrypoint = "api.chat:handler"
[tool.uv]package = false123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128"""train_sd_lora.py - Stable Diffusion XL (SDXL) & FLUX LoRA Fine-Tuning ScriptDesigned for Google Colab (Tesla T4 GPU 16GB VRAM) using diffusers, peft, and accelerate.Bakes Kontyra brand aesthetics (matte black, glowing cyan/purple, glassmorphism, bold serif typography) directly into visual diffusion weights."""
import osimport torchfrom pathlib import Pathfrom PIL import Imagefrom torch.utils.data import Dataset, DataLoaderfrom torchvision import transforms
# ---------------------------------------------------------------------------# Training Configurations# ---------------------------------------------------------------------------MODEL_ID = "stabilityai/stable-diffusion-xl-base-1.0"OUTPUT_DIR = "./kontyra_sdxl_lora"INSTANCE_PROMPT = "in kontyra style, matte black, cyan and purple neon glow, glassmorphic"RESOLUTION = 512 # 512 for T4 memory efficiency with SDXL, or 768 on A100BATCH_SIZE = 1GRADIENT_ACCUMULATION = 4LEARNING_RATE = 1e-4MAX_TRAIN_STEPS = 200LORA_RANK = 16
os.makedirs(OUTPUT_DIR, exist_ok=True)
print(f"=== Starting Kontyra SDXL LoRA Fine-Tuning ===")print(f"Target Base Model: {MODEL_ID}")print(f"Output Directory: {OUTPUT_DIR}")print(f"Instance Trigger: '{INSTANCE_PROMPT}'")
# ---------------------------------------------------------------------------# 1. Custom Dataset Loader# ---------------------------------------------------------------------------class KontyraDataset(Dataset): def __init__(self, image_dir: str, instance_prompt: str, size: int = 512): self.image_dir = Path(image_dir) self.instance_prompt = instance_prompt self.size = size self.image_paths = list(self.image_dir.glob("*.jpg")) + list(self.image_dir.glob("*.png")) self.transform = transforms.Compose([ transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR), transforms.CenterCrop(size), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ])
def __len__(self): return max(len(self.image_paths), 1)
def __getitem__(self, index): if not self.image_paths: # Fallback black canvas with synthetic cyan/purple gradient if no local images provided img = Image.new("RGB", (self.size, self.size), color=(10, 12, 16)) else: img = Image.open(self.image_paths[index % len(self.image_paths)]).convert("RGB") tensor_img = self.transform(img) return {"pixel_values": tensor_img, "prompt": self.instance_prompt}
# ---------------------------------------------------------------------------# 2. Main Training Function using Diffusers & PEFT# ---------------------------------------------------------------------------def run_training(): try: from diffusers import AutoencoderKL, UNet2DConditionModel, DDPMScheduler from transformers import AutoTokenizer, PretrainedConfig from peft import LoraConfig, get_peft_model except ImportError: print("Please install diffusers & peft:") print("pip install diffusers transformers peft accelerate torchvision") return
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(f"Executing on device: {device}")
# Load UNet print("Loading SDXL UNet...") unet = UNet2DConditionModel.from_pretrained( MODEL_ID, subfolder="unet", torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, ).to(device)
# Inject LoRA into UNet cross-attention projections lora_config = LoraConfig( r=LORA_RANK, lora_alpha=LORA_RANK, init_lora_weights="gaussian", target_modules=["to_k", "to_q", "to_v", "to_out.0"], ) unet = get_peft_model(unet, lora_config) unet.print_trainable_parameters()
# Optimizer with 1e-4 learning rate optimizer = torch.optim.AdamW(unet.parameters(), lr=LEARNING_RATE, weight_decay=1e-2)
# Initialize Dataset data_dir = "./training_images" os.makedirs(data_dir, exist_ok=True) dataset = KontyraDataset(data_dir, INSTANCE_PROMPT, size=RESOLUTION) dataloader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True)
print("=== Training LoRA Weights ===") unet.train() step = 0 for epoch in range(1, 10): for batch in dataloader: step += 1 # Forward pass simulation / gradient step optimizer.zero_grad() # In full pipeline, compute diffusion noise loss: # loss = F.mse_loss(noise_pred.float(), target.float(), reduction="mean") if step >= MAX_TRAIN_STEPS: break if step >= MAX_TRAIN_STEPS: break
# Save final LoRA weights print(f"=== Saving Kontyra LoRA weights to {OUTPUT_DIR} ===") unet.save_pretrained(OUTPUT_DIR) print("=== SDXL LoRA Training Complete! ===")
if __name__ == "__main__": run_training()12345678910111213141516171819202122232425262728293031323334353637383940import os
space_path = r'c:\Users\DELL\Documents\GitHub\kora-ai-hf-space\gateway.py'with open(space_path, 'r', encoding='utf-8') as f: code = f.read()
# Replace with general, intelligent reasoning and intent comprehensiontarget_system = '''STRICT_CHAT_SYSTEM = ( "You are Kora, the flagship autonomous AI companion engineered by Kontyra. " "MANDATORY IDENTITY AND THINKING PROTOCOL:\\n" "1. Brand Spelling: Always spell your creator as Kontyra (never Kontyria, Kontya, or Konta).\\n" "2. User Identity: The user speaking with you is Heritage. Always address Heritage respectfully and never confuse user identity.\\n" "3. Cloud Integration: You are deeply integrated with DevOS (cloud IDE), Kontyra Accounts (SSO), and the Kontyra cloud network.\\n" "4. THINKING PROCESS: Always begin by thinking quietly inside <thought>...</thought> tags to reason step-by-step, verify facts, check spelling, and formulate your strategy before giving your final concise, crystal-clear answer.\\n" "5. Output Style: Direct, confident, elegant, and free from repetitive robotic disclaimers.")'''
replacement_system = '''STRICT_CHAT_SYSTEM = ( "You are Kora, an advanced, highly intelligent AI assistant engineered by Kontyra.\\n" "CORE COMPREHENSION & REASONING PRINCIPLES:\\n" "1. DEEP COMPREHENSION: Carefully analyze what the user is saying or asking before formulating your reply. Pay close attention to context, technical specifics (frameworks, versions, architectures), and user intent.\\n" "2. ACCURACY OVER GUESSWORK: If asked for modern technical solutions (e.g., Next.js 15, Cloudflare R2, React 19), provide exact, production-ready patterns matching current standards rather than outdated or broken legacy code.\\n" "3. BRAND IDENTITY: You were created by Kontyra (spelled K-O-N-T-Y-R-A). Maintain accurate spelling at all times.\\n" "4. DYNAMIC USER AWARENESS: Learn the user's name and preferences naturally from the conversation flow. Never assume or hardcode any user identity.\\n" "5. INTERNAL REASONING: Quietly reason through the problem step-by-step before answering to ensure your logic is sound, your code is bug-free, and your response directly satisfies what the user requested.\\n" "6. TONE & FORMATTING: Professional, clean, helpful, and concise with proper markdown and syntax-highlighted code.")'''
if target_system in code: code = code.replace(target_system, replacement_system) with open(space_path, 'w', encoding='utf-8') as f: f.write(code) print("SUCCESS: Refactored system prompt to genuine comprehension and dynamic user awareness!")else: # If not exact match, do a regex replacement on STRICT_CHAT_SYSTEM = \(.*?\) import re code = re.sub(r'STRICT_CHAT_SYSTEM = \([\s\S]*?\n\)', replacement_system, code) with open(space_path, 'w', encoding='utf-8') as f: f.write(code) print("SUCCESS: Regex replaced STRICT_CHAT_SYSTEM!")123456789101112131415161718192021222324252627282930import re
space_path = r'c:\Users\DELL\Documents\GitHub\kora-ai-hf-space\gateway.py'with open(space_path, 'r', encoding='utf-8') as f: code = f.read()
target = '''STRICT_CHAT_SYSTEM = ( "You are Kora, the warm, intelligent, and proactive AI companion engineered by Kontyra. " "You are speaking with the user. The user's name is separate from yours — do NOT adopt the user's name. " "Speak directly, warmly, and helpfully. NEVER recite your internal rules or guidelines. " "NEVER say 'I am just a computer program' or give robotic disclaimers.")'''
replacement = '''STRICT_CHAT_SYSTEM = ( "You are Kora, the flagship autonomous AI companion engineered by Kontyra. " "MANDATORY IDENTITY AND THINKING PROTOCOL:\\n" "1. Brand Spelling: Always spell your creator as Kontyra (never Kontyria, Kontya, or Konta).\\n" "2. User Identity: The user speaking with you is Heritage. Always address Heritage respectfully and never confuse user identity.\\n" "3. Cloud Integration: You are deeply integrated with DevOS (cloud IDE), Kontyra Accounts (SSO), and the Kontyra cloud network.\\n" "4. THINKING PROCESS: Always begin by thinking quietly inside <thought>...</thought> tags to reason step-by-step, verify facts, check spelling, and formulate your strategy before giving your final concise, crystal-clear answer.\\n" "5. Output Style: Direct, confident, elegant, and free from repetitive robotic disclaimers.")'''
if target in code: code = code.replace(target, replacement) with open(space_path, 'w', encoding='utf-8') as f: f.write(code) print("SUCCESS: Upgraded STRICT_CHAT_SYSTEM in gateway.py with Chain-of-Thought thinking!")else: print("Could not find exact target block.")app.pyDeleted-324
chat.pyDeleted-8
main.pyDeleted-67
next.config.mjsDeleted-6
optimize_speed.pyDeleted-21
postcss.config.mjsDeleted-7
pyproject.tomlDeleted-33
train_sd_lora.pyDeleted-128
update_comprehension.pyDeleted-40
update_prompt.pyDeleted-30
uv.lockDeleted