Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,118 +1,15 @@
|
|
| 1 |
-
import
|
| 2 |
-
import json
|
| 3 |
-
from fastapi import FastAPI, HTTPException
|
| 4 |
-
from fastapi.responses import StreamingResponse
|
| 5 |
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
-
from pydantic import BaseModel
|
| 7 |
-
from typing import List
|
| 8 |
-
from pymongo import MongoClient
|
| 9 |
-
from huggingface_hub import hf_hub_download
|
| 10 |
-
from llama_cpp import Llama
|
| 11 |
|
| 12 |
-
# --- 1. BLOCKING INITIALIZATION (MODEL FIRST) ---
|
| 13 |
-
# We load the model BEFORE starting the app so it's ready to handle requests immediately.
|
| 14 |
-
REPO_ID = "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF"
|
| 15 |
-
MODEL_FILENAME = "qwen2.5-coder-1.5b-instruct-q4_k_m.gguf"
|
| 16 |
-
|
| 17 |
-
print("Downloading/Locating model...")
|
| 18 |
-
MODEL_PATH = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME, local_dir=".")
|
| 19 |
-
|
| 20 |
-
print("Loading LLM into RAM (n_ctx=2048)...")
|
| 21 |
-
llm = Llama(
|
| 22 |
-
model_path=MODEL_PATH,
|
| 23 |
-
n_ctx=2048,
|
| 24 |
-
n_threads=2,
|
| 25 |
-
chat_format="chatml",
|
| 26 |
-
verbose=False
|
| 27 |
-
)
|
| 28 |
-
|
| 29 |
-
# --- 2. APP DEFINITION ---
|
| 30 |
app = FastAPI()
|
| 31 |
|
| 32 |
app.add_middleware(
|
| 33 |
CORSMiddleware,
|
| 34 |
allow_origins=["*"],
|
| 35 |
-
allow_credentials=True,
|
| 36 |
allow_methods=["*"],
|
| 37 |
allow_headers=["*"],
|
| 38 |
)
|
| 39 |
|
| 40 |
-
# --- 3. MONGODB & KNOWLEDGE CACHE ---
|
| 41 |
-
MONGO_URI = os.getenv("MONGO_URI")
|
| 42 |
-
if not MONGO_URI:
|
| 43 |
-
print("Warning: MONGO_URI secret is missing!")
|
| 44 |
-
db_client = None
|
| 45 |
-
knowledge_col = None
|
| 46 |
-
else:
|
| 47 |
-
db_client = MongoClient(MONGO_URI)
|
| 48 |
-
knowledge_col = db_client["ai_memory"]["knowledge"]
|
| 49 |
-
|
| 50 |
-
CACHED_SYSTEM_PROMPT = "You are an elite, production-grade programming AI assistant."
|
| 51 |
-
|
| 52 |
-
def refresh_knowledge_cache():
|
| 53 |
-
global CACHED_SYSTEM_PROMPT
|
| 54 |
-
base_instruction = "You are an elite, production-grade programming AI assistant. Adhere strictly to these guidelines:\n"
|
| 55 |
-
if knowledge_col is not None:
|
| 56 |
-
try:
|
| 57 |
-
saved_items = knowledge_col.find({})
|
| 58 |
-
rules = [item["text"] for item in saved_items]
|
| 59 |
-
if not rules:
|
| 60 |
-
CACHED_SYSTEM_PROMPT = base_instruction + "- Always write clean, modular, and optimized code."
|
| 61 |
-
else:
|
| 62 |
-
CACHED_SYSTEM_PROMPT = base_instruction + "\n".join(f"- {rule}" for rule in rules)
|
| 63 |
-
except Exception as e:
|
| 64 |
-
print(f"Warning: Could not sync DB: {e}")
|
| 65 |
-
CACHED_SYSTEM_PROMPT = base_instruction
|
| 66 |
-
|
| 67 |
-
# Initialize knowledge on startup
|
| 68 |
-
refresh_knowledge_cache()
|
| 69 |
-
|
| 70 |
-
# --- 4. SCHEMAS ---
|
| 71 |
-
class ChatMessage(BaseModel):
|
| 72 |
-
role: str
|
| 73 |
-
content: str
|
| 74 |
-
|
| 75 |
-
class ChatRequest(BaseModel):
|
| 76 |
-
messages: List[ChatMessage]
|
| 77 |
-
|
| 78 |
-
class KnowledgeItem(BaseModel):
|
| 79 |
-
text: str
|
| 80 |
-
|
| 81 |
-
# --- 5. ENDPOINTS ---
|
| 82 |
-
|
| 83 |
@app.get("/")
|
| 84 |
-
|
| 85 |
-
return {"
|
| 86 |
-
|
| 87 |
-
@app.post("/v1/chat/completions")
|
| 88 |
-
async def chat_completion(request: ChatRequest):
|
| 89 |
-
try:
|
| 90 |
-
# Construct history with injected system prompt
|
| 91 |
-
history = [{"role": "system", "content": CACHED_SYSTEM_PROMPT}]
|
| 92 |
-
for msg in request.messages:
|
| 93 |
-
history.append({"role": msg.role, "content": msg.content})
|
| 94 |
-
|
| 95 |
-
def stream_generator():
|
| 96 |
-
response_stream = llm.create_chat_completion(
|
| 97 |
-
messages=history,
|
| 98 |
-
temperature=0.2,
|
| 99 |
-
stream=True
|
| 100 |
-
)
|
| 101 |
-
for chunk in response_stream:
|
| 102 |
-
yield f"data: {json.dumps(chunk)}\n\n"
|
| 103 |
-
yield "data: [DONE]\n\n"
|
| 104 |
-
|
| 105 |
-
return StreamingResponse(stream_generator(), media_type="text/event-stream")
|
| 106 |
-
except Exception as e:
|
| 107 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 108 |
-
|
| 109 |
-
@app.post("/admin/teach")
|
| 110 |
-
async def add_permanent_knowledge(item: KnowledgeItem):
|
| 111 |
-
if knowledge_col is None:
|
| 112 |
-
raise HTTPException(status_code=500, detail="Database not configured")
|
| 113 |
-
try:
|
| 114 |
-
knowledge_col.insert_one({"text": item.text.strip()})
|
| 115 |
-
refresh_knowledge_cache()
|
| 116 |
-
return {"status": "success", "detail": "Knowledge updated."}
|
| 117 |
-
except Exception as e:
|
| 118 |
-
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
|
|
|
|
|
|
|
|
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
app = FastAPI()
|
| 5 |
|
| 6 |
app.add_middleware(
|
| 7 |
CORSMiddleware,
|
| 8 |
allow_origins=["*"],
|
|
|
|
| 9 |
allow_methods=["*"],
|
| 10 |
allow_headers=["*"],
|
| 11 |
)
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
@app.get("/")
|
| 14 |
+
def read_root():
|
| 15 |
+
return {"message": "The server is working!"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|