ryan33121 commited on
Commit
9b1c7a4
·
verified ·
1 Parent(s): 351d332

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -8
app.py CHANGED
@@ -28,26 +28,35 @@ CACHED_SYSTEM_PROMPT = ""
28
  # 1. MongoDB Initialization
29
  MONGO_URI = os.getenv("MONGO_URI")
30
  if not MONGO_URI:
31
- raise RuntimeError("MONGO_URI secret is missing!")
32
 
33
  db_client = MongoClient(MONGO_URI)
34
  knowledge_col = db_client["ai_memory"]["knowledge"]
35
 
36
  def refresh_knowledge_cache():
37
  global CACHED_SYSTEM_PROMPT
38
- base_instruction = "You are an elite, production-grade programming AI assistant. Adhere to these guidelines:\n"
39
  try:
40
  saved_items = knowledge_col.find({})
41
  rules = [item["text"] for item in saved_items]
42
- CACHED_SYSTEM_PROMPT = base_instruction + "\n".join(f"- {rule}" for rule in rules)
43
- except:
 
 
 
 
44
  CACHED_SYSTEM_PROMPT = base_instruction
45
 
46
- # 2. Model Loading (with Memory Management)
47
- MODEL_PATH = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME, local_dir=".")
 
 
 
 
 
48
  llm = Llama(
49
  model_path=MODEL_PATH,
50
- n_ctx=2048, # Fix for Error 139
51
  n_threads=4,
52
  chat_format="chatml"
53
  )
@@ -66,9 +75,15 @@ class KnowledgeItem(BaseModel):
66
 
67
  # --- ENDPOINTS ---
68
 
 
 
 
 
 
69
  @app.post("/v1/chat/completions")
70
  async def chat_completion(request: ChatRequest):
71
  try:
 
72
  history = [{"role": "system", "content": CACHED_SYSTEM_PROMPT}]
73
  for msg in request.messages:
74
  history.append({"role": msg.role, "content": msg.content})
@@ -81,7 +96,7 @@ async def chat_completion(request: ChatRequest):
81
  )
82
  for chunk in response_stream:
83
  yield f"data: {json.dumps(chunk)}\n\n"
84
- yield "data: [DONE]\n\n" # Required for Chatbox to finish loading
85
 
86
  return StreamingResponse(stream_generator(), media_type="text/event-stream")
87
  except Exception as e:
 
28
  # 1. MongoDB Initialization
29
  MONGO_URI = os.getenv("MONGO_URI")
30
  if not MONGO_URI:
31
+ raise RuntimeError("MONGO_URI secret is missing from Space Settings!")
32
 
33
  db_client = MongoClient(MONGO_URI)
34
  knowledge_col = db_client["ai_memory"]["knowledge"]
35
 
36
  def refresh_knowledge_cache():
37
  global CACHED_SYSTEM_PROMPT
38
+ base_instruction = "You are an elite, production-grade programming AI assistant. Adhere strictly to these guidelines:\n"
39
  try:
40
  saved_items = knowledge_col.find({})
41
  rules = [item["text"] for item in saved_items]
42
+ if not rules:
43
+ CACHED_SYSTEM_PROMPT = base_instruction + "- Always write clean, modular, and optimized code."
44
+ else:
45
+ CACHED_SYSTEM_PROMPT = base_instruction + "\n".join(f"- {rule}" for rule in rules)
46
+ except Exception as e:
47
+ print(f"Warning: Could not sync DB: {e}")
48
  CACHED_SYSTEM_PROMPT = base_instruction
49
 
50
+ # 2. Model Download & Loading
51
+ MODEL_PATH = f"./{MODEL_FILENAME}"
52
+ if not os.path.exists(MODEL_PATH):
53
+ print("Downloading model...")
54
+ MODEL_PATH = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILENAME, local_dir=".")
55
+
56
+ print("Loading LLM into RAM (n_ctx=2048)...")
57
  llm = Llama(
58
  model_path=MODEL_PATH,
59
+ n_ctx=2048, # Fixes Exit Code 139
60
  n_threads=4,
61
  chat_format="chatml"
62
  )
 
75
 
76
  # --- ENDPOINTS ---
77
 
78
+ # Fixes the 404 Error:
79
+ @app.get("/")
80
+ async def root():
81
+ return {"status": "healthy", "message": "API is online and operational."}
82
+
83
  @app.post("/v1/chat/completions")
84
  async def chat_completion(request: ChatRequest):
85
  try:
86
+ # Construct history
87
  history = [{"role": "system", "content": CACHED_SYSTEM_PROMPT}]
88
  for msg in request.messages:
89
  history.append({"role": msg.role, "content": msg.content})
 
96
  )
97
  for chunk in response_stream:
98
  yield f"data: {json.dumps(chunk)}\n\n"
99
+ yield "data: [DONE]\n\n"
100
 
101
  return StreamingResponse(stream_generator(), media_type="text/event-stream")
102
  except Exception as e: