ryan33121 commited on
Commit
12e9294
·
verified ·
1 Parent(s): 57435c6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -43
app.py CHANGED
@@ -1,7 +1,7 @@
1
  import os
2
  import json
3
  from fastapi import FastAPI, HTTPException
4
- from fastapi.responses import StreamingResponse # <--- THIS IS THE MISSING PIECE
5
  from fastapi.middleware.cors import CORSMiddleware
6
  from pydantic import BaseModel
7
  from typing import List
@@ -9,10 +9,26 @@ from pymongo import MongoClient
9
  from huggingface_hub import hf_hub_download
10
  from llama_cpp import Llama
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  app = FastAPI()
13
- # ... (rest of your code continues here)
14
 
15
- # --- CORS SECURITY ---
16
  app.add_middleware(
17
  CORSMiddleware,
18
  allow_origins=["*"],
@@ -21,52 +37,37 @@ app.add_middleware(
21
  allow_headers=["*"],
22
  )
23
 
24
- # --- CONFIGURATION ---
25
- # SWAPPED TO 1.5B TO PREVENT EXIT CODE 139 (OOM CRASH)
26
- REPO_ID = "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF"
27
- MODEL_FILENAME = "qwen2.5-coder-1.5b-instruct-q4_k_m.gguf"
28
- CACHED_SYSTEM_PROMPT = ""
29
-
30
- # 1. MongoDB Initialization
31
  MONGO_URI = os.getenv("MONGO_URI")
32
  if not MONGO_URI:
33
- raise RuntimeError("MONGO_URI secret is missing from Space Settings!")
 
 
 
 
 
34
 
35
- db_client = MongoClient(MONGO_URI)
36
- knowledge_col = db_client["ai_memory"]["knowledge"]
37
 
38
  def refresh_knowledge_cache():
39
  global CACHED_SYSTEM_PROMPT
40
  base_instruction = "You are an elite, production-grade programming AI assistant. Adhere strictly to these guidelines:\n"
41
- try:
42
- saved_items = knowledge_col.find({})
43
- rules = [item["text"] for item in saved_items]
44
- if not rules:
45
- CACHED_SYSTEM_PROMPT = base_instruction + "- Always write clean, modular, and optimized code."
46
- else:
47
- CACHED_SYSTEM_PROMPT = base_instruction + "\n".join(f"- {rule}" for rule in rules)
48
- except Exception as e:
49
- print(f"Warning: Could not sync DB: {e}")
50
- CACHED_SYSTEM_PROMPT = base_instruction
51
-
52
- # 2. Model Download & Loading
53
- MODEL_PATH = f"./{MODEL_FILENAME}"
54
- if not os.path.exists(MODEL_PATH):
55
- print("Downloading model...")
56
- MODEL_PATH = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME, local_dir=".")
57
-
58
- print("Loading LLM into RAM (n_ctx=2048)...")
59
- # Reduced n_threads to 2 to ensure stability on shared hardware
60
- llm = Llama(
61
- model_path=MODEL_PATH,
62
- n_ctx=2048,
63
- n_threads=2,
64
- chat_format="chatml",
65
- verbose=False
66
- )
67
  refresh_knowledge_cache()
68
 
69
- # 3. Schemas
70
  class ChatMessage(BaseModel):
71
  role: str
72
  content: str
@@ -77,11 +78,11 @@ class ChatRequest(BaseModel):
77
  class KnowledgeItem(BaseModel):
78
  text: str
79
 
80
- # --- ENDPOINTS ---
81
 
82
  @app.get("/")
83
  async def root():
84
- return {"status": "healthy", "message": "API is online and operational."}
85
 
86
  @app.post("/v1/chat/completions")
87
  async def chat_completion(request: ChatRequest):
@@ -94,7 +95,7 @@ async def chat_completion(request: ChatRequest):
94
  def stream_generator():
95
  response_stream = llm.create_chat_completion(
96
  messages=history,
97
- temperature=0.2, # Slightly higher for creativity
98
  stream=True
99
  )
100
  for chunk in response_stream:
@@ -107,6 +108,8 @@ async def chat_completion(request: ChatRequest):
107
 
108
  @app.post("/admin/teach")
109
  async def add_permanent_knowledge(item: KnowledgeItem):
 
 
110
  try:
111
  knowledge_col.insert_one({"text": item.text.strip()})
112
  refresh_knowledge_cache()
 
1
  import os
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
 
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=["*"],
 
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
 
78
  class KnowledgeItem(BaseModel):
79
  text: str
80
 
81
+ # --- 5. ENDPOINTS ---
82
 
83
  @app.get("/")
84
  async def root():
85
+ return {"status": "healthy", "message": "API is online and ready for code generation."}
86
 
87
  @app.post("/v1/chat/completions")
88
  async def chat_completion(request: ChatRequest):
 
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:
 
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()