ryan33121 commited on
Commit
8818204
·
verified ·
1 Parent(s): f795cd0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -39
app.py CHANGED
@@ -15,6 +15,9 @@ REPO_ID = "Qwen/Qwen2.5-Coder-7B-Instruct-GGUF"
15
  MODEL_FILENAME = "qwen2.5-coder-7b-instruct-q4_k_m.gguf"
16
  # ---------------------------
17
 
 
 
 
18
  # 1. Connect to MongoDB using the secret from Space Settings
19
  MONGO_URI = os.getenv("MONGO_URI")
20
  if not MONGO_URI:
@@ -27,7 +30,30 @@ except Exception as e:
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):
@@ -44,10 +70,13 @@ llm = Llama(
44
  n_ctx=2048, # Total token capacity for system instructions + chat history
45
  n_threads=4 # Balanced CPU core assignment for Hugging Face Spaces
46
  )
 
 
 
47
  print("Model engine loaded and ready to process streams!")
48
 
49
 
50
- # 3. Data Schemas for Incoming Requests
51
  class ChatMessage(BaseModel):
52
  role: str
53
  content: str
@@ -59,68 +88,41 @@ class KnowledgeItem(BaseModel):
59
  text: str
60
 
61
 
62
- # 4. Helper Function to Assemble the Permanent Brain Layer
63
- def compile_permanent_knowledge() -> str:
64
- base_instruction = (
65
- "You are an elite, production-grade programming AI assistant. "
66
- "Adhere strictly to the following custom developer rules and ecosystem guidelines:\n"
67
- )
68
-
69
- try:
70
- saved_items = knowledge_col.find({})
71
- rules = [item["text"] for item in saved_items]
72
- except Exception as e:
73
- print(f"Database reading warning: {e}")
74
- rules = []
75
-
76
- if not rules:
77
- return base_instruction + "- Always prioritize writing clean, highly optimized, and modular architecture."
78
-
79
- return base_instruction + "\n".join(f"- {rule}" for rule in rules)
80
-
81
-
82
  # --- API ENDPOINTS ---
83
 
84
  @app.get("/")
85
  async def root_health_check():
86
  """Handles automatic framework pings from Hugging Face and Uptime monitors."""
87
- return {"status": "healthy", "engine": "Operational", "target": MODEL_FILENAME}
88
 
89
 
90
  @app.post("/v1/chat/completions")
91
  async def chat_completion(request: ChatRequest):
92
  """
93
- Streaming chat completion layer. Emits text chunk-by-chunk in real-time,
94
- massively improving UI responsiveness for the user.
95
  """
96
  try:
97
- # Step A: Pull your custom rules from your live MongoDB cluster
98
- system_prompt = compile_permanent_knowledge()
99
-
100
- # Step B: Establish the baseline system architecture rules
101
  temporary_context = [
102
- {"role": "system", "content": system_prompt}
103
  ]
104
 
105
- # Step C: Load the message array history coming from your client side application
106
  for msg in request.messages:
107
  temporary_context.append({"role": msg.role, "content": msg.content})
108
 
109
- # Step D: Create a background generator function to stream tokens safely
110
  def stream_generator():
111
- # Triggering stream=True tells llama.cpp to yield chunks instead of blocking
112
  response_stream = llm.create_chat_completion(
113
  messages=temporary_context,
114
  temperature=0.1,
115
  max_tokens=1024,
116
  stream=True
117
  )
118
-
119
  for chunk in response_stream:
120
- # Format each piece as a Server-Sent Event (SSE) data string
121
  yield f"data: {json.dumps(chunk)}\n\n"
122
 
123
- # Step E: Return the live running generator straight to your frontend
124
  return StreamingResponse(stream_generator(), media_type="text/event-stream")
125
 
126
  except Exception as e:
@@ -130,14 +132,19 @@ async def chat_completion(request: ChatRequest):
130
  @app.post("/admin/teach")
131
  async def add_permanent_knowledge(item: KnowledgeItem):
132
  """
133
- Write permanent rules directly to your external cloud cluster.
134
- Survives restarts, crashes, code updates, and sleeps forever.
135
  """
136
  if not item.text.strip():
137
  raise HTTPException(status_code=400, detail="Knowledge string cannot be empty.")
138
 
139
  try:
 
140
  knowledge_col.insert_one({"text": item.text.strip()})
141
- return {"status": "success", "detail": "Custom guideline committed securely to cloud cluster."}
 
 
 
 
142
  except Exception as e:
143
  raise HTTPException(status_code=500, detail=f"Database write execution failed: {str(e)}")
 
15
  MODEL_FILENAME = "qwen2.5-coder-7b-instruct-q4_k_m.gguf"
16
  # ---------------------------
17
 
18
+ # Global memory variable to cache your custom rules from MongoDB
19
+ CACHED_SYSTEM_PROMPT = ""
20
+
21
  # 1. Connect to MongoDB using the secret from Space Settings
22
  MONGO_URI = os.getenv("MONGO_URI")
23
  if not MONGO_URI:
 
30
  raise RuntimeError(f"Failed to initialize MongoDB client: {str(e)}")
31
 
32
 
33
+ # 2. Helper Function to Sync Database to Fast System RAM
34
+ def refresh_knowledge_cache():
35
+ """Reads MongoDB once and saves everything to local RAM for instant access."""
36
+ global CACHED_SYSTEM_PROMPT
37
+ base_instruction = (
38
+ "You are an elite, production-grade programming AI assistant. "
39
+ "Adhere strictly to the following custom developer rules and ecosystem guidelines:\n"
40
+ )
41
+ try:
42
+ saved_items = knowledge_col.find({})
43
+ rules = [item["text"] for item in saved_items]
44
+
45
+ if not rules:
46
+ CACHED_SYSTEM_PROMPT = base_instruction + "- Always prioritize writing clean, highly optimized, and modular architecture."
47
+ else:
48
+ CACHED_SYSTEM_PROMPT = base_instruction + "\n".join(f"- {rule}" for rule in rules)
49
+
50
+ print("⚡ System RAM Cache successfully synchronized with MongoDB Atlas rules.")
51
+ except Exception as e:
52
+ print(f"⚠️ Warning: Could not update RAM cache from database: {e}")
53
+ CACHED_SYSTEM_PROMPT = base_instruction
54
+
55
+
56
+ # 3. Automatic Cloud Download & Load Layer
57
  MODEL_PATH = f"./{MODEL_FILENAME}"
58
 
59
  if not os.path.exists(MODEL_PATH):
 
70
  n_ctx=2048, # Total token capacity for system instructions + chat history
71
  n_threads=4 # Balanced CPU core assignment for Hugging Face Spaces
72
  )
73
+
74
+ # Populate the RAM cache immediately on server startup
75
+ refresh_knowledge_cache()
76
  print("Model engine loaded and ready to process streams!")
77
 
78
 
79
+ # 4. Data Schemas for Incoming Requests
80
  class ChatMessage(BaseModel):
81
  role: str
82
  content: str
 
88
  text: str
89
 
90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  # --- API ENDPOINTS ---
92
 
93
  @app.get("/")
94
  async def root_health_check():
95
  """Handles automatic framework pings from Hugging Face and Uptime monitors."""
96
+ return {"status": "healthy", "engine": "Cached-Operational", "target": MODEL_FILENAME}
97
 
98
 
99
  @app.post("/v1/chat/completions")
100
  async def chat_completion(request: ChatRequest):
101
  """
102
+ Ultra-fast streaming endpoint. Reads prompt guidelines instantly from
103
+ system RAM cache instead of querying the database on every turn.
104
  """
105
  try:
106
+ # Step A: Instantly use the cached rules from RAM (Zero database lag!)
 
 
 
107
  temporary_context = [
108
+ {"role": "system", "content": CACHED_SYSTEM_PROMPT}
109
  ]
110
 
111
+ # Step B: Load the history array sent from your frontend interface
112
  for msg in request.messages:
113
  temporary_context.append({"role": msg.role, "content": msg.content})
114
 
115
+ # Step C: Background generator streams tokens back chunk-by-chunk
116
  def stream_generator():
 
117
  response_stream = llm.create_chat_completion(
118
  messages=temporary_context,
119
  temperature=0.1,
120
  max_tokens=1024,
121
  stream=True
122
  )
 
123
  for chunk in response_stream:
 
124
  yield f"data: {json.dumps(chunk)}\n\n"
125
 
 
126
  return StreamingResponse(stream_generator(), media_type="text/event-stream")
127
 
128
  except Exception as e:
 
132
  @app.post("/admin/teach")
133
  async def add_permanent_knowledge(item: KnowledgeItem):
134
  """
135
+ Writes new instructions to MongoDB AND instantly updates the live RAM cache
136
+ so changes take effect immediately without requiring a server reboot.
137
  """
138
  if not item.text.strip():
139
  raise HTTPException(status_code=400, detail="Knowledge string cannot be empty.")
140
 
141
  try:
142
+ # 1. Permanent commit to the external cloud database
143
  knowledge_col.insert_one({"text": item.text.strip()})
144
+
145
+ # 2. Instantly refresh the local RAM pool so the next chat request knows about it
146
+ refresh_knowledge_cache()
147
+
148
+ return {"status": "success", "detail": "Custom guideline committed securely and cached in RAM."}
149
  except Exception as e:
150
  raise HTTPException(status_code=500, detail=f"Database write execution failed: {str(e)}")