Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,10 +3,17 @@ from fastapi import FastAPI, HTTPException
|
|
| 3 |
from pydantic import BaseModel
|
| 4 |
from typing import List, Dict
|
| 5 |
from pymongo import MongoClient
|
|
|
|
| 6 |
from llama_cpp import Llama
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
# 1. Connect to MongoDB using the secret from Space Settings
|
| 11 |
MONGO_URI = os.getenv("MONGO_URI")
|
| 12 |
if not MONGO_URI:
|
|
@@ -20,24 +27,25 @@ except Exception as e:
|
|
| 20 |
raise RuntimeError(f"Failed to initialize MongoDB client: {str(e)}")
|
| 21 |
|
| 22 |
|
| 23 |
-
# 2.
|
| 24 |
-
|
| 25 |
-
MODEL_PATH = "./gemma-4-12b-coder.gguf"
|
| 26 |
|
| 27 |
if not os.path.exists(MODEL_PATH):
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
| 33 |
|
| 34 |
-
print("
|
| 35 |
llm = Llama(
|
| 36 |
model_path=MODEL_PATH,
|
| 37 |
-
n_ctx=2048, #
|
| 38 |
-
n_threads=4 #
|
| 39 |
)
|
| 40 |
-
print("
|
| 41 |
|
| 42 |
|
| 43 |
# 3. Data Schemas for Incoming Requests
|
|
@@ -55,8 +63,8 @@ class KnowledgeItem(BaseModel):
|
|
| 55 |
# 4. Helper Function to Assemble the Permanent Brain Layer
|
| 56 |
def compile_permanent_knowledge() -> str:
|
| 57 |
base_instruction = (
|
| 58 |
-
"You are
|
| 59 |
-
"Adhere strictly to the following custom rules and
|
| 60 |
)
|
| 61 |
|
| 62 |
try:
|
|
@@ -67,7 +75,7 @@ def compile_permanent_knowledge() -> str:
|
|
| 67 |
rules = []
|
| 68 |
|
| 69 |
if not rules:
|
| 70 |
-
return base_instruction + "- Always prioritize clean,
|
| 71 |
|
| 72 |
return base_instruction + "\n".join(f"- {rule}" for rule in rules)
|
| 73 |
|
|
@@ -76,37 +84,37 @@ def compile_permanent_knowledge() -> str:
|
|
| 76 |
|
| 77 |
@app.get("/")
|
| 78 |
async def root_health_check():
|
| 79 |
-
"""Handles
|
| 80 |
-
return {"status": "healthy", "
|
| 81 |
|
| 82 |
|
| 83 |
@app.post("/v1/chat/completions")
|
| 84 |
async def chat_completion(request: ChatRequest):
|
| 85 |
"""
|
| 86 |
-
Stateless
|
| 87 |
-
|
| 88 |
"""
|
| 89 |
try:
|
| 90 |
-
# Step A: Inject
|
| 91 |
system_prompt = compile_permanent_knowledge()
|
| 92 |
|
| 93 |
-
# Step B:
|
| 94 |
temporary_context = [
|
| 95 |
{"role": "system", "content": system_prompt}
|
| 96 |
]
|
| 97 |
|
| 98 |
-
# Step C:
|
| 99 |
for msg in request.messages:
|
| 100 |
temporary_context.append({"role": msg.role, "content": msg.content})
|
| 101 |
|
| 102 |
-
# Step D:
|
| 103 |
response = llm.create_chat_completion(
|
| 104 |
messages=temporary_context,
|
| 105 |
-
temperature=0.
|
| 106 |
max_tokens=1024
|
| 107 |
)
|
| 108 |
|
| 109 |
-
# Step E:
|
| 110 |
return response
|
| 111 |
|
| 112 |
except Exception as e:
|
|
@@ -116,14 +124,14 @@ async def chat_completion(request: ChatRequest):
|
|
| 116 |
@app.post("/admin/teach")
|
| 117 |
async def add_permanent_knowledge(item: KnowledgeItem):
|
| 118 |
"""
|
| 119 |
-
Write
|
| 120 |
-
|
| 121 |
"""
|
| 122 |
if not item.text.strip():
|
| 123 |
-
raise HTTPException(status_code=400, detail="
|
| 124 |
|
| 125 |
try:
|
| 126 |
knowledge_col.insert_one({"text": item.text.strip()})
|
| 127 |
-
return {"status": "success", "detail": "Custom
|
| 128 |
except Exception as e:
|
| 129 |
-
raise HTTPException(status_code=500, detail=f"Database write
|
|
|
|
| 3 |
from pydantic import BaseModel
|
| 4 |
from typing import List, Dict
|
| 5 |
from pymongo import MongoClient
|
| 6 |
+
from huggingface_hub import hf_hub_download
|
| 7 |
from llama_cpp import Llama
|
| 8 |
|
| 9 |
app = FastAPI()
|
| 10 |
|
| 11 |
+
# --- CONFIGURATION LAYER ---
|
| 12 |
+
# Change these two variables if you want to swap out the model engine later
|
| 13 |
+
REPO_ID = "Qwen/Qwen2.5-Coder-7B-Instruct-GGUF"
|
| 14 |
+
MODEL_FILENAME = "qwen2.5-coder-7b-instruct-q4_k_m.gguf"
|
| 15 |
+
# ---------------------------
|
| 16 |
+
|
| 17 |
# 1. Connect to MongoDB using the secret from Space Settings
|
| 18 |
MONGO_URI = os.getenv("MONGO_URI")
|
| 19 |
if not MONGO_URI:
|
|
|
|
| 27 |
raise RuntimeError(f"Failed to initialize MongoDB client: {str(e)}")
|
| 28 |
|
| 29 |
|
| 30 |
+
# 2. Automatic Cloud Download & Load Layer
|
| 31 |
+
MODEL_PATH = f"./{MODEL_FILENAME}"
|
|
|
|
| 32 |
|
| 33 |
if not os.path.exists(MODEL_PATH):
|
| 34 |
+
print(f"Model file not found locally. Downloading {MODEL_FILENAME} from HF Hub...")
|
| 35 |
+
try:
|
| 36 |
+
# Pulls the raw GGUF weights directly into your working container directory
|
| 37 |
+
MODEL_PATH = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME, local_dir=".")
|
| 38 |
+
print("Download complete successfully!")
|
| 39 |
+
except Exception as e:
|
| 40 |
+
raise RuntimeError(f"Failed to automatically pull weights from Hugging Face Hub: {str(e)}")
|
| 41 |
|
| 42 |
+
print("Allocating system RAM pool and pinning LLM matrix...")
|
| 43 |
llm = Llama(
|
| 44 |
model_path=MODEL_PATH,
|
| 45 |
+
n_ctx=2048, # Total token capacity for system instructions + chat history
|
| 46 |
+
n_threads=4 # Balanced CPU core assignment for Hugging Face Spaces
|
| 47 |
)
|
| 48 |
+
print("Model engine loaded and ready to process streams!")
|
| 49 |
|
| 50 |
|
| 51 |
# 3. Data Schemas for Incoming Requests
|
|
|
|
| 63 |
# 4. Helper Function to Assemble the Permanent Brain Layer
|
| 64 |
def compile_permanent_knowledge() -> str:
|
| 65 |
base_instruction = (
|
| 66 |
+
"You are an elite, production-grade programming AI assistant. "
|
| 67 |
+
"Adhere strictly to the following custom developer rules and ecosystem guidelines:\n"
|
| 68 |
)
|
| 69 |
|
| 70 |
try:
|
|
|
|
| 75 |
rules = []
|
| 76 |
|
| 77 |
if not rules:
|
| 78 |
+
return base_instruction + "- Always prioritize writing clean, highly optimized, and modular architecture."
|
| 79 |
|
| 80 |
return base_instruction + "\n".join(f"- {rule}" for rule in rules)
|
| 81 |
|
|
|
|
| 84 |
|
| 85 |
@app.get("/")
|
| 86 |
async def root_health_check():
|
| 87 |
+
"""Handles automatic framework pings from Hugging Face infrastructure."""
|
| 88 |
+
return {"status": "healthy", "engine": "Operational", "target": MODEL_FILENAME}
|
| 89 |
|
| 90 |
|
| 91 |
@app.post("/v1/chat/completions")
|
| 92 |
async def chat_completion(request: ChatRequest):
|
| 93 |
"""
|
| 94 |
+
Stateless chat completion layer. Processes full history streams,
|
| 95 |
+
generates responses, and safely flushes conversational RAM context.
|
| 96 |
"""
|
| 97 |
try:
|
| 98 |
+
# Step A: Inject dynamic custom instructions pulled straight from MongoDB Atlas
|
| 99 |
system_prompt = compile_permanent_knowledge()
|
| 100 |
|
| 101 |
+
# Step B: Spin up a fresh, zero-persistence context window array
|
| 102 |
temporary_context = [
|
| 103 |
{"role": "system", "content": system_prompt}
|
| 104 |
]
|
| 105 |
|
| 106 |
+
# Step C: Load the historical message history passed over from your client UI
|
| 107 |
for msg in request.messages:
|
| 108 |
temporary_context.append({"role": msg.role, "content": msg.content})
|
| 109 |
|
| 110 |
+
# Step D: Hand the compiled array over to the llama-cpp execution matrix
|
| 111 |
response = llm.create_chat_completion(
|
| 112 |
messages=temporary_context,
|
| 113 |
+
temperature=0.1, # Low temperature ensures highly structured, accurate code compilation
|
| 114 |
max_tokens=1024
|
| 115 |
)
|
| 116 |
|
| 117 |
+
# Step E: Return payload. Temporary context array is discarded instantly from memory.
|
| 118 |
return response
|
| 119 |
|
| 120 |
except Exception as e:
|
|
|
|
| 124 |
@app.post("/admin/teach")
|
| 125 |
async def add_permanent_knowledge(item: KnowledgeItem):
|
| 126 |
"""
|
| 127 |
+
Write permanent rules directly to your external cloud cluster.
|
| 128 |
+
Survives restarts, crashes, code updates, and sleeps forever.
|
| 129 |
"""
|
| 130 |
if not item.text.strip():
|
| 131 |
+
raise HTTPException(status_code=400, detail="Knowledge string cannot be empty.")
|
| 132 |
|
| 133 |
try:
|
| 134 |
knowledge_col.insert_one({"text": item.text.strip()})
|
| 135 |
+
return {"status": "success", "detail": "Custom guideline committed securely to cloud cluster."}
|
| 136 |
except Exception as e:
|
| 137 |
+
raise HTTPException(status_code=500, detail=f"Database write execution failed: {str(e)}")
|